Framework Mode - Conftest.py purpose
Folder Structure of a Pytest Framework
project-root/ ├── tests/ │ ├── test_login.py │ ├── test_checkout.py │ └── conftest.py ├── src/ │ └── app_code.py ├── requirements.txt └── pytest.ini
project-root/ ├── tests/ │ ├── test_login.py │ ├── test_checkout.py │ └── conftest.py ├── src/ │ └── app_code.py ├── requirements.txt └── pytest.ini
tests/ folder, e.g., test_login.py.src/ or similar.pytest.ini to configure pytest behavior.conftest.py is used to define fixtures that can be shared across multiple test files without importing them explicitly. It helps manage:
Example snippet inside conftest.py:
import pytest
@pytest.fixture(scope="session")
def browser():
print("Setup browser")
yield "ChromeDriver"
print("Teardown browser")
Pytest integrates easily with reporting tools and CI/CD pipelines:
pytest --junitxml=report.xml to generate XML reports readable by CI tools.pytest-html create human-friendly HTML reports.conftest.py can include hooks to customize reporting or logging.conftest.py to avoid repetitive code in tests.function, module, session) to optimize setup time.conftest.py manually; pytest discovers it automatically.conftest.py files in subfolders for modular fixture management.Where in this folder structure would you add a new fixture to initialize a database connection for all tests?
conftest.py in pytest?conftest.pyconftest.py is used to hold fixtures and setup code that multiple test files can use.conftest.py.conftest.py?@pytest.fixture decorator followed by a function.@pytest.fixture and defines a function returning a value. Others either lack the decorator or are incorrect syntax.conftest.py fixture:
import pytest
@pytest.fixture
def number():
return 5
And this test file:
def test_double(number):
assert number * 2 == 10
What will be the test result when running pytest?number returns 5 and is automatically injected into the test function.number * 2 == 10, which is 5 * 2 == 10, true, so the test passes.conftest.py fixture:
import pytest
@pytest.fixture
def data():
return [1, 2, 3]
But your test fails with an error: fixture 'data' not found. What is the likely cause?conftest.py files in the test directory or its parents. If conftest.py is elsewhere, fixtures won't be found.conftest.py file is not in the same or parent directory of the test file -> Option Dconftest.py. Which approach best follows pytest best practices?yield allows setup before tests and cleanup after, ideal for resources like DB connections.conftest.py holding the connection without a fixture lacks cleanup and is not recommended. Use a class with static methods in conftest.py to manage the connection is more complex and less idiomatic.conftest.py that creates and yields the connection, then closes it after tests -> Option APass the test and this pattern moves unknown