Meaning
A pytest fixture that automatically mocks an external HTTP GET request to return a predefined JSON response, ensuring tests run without making real network calls.
Primary Function
Provides a mocked external API response for tests, isolating them from external services and ensuring deterministic behavior.
Communicative Purpose
Indicates that the test suite should simulate a successful GET request to https://api.example.com/data returning JSON {'status': 'ok'}, allowing tests to focus on application logic rather than network dependencies.
Pattern
@pytest.fixture(autouse=True) def <fixture_name>(requests_mock): requests_mock.get('<url>', json=<payload>) yield
Core Structure
@pytest.fixture(autouse=True) def <name>(requests_mock): requests_mock.get(<url>, json=<json_payload>) yield
Função primária
Provides a mocked external API response for tests, isolating them from external services and ensuring deterministic behavior.
Propósito comunicativo
Indicates that the test suite should simulate a successful GET request to https://api.example.com/data returning JSON {'status': 'ok'}, allowing tests to focus on application logic rather than network dependencies.
Situações de gatilho
Used when writing tests that depend on external HTTP APIs; when deterministic, fast, offline tests are required; when avoiding flaky tests caused by network variability or service downtime.
Contextos
Applied in pytest test modules that use the requests-mock plugin to mock HTTP calls; typical in unit or integration tests where the code under test makes requests.get to external services.
Padrão
@pytest.fixture(autouse=True) def <fixture_name>(requests_mock): requests_mock.get('<url>', json=<payload>) yield
Estrutura central
@pytest.fixture(autouse=True) def <name>(requests_mock): requests_mock.get(<url>, json=<json_payload>) yield
Slots de substituição
fixture_name: valid Python identifier for the fixture, url: str representing the HTTP endpoint to mock, json_payload: dict or JSON-serializable object to return, requests_mock: the requests-mock fixture providing the mock adapter
Colocados típicos
- requests-mock fixture
- pytest
- requests library
- JSON payloads
- autouse fixtures
- test functions that perform HTTP GET calls
Substituições comuns
- Using requests_mock.post for POST endpoints
- varying the JSON payload or using side_effect for dynamic responses
- using different URLs or query parameters
- switching to the responses library or VCR.py for recorded real interactions.
Erros comuns
1. Forgetting to yield: causes the fixture to not release the mock, leading to leaked state across tests. 2. Using requests.get instead of requests_mock.get: results in real network calls, defeating mocking. 3. Omitting autouse=True: requires explicitly requesting the fixture in each test, causing missing mock errors. 4. Specifying an incorrect URL: mock not triggered, leading to real requests or unhandled exceptions. 5. Returning non-JSON data when json= is used: causes JSON decoding errors in code expecting JSON.
Similar / contraste
Using requests_mock without autouse (explicit fixture request) gives finer control per test; using unittest.mock.patch to replace requests.get offers less realistic HTTP simulation; using the responses library provides similar mocking with a different API; using VCR.py records and replays real HTTP interactions for higher fidelity.
Interferências
Coming from unittest.mock: may try to patch requests.get directly, which does not work with requests-mock; use the requests_mock fixture instead. Coming from unittest: may forget to start/stop mocks; the autouse fixture ensures automatic teardown.
Família do chunk
- pytest fixtures
- requests-mock mocking
- test isolation patterns
- HTTP mocking
Nuance
1. Do not use when you need to test actual network behavior, error handling, or timeout scenarios that require real HTTP interactions. 2. Performance impact is minimal because mocking avoids network latency, making tests fast. 3. Ensure the mocked URL exactly matches the request made by the code; query parameters, headers, or different HTTP methods will not match unless explicitly configured.
Efeito pragmático
Guarantees deterministic, fast, offline tests, eliminating flakiness due to external services and enabling reliable CI pipelines.
Dica de memória
Think of this fixture as a stand‑in actor who always delivers the same line, letting the play proceed without waiting for the real performer.
Nota
The autouse=True flag applies this fixture to all tests in the module; ensure no test inadvertently relies on real external calls, as they will be silently mocked.
Upgrade path
Consider using the responses library for more complex matching or VCR.py to record and replay real HTTP interactions when higher fidelity is needed.
Log in to save chunks.