Home »
MCQs
PyTest MCQs (Multiple-Choice Questions)
PyTest is a popular testing framework for Python that makes it easy to write and execute automated tests. It provides powerful features such as assertions, fixtures, parameterization, markers, test discovery, exception testing, and plugins.
PyTest MCQs
These PyTest MCQs cover important concepts such as test functions, assertions, fixtures, test discovery, parameterization, markers, exception handling, command-line options, mocking, and test configuration.
List of PyTest MCQs
The following PyTest multiple-choice questions are designed to test your knowledge of the pytest testing framework and its commonly used features and commands.
1. What is PyTest?
- A testing framework for Python
- A Python web framework
- A database system
- A version control system
Answer: A) A testing framework for Python
Explanation:
PyTest is a Python testing framework that provides tools for writing, organizing, and running automated tests.
2. Which command is commonly used to run tests with pytest?
- pytest
- python-test
- runpytest
- py-test-runner
Answer: A) pytest
Explanation:
The pytest command-line tool discovers and runs tests according to pytest's test discovery rules.
3. Which filename pattern is recognized by pytest by default for test modules?
- test_*.py or *_test.py
- pytest_*.py only
- testfile_*.py only
- *.pytest.py only
Answer: A) test_*.py or *_test.py
Explanation:
Pytest's default test discovery includes Python modules matching test_*.py and *_test.py.
4. Which naming convention is commonly used for pytest test functions?
- test_*
- pytest_*
- check_*
- verify_*
Answer: A) test_*
Explanation:
Pytest normally discovers test functions whose names begin with test_.
5. What is the purpose of an assert statement in pytest?
- To verify that a condition is true
- To define a fixture
- To skip a test
- To configure a plugin
Answer: A) To verify that a condition is true
Explanation:
Pytest uses Python's built-in assert statement to verify expected conditions and provides detailed assertion failure information.
6. What happens when an assertion fails in a pytest test?
- The test is reported as failed
- The entire Python interpreter always terminates
- The test is automatically skipped
- The test is automatically marked as xfail
Answer: A) The test is reported as failed
Explanation:
When an assertion raises an AssertionError, pytest reports the corresponding test as failed and provides assertion details.
7. Which command runs a specific pytest test file?
- pytest test_example.py
- pytest --file test_example.py
- pytest --run-file test_example.py
- pytest -file test_example.py
Answer: A) pytest test_example.py
Explanation:
A test file can be passed directly to the pytest command, such as pytest test_example.py.
8. Which pytest option is used to select tests based on their names or keywords?
- -k
- -n
- -x
- -q
Answer: A) -k
Explanation:
The -k option selects tests based on a keyword expression matching test names and related node information.
9. Which command runs tests matching a keyword expression?
- pytest -k "login"
- pytest -m "login"
- pytest -t "login"
- pytest --keyword-only "login"
Answer: A) pytest -k "login"
Explanation:
The -k option can be followed by an expression such as "login" to select matching tests.
10. Which pytest option runs tests with more detailed output?
- -v
- -s
- -q
- -x
Answer: A) -v
Explanation:
The -v or --verbose option increases the verbosity of pytest's output.
11. Which pytest option disables output capturing so that print output can be displayed?
- -s
- -v
- -p
- -d
Answer: A) -s
Explanation:
The -s option prevents pytest from capturing standard output and error output, allowing output such as print() statements to appear directly.
12. Which pytest option stops the test run after the first failure?
- -x
- -f
- -stop
- -1
Answer: A) -x
Explanation:
The -x option causes pytest to exit after the first test failure.
13. What is a pytest fixture?
- A reusable function that provides test setup or other test context
- A test result file
- A command-line argument
- A Python package manager
Answer: A) A reusable function that provides test setup or other test context
Explanation:
Fixtures provide a reliable context or resources for tests, such as test data, temporary files, database connections, or setup and cleanup logic.
14. Which decorator is used to define a pytest fixture?
- @pytest.fixture
- @pytest.test
- @pytest.setup
- @pytest.context
Answer: A) @pytest.fixture
Explanation:
The @pytest.fixture decorator marks a function as a fixture that can be requested by tests or other fixtures.
15. How does a test normally request a pytest fixture?
- By declaring the fixture name as a function argument
- By importing the fixture inside the test only
- By calling pytest.use()
- By adding the fixture name to the filename
Answer: A) By declaring the fixture name as a function argument
Explanation:
Pytest injects requested fixtures into tests by matching fixture names with the test function's arguments.
16. What is the default scope of a pytest fixture?
- function
- class
- module
- session
Answer: A) function
Explanation:
Unless another scope is specified, a pytest fixture has function scope and is normally created for each test function that requests it.
17. Which fixture scope shares a fixture instance across all tests in a module?
- module
- function
- test
- method
Answer: A) module
Explanation:
A fixture with scope="module" is shared among tests within the same module according to pytest's fixture lifecycle.
18. Which fixture scope can share a fixture across the entire test session?
- session
- global
- project
- all
Answer: A) session
Explanation:
A fixture with scope="session" can be created once for the test session and reused by tests that request it.
19. What is the purpose of conftest.py in pytest?
- To define fixtures, hooks, and local pytest configuration
- To store Python package dependencies only
- To define application database tables
- To replace test files
Answer: A) To define fixtures, hooks, and local pytest configuration
Explanation:
A conftest.py file can contain fixtures and hooks that are available to tests within its directory scope and below.
20. Which decorator is used to run a test with multiple sets of parameters?
- @pytest.mark.parametrize
- @pytest.mark.multiple
- @pytest.parameters
- @pytest.repeat
Answer: A) @pytest.mark.parametrize
Explanation:
The @pytest.mark.parametrize decorator creates multiple invocations of a test using different parameter values.
21. What is the primary benefit of pytest parameterization?
- It allows the same test logic to run with different input values
- It disables assertions
- It prevents test discovery
- It automatically fixes failed tests
Answer: A) It allows the same test logic to run with different input values
Explanation:
Parameterization lets one test function be executed with multiple argument sets, reducing duplicated test code.
22. Which marker is used to skip a test unconditionally?
- pytest.mark.skip
- pytest.mark.ignore
- pytest.mark.disabled
- pytest.mark.skip_all
Answer: A) pytest.mark.skip
Explanation:
The pytest.mark.skip marker skips a test unconditionally.
23. Which marker conditionally skips a test?
- pytest.mark.skipif
- pytest.mark.ifskip
- pytest.mark.conditionalskip
- pytest.mark.skipwhen
Answer: A) pytest.mark.skipif
Explanation:
pytest.mark.skipif skips a test when its specified condition evaluates to true.
24. Which marker is used for a test that is expected to fail?
- pytest.mark.xfail
- pytest.mark.expected
- pytest.mark.fail_expected
- pytest.mark.future_fail
Answer: A) pytest.mark.xfail
Explanation:
The pytest.mark.xfail marker indicates that a test is expected to fail under specified conditions.
25. Which command-line option selects tests by their registered marker?
- -m
- -k
- -t
- -mark
Answer: A) -m
Explanation:
The -m option allows pytest to select tests based on marker expressions, such as pytest -m slow.
26. Which command displays the markers available in the pytest environment?
- pytest --markers
- pytest --list-markers
- pytest -markers
- pytest --show-tags
Answer: A) pytest --markers
Explanation:
The --markers option displays the available pytest markers, including registered custom markers and built-in markers.
27. Which pytest function is used to test whether an exception is raised?
- pytest.raises()
- pytest.exception()
- pytest.assert_raises()
- pytest.expect_error()
Answer: A) pytest.raises()
Explanation:
pytest.raises() can be used as a context manager to verify that a specified exception is raised by the code under test.
28. Which code correctly tests for a ValueError using pytest?
with pytest.raises(ValueError):
with pytest.error(ValueError):
pytest.expect(ValueError)
pytest.assert_error(ValueError)
Answer: A) with pytest.raises(ValueError):
Explanation:
The pytest.raises() context manager verifies that the code inside the context raises the specified exception.
29. Which built-in fixture captures text written to sys.stdout and sys.stderr?
- capsys
- capoutput
- capture_io
- stdout_capture
Answer: A) capsys
Explanation:
The capsys fixture captures text written to standard output and standard error and provides methods such as readouterr() to inspect it.
30. Which built-in fixture is useful for capturing log messages?
- caplog
- logcapture
- capturelogfile
- pytestlog
Answer: A) caplog
Explanation:
The caplog fixture provides access to log records generated during a test.
31. Which built-in fixture provides a temporary directory as a pathlib.Path object?
- tmp_path
- temp_path
- tmp_dir_path
- temporary_path
Answer: A) tmp_path
Explanation:
The tmp_path fixture provides a temporary directory represented by a pathlib.Path object for test use.
32. Which pytest fixture allows temporary modification of objects, dictionaries, environment variables, and paths?
- monkeypatch
- patcher
- modifyenv
- mockpatch
Answer: A) monkeypatch
Explanation:
The monkeypatch fixture provides methods for temporarily modifying attributes, dictionary items, environment variables, paths, and related objects. The changes are undone after the requesting test or fixture finishes.
33. Which monkeypatch method changes an attribute on an object?
- setattr()
- setattribute()
- modifyattr()
- changeattr()
Answer: A) setattr()
Explanation:
monkeypatch.setattr() temporarily changes an attribute on an object and restores the original state after the test.
34. Which monkeypatch method can temporarily set an environment variable?
- setenv()
- setvariable()
- envset()
- set_environment()
Answer: A) setenv()
Explanation:
The monkeypatch.setenv() method temporarily sets an environment variable for the duration of the relevant test or fixture.
35. Which pytest option collects tests without actually running them?
- --collect-only
- --discover-only
- --list-tests-only
- --dry-run-tests
Answer: A) --collect-only
Explanation:
The --collect-only option performs test collection and displays the tests that would be collected without executing them.
36. Which pytest option reruns only tests that failed in the previous run when cache information is available?
- --lf
- --failed-only
- --retry-failed
- --last-error
Answer: A) --lf
Explanation:
The --lf or --last-failed option runs the tests that failed during the previous test run.
37. Which pytest option first runs the previously failed tests and then the remaining tests?
- --ff
- --first-failed
- --failed-first-only
- --retry-all
Answer: A) --ff
Explanation:
The --ff or --failed-first option runs previously failed tests first and then continues with the other tests.
38. Which option generates a JUnit-style XML test report?
- --junitxml
- --xmlreport
- --junit-report
- --reportxml
Answer: A) --junitxml
Explanation:
The --junitxml option creates a JUnit-style XML report that can be consumed by various CI and reporting systems.
39. Which command can be used to run a specific test function directly by node ID?
- pytest test_file.py::test_function
- pytest --function test_file.py test_function
- pytest -function test_function
- pytest test_function::test_file.py
Answer: A) pytest test_file.py::test_function
Explanation:
Pytest uses node IDs to identify individual tests. A test function can be selected using syntax such as pytest test_file.py::test_function.
40. What is a custom marker in pytest?
- User-defined metadata attached to tests
- A replacement for Python decorators
- A type of fixture
- A test output format
Answer: A) User-defined metadata attached to tests
Explanation:
Custom markers can attach metadata to test functions or classes and can be used to categorize and select tests.
41. Which command can be used to select tests marked with a custom marker named slow?
- pytest -m slow
- pytest -k-marker slow
- pytest --tag slow
- pytest -select slow
Answer: A) pytest -m slow
Explanation:
The -m option selects tests using marker expressions, so pytest -m slow selects tests marked with slow.
42. Which pytest plugin is commonly used to distribute tests across multiple workers?
- pytest-xdist
- pytest-parallel-core
- pytest-multi
- pytest-workers
Answer: A) pytest-xdist
Explanation:
pytest-xdist is a plugin that provides distributed testing capabilities. Options such as -n are provided by the plugin rather than core pytest.
43. Which pytest plugin is commonly used to measure test coverage?
- pytest-cov
- pytest-coverage-core
- pytest-testcoverage
- pytest-coverall
Answer: A) pytest-cov
Explanation:
pytest-cov integrates coverage measurement with pytest and can generate coverage reports.
44. Which library is commonly used to provide mocking support through the pytest-mock plugin?
- unittest.mock
- pytest.mockcore
- mocktest
- pytest.fake
Answer: A) unittest.mock
Explanation:
The pytest-mock plugin provides a convenient mocker fixture built around Python's standard mocking facilities from unittest.mock.
45. What is the purpose of mocking in unit testing?
- To replace or simulate dependencies during a test
- To execute every external service for real
- To permanently modify application code
- To disable all assertions
Answer: A) To replace or simulate dependencies during a test
Explanation:
Mocking allows tests to replace external or complex dependencies with controlled objects so that specific behavior can be tested in isolation.
46. What is an autouse fixture?
- A fixture that is automatically used within its applicable scope
- A fixture that can only be used once
- A fixture that cannot contain setup code
- A fixture that runs only after all tests
Answer: A) A fixture that is automatically used within its applicable scope
Explanation:
Setting autouse=True on a fixture causes pytest to use that fixture automatically for tests within its applicable scope without requiring it as a test argument.
47. Which fixture can provide access to pytest's temporary test directory as a pathlib.Path object?
- tmp_path
- path_fixture
- test_path
- pytest_path
Answer: A) tmp_path
Explanation:
The built-in tmp_path fixture provides a temporary directory using a pathlib.Path object, which is useful for tests involving files and directories.
48. Which pytest command-line option provides quiet output?
- -q
- -v
- -s
- -d
Answer: A) -q
Explanation:
The -q or --quiet option reduces the amount of output produced by pytest.
49. What is the purpose of pytest's cache mechanism?
- To store information that can be reused across pytest runs
- To permanently store application data
- To replace all test fixtures
- To compile Python source code
Answer: A) To store information that can be reused across pytest runs
Explanation:
Pytest's cache mechanism stores data between test runs and is used by features such as selecting previously failed tests.
50. Which sequence represents a common pytest testing workflow?
- Write tests, collect tests, execute tests, and inspect the results
- Compile all tests into machine code before writing them
- Delete fixtures before running every test
- Disable assertions and inspect only application logs
Answer: A) Write tests, collect tests, execute tests, and inspect the results
Explanation:
A typical pytest workflow involves writing test functions and fixtures, allowing pytest to discover and collect them, executing the tests, and reviewing the resulting reports and failures.
Advertisement
Advertisement