Ask Your Question
3

How can I use the same fixture multiple times in py.test?

asked 2021-11-02 11:00:00 +0000

ladyg gravatar image

edit retag flag offensive close merge delete

1 Answer

Sort by ยป oldest newest most voted
1

answered 2022-04-29 18:00:00 +0000

huitzilopochtli gravatar image

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.

edit flag offensive delete link more

Your Answer

Please start posting anonymously - your entry will be published after you log in or create a new account. This space is reserved only for answers. If you would like to engage in a discussion, please instead post a comment under the question or an answer that you would like to discuss

Add Answer


Question Tools

Stats

Asked: 2021-11-02 11:00:00 +0000

Seen: 10 times

Last updated: Apr 29 '22