Created
March 14, 2022 15:05
-
-
Save creisor/e67c27cd5ffb45dfa0001c30f9794282 to your computer and use it in GitHub Desktop.
How to use MagicMock and some fixtures for python testing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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