Pytest Tutorial - 10 | Advanced - Fixture Scopes and Performance Optimization
In this tutorial, we focus on optimizing test performance by choosing the right fixture scope and managing complex test setups with proper teardown using yield . 1. Optimizing Test Performance: Choosing the Right Fixture Scope Fixtures can have different scopes, such as function , class , module , or session , depending on how long you want the fixture to persist. Simple Example: Module-Scoped Database Connection import pytest @pytest.fixture(scope="module") def db_connection(): print("Connecting to the database...") yield {"db": "connected"} print("Closing database connection") def test_query_1(db_connection): assert db_connection["db"] == "connected" def test_query_2(db_connection): assert db_connection["db"] == "connected" Explanation: The database connection is created once for the entire module and shared across multiple tests, reducing setup overhead. C...