Providing pytest fixture with Docker container and parametrized tests
# conftest.py
import pytest
from testcontainers.postgres import PostgresContainer
@pytest.fixture(scope="session")
def test_db():
with PostgresContainer("postgres:15.2") as postgres:
postgres.start()
yield postgres
# test_sample.py
import pytest
@pytest.mark.parametrize("input_value", range(1, 21))
def test_example(test_db, input_value):
# Example trivial test using input_value and test_db container
assert input_value is not None
```</think>
Below is an example layout with a session‐scoped fixture that starts a PostgreSQL test database inside Docker (using `testcontainers`) and a parametrized test that runs the same test logic over 20 inputs.
**conftest.py**:
```python
import pytest
from testcontainers.postgres import PostgresContainer
@pytest.fixture(scope="session")
def test_db():
"""
Spins up a PostgreSQL test database in Docker before the test session
and tears it down afterward.
"""
with PostgresContainer("postgres:15.2") as postgres:
# Starts the container and sets up env vars (host, port, user, etc.)
postgres.start()
# Provide the container object (or connection info) to tests
yield postgres
# Container automatically stops/tears down when exiting the context manager
test_sample.py:
import pytest
@pytest.mark.parametrize("value", range(1, 21)) # 20 different inputs
def test_insert_and_fetch(test_db, value):
# Example: retrieve connection info from the container
db_url = test_db.get_connection_url() # e.g. "postgresql://.../test"
# In a real test, you might connect via psycopg2 or sqlalchemy:
# engine = create_engine(db_url)
# with engine.begin() as conn:
# conn.execute(text("CREATE TABLE IF NOT EXISTS items (id int)"))
# conn.execute(text("INSERT INTO items (id) VALUES (:val)"), {"val": value})
# result = conn.execute(text("SELECT COUNT(*) FROM items")).scalar()
# assert result == expected_count
#
# For demo purposes, we simply assert the DB URL is available:
assert "postgresql://" in db_url
# And assert the param is not None (placeholder check)
assert value is not None
This setup:
- Uses a session-scoped fixture to start a Dockerized PostgreSQL database before any tests run and tear it down afterward.
- Parametrizes a single test over 20 different values with
pytest.mark.parametrize.
- Demonstrates how you’d access the connection URL from the container to run real DB checks.