Simulate network latency and packet loss in pytest
Nothing mocked: the beannetworktester package on PyPI gives pytest a bad_network fixture that slows the real network for the length of a test. Latency, packet loss, a speed limit or a whole outage, for one server or one process, while your app, your browser and your server really talk to each other. The package carries Bean Network Tester's own program and runs it on Windows and Linux. It is published with every stable release from 1.1.0 on.
Install it
pip install beannetworktester
It needs Windows x64 or Linux x64 (glibc 2.39 or newer, such as Ubuntu 24.04) and Python 3.10 or newer.
Changing the network needs administrator rights on Windows: open the terminal with Run as administrator. On Linux it needs root, or a user who may run sudo without a password, and then only the program runs under sudo. GitHub's hosted Windows runners run elevated and its Ubuntu runners allow sudo, so a workflow needs no extra step.
A test on a slow network
Save this as test_slow.py and run pytest:
import subprocess
import sys
import time
import urllib.request
import pytest
@pytest.fixture
def web_server():
server = subprocess.Popen([sys.executable, "-m", "http.server", "8000"])
time.sleep(1)
yield "http://localhost:8000"
server.terminate()
def test_a_page_takes_longer_on_a_slow_network(bad_network, web_server):
bad_network(server=web_server, latency=500)
started = time.monotonic()
urllib.request.urlopen(web_server).read()
assert time.monotonic() - started >= 0.5
The test passes because the answer really arrives later: every packet to and from that server waits 500 ms. When the test ends, the network is back to normal. Measured on Windows with latency=200: a request to the server in the aim went from 4 ms to 404 ms, because the request and the answer both wait, and a page in Chromium from 61 ms to 412 ms. Another local server, outside the aim, answered in 11 ms meanwhile.
No rights at hand? bad_network(simulate=True, latency=500) runs the program on made-up traffic and changes nothing on the network. It checks that the package is set up, and slows nothing.
The bad_network fixture
pytest finds the fixture on its own once the package is installed. bad_network starts a session when you call it and returns once the network is slow. The session stops when the test ends, whether it passed, failed or crashed, and the program's summary goes into the test's user_properties, and from there into a JUnit XML report. To change the conditions halfway, stop the first session before you start the next:
def test_the_app_recovers_when_the_api_comes_back(bad_network):
outage = bad_network(server="http://localhost:8000", loss=100)
assert app_shows_offline_banner()
outage.stop()
assert app_hides_offline_banner()
Outside pytest, from beannetworktester import bad_network starts the same session, and with bad_network(...) as session: stops it at the end of the block.
Playwright for Python
Playwright for Python runs on pytest, so the fixture is the same. Chromium, Firefox and WebKit are slowed the same way, WebSockets included, because the network itself is slow, not the browser's idea of it:
from playwright.sync_api import expect
def test_the_spinner_shows_on_a_slow_network(bad_network, page):
bad_network(server="http://localhost:3000", latency=800)
page.goto("http://localhost:3000")
expect(page.get_by_role("progressbar")).to_be_visible()
What a session aims at
Every session aims at something, and only that traffic changes. A session without an aim would slow every connection of the machine, the test runner's own included, so it does not start.
server="http://localhost:3000"slows every connection to that address and port, from your app, your browser or any other program."db.local:5432",("10.0.0.5", 443)and a list of servers work too. This is the first choice, and it is exact on Windows and Linux.process="self"slows the test process and every program it started, such as Playwright's browser. A process your test started itself is given as itssubprocess.Popen.dst_port,dst_ipandtargetare the program's own aims, written in its syntax, for an API on a known port or address. They reach everything that matches:dst_port=443is every HTTPS connection of the machine, your editor's included, andtarget="python"every program with "python" in its name.
Aims given together narrow each other: server= with process="self" slows only this test's connections to that server. On Linux, process= and target reach a new connection up to about 0.2 seconds after it opens, so aim at the server when the first request counts.
What a session can do
Every setting is one of the program's command-line options, written with _ instead of -. latency=300 adds 300 ms to every packet, jitter=100 varies that delay, loss=5 drops 5 % of the packets, down and up limit the speed in KB/s, and loss=100 cuts the server off. preset="presets.3g" is a whole link profile, and seed=42 makes the same random choices on every run. A scenario changes the conditions as the seconds pass: scenario="scenarios/cafe-wifi.json". A scenario step may change how the network behaves, but not what the session aims at.
pytest-xdist and limits
- One at a time. Two sessions over the same traffic would add up, so pytest-xdist workers take turns, each waiting up to
waitseconds (600 unless you give another). A second session in the same test is refused at once. - It ends with the test. If the test process dies, the program sees it and stops at once.
duration(300 seconds unless you give another) is the most a session may run in any case. - It says when it did nothing. A session that slowed nothing, because nothing reached its aim, ends with a
BadNetworkWarning. The usual cause is an app that talks to another address than the aim, such as a container. - macOS. The program runs on Windows and Linux. On a Mac, run the tests in a Linux x86_64 container or virtual machine, or on a CI runner.
The package's README on GitHub lists every option and what each message means.