0
0
PyTesttesting~10 mins

Context manager fixtures 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 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'
Aresource_manager
Bopen_resource
Ccontextlib.contextmanager
Dsetup_resource
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.
2fill in blank
medium

Complete 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'
Acontext
Bsetup
Cresource
Dmanager
Attempts:
3 left
💡 Hint
Common Mistakes
Using a different argument name than the fixture.
Not passing the fixture as a parameter.
3fill in blank
hard

Fix 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'
Ares.cleanup()
Bres.open()
Cclose(res)
Dres.close()
Attempts:
3 left
💡 Hint
Common Mistakes
Calling open() instead of close().
Using a non-existent cleanup method.
Not closing the resource at all.
4fill in blank
hard

Fill 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'
Afixture
Bcontextmanager
Ccontextmanager_decorator
Dfixture_decorator
Attempts:
3 left
💡 Hint
Common Mistakes
Mixing up decorators.
Using incorrect decorator names.
Not returning the context manager.
5fill in blank
hard

Fill 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'
Aresource
C'resource'
D'value'
Attempts:
3 left
💡 Hint
Common Mistakes
Using a wrong fixture name.
Not using 'with' statement properly.
Asserting incorrect value.