pytest is a Python testing tool favored for concise tests: plain assert statements reduce ceremony, while test discovery and fixtures support organized test suites. It is used here as the preferred target when AI assistants initially generate unittest code instead. section 8.4.1 section 8.4
A practical workflow starts by installing pytest, naming test files with a test_ prefix, and running the selected test file. The naming convention lets pytest recognize tests while keeping their intent visible to developers. section 8.4.2
Testing a question model
A pytest test creates a Question, asserts its text and answer, then checks invalid empty values with pytest.raises(ValueError). A second test verifies correct, incorrect, and case-insensitive answers with plain assertions. section 8.4.2
Fixtures make isolated database tests reusable. A db_connection fixture creates an in-memory SQLite database, yields it to each test, and closes it afterward; tests then query the database or exercise application methods through that connection. section 8.4.2
Testing an empty result
After a fixture supplies the in-memory database, a test deletes all questions, commits, calls get_all_questions(), and asserts that the result is an empty list. This checks behavior without relying on a production database. section 8.4.3
AI-generated pytest tests need deliberate review. Generators commonly default to unittest, may propose unsuitable mocks or test placement, and can require prompt refinement or small fixes before passing. Use generated tests as a fast starting point, then validate their assumptions and results. section 8.4.2 section 8.4.3
```python
import pytest
import sqlite3
@pytest.fixture
def db_connection():
# Setup: create the in-memory database connection
memory_conn = create_in_memory_db_from_existing('../data/questions.db')
yield memory_conn # This is where the testing happens
# Teardown: close the database connection
memory_conn.close()
def test_connection(db_connection):
db_connection.execute("SELECT * FROM questions")
def test_get_question(db_connection):
# Example test using the db_connection fixture
result = db_connection.execute("SELECT * FROM questions WHERE id = 1")
question = result.fetchone()
assert question is not None
```
The fixture listing shows setup, yield-based test access, teardown, and two tests sharing one in-memory database connection. section 8.4.2










