Skip to Content

How do you mock external systems without breaking production code?

Category: Python Fundamentals

Answer

pytest-mock (or unittest.mock) wraps the dependency in a fixture; calls happen on the mock. In production the same code calls the real dependency. The test should not need prod credentials, network, or time. Mock at the BOUNDARY (HTTP, DB, file), not deep inside business logic.

Concrete examples from the fca project context

Example 1

conftest.py: pytest fixture returns a Mock(spec=requests.Session).

Example 2

service.process(session=mocked_session, …) - the function takes its dependency as an argument.

Example 3

Asserting: mocked_session.post.assert_called_once_with(expected_url, json=payload).

Data flow / flow chart

test fixture -> Mock(spec=Session)
  service(session=mocked)
  assert mocked_session.post.assert_called_once_with(...)

Takeaway

Inject dependencies, then mock them at the boundary. Easier to test, easier to reuse.