0
0
PyTesttesting~10 mins

monkeypatch fixture 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 patch the function using monkeypatch.

PyTest
def test_example(monkeypatch):
    def fake_return():
        return 42
    monkeypatch.[1]('module.function', fake_return)
    assert module.function() == 42
Drag options to blanks, or click blank then click option'
Apatch
Bsetattr
Creplace
Dmock
Attempts:
3 left
💡 Hint
Common Mistakes
Using 'patch' which is from unittest.mock, not monkeypatch.
Using 'replace' which is not a valid monkeypatch method.
2fill in blank
medium

Complete the code to patch an environment variable using monkeypatch.

PyTest
def test_env(monkeypatch):
    monkeypatch.[1]('ENV_VAR', 'test_value')
    assert os.getenv('ENV_VAR') == 'test_value'
Drag options to blanks, or click blank then click option'
Asetenv
Bsetattr
Cpatchenv
Dmockenv
Attempts:
3 left
💡 Hint
Common Mistakes
Using 'setattr' which patches attributes, not environment variables.
Using 'patchenv' which does not exist.
3fill in blank
hard

Fix the error in patching a dictionary key using monkeypatch.

PyTest
def test_dict(monkeypatch):
    config = {'key': 'original'}
    monkeypatch.[1](config, 'key', 'patched')
    assert config['key'] == 'patched'
Drag options to blanks, or click blank then click option'
Asetenv
Bsetattr
Cpatchitem
Dsetitem
Attempts:
3 left
💡 Hint
Common Mistakes
Using 'setattr' which works on object attributes, not dict keys.
Using 'setenv' which is for environment variables.
4fill in blank
hard

Fill both blanks to patch a function and check its call count.

PyTest
def test_call_count(monkeypatch):
    calls = {'count': 0}
    def fake_func():
        calls['count'] += 1
    monkeypatch.[1]('module.func', fake_func)
    module.func()
    assert calls['count'] [2] 1
Drag options to blanks, or click blank then click option'
Asetattr
B==
C>=
Dsetitem
Attempts:
3 left
💡 Hint
Common Mistakes
Using 'setitem' to patch a function (wrong for attributes).
Using '>=' instead of '==' for exact call count.
5fill in blank
hard

Fill all three blanks to patch environment, attribute, and dictionary key correctly.

PyTest
def test_all(monkeypatch):
    monkeypatch.[1]('ENV', 'value')
    class Obj:
        attr = 5
    obj = Obj()
    monkeypatch.[2](obj, 'attr', 10)
    data = {'key': 'old'}
    monkeypatch.[3](data, 'key', 'new')
    assert os.getenv('ENV') == 'value'
    assert obj.attr == 10
    assert data['key'] == 'new'
Drag options to blanks, or click blank then click option'
Asetenv
Bsetattr
Csetitem
Dpatch
Attempts:
3 left
💡 Hint
Common Mistakes
Using 'patch' which is not a monkeypatch method.
Mixing up 'setattr' and 'setitem' for objects and dicts.