0
0
PyTesttesting~10 mins

Handling shared resources 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 create a fixture that sets up a shared resource.

PyTest
import pytest

@pytest.fixture
 def shared_resource():
     resource = {'count': 0}
     yield resource
     resource.clear()

def test_increment(shared_resource):
     shared_resource['count'] [1] 1
     assert shared_resource['count'] == 1
Drag options to blanks, or click blank then click option'
A+=
B-=
C*=
D/=
Attempts:
3 left
💡 Hint
Common Mistakes
Using '-=' decreases the count, causing the test to fail.
Using '*=' or '/=' changes the count incorrectly.
2fill in blank
medium

Complete the code to ensure the shared resource is reset before each test.

PyTest
import pytest

@pytest.fixture(autouse=True)
 def reset_resource(shared_resource):
     shared_resource['count'] = [1]

def test_reset(shared_resource):
     assert shared_resource['count'] == 0
Drag options to blanks, or click blank then click option'
A1
B-1
C0
DNone
Attempts:
3 left
💡 Hint
Common Mistakes
Setting count to 1 causes the test to fail because the assertion expects 0.
Setting count to None or negative values is not appropriate here.
3fill in blank
hard

Fix the error in the test that modifies the shared resource incorrectly.

PyTest
def test_decrement(shared_resource):
     shared_resource['count'] [1] 1
     assert shared_resource['count'] == -1
Drag options to blanks, or click blank then click option'
A+=
B-=
C*=
D/=
Attempts:
3 left
💡 Hint
Common Mistakes
Using '+=' increases the count, causing the assertion to fail.
Using '*=' or '/=' changes the value incorrectly.
4fill in blank
hard

Fill both blanks to create a fixture that yields a resource and cleans it after use.

PyTest
import pytest

@pytest.fixture
 def resource():
     data = []
     yield [1]
     [2].clear()
Drag options to blanks, or click blank then click option'
Adata
Bresource
Attempts:
3 left
💡 Hint
Common Mistakes
Yielding or clearing a variable not defined causes errors.
Using different variable names for yield and clear breaks the cleanup.
5fill in blank
hard

Fill all three blanks to create a test that uses a shared resource and asserts its state.

PyTest
def test_shared_state([1]):
     [2]['count'] += 2
     assert [3]['count'] == 2
Drag options to blanks, or click blank then click option'
Ashared_resource
Dresource
Attempts:
3 left
💡 Hint
Common Mistakes
Using different names causes NameError or test failures.
Referencing undefined variables breaks the test.