#StackBounty: #python #unit-testing #mocking Mocking attribute to change each time it is accessed

Bounty: 50

Here is the function I want to test:

def send_something():
    conn = lib.conn.SSH1
    if 'home' not in conn.recbuf:
        return lib.FAIL

    if USER not in conn.recbuf:
        return lib.FAIL
    return lib.PASS

Every time I call conn.send() the output of the call is stored in conn.recbuf. To test this I need conn.recbuf to be different each time it is called. (I know I could just change conn.recbuf to be a string that contains both home and USER but that won’t work for more complicated functions)

Here is what I have come up with so far in my test:

@mock.patch.object(demo_sequence.lib, 'conn')
def test_send_something(mock_conn):
    mock_conn.SSH1.recbuf = 'home'
    assert demo_sequence.lib.PASS == demo_sequence.send_something()

Obviously this fails because conn.recbuf is only ‘home’ and does not contain USER.

I need something like conn.recbuf.side_effect = [‘home’, USER] but will work when just referencing recbuf and not calling it.

Get this bounty!!!

Leave a Reply

This site uses Akismet to reduce spam. Learn how your comment data is processed.