Practice - 5 Tasks
Answer the questions below
1fill in blank
easyComplete 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'
Attempts:
3 left
💡 Hint
Common Mistakes
Using 'patch' which is from unittest.mock, not monkeypatch.
Using 'replace' which is not a valid monkeypatch method.
✗ Incorrect
The monkeypatch.setattr method replaces an attribute or function for the test.
2fill in blank
mediumComplete 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'
Attempts:
3 left
💡 Hint
Common Mistakes
Using 'setattr' which patches attributes, not environment variables.
Using 'patchenv' which does not exist.
✗ Incorrect
monkeypatch.setenv sets an environment variable temporarily for the test.
3fill in blank
hardFix 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'
Attempts:
3 left
💡 Hint
Common Mistakes
Using 'setattr' which works on object attributes, not dict keys.
Using 'setenv' which is for environment variables.
✗ Incorrect
monkeypatch.setitem patches dictionary keys temporarily.
4fill in blank
hardFill 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'
Attempts:
3 left
💡 Hint
Common Mistakes
Using 'setitem' to patch a function (wrong for attributes).
Using '>=' instead of '==' for exact call count.
✗ Incorrect
Use setattr to patch the function and == to assert exact call count.
5fill in blank
hardFill 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'
Attempts:
3 left
💡 Hint
Common Mistakes
Using 'patch' which is not a monkeypatch method.
Mixing up 'setattr' and 'setitem' for objects and dicts.
✗ Incorrect
Use setenv for environment variables, setattr for object attributes, and setitem for dictionary keys.