Barend Linders - From mocking to rocking your tests with testcontainers | PyData Amsterdam 2024

Learn how Testcontainers can revolutionize your Python testing by replacing mocks with real containerized services. A hands-on guide to better integration testing.

Key takeaways
  • Testcontainers is an open source library that allows spinning up Docker containers for integration testing, originally created for Java in 2015 but now supports 10+ languages

  • Key benefits:

    • Enables “integration test light” capabilities between unit tests and full integration tests
    • Containers are managed automatically (startup/shutdown)
    • Provides realistic test environments while keeping tests local
    • Supports many common services out of the box (Redis, PostgreSQL, etc)
    • Can help speed up development feedback loops vs full integration testing
  • Best practices:

    • Use primarily for black box testing scenarios
    • Be mindful of container startup overhead and state management
    • Consider session scoping to reuse containers across tests
    • Can use config files and scripts to seed test data
    • Good for testing service interactions without mocking
  • Limitations to consider:

    • Additional overhead from container management
    • May not 100% match production environment
    • Need Docker available for tests to run
    • Can be more complex to setup than simple mocks
    • May require CI/CD environment considerations
  • The library helps address common testing challenges:

    • Managing external dependencies
    • Providing realistic test environments
    • Reducing reliance on mocks
    • Enabling faster development cycles
    • Simplifying integration testing
  • Works well with pytest fixtures and can be integrated into existing test suites while still maintaining the benefits of containment and isolation