Pytest: Mocking slow external API call
We have a module called mymath (again) that does some computation for us.
I think it uses the Pythagoras theorem to calculate the distance from the “origin”.
import externalapi
def compute(x, y):
xx = externalapi.remote_compute(x)
yy = externalapi.remote_compute(y)
result = (xx+yy) ** 0.5
return result
It uses an external API implemented in the externalapi.py file to compue the square of each number.
Unfortunatelly this external API is slow.
import time
def remote_compute(x):
time.sleep(5) # to imitate long running process
return x*x
We can try to run the following code. It will take 10 seconds to compute this. When testing the mymath library we don’t want to wait 10 seconds for every test-case.
time python use_mymath.py
import mymath
print(mymath.compute(3, 4))