How to unit test a function whose output can vary?
You should use mock. Either a standard mock or a requests_mock
:
class Test(unittest.TestCase):
def test_with_simple_mock(self):
fake_result = collections.namedtuple("Response", ("status_code", "json"))(
200, lambda: {"something": "somevalue"}
)
with mock.patch("requests.get", return_value=fake_result):
self.assertEquals(
requests.get("https://some-service/get_data/").json()["something"],
"somevalue",
)
def test_with_requests_mock(self):
with requests_mock.Mocker() as m:
m.get("https://some-service/get_data/", text='{"something": "somevalue"}')
self.assertEquals(
requests.get("https://some-service/get_data/").json()["something"],
"somevalue",
)