Search code examples
pythonmockingpython-mock

Mocking class vs methods


I want to mock a python object -psycopg2 - to test my classes.

When I print the object - dir(conn), I see the connect, extras, etc, all being listed.

conn = mock.MagicMock(psycopg2.connect)

Result:

['BINARY', 'Binary', 'DATETIME', 'DataError', 'DatabaseError', 'Date',
'DateFromTicks', 'Error', 'IntegrityError', 'InterfaceError',
'InternalError', 'NUMBER', 'NotSupportedError', 'OperationalError',
'ProgrammingError', 'ROWID', 'STRING', 'Time', 'TimeFromTicks',
'Timestamp', 'TimestampFromTicks', 'Warning', '__builtins__',
'__doc__', '__file__', '__libpq_version__', '__name__', '__package__',
'__path__', '__version__', '__warningregistry__', '_connect', '_ext',
'_ipaddress', '_json', '_psycopg', '_range', 'apilevel',
'assert_any_call', 'assert_called', 'assert_called_once',
'assert_called_once_with', 'assert_called_with', 'assert_has_calls',
'assert_not_called', 'attach_mock', 'call_args', 'call_args_list',
'call_count', 'called', 'configure_mock', 'connect', 'extensions',
'extras', 'method_calls', 'mock_add_spec', 'mock_calls', 'paramstyle',
'reset_mock', 'return_value', 'side_effect', 'threadsafety', 'tz',
'warn']

Now, when I want to set the side_effect of the execute method return value.

conn.cursor().execute().side_effect = psycopg2.DatabaseError

I get this error:

AttributeError: Mock object has no attribute 'cursor'

New code:-

pg = mock.MagicMock(psycopg2)
print dir(pg())
print dir(pg.connect)
pg.connect()

Output

AttributeError: Mock object has no attribute 'cursor'

Solution

  • You need to configure the return value of conn, not conn itself, because you are mocking the function connect.

    conn().cursor().execute().side_effect = psycopg2.DatabaseError