If you want to incorporate database testing seamlessly within your pytest test suite, use pytest-postgresql.
pytest-postgres provides fixtures that manage the setup and cleanup of test databases, ensuring repeatable tests. Additionally, each test runs in isolation, preventing any impact on the production database from testing changes.
To see how pytest-postgres works, let’s create a test function that sets up a test table in a PostgreSQL database, inserts some test data, and then verifies that the query results match the expected data.
def test_query_results(postgresql):
"""Check that the query results are as expected."""
with postgresql.cursor() as cur:
cur.execute("CREATE TABLE test_table (id SERIAL PRIMARY KEY, name VARCHAR);")
cur.execute("INSERT INTO test_table (name) VALUES ('John'), ('Jane'), ('Alice');")
# Assert the results
cur.execute("SELECT * FROM test_table;")
assert cur.fetchall() == [(1, 'John'), (2, 'Jane'), (3, 'Alice')]
Run the test:
$ pytest test_postgres.py
test_postgres.py . [100%]
============================== 1 passed in 1.20s ===============================