0
0
PyTesttesting~10 mins

monkeypatch.setenv 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 an environment variable using monkeypatch.

PyTest
def test_env_var(monkeypatch):
    monkeypatch.[1]('MY_VAR', '123')
    import os
    assert os.getenv('MY_VAR') == '123'
Drag options to blanks, or click blank then click option'
Aset_env
Bsetenv_var
Csetenv
Dset_environment
Attempts:
3 left
💡 Hint
Common Mistakes
Using incorrect method names like set_env or set_environment.
Trying to set environment variables without monkeypatch.
2fill in blank
medium

Complete the code to check that the environment variable is changed inside the test.

PyTest
def test_change_env(monkeypatch):
    monkeypatch.setenv('PATH', '/tmp')
    import os
    assert os.getenv('PATH') == [1]
Drag options to blanks, or click blank then click option'
A'/tmp'
B'/var/log'
C'/home/user'
D'/usr/bin'
Attempts:
3 left
💡 Hint
Common Mistakes
Expecting the original PATH value instead of the patched one.
Using incorrect string quotes.
3fill in blank
hard

Fix the error in the code to correctly set the environment variable using monkeypatch.

PyTest
def test_fix_env(monkeypatch):
    monkeypatch.[1]('DEBUG', 'True')
    import os
    assert os.getenv('DEBUG') == 'True'
Drag options to blanks, or click blank then click option'
Asetenv_var
Bset_env_var
Cset_environment
Dsetenv
Attempts:
3 left
💡 Hint
Common Mistakes
Using incorrect method names that cause AttributeError.
Forgetting to import monkeypatch fixture.
4fill in blank
hard

Fill both blanks to set and then delete an environment variable using monkeypatch.

PyTest
def test_set_and_delete(monkeypatch):
    monkeypatch.[1]('TEMP_VAR', 'value')
    monkeypatch.[2]('TEMP_VAR', raising=False)
    import os
    assert os.getenv('TEMP_VAR') is None
Drag options to blanks, or click blank then click option'
Asetenv
Bdelenv
Cunsetenv
Dremoveenv
Attempts:
3 left
💡 Hint
Common Mistakes
Using unsetenv or removeenv which are not monkeypatch methods.
Not passing raising=False to delenv to avoid errors if variable missing.
5fill in blank
hard

Fill all three blanks to set an environment variable, check its value, and then delete it using monkeypatch.

PyTest
def test_full_env(monkeypatch):
    monkeypatch.[1]('API_KEY', 'abc123')
    import os
    assert os.getenv([2]) == 'abc123'
    monkeypatch.[3]('API_KEY', raising=False)
    assert os.getenv('API_KEY') is None
Drag options to blanks, or click blank then click option'
Asetenv
B'API_KEY'
Cdelenv
D'api_key'
Attempts:
3 left
💡 Hint
Common Mistakes
Using wrong case for environment variable name.
Forgetting to delete the variable after test.