Framework Mode - Handling shared resources
Folder Structure
tests/ ├── test_login.py ├── test_shopping_cart.py ├── test_checkout.py conftest.py utils/ ├── db_helper.py ├── api_client.py pytest.ini requirements.txt
Jump into concepts and practice - no test required
tests/ ├── test_login.py ├── test_shopping_cart.py ├── test_checkout.py conftest.py utils/ ├── db_helper.py ├── api_client.py pytest.ini requirements.txt
conftest.py to setup and teardown shared resources like database connections, test data, or web drivers.tests/ folder use fixtures to access shared resources safely.utils/ provide reusable functions for resource management, e.g., database queries or API calls.pytest.ini and environment variables control test settings and resource parameters.pytest.ini to define default test options and markers..env files to store sensitive data like credentials or URLs.conftest.py that read configuration and initialize shared resources once per session or module.scope="session" to share the connection across all tests safely.--junitxml=report.xml for CI systems.pytest-html for readable HTML reports.Where in this framework structure would you add a new fixture to manage a shared API client used by multiple tests?
import pytest
@pytest.fixture(scope="module")
def resource():
print("Setup resource")
yield "data"
print("Teardown resource")
def test_one(resource):
assert resource == "data"
def test_two(resource):
assert resource == "data"@pytest.fixture(scope="module")
def db_connection():
conn = open_db()
yield conn
conn.close()
def test_query(db_connection):
assert db_connection.execute("SELECT 1") == 1
def test_insert(db_connection):
db_connection.execute("INSERT INTO table VALUES (1)")