Skip to content
Tutorials Center
My learning

Topics

Lesson 24 of 38 ยท Mocking and Monkeypatching

Mocking Time, Files and the Network

Make tests deterministic by faking the clock with monkeypatch and freezegun, using tmp_path for files, and replacing HTTP calls with fakes or the responses library.

Three things make tests flaky more than any others: time (the clock keeps moving), files (the disk keeps state) and the network (slow, unreliable, and not available on the build server). A good test suite removes all three from the equation. Each has a standard technique, and you will meet them in nearly every real project.

The guiding idea is the same as in the earlier lessons: find the smallest seam where your code touches the outside world, and substitute something you control.

flowchart LR
    A["Your code"] --> T["time.time(), datetime.now()"]
    A --> F["open(), Path.write_text()"]
    A --> N["requests.get(), urlopen()"]
    T -. "freeze or monkeypatch" .-> T2["fixed clock"]
    F -. "tmp_path" .-> F2["throwaway folder"]
    N -. "fake / responses" .-> N2["canned reply"]

Time, files and network each get a controlled stand-in.

Time: a clock you control

Code that asks "what time is it?" produces different answers every run. There are three levels of solution, from simplest to most automatic.

1. Inject the time. Pass now as an argument with a default. The test passes a fixed value and needs no patching.

2. Patch a tiny wrapper. Wrap the clock in one function, as in the monkeypatch lesson, and replace it.

3. Freeze time globally with freezegun. The freezegun package patches datetime, time and friends so every call returns your chosen moment, and tick() moves it forward.

Python Three ways to control the clock

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.

When you own the code, injecting now is the cleanest option: no library, no patching, and the function documents its own dependency. Reach for freezegun when the clock is buried deep in code you cannot easily change.

Do not "fix" slow code by sleeping in tests. If your code waits (time.sleep(30) for a retry), patch sleep so the test finishes instantly and assert on the argument it received:

Python
def test_retry_backs_off(mocker):
    sleeper = mocker.patch("client.time.sleep")
    ...
    assert sleeper.call_args_list == [call(1), call(2), call(4)]

Files: use tmp_path, not mocks

For files, the best advice is do not mock open. Pytest gives every test its own empty directory through the tmp_path fixture (a pathlib.Path), and the real filesystem is fast and honest. Mocking open tests your mock, and it breaks when you switch from open to Path.read_text.

Python Testing file code with tmp_path

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.

Use tmp_path_factory for a directory shared by several tests, and monkeypatch.chdir(tmp_path) for code that works with relative paths. Mock open only for failures that are hard to create for real, such as a disk-full error (side_effect=OSError(28, "No space left")).

The network: fakes and canned responses

Tests must never call a real service: it is slow, it fails at random, it may cost money, and CI may have no internet. There are two good approaches.

A fake client you inject. Write a small class with the same methods as the real client and give it canned data. It is plain Python, easy to read and works without any library.

A library that intercepts HTTP. For code using requests, the responses package registers URLs and their replies and blocks everything else. For httpx there is respx, and for urllib you can patch urlopen.

Python Intercepting requests with the responses library

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.

In a browser, a real requests.get to the internet would not behave like on your machine anyway, which is one more reason these tests intercept the call. The unregistered-URL test is a safety net: any request your test forgot to declare fails loudly instead of reaching out.

If you cannot or prefer not to install an interceptor, patch the one function you use:

Python
def test_with_a_manual_fake(mocker):
    fake = mocker.Mock(status_code=200)
    fake.json.return_value = {"stars": 7}
    mocker.patch("github.requests.get", return_value=fake)
    assert star_count("a/b") == 7

Test the failures too

Real networks time out and real servers return 500. With canned replies it costs nothing to test those paths: set status=503, or use side_effect=requests.Timeout. Error handling is where untested code usually breaks first.

Keep one thin layer of integration tests that does use real services, mark them (@pytest.mark.integration) and run them separately, as the CI lesson shows. Unit tests stay fake; a few integration tests prove the fakes match reality.

Check your understanding

Quick check ยท 4 questions

of 4 answered You scored / 4 ยท perfect!

  1. 1. Which is usually the cleanest way to make time-dependent code testable when you own it?

    Injecting now (with a default) makes the dependency explicit and needs no patching or extra library.
  2. 2. Why is it recommended to use tmp_path instead of mocking open()?

    A mocked open() tests the mock. tmp_path gives each test a real, empty directory that pytest cleans up for you.
  3. 3. What does the responses library do when your code requests a URL you did not register?

    While active, responses blocks unregistered URLs, which stops tests from silently hitting the real network.
  4. 4. How should you handle time.sleep(30) inside code under test?

    Patching sleep keeps tests instant while still checking the backoff behaviour.

Summary

  • Control time by injecting it, patching a small wrapper, or freezing it with freezegun.
  • Test file code with real files in tmp_path; mock open only for hard-to-create errors.
  • Never call real networks in unit tests: inject a fake client, use responses/respx, or patch the single call.
  • Test the failure paths (timeouts, 5xx errors) while you have canned replies.
  • Keep a small, separately marked set of integration tests against the real thing.

Next: Coverage with pytest-cov