Pytest: Mocking slow external API call - manually replace function
We can create a function (we call it mocked_remote_compute) that we’ll use to
replace the remote API call. However, ee don’t need to re-implement the whole complex algorithm of
computing the square of numbers provided by the remote service.
It is enough that we hard-code the responses we should get from the API for the values we are going to use in the tests.
Then we can manuall monkey-patch the method in the externalapi library.
import mymath
def mocked_remote_compute(x):
print(f"mocked received {x}")
if x == 3:
return 9
if x == 4:
return 16
raise Exception (f"The value {x} isn't supported by the mock")
mymath.externalapi.remote_compute = mocked_remote_compute
def test_compute():
assert mymath.compute(3, 4) == 5
#def test_other():
# res = mymath.compute(2, 7)
# assert res == 7.28010988928
time pytest test_mymath.py