0
0
PyTesttesting~5 mins

pytest-mock for enhanced mocking - Cheat Sheet & Quick Revision

Choose your learning style9 modes available
Recall & Review
beginner
What is pytest-mock and why is it useful?
pytest-mock is a plugin for pytest that simplifies mocking in tests by providing a mocker fixture. It helps replace parts of your system under test with mock objects easily and cleanly.
Click to reveal answer
beginner
How do you use the mocker fixture in a pytest test function?
You add mocker as a parameter to your test function. Then use mocker.patch() to replace a function or object with a mock during the test.
Click to reveal answer
intermediate
What is the difference between mocker.patch and unittest.mock.patch?
mocker.patch is a pytest-mock wrapper around unittest.mock.patch. It integrates better with pytest, automatically cleans up mocks after tests, and provides simpler syntax.
Click to reveal answer
intermediate
How does pytest-mock help with test cleanup?
pytest-mock automatically undoes all patches after each test, so you don't need to manually stop or reset mocks. This prevents side effects between tests.
Click to reveal answer
beginner
Give an example of mocking a function using pytest-mock.
Example: ```python def test_example(mocker): mock_func = mocker.patch('module.function_to_mock') mock_func.return_value = 42 result = module.function_to_mock() assert result == 42 ```
Click to reveal answer
What is the main benefit of using pytest-mock over unittest.mock directly?
ARequires no imports
BAutomatic cleanup of mocks after each test
CSupports only Python 2
DFaster test execution
How do you apply a mock patch using pytest-mock?
AUse mocker.mock('target')
BCall unittest.mock.patch directly without parameters
CUse mocker.patch('target') inside a test function with mocker parameter
DAdd @patch decorator to the test function
What does mocker.patch return?
AA mock object replacing the target
BThe original function
CA boolean indicating success
DNone
Which of these is true about pytest-mock's mocker fixture?
AIt is automatically available when pytest-mock is installed
BIt must be imported manually in each test file
CIt only works with unittest tests
DIt disables all mocks after the test
If you want to mock a method 'foo' in class 'Bar' in module 'baz', what is the correct patch target string?
A'baz.foo.Bar'
B'Bar.foo'
C'foo.Bar.baz'
D'baz.Bar.foo'
Explain how pytest-mock simplifies mocking in pytest tests.
Think about how mocker.patch works and test cleanup.
You got /4 concepts.
    Describe the steps to mock a function using pytest-mock and verify its return value.
    Consider a simple example mocking a function to return a fixed value.
    You got /4 concepts.