|
| 1 | +""" |
| 2 | +Simple example test demonstrating pysql-test usage. |
| 3 | +
|
| 4 | +This is a minimal example showing how to use the testing framework |
| 5 | +for PostgreSQL integration tests with automatic database isolation. |
| 6 | +""" |
| 7 | + |
| 8 | +import pytest |
| 9 | + |
| 10 | +from pysql_test import get_connections, seed |
| 11 | + |
| 12 | + |
| 13 | +@pytest.fixture |
| 14 | +def db(): |
| 15 | + """ |
| 16 | + Create an isolated test database with sample schema. |
| 17 | +
|
| 18 | + Each test gets a fresh database that is automatically |
| 19 | + cleaned up after the test completes. |
| 20 | + """ |
| 21 | + conn = get_connections( |
| 22 | + seed_adapters=[ |
| 23 | + seed.fn(lambda ctx: ctx["pg"].query(""" |
| 24 | + CREATE TABLE users ( |
| 25 | + id SERIAL PRIMARY KEY, |
| 26 | + name TEXT NOT NULL, |
| 27 | + email TEXT UNIQUE |
| 28 | + ) |
| 29 | + """)) |
| 30 | + ] |
| 31 | + ) |
| 32 | + db = conn.db |
| 33 | + db.before_each() |
| 34 | + yield db |
| 35 | + db.after_each() |
| 36 | + conn.teardown() |
| 37 | + |
| 38 | + |
| 39 | +def test_insert_and_query_user(db): |
| 40 | + """Test inserting and querying a user.""" |
| 41 | + # Insert a user |
| 42 | + db.execute( |
| 43 | + "INSERT INTO users (name, email) VALUES (%s, %s)", |
| 44 | + ("Alice", "alice@example.com"), |
| 45 | + ) |
| 46 | + |
| 47 | + # Query the user |
| 48 | + user = db.one("SELECT * FROM users WHERE name = %s", ("Alice",)) |
| 49 | + |
| 50 | + assert user["name"] == "Alice" |
| 51 | + assert user["email"] == "alice@example.com" |
| 52 | + |
| 53 | + |
| 54 | +def test_transaction_isolation(db): |
| 55 | + """Test that changes are rolled back between tests.""" |
| 56 | + # This insert will be rolled back after the test |
| 57 | + db.execute( |
| 58 | + "INSERT INTO users (name, email) VALUES (%s, %s)", |
| 59 | + ("Bob", "bob@example.com"), |
| 60 | + ) |
| 61 | + |
| 62 | + # Verify the user exists within this test |
| 63 | + count = db.one("SELECT COUNT(*) as count FROM users") |
| 64 | + assert count["count"] == 1 |
| 65 | + |
| 66 | + |
| 67 | +def test_empty_table_after_rollback(db): |
| 68 | + """Verify previous test's data was rolled back.""" |
| 69 | + # Table should be empty because previous test's insert was rolled back |
| 70 | + count = db.one("SELECT COUNT(*) as count FROM users") |
| 71 | + assert count["count"] == 0 |
0 commit comments