Ten questions at a time, drawn from 125. Every answer is explained. Nothing is saved and no account is needed.
What is the primary reason for using a fixture instead of a standard setup function in pytest?
Practice quiz for pytest & Testing. Scores are not saved.
What is the primary reason for using a fixture instead of a standard setup function in pytest?
Answer: Fixtures allow for modularity, dependency injection, and automatic teardown.. Fixtures enable dependency injection and systematic setup/teardown, which modularizes test environments. The other options are incorrect because fixtures are not strictly required for parallelism, they are not inherently faster, and they do not remove the need for assertions.
From lesson: Introduction to Testing and pytest
How does pytest determine which functions are tests?
Answer: By looking for functions that start with the 'test_' prefix.. Pytest uses a default discovery pattern where it collects files starting with 'test_' and functions/methods within them starting with 'test_'. The other options refer to incorrect decorators, implementation details, or misinterpret the purpose of configuration files.
From lesson: Introduction to Testing and pytest
When a test function fails with an assertion error, what does pytest do?
Answer: It uses internal introspection to provide a detailed report of the failure.. Pytest performs assertion rewriting, allowing it to inspect the expression and show the values of the variables involved in the failure. It does not stop the suite by default, does not mark them as skipped, and does not require manual prompts.
From lesson: Introduction to Testing and pytest
What is the benefit of 'assert' rewriting in pytest?
Answer: It allows developers to use plain 'assert' statements while getting rich failure diagnostics.. Assertion rewriting transforms the simple Python assert into a diagnostic powerhouse, reporting the state of the comparison at the moment of failure. It is not related to compilation, OS compatibility, or environment configuration.
From lesson: Introduction to Testing and pytest
Which of the following best describes the philosophy of an isolated test?
Answer: A test that executes without any dependencies on external systems or previous tests.. Isolation ensures that a test's outcome is independent of side effects from other tests or external state. Using local variables is just a coding style, requiring a database violates isolation, and separate processes are a performance optimization, not a definition of isolation.
From lesson: Introduction to Testing and pytest
Which of the following describes the purpose of the 'test_' prefix in pytest?
Answer: It acts as a marker for the test discovery process. The 'test_' prefix is the default pattern pytest uses to discover files and functions; without it, pytest ignores the code. The other options are incorrect as it is a configuration convention, not a language requirement or performance optimization.
From lesson: Writing Your First Test
When a simple 'assert' statement fails in pytest, what is the primary benefit of the reporting system?
Answer: It provides a detailed breakdown of the values involved in the expression. Pytest uses introspection to rewrite assertions, providing detailed info on variables during failure. It does not auto-fix code, dump memory, or handle notifications, as those are outside the scope of assertion reporting.
From lesson: Writing Your First Test
Why is it recommended to use fixtures over standard setup/teardown methods?
Answer: Fixtures provide modularity, dependency injection, and scope management. Fixtures offer scope management (e.g., session vs function) and dependency injection, making tests cleaner. Parallelism is handled by plugins, not fixtures themselves, and fixtures are not language requirements or needed for library imports.
From lesson: Writing Your First Test
What happens if a test function fails during its execution in a suite of 10 tests?
Answer: Pytest logs the error and continues to run the remaining tests. Pytest is designed to run all discovered tests regardless of individual failures, reporting results at the end. It does not halt the suite, delete tests, or skip others unless explicitly configured to do so via command-line flags.
From lesson: Writing Your First Test
In the context of writing your first test, what does 'test isolation' imply?
Answer: A test should not rely on the state or side effects of another test. Isolation ensures that tests are independent, making them predictable and debuggable. The other options are either false requirements (directory structure) or specific implementation details (network or mocks) that do not define the core concept of isolation.
From lesson: Writing Your First Test
If your test output is missing print statements you included for debugging, what is the most direct way to see them in the console?
Answer: Use the -s flag. The -s flag allows output to be printed to stdout. --verbose and -v increase detail but do not disable capture, and --collect-only just lists tests without running them.
From lesson: Running Tests and Reading Output
Why does pytest not execute a function named 'check_login_functionality' even if it contains valid assertions?
Answer: It does not start with the 'test_' prefix. Pytest uses test discovery based on the prefix 'test_'. Changing the name to 'test_check_login_functionality' would allow pytest to find it automatically.
From lesson: Running Tests and Reading Output
What happens when an assertion fails midway through a test function?
Answer: The execution stops immediately, and the remainder of the test is skipped. Pytest treats an assertion failure as a failure that terminates the execution of that specific test function immediately. It is not skipped or errored; it is failed.
From lesson: Running Tests and Reading Output
How can you run only a specific subset of tests defined by a keyword in their name?
Answer: Using the -k flag. The -k flag allows filtering tests by matching substrings in their names. -m is for markers, -n is for parallelization, and --collect-only is for inspection.
From lesson: Running Tests and Reading Output
Which of the following describes the best practice for reading test failure output?
Answer: Look for the assertion failure details in the 'FAILURES' section of the output. The 'FAILURES' section provides the specific line where the assertion failed and the values of the variables involved, which is essential for debugging. The other options ignore critical diagnostic data.
From lesson: Running Tests and Reading Output
Which file naming pattern does pytest use by default for test discovery?
Answer: test_*.py or *_test.py. pytest uses 'test_*.py' and '*_test.py' to identify test modules. Other options like 'spec_' or 'case_' are not standard pytest conventions and would require manual configuration.
From lesson: Test Discovery and Naming Conventions
If you have a function named 'calculate_sum' inside a test file, what will happen?
Answer: pytest will ignore the function during execution. pytest only discovers functions prefixed with 'test_'. Since 'calculate_sum' lacks this prefix, it is treated as a standard helper function and ignored by the test runner.
From lesson: Test Discovery and Naming Conventions
Why is it important to follow consistent naming conventions in a test suite?
Answer: It allows pytest to discover and execute tests automatically. Naming conventions allow pytest's discovery mechanism to locate tests without explicit configuration. Performance, language rules, and collision prevention are not the primary reasons for these specific naming patterns.
From lesson: Test Discovery and Naming Conventions
How does pytest handle test classes that do not start with 'Test'?
Answer: It skips them by default during collection. pytest skips classes that do not start with 'Test' by default, as they do not meet the collection criteria. It will not treat them as fixtures nor will it execute them.
From lesson: Test Discovery and Naming Conventions
When should you use a custom pytest configuration for discovery?
Answer: When you prefer using 'check_' as a prefix instead of 'test_'. Custom configuration is specifically for changing the default discovery rules, such as supporting 'check_' prefixes. Project size, folder location, and multiple frameworks do not necessitate changing discovery patterns.
From lesson: Test Discovery and Naming Conventions
What is the primary benefit of using 'yield' in a fixture over 'return'?
Answer: It provides a clear point to perform teardown code after the test finishes. Yield allows code after the statement to run as teardown, which is essential for cleanup. Return simply passes the object, whereas yield pauses the fixture, runs the test, and resumes execution to finish the teardown. The other options are incorrect because they describe unrelated or false performance/scope benefits.
From lesson: Fixtures — Setup and Teardown
If you have a 'session' scoped fixture, when is its teardown code executed?
Answer: Only after all tests in the entire session have finished. Session scope means the fixture is created once for the entire test run and torn down only once, at the very end. Option 1 describes function scope; option 2 describes class scope; option 4 is not how pytest scoping works.
From lesson: Fixtures — Setup and Teardown
When should you define a fixture in 'conftest.py' instead of a local test file?
Answer: When the fixture needs to be shared across multiple test files. conftest.py is automatically discovered by pytest and makes fixtures available to all tests in that directory and subdirectories. Defining it locally limits it to one file. The other options do not dictate location; scope dictates performance or frequency, not file placement.
From lesson: Fixtures — Setup and Teardown
What happens if a fixture used by a test fails during the setup phase?
Answer: The test is marked as 'error' and execution stops. A failure in setup occurs before the test starts, which pytest classifies as an 'error' rather than a test 'failure'. Options 1 and 2 are incorrect because the test suite does not just proceed or ignore the error; option 4 describes retry plugins, not default behavior.
From lesson: Fixtures — Setup and Teardown
How do you ensure a specific setup/teardown sequence if one fixture depends on another?
Answer: List the required fixture as an argument in the dependent fixture's definition. Pytest handles dependency injection by resolving arguments; if fixture B requests fixture A as an argument, pytest guarantees A is set up before B. Global variables are bad practice, and naming has no impact on execution. The dependency mark is for test-to-test dependency, not fixture management.
From lesson: Fixtures — Setup and Teardown
You have a suite where multiple test classes require a database connection. If you want the connection to be opened once per module to save time, which scope should you use?
Answer: module. Module scope ensures the fixture runs once for the entire file (module), which is the intended goal. Function scope would be too slow, class scope wouldn't share across classes in the same module, and session scope is overkill and risks state leakage if only one module needs it.
From lesson: Fixture Scopes — function, class, module, session
What happens if a test function requires a 'function' scoped fixture that depends on a 'session' scoped fixture?
Answer: The session fixture is initialized once and reused by the function fixture.. Lower-scoped fixtures can depend on higher-scoped ones without issue. The session fixture remains alive for the duration of the test run, while the function fixture is created fresh for each test. Option 1 is false, Option 2 defeats the purpose of session, and Option 4 is syntactically impossible.
From lesson: Fixture Scopes — function, class, module, session
Why would you choose 'function' scope over 'session' scope for a fixture that clears a temporary directory?
Answer: To ensure each test starts with a completely empty directory.. Function scope ensures isolation; if one test leaves files in the directory, the next test won't see them because the fixture re-runs. Session scope would mean all tests share the same directory, leading to file collisions. The other options are factually incorrect regarding pytest capabilities.
From lesson: Fixture Scopes — function, class, module, session
If you have a base test class with a 'class' scoped fixture, and a subclass that inherits from it, how many times does the fixture run?
Answer: Once for the base class and once for each subclass.. Pytest scopes are applied to the specific class they are defined in. If the fixture is defined in the base class, subclasses will trigger the fixture again upon their own execution. Option 1 is the correct behavior; others misunderstand the scope's lifecycle.
From lesson: Fixture Scopes — function, class, module, session
Which of the following scenarios best justifies the use of a 'session' scoped fixture?
Answer: Setting up a local mock server that needs to be active for the entire test suite.. Session scope is ideal for expensive resources that are needed globally, such as a mock server. Function scope (Option 1 and 3) is better for specific test requirements, and module scope (Option 4) is better for single-file dependencies to avoid unnecessary global overhead.
From lesson: Fixture Scopes — function, class, module, session
How does pytest determine which tests have access to a fixture defined in a conftest.py file?
Answer: The fixture is available to all tests in the same directory and all subdirectories.. Pytest uses a directory-based scope for conftest.py files. It is available to the directory containing the file and all subdirectories. Importing is unnecessary and discouraged; global marks and ini registration are not required for fixture discovery.
From lesson: conftest.py — Shared Fixtures
If you have a conftest.py in the root folder and another in a subdirectory, which one takes precedence for a test in that subdirectory?
Answer: The one in the subdirectory takes precedence.. Pytest follows a hierarchical lookup; the conftest.py closest to the test file takes precedence, allowing for overrides or local modifications. Merging is not the mechanism used for same-named fixtures; shadowing is.
From lesson: conftest.py — Shared Fixtures
What is the primary benefit of using a yield fixture in conftest.py compared to a return fixture?
Answer: It allows for explicit teardown code to run after the test completes.. Yield fixtures allow you to perform setup before 'yield' and cleanup after, which is essential for shared resources. Return fixtures have no built-in mechanism for teardown. Performance and scope are independent of the yield keyword.
From lesson: conftest.py — Shared Fixtures
When is an 'autouse' fixture defined in a conftest.py executed?
Answer: For every test case within the scope of the conftest.py file.. An autouse fixture automatically runs for every test in its scope without needing to be named in the test function parameters. Session-wide is an option for scope, but it doesn't describe the triggering mechanism, and the other options are incorrect.
From lesson: conftest.py — Shared Fixtures
You have a fixture in conftest.py that is slow to initialize. You want it to run only once per test file rather than for every test function. How should you define the scope?
Answer: Use scope='module'.. Setting scope='module' ensures the fixture setup runs once for each test file (module). 'Session' runs once per test run, 'function' runs for every test, and 'class' runs per test class, making module the correct choice for file-level reuse.
From lesson: conftest.py — Shared Fixtures
What is the primary advantage of using a factory pattern fixture over a static object fixture?
Answer: It allows tests to customize the generated data on a per-test basis. The factory pattern provides a callable fixture that allows tests to override specific fields, providing flexibility. Static fixtures don't do this (Option 2). Speed isn't the primary goal (Option 1). It doesn't handle database cleanup (Option 3). Code length is not the main benefit (Option 4).
From lesson: Fixture Dependencies and Factories
If two fixtures depend on each other, what happens when a test requests them?
Answer: Pytest raises an error about a circular dependency. Pytest detects circular dependencies during the dependency resolution phase and raises a RecursionError. It does not run them in parallel (Option 2), order of definition is irrelevant (Option 3), and it does not ignore the dependency (Option 4).
From lesson: Fixture Dependencies and Factories
What is the purpose of the 'yield' keyword in a pytest fixture?
Answer: To separate the setup code from the teardown/cleanup code. Yield is the standard way to provide a teardown phase; code before yield runs before the test, and code after runs after the test. It does not return multiple values (Option 1), pause tests for the database (Option 2), or bypass scope (Option 4).
From lesson: Fixture Dependencies and Factories
Which scope should you choose for a fixture that creates a temporary database connection that must be fresh for every test?
Answer: function. Function scope ensures the fixture is recreated for every individual test function, providing isolation. Session, module, and class scopes persist the fixture longer than a single test, which risks cross-test contamination.
From lesson: Fixture Dependencies and Factories
Why is it recommended to use 'autouse=True' sparingly?
Answer: Because it makes it difficult to track which fixtures affect a specific test. Autouse fixtures run implicitly, making it hard to see dependencies in the test signature. It doesn't inherently slow things down (Option 2), break DI (Option 3), or prevent yield (Option 4).
From lesson: Fixture Dependencies and Factories
What happens if you provide a list of tuples to @pytest.mark.parametrize where the tuple lengths do not match the number of argument names?
Answer: Pytest raises an error during collection. Pytest requires a strict mapping between the argument names string and the values in the tuples. If they don't align, the collection phase fails because it cannot map the inputs to the function arguments.
From lesson: pytest.mark.parametrize — Multiple Inputs
Which of the following correctly defines multiple inputs for a test function?
Answer: @pytest.mark.parametrize('x, y', [(1, 2), (3, 4)]). Pytest expects a single string of comma-separated names as the first argument, followed by a list of tuples for the values. Using lists, sets, or separate strings for names is incorrect syntax.
From lesson: pytest.mark.parametrize — Multiple Inputs
Why is it generally preferred to use @pytest.mark.parametrize over using a for-loop inside a test function?
Answer: Each parameter set is treated as an individual test result. Using parametrize creates independent test nodes. If one case fails, the others continue running, and you get a clear report of which specific input caused the failure, whereas a loop stops at the first assertion error.
From lesson: pytest.mark.parametrize — Multiple Inputs
If you have a test function `def test_add(a, b, expected):`, how should the values be passed to correctly map the parameters?
Answer: [(1, 2, 3), (4, 5, 9)]. Pytest expects an iterable of tuples, where each tuple corresponds to the full set of arguments for one test run. Lists of lists are sometimes accepted by duck typing but tuples are the convention, while sets are unordered and incorrect here.
From lesson: pytest.mark.parametrize — Multiple Inputs
What is the purpose of the 'ids' argument in @pytest.mark.parametrize?
Answer: To provide custom names for each test case in the output. The 'ids' argument allows you to provide descriptive labels for each test case, making the test output much easier to read when debugging failures, as opposed to default index-based labels.
From lesson: pytest.mark.parametrize — Multiple Inputs
What is the primary advantage of using a custom mark over string-based filtering with the -k option?
Answer: It provides a semantic, stable identifier that survives code refactoring. Custom marks are semantic identifiers attached to test nodes, which remain stable even if test names change. String-based -k filtering is brittle because it depends on function names. Other options are incorrect as marks do not influence execution speed by skipping imports, report generation, or test order.
From lesson: Custom Marks and Filtering Tests
When running 'pytest -m slow', what happens if a test is marked with @pytest.mark.slow but is not registered in the configuration file?
Answer: The test runs, but pytest issues a warning. Pytest allows the use of unregistered marks but issues a 'PytestUnknownMarkWarning' to alert the developer of potential typos. It does not terminate, skip the test, or treat it as a standard unit test unless configured to fail on warnings.
From lesson: Custom Marks and Filtering Tests
If you apply @pytest.mark.database to a class, how does this affect the methods within that class?
Answer: All test methods within the class automatically inherit the 'database' mark. Pytest marks applied to a class are inherited by all test methods within that class. The mark is not ignored, nor does it require individual decoration, and it certainly does not require the mark to be present for the test to pass.
From lesson: Custom Marks and Filtering Tests
You have tests marked with @pytest.mark.smoke and @pytest.mark.regression. How do you run only tests that are marked as 'smoke' but specifically EXCLUDE those that are 'regression'?
Answer: pytest -m 'smoke and not regression'. Pytest supports logical expressions in the -m flag, allowing for complex selection using 'and', 'or', and 'not'. Option 1 is the correct syntax. The other options use invalid command-line flag structures for pytest.
From lesson: Custom Marks and Filtering Tests
Why is it recommended to add a description to a mark definition in the pytest.ini file?
Answer: It allows other developers to see the purpose of the mark when running 'pytest --markers'. The 'pytest --markers' command displays the documentation provided in the configuration file, making it easier for teams to understand the intent of custom markers. The other options are incorrect as the description does not influence runtime execution, XML outputs, or crash handling.
From lesson: Custom Marks and Filtering Tests
When is the condition provided to @pytest.mark.skipif evaluated?
Answer: Immediately when the test is collected. Conditions in skipif are evaluated during collection, which is why they cannot access data produced by fixtures. Option 0 and 2 are wrong because those happen post-collection; option 3 is too late.
From lesson: Skipping Tests — skip and skipif
What is the primary difference between @pytest.mark.skip and pytest.skip()?
Answer: Mark skip is applied at collection, while pytest.skip() is called at runtime. The decorator is evaluated at collection time, whereas the function call happens inside the test body during execution. Options 0, 1, and 3 are incorrect as they misstate the flexibility and usage of these tools.
From lesson: Skipping Tests — skip and skipif
If you want to skip a test only when running on a specific Python version, what is the best practice?
Answer: Use @pytest.mark.skipif(sys.version_info < (3, 9), reason='Requires newer Python'). Using skipif with a conditional expression is the standard pytest approach. Option 1 stops the whole session, 2 is non-idiomatic, and 3 is not a conditional skip.
From lesson: Skipping Tests — skip and skipif
What happens if a test is skipped using @pytest.mark.skip?
Answer: The test is not executed, but it appears as 's' in the output. Skipped tests are reported as 's' (skipped) in the pytest output. Option 0 describes xfail, 2 is wrong because the report tracks it, and 3 is wrong because reason is optional.
From lesson: Skipping Tests — skip and skipif
Why might you choose @pytest.mark.xfail over @pytest.mark.skip?
Answer: To ensure the test is run but document that it is expected to fail. Xfail is used when you know a test will fail but you still want to run it to track its status. Skip prevents the test from running at all. Options 0, 2, and 3 are fundamentally incorrect regarding the purpose of xfail.
From lesson: Skipping Tests — skip and skipif
When a test is marked with @pytest.mark.xfail and it unexpectedly passes (xpass), what is the default behavior in pytest?
Answer: The test is reported as an expected pass (xpass). By default, pytest reports an xpass as a special 'xpass' outcome. Option 0 is incorrect because it only happens if strict=True is set. Option 2 is incorrect because the test still executes. Option 3 is irrelevant to the reporting mechanism.
From lesson: Expected Failures — xfail
Which of the following scenarios is the most appropriate use case for pytest.mark.xfail?
Answer: A platform-specific bug exists that cannot be fixed until a third-party dependency is updated. xfail is for tests that are known to fail due to external factors or deferred fixes. Option 0 is better handled by a 'skip' mark. Option 2 is a performance issue, not an expectation issue. Option 3 is explicitly solved by 'skip'.
From lesson: Expected Failures — xfail
What happens if a test is marked @pytest.mark.xfail(strict=True) and the test passes?
Answer: The test is reported as a failure. When strict=True, an unexpected pass is treated as a test failure. This is used to ensure developers clean up tests that no longer need the xfail status. The other options describe default behaviors, not strict mode behavior.
From lesson: Expected Failures — xfail
If you want to only mark a test as xfail if a specific condition is met (e.g., based on the Python version), how should you implement this?
Answer: Pass a 'condition' argument to @pytest.mark.xfail. The 'condition' argument (or boolean expression) inside @pytest.mark.xfail allows for dynamic marking. Option 0 is possible but less declarative than the decorator. Option 2 skips the test, which is a different outcome. Option 3 is false because the decorator is designed for this.
From lesson: Expected Failures — xfail
What is the primary difference between @pytest.mark.skip and @pytest.mark.xfail?
Answer: xfail runs the test, skip does not. xfail executes the code to check if it still fails (or if it has started passing), whereas skip stops the test runner from executing the code entirely. Options 1, 2, and 3 misrepresent the execution flow and the outcomes of these two markers.
From lesson: Expected Failures — xfail
If you are testing 'app.services.get_user' which calls 'app.db.query', where should you apply the @patch decorator?
Answer: @patch('app.services.db.query'). You must patch where the name is looked up, which is 'app.services'. Options 0 and 1 target the wrong namespaces, and option 3 assumes an incorrect import path.
From lesson: unittest.mock — MagicMock and patch
What is the primary benefit of using autospec=True in a mock patch?
Answer: It ensures the mock raises an error if you call it with incorrect arguments or invalid attribute names.. autospec ensures the mock follows the signature of the object it replaces. The other options describe features unrelated to the mock's interface validation.
From lesson: unittest.mock — MagicMock and patch
How do you configure a mock to raise a ConnectionError the first time it is called and return a valid user object the second time?
Answer: Set side_effect to [ConnectionError, {'id': 1}]. side_effect accepts an iterable; if an item is an exception class, it is raised. return_value would return the list itself. A lambda is less efficient for this specific sequence requirement.
From lesson: unittest.mock — MagicMock and patch
Why should you avoid patching objects inside the setup method of a test class?
Answer: Because setup runs before every test and might not properly clean up the patches.. Patches in setup require careful management to avoid leakage. Decorators and context managers are preferred in pytest for isolation. Pytest does not deprecate setup, but fixtures are superior.
From lesson: unittest.mock — MagicMock and patch
Which of these assertions correctly verifies that a mocked function was called with specific keyword arguments?
Answer: mock.assert_called_with(id=5). assert_called_with is the standard method for argument verification. called_with and verify_args are not valid methods, and checking call_args directly is less readable and error-prone.
From lesson: unittest.mock — MagicMock and patch
Which of the following best describes the primary advantage of the 'mocker' fixture over the standard 'unittest.mock.patch' decorator?
Answer: It automatically cleans up patches after the test finishes, reducing boilerplate code.. The mocker fixture manages the lifecycle of patches automatically via pytest's teardown process. Option 0 is false as performance is similar. Option 2 is false as the underlying patch logic is identical. Option 3 is false as race conditions are outside the scope of mocking.
From lesson: pytest-mock — mocker fixture
You have a module 'app.services' that uses 'requests.get'. Where should you place the mocker path for testing?
Answer: mocker.patch('app.services.requests.get'). In Python, you must mock the object where it is imported and used, not where it is defined. Option 0 and 2 fail because they mock the origin. Option 3 is an incorrect pathing. Option 1 correctly targets the lookup location in the service.
From lesson: pytest-mock — mocker fixture
What is the primary benefit of using 'autospec=True' when creating a mock?
Answer: It creates a mock object that has the same attributes and methods as the object being replaced.. Autospec verifies the mock object matches the interface of the target, catching signature mismatches. Option 0 is nonsense. Option 1 is standard mock behavior. Option 3 is incorrect as the mock does not execute the original logic by default.
From lesson: pytest-mock — mocker fixture
When testing a function that performs a network request, why might you prefer 'mocker.patch' over creating a manual Mock class?
Answer: It allows for easier assertion of how many times the dependency was called and with what arguments.. Mocker makes inspection of call counts and arguments trivial using assert_called_with. Option 0 is false; it is a convenience. Option 2 is false. Option 3 is false; you still must assert outcomes.
From lesson: pytest-mock — mocker fixture
If you need to verify that a mock was called twice with specific arguments, which method should you use?
Answer: mock_obj.assert_has_calls([call(args), call(args)]). assert_has_calls allows verifying an ordered sequence of calls. Option 0 does not exist in standard unittest.mock. Option 2 and 3 are not valid API methods.
From lesson: pytest-mock — mocker fixture
You want to mock 'requests.get' inside 'myapp.api'. Which path should you provide to patch()?
Answer: patch('myapp.api.requests.get'). Correct: You must patch where the name is looked up, which is inside your module. Option 0 patches the original library, which won't affect the import already inside 'myapp.api'. Option 2 assumes 'get' was imported directly. Option 3 is an invalid path structure.
From lesson: Patching — patch, patch.object
What is the primary difference between patch() and patch.object()?
Answer: patch requires a string path, patch.object takes the actual object. Correct: patch() takes a string path to resolve the object, while patch.object takes the object instance/class directly. Option 0 is false. Option 1 is false, both can handle functions or classes. Option 3 is false, both work as decorators.
From lesson: Patching — patch, patch.object
When using a decorator for patching, in what order are the mock objects passed to your test function?
Answer: In the order they are defined from innermost to outermost. Correct: Decorators are applied from bottom to top, meaning the innermost decorator's mock is passed as the first argument. Option 1 is backwards. Option 2 is false as they are indeed passed. Option 3 is false.
From lesson: Patching — patch, patch.object
Why is it recommended to use patch as a context manager if you aren't using a decorator?
Answer: It prevents the need for an explicit stop() call. Correct: Using 'with patch(...) as m:' ensures that the patch is automatically cleaned up when the block exits. Option 0 is irrelevant. Option 2 is possible with both styles. Option 3 is false.
From lesson: Patching — patch, patch.object
If you mock a class using patch, what is the default return value when the mock is called?
Answer: A new MagicMock instance. Correct: Mocking a class results in a MagicMock; when that mock is called (instantiated), it returns another MagicMock representing the instance. Option 1, 2, and 3 are incorrect behaviors of the mocking framework.
From lesson: Patching — patch, patch.object
You are testing a function that processes an image and saves it to a directory. Which approach best validates the full behavior?
Answer: Mock the filesystem and verify the file creation and return value.. Option 1 fails to check if the file was actually saved. Option 3 ignores the result and the side effect. Option 4 is risky because it relies on real disk I/O. Option 2 is correct because it isolates the logic from the disk while verifying both the side effect (mock call) and the return value.
From lesson: Side Effects and Return Values
A test asserts a return value but ignores a side effect that modifies a shared object. What is the primary risk?
Answer: The test provides a false sense of security while the system state remains invalid.. If the side effect is the primary purpose of the function, verifying only the return value misses the logic failure. Option 1 is incorrect as standard tests are usually sequential. Option 4 is false as pytest does not monitor side effects automatically.
From lesson: Side Effects and Return Values
When using `monkeypatch` to replace a function, why is it safer than manually overriding a function object?
Answer: It automatically reverses the change after the test, regardless of success or failure.. Monkeypatch is designed to handle teardown automatically. Manual overrides persist across tests unless explicitly reverted, which is prone to error. The other options do not describe the primary benefit of the fixture's cleanup mechanism.
From lesson: Side Effects and Return Values
If a test function fails during an assertion of a side effect, what happens to the subsequent assertions in the same test?
Answer: They are ignored because the test execution stops at the first failed assertion.. Pytest stops executing a test function as soon as an assertion fails. This is why testing the return value and the side effect together is important; if the return value check fails, you never reach the side effect check, potentially masking a secondary bug.
From lesson: Side Effects and Return Values
How should you test a function that has a side effect of incrementing a counter in a database?
Answer: Mock the database increment method and verify it was called with the correct parameters.. Mocking the interaction verifies that the function correctly triggered the specific side effect. Querying the database (Option 1) is a test of the database integration, not the function's logic. Option 3 ignores the side effect entirely. Option 4 is inefficient and unnecessary.
From lesson: Side Effects and Return Values
What happens if a block of code inside 'with pytest.raises(ValueError):' executes successfully without raising any error?
Answer: The test fails because no exception was raised.. If no exception is raised, pytest explicitly fails the test. Option 0 is wrong because a failure is required. Option 2 is wrong because no exception occurred. Option 3 is wrong as pytest handles the termination.
From lesson: Testing Exceptions — pytest.raises
Which of the following is the correct way to capture an exception object for further inspection?
Answer: with pytest.raises(ZeroDivisionError) as exc_info:. Using 'as' assigns an ExceptionInfo object to the variable, which allows checking the message or traceback. Options 1, 2, and 3 use incorrect syntax for the pytest API.
From lesson: Testing Exceptions — pytest.raises
You want to ensure that a function raises a 'RuntimeError' with the message 'Connection failed'. How do you do this properly?
Answer: with pytest.raises(RuntimeError, match='Connection failed'):. The 'match' parameter uses regex to check the exception message. Option 0 is a non-existent parameter. Option 2 is inefficient compared to 'match', and Option 3 is not a standard pytest function.
From lesson: Testing Exceptions — pytest.raises
Why is it best practice to keep the code inside the 'with pytest.raises' block minimal?
Answer: To avoid capturing exceptions that occur in unrelated code lines.. If you put too much code in the block, you might accidentally catch an exception you didn't intend to test. Options 0, 2, and 3 are incorrect as they do not relate to the logic of exception scoping.
From lesson: Testing Exceptions — pytest.raises
When using 'exc_info = pytest.raises(...):', how do you access the exception instance itself?
Answer: exc_info.value. In pytest, the ExceptionInfo object stores the actual exception instance in the '.value' attribute. The other attributes listed do not exist or are not the correct way to retrieve the exception instance.
From lesson: Testing Exceptions — pytest.raises
What is the primary function of the @pytest.mark.asyncio decorator?
Answer: It instructs the pytest-asyncio plugin to execute the function as a coroutine.. Option 2 is correct because the decorator registers the test with the plugin, which handles the event loop setup. Option 1 is wrong because it doesn't change the function type. Option 3 is unrelated to memory allocation. Option 4 is wrong because async tests run within the event loop, not necessarily a separate thread.
From lesson: Testing Async Code — pytest-asyncio
If you have an async fixture, how should you use it in an async test?
Answer: By requesting the fixture as an argument in the test function signature.. Option 3 is correct because pytest handles the injection and awaiting of async fixtures automatically. Option 1 fails because calling it synchronously returns the coroutine object. Option 2 is redundant as the plugin handles the loop. Option 4 is unnecessary boilerplate code.
From lesson: Testing Async Code — pytest-asyncio
Why might a test pass locally but fail in CI when testing async code?
Answer: Because of race conditions caused by implicit event loop dependencies.. Option 2 is correct; asynchronous tests often rely on implicit shared state or loop settings that differ in varied environments, causing race conditions. Option 1 is standard behavior for all tests. Option 3 is incorrect as the plugin is framework-agnostic. Option 4 is false, as CI environments support async test execution.
From lesson: Testing Async Code — pytest-asyncio
When using the 'asyncio_mode = auto' configuration, what happens to async functions?
Answer: They are automatically treated as async tests without needing the decorator.. Option 2 is correct because 'auto' mode detects 'async def' functions and treats them as asyncio tests automatically. Option 1 is wrong as they are collected. Option 3 is a common misinterpretation; the mode removes the need for the decorator. Option 4 is incorrect as pytest-asyncio does not default to thread pooling for async tests.
From lesson: Testing Async Code — pytest-asyncio
What happens if you use 'time.sleep(1)' inside an async test method?
Answer: The entire test process blocks, pausing all other concurrent tasks.. Option 2 is correct; 'time.sleep' is a blocking call that halts the thread, which stops the event loop from advancing any other pending tasks. Option 1 is incorrect because it is blocking. Option 3 is incorrect because the test doesn't necessarily time out. Option 4 is incorrect as standard libraries are not magically patched by pytest.
From lesson: Testing Async Code — pytest-asyncio
If your coverage report shows 100% coverage, what does that confirm?
Answer: Every line of your code has been executed during the test suite run.. 100% line coverage means every line was executed at least once. It does not prove correctness (logic), sufficiency (edge cases), or readiness, making the other options false.
From lesson: Coverage with pytest-cov
What is the primary difference between line coverage and branch coverage?
Answer: Branch coverage tracks whether both 'True' and 'False' outcomes for every decision point were executed.. Branch coverage ensures that every path through a control structure (like if/else) is traversed. Line coverage just checks if the line is hit; branch coverage is stricter and more informative.
From lesson: Coverage with pytest-cov
Why is it recommended to use the '--cov' flag in conjunction with a specific directory or package?
Answer: To restrict the measurement scope to your own application code rather than dependencies.. Specifying a source restricts the coverage tool to your project files, preventing it from reporting on installed libraries in your virtual environment, which would pollute the report.
From lesson: Coverage with pytest-cov
When a line of code is marked as 'missing' in a report, what does that usually imply?
Answer: No test case in your suite triggered that specific line of code during execution.. A 'missing' line simply means the test runner did not pass through that line during the test cycle. It is not necessarily unreachable, nor is it a syntax error.
From lesson: Coverage with pytest-cov
How can you permanently exclude specific files or directories from your coverage report?
Answer: By configuring the '[run]' section in a '.coveragerc' file or project config file.. Using a configuration file like '.coveragerc' is the standard way to define persistent settings such as omissions, whereas the other options are either temporary, incorrect, or poor practice.
From lesson: Coverage with pytest-cov
What is the primary benefit of using TestClient over calling route functions directly?
Answer: It simulates the full request/response lifecycle including middleware and routing. TestClient allows you to test the app as it would behave in production, processing middleware, validation, and dependency injection. Option 0 is false, it uses DI; Option 2 is false, it still uses the event loop; Option 3 is false, it is strictly local.
From lesson: Testing FastAPI with TestClient
How should you handle an external database dependency when running a suite of tests?
Answer: Use FastAPI's dependency_overrides to replace the real DB with a test database. dependency_overrides allow for clean, surgical replacement of services during testing. Connecting to production (0) is dangerous, global variables (1) lead to race conditions, and manual deletion (3) is inefficient compared to fixture-based cleanup.
From lesson: Testing FastAPI with TestClient
When a route requires an 'Authorization' header, how do you provide it in a TestClient request?
Answer: By passing it in the 'headers' argument of the request method. TestClient request methods accept a 'headers' dictionary that matches the standard HTTP interface. Modifying global state (2) is risky, and environment variables (0) are not granular enough for specific headers.
From lesson: Testing FastAPI with TestClient
Why would a test that passes in isolation fail when run as part of a larger test suite?
Answer: Because of shared mutable state like a database or application singleton. Shared mutable state is the primary cause of flaky tests. Option 0 is a red herring regarding order, Option 2 is incorrect as TestClient handles concurrency, and Option 3 is false.
From lesson: Testing FastAPI with TestClient
What is the correct way to handle a test that needs to reset the application state after execution?
Answer: A pytest fixture using 'yield' for setup and teardown. Fixtures with yield are the standard pytest idiom for setup/teardown. A standard function call (0) won't run if the test fails, a try/except (2) is overly verbose, and a separate test (3) is unreliable.
From lesson: Testing FastAPI with TestClient
Why is it recommended to use a 'function' scope for database session fixtures in pytest?
Answer: It ensures that each test starts with a clean, isolated database state.. Function scope ensures the fixture runs for every individual test, providing a fresh transaction. Option 0 is wrong because function scope is often slower than session scope. Option 2 is incorrect as it is a pytest convention, not a SQLAlchemy requirement. Option 3 is false as scope does not dictate parallelism capabilities.
From lesson: Testing SQLAlchemy — Database Fixtures
What is the primary purpose of using 'yield' in a pytest database fixture?
Answer: To provide a mechanism to perform teardown actions after the test completes.. The 'yield' statement acts as a breakpoint; code before 'yield' is setup, and code after is teardown. Option 0 and 3 are incorrect technical definitions. Option 1 is wrong because pytest handles the test start once the fixture yields.
From lesson: Testing SQLAlchemy — Database Fixtures
When testing database code, why is an in-memory SQLite database often preferred?
Answer: It provides rapid setup and teardown speeds without disk I/O.. In-memory databases exist only in RAM, making them extremely fast for unit tests. Option 0 is false because SQLite lacks many production features (e.g., custom types). Option 1 is false (it is ephemeral). Option 3 is false (it does not resolve concurrency).
From lesson: Testing SQLAlchemy — Database Fixtures
How does wrapping a test in a transaction and rolling it back benefit a test suite?
Answer: It ensures that even if a test fails, the database remains in its initial state.. Rollbacks ensure test isolation by removing any changes made during the test. Option 0 is not the primary benefit. Option 2 is irrelevant to the rollback process. Option 3 is false as transactions do not alter schemas.
From lesson: Testing SQLAlchemy — Database Fixtures
If your tests are failing because of foreign key constraint errors during cleanup, what should you do?
Answer: Use a fixture that clears tables in the correct order or disables foreign key checks.. Foreign keys enforce dependencies; clearing tables out of order causes errors. Option 0 is inefficient. Option 2 is dangerous for production. Option 3 is wrong because ignoring test errors leads to unreliable test suites.
From lesson: Testing SQLAlchemy — Database Fixtures
What is the primary goal of the 'Red' phase in the TDD cycle when using pytest?
Answer: To verify that the test fails for the correct reason before writing implementation.. The 'Red' phase is about confirming the test fails, which proves the test is valid and that the feature is indeed missing. Other options are incorrect because coverage, refactoring, and CI configuration are not the primary focus of this specific cycle phase.
From lesson: Test-Driven Development (TDD)
If you are following TDD and your new test passes immediately, what should you do?
Answer: Delete the test and write a different test to ensure you can make it fail.. If a test passes immediately, you have no proof the test is actually testing what you think it is (it might be a false positive). You must delete it and write a test that fails to confirm the test works. The other options ignore the risk of a false positive.
From lesson: Test-Driven Development (TDD)
Which of the following best describes the 'Refactor' phase in a pytest-driven workflow?
Answer: Changing the implementation to improve design without altering behavior.. Refactoring is strictly about improving internal code quality (DRY, readability) while maintaining existing behavior, verified by tests. Other options involve changing requirements or tests, which violates the intent of the refactor phase.
From lesson: Test-Driven Development (TDD)
When using pytest in TDD, why should you avoid testing internal private methods directly?
Answer: Testing internal implementation details makes tests fragile and resistant to refactoring.. Tests should verify behavior through public APIs; binding tests to private methods forces you to update tests whenever you change internal structure, even if the public output remains the same. The other options are either false (pytest can access private methods) or logical fallacies.
From lesson: Test-Driven Development (TDD)
Why is it important to keep pytest tests fast in a TDD cycle?
Answer: Because TDD relies on a short, frequent feedback loop.. TDD depends on running tests constantly; if tests are slow, the developer loses focus and disrupts the flow. The other options are incorrect: coverage speed is not the priority, fast tests do not enable more complex logic, and pytest does not crash on slow tests.
From lesson: Test-Driven Development (TDD)
Why is 'function' scope preferred over 'module' scope for fixtures dealing with shared mutable state?
Answer: It ensures that state modifications made in one test do not impact the assertions of another.. Option 2 is correct because isolation prevents test pollution. Option 1 is wrong because function scope is the least cached. Option 3 is wrong because scope doesn't dictate parallelization. Option 4 is wrong because the default scope is 'function', but you can specify others.
From lesson: Test Isolation and State
What is the primary benefit of using the 'yield' keyword in a pytest fixture?
Answer: It converts the fixture into a generator, allowing for explicit teardown code after the test execution.. Option 2 is correct as it enables the cleanup phase. Option 1 is wrong because yield only yields once per fixture execution. Option 3 is wrong because yield has no effect on process isolation. Option 4 is wrong as it relates to mocking, not lifecycle management.
From lesson: Test Isolation and State
You have a test that modifies a configuration file. What should you do to ensure test isolation?
Answer: Use a fixture that copies the file to a temporary directory and restores it after the test.. Option 2 is the best practice using tmp_path/tmpdir to ensure no collateral damage. Option 1 is risky if the test crashes before reverting. Option 3 does not solve state corruption. Option 4 limits testing capability.
From lesson: Test Isolation and State
If Test A modifies a database and Test B checks the database count, why might they fail when running together but pass individually?
Answer: Because the tests are not isolated, and Test B is reading the side effects of Test A.. Option 2 is correct; shared state is the root cause of non-deterministic behavior. Option 1 is incorrect as this is a logic dependency, not an OS issue. Option 3 is nonsense. Option 4 is incorrect as scope is not the reason for test interdependence.
From lesson: Test Isolation and State
How does the 'tmp_path' fixture improve test isolation compared to using a hardcoded directory like '/tmp/test_dir'?
Answer: It ensures every test gets a unique subdirectory, preventing collisions and partial state contamination.. Option 2 is correct as unique paths per test are the key to isolation. Option 1 is false. Option 3 is false and dangerous. Option 4 is false as isolation is about logic independence, not security.
From lesson: Test Isolation and State
When implementing the AAA pattern, where should you place the primary logic that triggers the behavior under test?
Answer: Inside the Act section. The Act section is designated for calling the method or function being tested. Arrange is for setup, and Assert is for verification; putting the logic elsewhere violates the clear structure required for readability.
From lesson: Testing Patterns — AAA, Factory
What is the primary benefit of using a Factory pattern within a pytest suite?
Answer: To abstract complex object construction and reduce code duplication. Factories are used to encapsulate complex object creation, making tests cleaner. They do not replace fixtures, nor should they handle assertions, and they definitely shouldn't be used to manage database connections globally.
From lesson: Testing Patterns — AAA, Factory
If your 'Arrange' phase is becoming excessively long, what is the best practice to keep the test readable?
Answer: Create a dedicated fixture to handle the setup complexity. Fixtures allow you to move setup logic outside the test body, keeping it concise. Moving setup to Act or Assert ruins the test structure, and skipping Arrange is rarely possible in meaningful tests.
From lesson: Testing Patterns — AAA, Factory
Which of the following is a symptom that your AAA test is incorrectly structured?
Answer: You have multiple 'Act' calls separated by logic that should be in the setup. An AAA test should generally have one logical 'Act'. If you have multiple actions separated by setup-like logic, the test is likely doing too much and should be broken down into separate tests.
From lesson: Testing Patterns — AAA, Factory
Why should you avoid performing 'Assert' logic inside a factory function?
Answer: Because it couples the creation of test data to a specific verification outcome. Factories should be reusable for different scenarios. Assertions inside a factory lock that factory into one specific test case, which breaks the purpose of having a reusable creation helper.
From lesson: Testing Patterns — AAA, Factory
When designing a test suite, why is it considered better to use dependency injection via fixtures rather than calling setup/teardown functions directly?
Answer: It allows fixtures to manage their own scope and lifecycle automatically, preventing state leakage.. Fixture injection enables automatic setup/teardown and scoping (e.g., session vs. function). Calling functions directly leads to manual cleanup, which is error-prone. The other options are incorrect because fixtures don't affect order, don't necessarily increase speed, and don't restrict assertion usage.
From lesson: Testing Interview Questions
What is the primary benefit of using @pytest.mark.parametrize?
Answer: It allows you to run the same test logic against multiple datasets without duplicating code.. Parametrization promotes DRY (Don't Repeat Yourself) principles by separating data from logic. It does not automatically document code, mask errors, or magically improve coverage metrics.
From lesson: Testing Interview Questions
What happens if a test function has a yield fixture, and an exception is raised during the test?
Answer: The fixture teardown code after the yield will still execute.. Pytest guarantees that code after the 'yield' statement in a fixture executes regardless of whether the test passed or raised an exception. This is essential for proper resource cleanup. The other options describe incorrect behaviors.
From lesson: Testing Interview Questions
Which of the following describes the most effective way to test code that interacts with an external API?
Answer: Mock the network layer to return deterministic responses, ensuring the test is fast and independent.. Mocking external dependencies ensures tests are deterministic, fast, and independent of external service uptime. Real network calls make tests flaky, while hardcoding responses inside the test function mixes concerns.
From lesson: Testing Interview Questions
Why should you avoid having tests that are dependent on the execution order of other tests?
Answer: Because dependent tests make it impossible to run tests in parallel or in isolation.. Independent tests allow for parallel execution and allow you to run individual tests without running the entire suite. Options A, C, and D are factually incorrect regarding how the pytest runner works.
From lesson: Testing Interview Questions