Practice - 5 Tasks
Answer the questions below
1fill in blank
easyComplete the code to replace the function using monkeypatch.setattr.
PyTest
def test_func(monkeypatch): def fake_return(): return 42 monkeypatch.setattr('module.func', [1]) assert module.func() == 42
Drag options to blanks, or click blank then click option'
Attempts:
3 left
💡 Hint
Common Mistakes
Passing the function name as a string instead of the function object.
Using the original function instead of the fake function.
✗ Incorrect
We use monkeypatch.setattr to replace 'module.func' with the fake_return function.
2fill in blank
mediumComplete the code to patch the attribute 'value' of the object using monkeypatch.setattr.
PyTest
class MyClass: value = 10 def test_value(monkeypatch): obj = MyClass() monkeypatch.setattr(obj, 'value', [1]) assert obj.value == 99
Drag options to blanks, or click blank then click option'
Attempts:
3 left
💡 Hint
Common Mistakes
Passing the old value 10 instead of the new value.
Passing the attribute name instead of the new value.
✗ Incorrect
We patch the attribute 'value' to be 99, so obj.value should equal 99.
3fill in blank
hardFix the error in the code to correctly patch the function using monkeypatch.setattr.
PyTest
def original(): return 'original' def fake(): return 'fake' def test_patch(monkeypatch): monkeypatch.setattr("original", [1]) assert original() == 'fake'
Drag options to blanks, or click blank then click option'
Attempts:
3 left
💡 Hint
Common Mistakes
Passing the function name as a string.
Passing the original function instead of the fake function.
✗ Incorrect
monkeypatch.setattr expects the target and the new value (function) to replace it. We pass the function fake without quotes.
4fill in blank
hardFill both blanks to patch the method 'get_data' of the class 'DataClass' to return 'mocked'.
PyTest
class DataClass: def get_data(self): return 'real' def test_data(monkeypatch): monkeypatch.setattr(DataClass, [1], [2]) obj = DataClass() assert obj.get_data() == 'mocked'
Drag options to blanks, or click blank then click option'
Attempts:
3 left
💡 Hint
Common Mistakes
Using wrong method name string.
Using lambda without self parameter.
✗ Incorrect
We patch the method 'get_data' with a lambda that takes self and returns 'mocked'.
5fill in blank
hardFill all three blanks to patch the function 'calculate' in module 'calc' to return 100 during the test.
PyTest
import calc def fake_calc(): return 100 def test_calculate(monkeypatch): monkeypatch.setattr(calc, [1], [2]) result = calc.calculate() assert result == [3]
Drag options to blanks, or click blank then click option'
Attempts:
3 left
💡 Hint
Common Mistakes
Passing function name without quotes.
Passing the function name as string instead of function object.
Asserting wrong expected value.
✗ Incorrect
We patch 'calculate' in calc module with fake_calc function and assert the result is 100.