Which of the following directory structures correctly represents a pytest test package that will be automatically discovered and run by pytest?
pytest discovers tests in files named test_*.py or *_test.py in any directory, even without __init__.py.
pytest discovers test files named test_*.py or *_test.py recursively in directories, even if they don't have __init__.py. Option D is correct because it has a test file in a directory named tests. Option D is not necessary for pytest discovery.
Given the following package structure and test code, what will be the output when running pytest from project_root?
project_root/
mypackage/
__init__.py
utils.py
tests/
__init__.py
test_utils.py
# test_utils.py content:
import mypackage.utils
def test_example():
assert mypackage.utils.func() == 42
# utils.py content:
def func():
return 42
pytest adds the project root to sys.path, so imports from sibling packages work.
pytest runs tests with the project root in the Python path, so import mypackage.utils works. The function returns 42, so the assertion passes.
You want to write a pytest test to check that the tests package contains exactly 3 test files named test_*.py. Which assertion correctly verifies this?
import os def test_number_of_test_files(): test_dir = os.path.join(os.path.dirname(__file__), '..', 'tests') test_files = [f for f in os.listdir(test_dir) if f.startswith('test_') and f.endswith('.py')] # Which assertion is correct here?
Use len() to get the number of items in a list.
len(test_files) returns the number of test files. Comparing it to 3 with == checks for exactly 3 files. Other options are invalid syntax or wrong logic.
You have this structure:
project_root/
app/
__init__.py
module.py
tests/
test_module.py
In test_module.py, you write import app.module but get ModuleNotFoundError when running pytest. What is the most likely cause?
pytest uses the current working directory to set the Python path.
Running pytest from inside the tests directory means the parent directory (project_root) is not in sys.path, so import app.module fails. Running pytest from project_root fixes this.
You have a test package located at project_root/integration_tests/ which contains test files. By default, pytest does not discover tests there. Which configuration change will make pytest discover tests in integration_tests?
pytest.ini can specify directories to search for tests.
Adding testpaths = integration_tests in pytest.ini tells pytest to look in that directory for tests. Renaming or adding __init__.py alone does not change discovery paths. The -k option filters tests by name but does not add directories.