Skip to content

Instantly share code, notes, and snippets.

@creisor
Created March 14, 2022 15:05
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save creisor/e67c27cd5ffb45dfa0001c30f9794282 to your computer and use it in GitHub Desktop.
Save creisor/e67c27cd5ffb45dfa0001c30f9794282 to your computer and use it in GitHub Desktop.
How to use MagicMock and some fixtures for python testing
from unittest.mock import MagicMock
from pathlib import Path
# this creates an ldap server entry, which has an info method
# and populates it with some static fixture data
with open(Path(__file__).parent / 'testdata/user_entry1.json') as f:
ldap_server_entry_json = f.read()
ldap_server_entry = MagicMock(**{'info.return_value': ldap_server_entry_json})
# this uses the entry, mocking the search method on the ldap_server object
ldap_server = MagicMock(**{'search.return_value': [self.ldap_server_entry]})
# you could also fake an exception
sad_ldap_server = MagicMock(**{'search.side_effect': ValueError('oops!')})
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment