Ask Your Question

Revision history [back]

You can use the @pytest.fixture(scope="session") decorator with scope set to "session" to reuse the same fixture for all tests in a session. This will create the fixture only once per session and reuse it for all subsequent tests.

For example, suppose you have a fixture "db" that sets up a database connection. You could declare this fixture with a session scope like this:

import pytest
import psycopg2

@pytest.fixture(scope="session")
def db():
    conn = psycopg2.connect(database="mydb", user="myuser", password="mypassword", host="localhost", port=5432)
    yield conn
    conn.close()

Now, you can use this fixture in multiple test functions like this:

def test_insert(db):
    # Insert some data into the database
    cursor = db.cursor()
    cursor.execute("INSERT INTO mytable VALUES (1, 'foo')")
    db.commit()
    assert cursor.rowcount == 1

def test_select(db):
    # Retrieve data from the database
    cursor = db.cursor()
    cursor.execute("SELECT * FROM mytable")
    rows = cursor.fetchall()
    assert len(rows) == 1
    assert rows[0][0] == 1
    assert rows[0][1] == 'foo'

Both of these functions use the same "db" fixture, which will be created only once for the entire session.