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.
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
Asked: 2021-11-02 11:00:00 +0000
Seen: 10 times
Last updated: Apr 29 '22
What is the process of deleting a product from both the cart and session in WooCommerce?
How can it be explained that rprofile is executed multiple times?
Why are cookies not staying across different windows of the browser?
At what time does a cookie that has an expiration time set as "At end of session" expire?
After restarting the session, my unzipped files are deleted by Google Colab.