0
0
PyTesttesting~10 mins

Mock return values and side effects 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 set a mock's return value.

PyTest
from unittest.mock import Mock
mock_obj = Mock()
mock_obj.method.return_value = [1]
assert mock_obj.method() == 10
Drag options to blanks, or click blank then click option'
A10
B'10'
CNone
DFalse
Attempts:
3 left
💡 Hint
Common Mistakes
Using a string '10' instead of integer 10
Setting return_value to None
2fill in blank
medium

Complete the code to set a mock's side effect to raise an exception.

PyTest
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
Drag options to blanks, or click blank then click option'
AException('error')
BRuntimeError('error')
CValueError('error')
DTypeError('error')
Attempts:
3 left
💡 Hint
Common Mistakes
Using Exception instead of ValueError
Using a different exception type
3fill in blank
hard

Fix the error in setting a mock's side effect to return different values on each call.

PyTest
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
Drag options to blanks, or click blank then click option'
A1, 2, 3
B(1, 2, 3)
C{1, 2, 3}
D[1, 2, 3]
Attempts:
3 left
💡 Hint
Common Mistakes
Using a set which is unordered
Using a tuple which works but list is preferred for mutability
4fill in blank
hard

Fill both blanks to create a mock that returns 5 and then raises an exception on the second call.

PyTest
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
Drag options to blanks, or click blank then click option'
A5
BValueError('fail')
CValueError
DException('fail')
Attempts:
3 left
💡 Hint
Common Mistakes
Using exception type instead of instance in side_effect list
Mismatch between exception raised and caught
5fill in blank
hard

Fill all three blanks to create a mock that returns the length of input string, then raises TypeError, then returns 'done'.

PyTest
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'
Drag options to blanks, or click blank then click option'
ATypeError('wrong type')
BValueError('error')
Cdone
DTypeError
Attempts:
3 left
💡 Hint
Common Mistakes
Using exception type instead of instance in side_effect list
Mismatch between exception raised and caught