Bird
Raised Fist0
PyTesttesting~10 mins

Mock and MagicMock in PyTest - Interactive Code Practice

Choose your learning style10 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.

Practice

(1/5)
1. What is the main difference between Mock and MagicMock in pytest?
easy
A. MagicMock supports special methods like __len__ and __getitem__, Mock does not.
B. Mock can only mock functions, while MagicMock can mock classes.
C. Mock is used for asynchronous code, MagicMock is not.
D. MagicMock is slower and less flexible than Mock.

Solution

  1. Step 1: Understand the purpose of Mock and MagicMock

    Mock creates fake objects for testing, but does not automatically support Python's special methods like __len__ or __getitem__.
  2. Step 2: Recognize MagicMock's special feature

    MagicMock extends Mock by including default implementations for many special methods, making it useful when those methods are called during tests.
  3. Final Answer:

    MagicMock supports special methods like __len__ and __getitem__, Mock does not. -> Option A
  4. Quick Check:

    Special methods = MagicMock [OK]
Hint: MagicMock handles special methods automatically [OK]
Common Mistakes:
  • Thinking Mock supports special methods by default
  • Confusing MagicMock as only for classes
  • Believing Mock is for async only
2. Which of the following is the correct way to create a MagicMock object in pytest?
easy
A. mock = MagicMock[]
B. mock = MagicMock()
C. mock = MagicMock
D. mock = MagicMock{}

Solution

  1. Step 1: Recall the syntax for creating instances in Python

    To create an instance of a class, you call it with parentheses, e.g., MagicMock().
  2. Step 2: Identify the correct syntax for MagicMock

    MagicMock is a class, so MagicMock() creates a new mock object. The other options use invalid syntax for instantiation.
  3. Final Answer:

    mock = MagicMock() -> Option B
  4. Quick Check:

    Instance creation uses parentheses () [OK]
Hint: Use parentheses () to create MagicMock instances [OK]
Common Mistakes:
  • Forgetting parentheses when creating mock objects
  • Using square or curly brackets instead of parentheses
  • Assigning class without instantiation
3. What will be the output of this pytest code snippet?
from unittest.mock import MagicMock
mock = MagicMock()
mock.__len__.return_value = 5
print(len(mock))
medium
A. 0
B. TypeError
C. 5
D. AttributeError

Solution

  1. Step 1: Understand MagicMock and special methods

    Setting mock.__len__.return_value = 5 tells the mock to return 5 when len() is called on it, because len() calls the __len__ method.
  2. Step 2: Predict the output of print(len(mock))

    Since __len__ is mocked to return 5, len(mock) will print 5.
  3. Final Answer:

    5 -> Option C
  4. Quick Check:

    len(mock) returns mocked __len__ value [OK]
Hint: Set __len__.return_value to mock len() calls [OK]
Common Mistakes:
  • Expecting default length 0 instead of mocked value
  • Confusing len(mock) with attribute access
  • Thinking TypeError occurs without __len__
4. Identify the error in this pytest mocking code:
from unittest.mock import Mock
mock = Mock()
mock.__getitem__.return_value = 'value'
print(mock[0])
medium
A. Mock does not support special methods like __getitem__ by default.
B. The syntax for setting return_value is incorrect.
C. You cannot use indexing on mock objects.
D. Missing import for MagicMock.

Solution

  1. Step 1: Check support for special methods in Mock

    Mock does not implement special methods like __getitem__ automatically, so setting mock.__getitem__.return_value has no effect on indexing.
  2. Step 2: Understand why the code fails

    Using mock[0] calls __getitem__, but since Mock does not handle it, this raises a TypeError. To mock indexing, use MagicMock.
  3. Final Answer:

    Mock does not support special methods like __getitem__ by default. -> Option A
  4. Quick Check:

    Special methods need MagicMock [OK]
Hint: Use MagicMock for special methods like indexing [OK]
Common Mistakes:
  • Assuming Mock supports all special methods
  • Confusing syntax errors with capability errors
  • Not importing MagicMock when needed
5. You want to test a function that calls obj.__str__() internally. Which mock object and setup will correctly simulate str(obj) returning 'mocked string'?
hard
A. Use mock = Mock() and set mock.str = 'mocked string'
B. Use mock = Mock() and set mock.__str__ = lambda: 'mocked string'
C. Use mock = MagicMock() and set mock.str.return_value = 'mocked string'
D. Use mock = MagicMock() and set mock.__str__.return_value = 'mocked string'

Solution

  1. Step 1: Identify the need to mock __str__ special method

    The str(obj) call internally uses the __str__ method, which is a special method.
  2. Step 2: Choose the correct mock and setup

    MagicMock supports special methods like __str__. Setting mock.__str__.return_value = 'mocked string' makes str(mock) return 'mocked string'.
  3. Step 3: Eliminate incorrect options

    Use mock = Mock() and set mock.__str__ = lambda: 'mocked string' uses Mock which does not support special methods by default. Options C and D use incorrect attribute names or types.
  4. Final Answer:

    Use mock = MagicMock() and set mock.__str__.return_value = 'mocked string' -> Option D
  5. Quick Check:

    Mock special methods with MagicMock and return_value [OK]
Hint: Set __str__.return_value on MagicMock for str() calls [OK]
Common Mistakes:
  • Using Mock instead of MagicMock for special methods
  • Setting wrong attribute names like str instead of __str__
  • Assigning string directly instead of return_value
Recommended

Ready to prove it?

Pass the test and this pattern moves unknown strong while earning +1 Grip toward your certificate.

10 questions~5 mineasy hard