def fetchSpotifyArtist(): opts = unmock.init(ignore=["headers", "story"]) # opts.save = True # For saving mocked response to local response = requests.get( "https://api.spotify.com/v1/artists") # will be mocked unmock.reset() return response
def test_unmock_signature(): # Because we used different signatures, the content might be identical but the mocks are unique and have their own # ID, making sharing them quite easy! opts = unmock.init(signature="Hello ", save=True) res = requests.get("https://www.example.com") opts.signature = "world!" res2 = requests.get("https://www.example.com") assert res.json() == res2.json()
def init(**kwargs): default_kwargs = {"refresh_token": get_token(), "logger": get_logger()} default_kwargs.update(kwargs) return unmock.init(**default_kwargs)
""" Basic example showing a single request with `unmock` Things to note: - Summarized with 2 calls - import and initialization - Mocks are stored locally if desired, but data is generated off-site and is semantically correct - Mocks can be chosen to be non-deterministic (imitating failure points, bad answers, etc) - Only required familiarity with call and points of interest, not necessarily the entire response - No need to specify URLs, intercepts all calls and returns a "bad news" response silently if an API is not yet mocked. - Trivial usage """ import requests import unmock unmock.init() def test_unmock_once(): res = requests.get( "https://www.behance.net/v2/projects?api_key=u_n_m_o_c_k_200") # This is not guaranteed if we use 'flaky' mode - our code should know how to handle those cases! assert res.status_code == 200 content = res.json() assert content.get('projects') # We can't determine the exact number (unless we know what our mock contains), but we care about the TYPE assert isinstance(content.get('projects')[0].get('id'), int) # This should be expected, but we didn't need to code it assert "json" in res.headers.get("Content-Type", "")
def test_unmock_whitelist(): unmock.init(whitelist="www.example.com") res = requests.get("https://www.example.com") # Unmatched, so it is redirected with pytest.raises(Exception): assert res.json() unmock.reset()
def test_unmock_status(): unmock.init() assert unmock.is_mocking() unmock.reset() assert not unmock.is_mocking()
def test_init_and_reset(): unmock.init() assert_number_of_patches( 5) # Four different mocks for HTTPRequest plus one for HTTPResponse unmock.reset() assert_number_of_patches(0)