Complete the code to set a mock's return value.
from unittest.mock import Mock mock_obj = Mock() mock_obj.method.return_value = [1] assert mock_obj.method() == 10
The return_value sets what the mock method returns. Here, it should be the integer 10, not a string.
Complete the code to set a mock's side effect to raise an exception.
from unittest.mock import Mock mock_obj = Mock() mock_obj.method.side_effect = [1] try: mock_obj.method() except ValueError: caught = True else: caught = False assert caught is True
The side_effect can be set to an exception instance to make the mock raise it when called. The test expects a ValueError.
Fix the error in setting a mock's side effect to return different values on each call.
from unittest.mock import Mock mock_obj = Mock() mock_obj.method.side_effect = [1] assert mock_obj.method() == 1 assert mock_obj.method() == 2 assert mock_obj.method() == 3
The side_effect can be set to a list to return each value on successive calls. A list preserves order and allows repeated calls.
Fill both blanks to create a mock that returns 5 and then raises an exception on the second call.
from unittest.mock import Mock mock_obj = Mock() mock_obj.method.side_effect = [[1], [2]] assert mock_obj.method() == 5 try: mock_obj.method() except ValueError: caught = True else: caught = False assert caught is True
The side_effect list must have the return value 5 first, then the exception instance. The except block catches the exception type, which is ValueError.
Fill all three blanks to create a mock that returns the length of input string, then raises TypeError, then returns 'done'.
from unittest.mock import Mock mock_obj = Mock() mock_obj.method.side_effect = [lambda s: len(s), [1], [2]] assert mock_obj.method('test') == 4 try: mock_obj.method('fail') except [3]: caught = True else: caught = False assert caught is True assert mock_obj.method('end') == 'done'
The side_effect list has a lambda returning length, then a TypeError instance, then a string 'done'. The except block catches TypeError type.