0
0
PyTesttesting~10 mins

Mock and MagicMock in PyTest - Interactive Code Practice

Choose your learning style9 modes available
Practice - 5 Tasks
Answer the questions below
1fill in blank
easy

Complete the code to create a mock object using unittest.mock.

PyTest
from unittest.mock import [1]

mock_obj = [1]()
Drag options to blanks, or click blank then click option'
AMock
BMagicMock
Cpatch
Dcall
Attempts:
3 left
💡 Hint
Common Mistakes
Using MagicMock when only a basic mock is needed.
Using patch instead of Mock to create a mock object.
2fill in blank
medium

Complete the code to assert that a mock method was called exactly once.

PyTest
mock_obj.method()

mock_obj.method.[1]()
Drag options to blanks, or click blank then click option'
Aassert_called
Bassert_called_once_with
Cassert_called_once
Dassert_not_called
Attempts:
3 left
💡 Hint
Common Mistakes
Using assert_called which only checks if called at least once.
Using assert_called_once_with which also checks call arguments.
3fill in blank
hard

Fix the error in the code to set a return value for a mock method.

PyTest
mock_obj = MagicMock()
mock_obj.get_data.[1] = 42
Drag options to blanks, or click blank then click option'
Aside_effect
Bvalue
Creturn
Dreturn_value
Attempts:
3 left
💡 Hint
Common Mistakes
Using 'return' which is a keyword, not an attribute.
Using 'side_effect' when only a fixed return value is needed.
4fill in blank
hard

Fill both blanks to patch a function and check it was called with specific arguments.

PyTest
from unittest.mock import patch

with patch('module.func') as mock_func:
    mock_func([1])
    mock_func.[2]('hello', 5)
Drag options to blanks, or click blank then click option'
A'hello', 5
Bassert_called_with
Cassert_called_once
D'test', 10
Attempts:
3 left
💡 Hint
Common Mistakes
Using assert_called_once which checks call count but not arguments.
Passing wrong arguments to the mock function call.
5fill in blank
hard

Fill all three blanks to create a MagicMock, set a side effect, and verify the exception is raised.

PyTest
from unittest.mock import MagicMock
import pytest

mock_func = MagicMock()
mock_func.side_effect = [1]

with pytest.raises([2]):
    mock_func([3])
Drag options to blanks, or click blank then click option'
AValueError
BException
Clambda x: (_ for _ in ()).throw(ValueError('error'))
D42
Attempts:
3 left
💡 Hint
Common Mistakes
Setting side_effect to an exception instance instead of a callable.
Using wrong exception type in pytest.raises.
Calling mock_func without arguments when side_effect expects one.