Sitemap

How to make your tests fail when they try to access the network (Python)

2 min readJan 9, 2022

--

The other night I re-watched the video of the talk I gave at EuroPython 2013, when Andrea and I presented Mocket to the Python community.

Of all the questions we were asked at the end of that talk, there was only a single feature that I never ended up implementing, until today. That specific feature request, sometimes received as a complaint, was the most recurrent one when showing Mocket to friends and former colleagues.

Mocking external calls is complicated, and things can go wrong. We all know that. What is very annoying is when things go wrong in the future, unexpectedly.

Assume you write some tests today, in which you believe you mocked a call your software makes at some point during the flow with Mocket or httpretty, but you failed in mocking it. If you are lucky, the real service cannot be reached by the servers where you run your CI and the tests will fail as soon as you run them.

But what if the service you want to mock exists and it CAN be reached by your CI?

  • You may end up consuming some limited resources or even spending some extra money.
  • The tests may fail in the future when the response from the real service changes.
  • The tests may even pass when, after a change, they should have not.

That’s why I decided to introduce the STRICT MODE for Mocket.

with Mocketizer(strict_mode=True):
with pytest.raises(StrictMocketException):
requests.get("https://duckduckgo.com/")

# OR

@mocketize(strict_mode=True)
def test_get():
with pytest.raises(StrictMocketException):
requests.get("https://duckduckgo.com/")

You just have to pip install -U mocket and decorate your test case function with @mocketize(strict_mode=True) to see your Python code raising a StrictMocketException as soon as Mocket — which is in control of the socketmodule — tries to open and write to a real socket.

--

--

Giorgio Salluzzo
Giorgio Salluzzo

Written by Giorgio Salluzzo

Python developer and FLOSS user, RPG player, Android bricker, beer drinker, food producer and consumer. Author of mocket http://bit.ly/2iNWmvP — anti-ʇsᴉɔsɐɟ

No responses yet