0
0
PyTesttesting~10 mins

Database fixture patterns in PyTest - Interactive Code Practice

Choose your learning style9 modes available
Practice - 5 Tasks
Answer the questions below
1fill in blank
easy

Complete the code to define a pytest fixture that sets up a database connection.

PyTest
import pytest

@pytest.fixture
 def db_connection():
    conn = create_connection()  # Setup connection
    yield conn
    conn.[1]()  # Teardown connection
Drag options to blanks, or click blank then click option'
Aclose
Bopen
Ccommit
Dconnect
Attempts:
3 left
💡 Hint
Common Mistakes
Using 'commit' instead of 'close' for teardown.
Forgetting to close the connection causing resource leaks.
2fill in blank
medium

Complete the code to use the database fixture in a test function.

PyTest
def test_user_count([1]):
    count = db_connection.execute('SELECT COUNT(*) FROM users').fetchone()[0]
    assert count >= 0
Drag options to blanks, or click blank then click option'
Adb_connection
Bconn
Cconnection
Ddb_conn
Attempts:
3 left
💡 Hint
Common Mistakes
Using a different parameter name than the fixture name.
Not including the fixture as a parameter.
3fill in blank
hard

Fix the error in the fixture to ensure the database transaction rolls back after each test.

PyTest
import pytest

@pytest.fixture
 def db_session():
    session = create_session()
    yield session
    session.[1]()
Drag options to blanks, or click blank then click option'
Aclose
Bcommit
Crollback
Dflush
Attempts:
3 left
💡 Hint
Common Mistakes
Using commit instead of rollback causing test data to persist.
Not rolling back causing side effects between tests.
4fill in blank
hard

Fill both blanks to create a fixture that sets up a test database and tears it down after tests.

PyTest
import pytest

@pytest.fixture(scope='module')
 def test_db():
    db = setup_test_db()
    yield db
    db.[1]()
    [2]_test_db()
Drag options to blanks, or click blank then click option'
Adrop_all
Bcreate_all
Cdestroy
Dcleanup
Attempts:
3 left
💡 Hint
Common Mistakes
Using create_all instead of drop_all for teardown.
Not cleaning up test database resources.
5fill in blank
hard

Fill all three blanks to create a fixture that starts a transaction, yields a session, and rolls back after the test.

PyTest
import pytest

@pytest.fixture
 def transactional_session():
    connection = engine.connect()
    transaction = connection.[1]()
    session = Session(bind=connection)
    yield session
    session.[2]()
    transaction.[3]()
    connection.close()
Drag options to blanks, or click blank then click option'
Abegin
Brollback
Ccommit
Dflush
Attempts:
3 left
💡 Hint
Common Mistakes
Committing before rollback causing test data to persist.
Not closing the connection after tests.