Middle+
What are fixtures in pytest? What are they used for?
sobes.tech AI
Answer from AI
In pytest, fixtures are special functions that prepare and provide the necessary data or environment for tests. They are used to set up preconditions, such as creating test data, connecting to a database, configuring the environment, and cleaning up after the test.
Fixtures help avoid code duplication and make tests more readable and maintainable. They can be reused across different tests and can also have scope settings (e.g., for a function, class, or module).
Example of a fixture:
import pytest
@pytest.fixture
def db_connection():
conn = create_connection()
yield conn
conn.close()
def test_query(db_connection):
result = db_connection.execute('SELECT 1')
assert result == 1
Here, the db_connection fixture creates a connection, passes it to the test, and closes the connection after the test.