What is the main purpose of the conftest.py file in a pytest testing project?
Think about how pytest shares setup code between tests.
The conftest.py file is used to define fixtures and hooks that pytest can share across multiple test files in the same directory or subdirectories. It helps avoid repeating setup code.
Given this conftest.py fixture, what will be the output when running two tests that use it?
import pytest
@pytest.fixture(scope="module")
def resource():
print("Setup resource")
yield "resource"
print("Teardown resource")Two tests use this fixture in the same module.
Remember what scope="module" means for fixture lifetime.
With scope="module", the fixture runs once before any tests in the module and once after all tests finish. So setup and teardown print once each.
Which assertion correctly tests that a fixture named db_connection from conftest.py returns a non-empty string?
Check type and length to confirm non-empty string.
Option C checks that the fixture returns a string and that it is not empty, which is the correct way to assert a non-empty string.
You have a fixture api_client defined in conftest.py in the root tests folder. When running tests in a subfolder, pytest reports fixture 'api_client' not found. What is the most likely cause?
Think about how pytest discovers conftest.py files.
Pytest discovers conftest.py files only in directories it recognizes as test roots. If the subfolder is outside or pytest is run from a different root, it won't find the fixture.
You want a fixture to be available only to tests inside the tests/api folder and its subfolders, but not elsewhere. How should you organize your conftest.py files?
Think about how pytest applies conftest.py files based on folder location.
Pytest applies fixtures defined in a conftest.py file to tests in that folder and its subfolders. Placing the fixture in tests/api/conftest.py limits its scope correctly.