Practice - 5 Tasks
Answer the questions below
1fill in blank
easyComplete the code to define a pytest fixture using a context manager.
PyTest
import pytest @pytest.fixture def resource(): with [1]() as res: yield res
Drag options to blanks, or click blank then click option'
Attempts:
3 left
💡 Hint
Common Mistakes
Using a function that is not a context manager.
Forgetting to use 'with' statement.
Yielding without a context manager.
✗ Incorrect
The fixture uses a context manager called 'resource_manager' to manage the resource lifecycle.
2fill in blank
mediumComplete the code to use the fixture in a test function.
PyTest
def test_example([1]): assert resource.is_active()
Drag options to blanks, or click blank then click option'
Attempts:
3 left
💡 Hint
Common Mistakes
Using a different argument name than the fixture.
Not passing the fixture as a parameter.
✗ Incorrect
The test function receives the fixture named 'resource' as an argument to use it.
3fill in blank
hardFix the error in the fixture to properly close the resource after the test.
PyTest
import pytest @pytest.fixture def resource(): res = open_resource() yield res [1]
Drag options to blanks, or click blank then click option'
Attempts:
3 left
💡 Hint
Common Mistakes
Calling open() instead of close().
Using a non-existent cleanup method.
Not closing the resource at all.
✗ Incorrect
After yielding the resource, calling 'res.close()' ensures proper cleanup.
4fill in blank
hardFill both blanks to create a fixture that uses contextlib.contextmanager.
PyTest
import pytest import contextlib @[1] def resource(): @contextlib.[2] def manager(): print('setup') yield 'resource' print('teardown') return manager()
Drag options to blanks, or click blank then click option'
Attempts:
3 left
💡 Hint
Common Mistakes
Mixing up decorators.
Using incorrect decorator names.
Not returning the context manager.
✗ Incorrect
The fixture is decorated with '@pytest.fixture' and the inner function with '@contextlib.contextmanager'.
5fill in blank
hardFill all three blanks to write a test using the context manager fixture and assert the resource value.
PyTest
def test_resource_value([1]): with [2] as res: assert res == [3]
Drag options to blanks, or click blank then click option'
Attempts:
3 left
💡 Hint
Common Mistakes
Using a wrong fixture name.
Not using 'with' statement properly.
Asserting incorrect value.
✗ Incorrect
The test uses the fixture 'resource', enters its context with 'with resource as res', and asserts the value is 'resource'.