Pytest – What to use and why?

Written by

pip install pytest
pytest .

Create a new test file.
Make sure to prefix the file containing your tests with test_

test_handle_messages

Mocking

When to use mocking?

  • You want to isolate the code under test.
    • You mock out dependencies (like APIs, databases, files) so your test only evaluates your logic.
  • You’re dealing with side effects.
    • requests.get, open(), or writing files
    • Time-based behavior (time.sleep, datetime.now)
    • OS/system calls (os.remove, shutil.rmtree)
    • External services (APIs, databases, message queues)
  • You need control over behavior.
    • Set specific return values
    • Raise specific exceptions
    • Track calls and arguments
  • You want to avoid slowness or flakiness.
    • Don’t call real APIs or write to disk in unit tests β€” mocking keeps tests fast and reliable.

When not to use mocking?

  • You’re testing logic that doesn’t depend on external systems.
    if it’s pure logic (e.g., a math function, a data transform), mocking isn’t needed.
  • The mock becomes more complicated than the real thing.
    Over-mocking can make tests harder to read and maintain. If the mock setup is 10 lines and the function is 2 lines, maybe reconsider.

Mocking to test your work before your colleague to complete his work for you to test the complete project

Using mocks to work in parallel with colleagues is a common and effective strategy in software development, especially in teams working on tightly coupled components (like frontend/backend or microservices). Here’s a breakdown of the pros and cons of this approach:


βœ… Pros of Using Mocks to Work in Parallel

1. Unblocks Development

  • You don’t need to wait for your colleague to finish their part.
  • Keeps productivity high and prevents idle time.

2. Faster Iteration

  • Teams can move forward independently.
  • Speeds up the overall development process.

3. Better Planning & Resource Use

  • Developers can parallelize efforts and stick to deadlines.
  • Improves team agility.

4. Early Frontend/Integration Testing

  • Frontend/UI can be built and tested with mock data.
  • API clients or service consumers can be developed and tested early.

5. Reduced Bottlenecks

  • If one team/member is delayed, others can still proceed.
  • Mitigates dependency-related slowdowns.

❌ Cons of Using Mocks to Work in Parallel

1. Mock-Real Mismatch

  • Mock data or behavior might not match the actual implementation.
  • Leads to integration bugs or rework.

2. False Sense of Completion

  • Work may appear done but still need rework after real integration.
  • Can create an illusion of progress.

3. Extra Work to Maintain Mocks

  • Time is needed to build and update mocks.
  • Maintenance overhead, especially if the API contracts change often.

4. Potential Technical Debt

  • Quick-and-dirty mocks might remain in the codebase longer than planned.
  • Risks of neglecting proper integration later.

5. May Miss Edge Cases

  • Mocks often focus on the “happy path.”
  • Real data or responses may expose unexpected issues.

🧠 Best Practices

  • Use contract-first development (e.g., OpenAPI, gRPC interfaces) to define clear expectations.
  • Ensure automated tests validate the mocks against real data later.
  • Communicate constantly with teammates to keep mocks in sync with real interfaces.
  • Treat mocks as temporary scaffolding, not final implementations.

Fixtures

Scope

ScopeLifespanExample Use Case
"function"(default) Runs once per test functionBasic data setup
"class"Runs once per test classClass-wide setup like mock servers
"module"Runs once per test moduleShared database connection for all tests in a file
"package"Runs once per test package(Rarely used, but available)
"session"Runs once for the entire test sessionExpensive setups like docker containers or test databases

Useful pytest options

pytest . -s # see prints
pytest . -k test_filter_data_with_fixture_o # execute a specific test
pytest . -v # get more info about the tests running