0
0
PyTesttesting~10 mins

monkeypatch.setattr 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 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'
Afunc
Bmodule.func
Creturn 42
Dfake_return
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.
2fill in blank
medium

Complete 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'
A99
B10
C'value'
Dobj.value
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.
3fill in blank
hard

Fix 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'
A'fake'
Bfake
C'original'
Doriginal
Attempts:
3 left
💡 Hint
Common Mistakes
Passing the function name as a string.
Passing the original function instead of the fake function.
4fill in blank
hard

Fill 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'
A'get_data'
Blambda self: 'mocked'
C'getData'
Dlambda: 'mocked'
Attempts:
3 left
💡 Hint
Common Mistakes
Using wrong method name string.
Using lambda without self parameter.
5fill in blank
hard

Fill 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'
A'calculate'
Bfake_calc
C100
D'calc'
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.