Practice - 5 Tasks
Answer the questions below
1fill in blank
easyComplete the code to add a finalizer function that prints 'Cleanup done' after the test.
PyTest
def test_example(request): def cleanup(): print('Cleanup done') request.[1](cleanup) assert True
Drag options to blanks, or click blank then click option'
Attempts:
3 left
💡 Hint
Common Mistakes
Using 'finalize' instead of 'addfinalizer'.
Trying to call 'register_finalizer' which does not exist.
✗ Incorrect
The correct method to add a finalizer in pytest fixtures is 'addfinalizer'.
2fill in blank
mediumComplete the fixture code to add a finalizer that closes the resource after the test.
PyTest
import pytest @pytest.fixture def resource(request): res = open('file.txt') request.[1](res.close) return res
Drag options to blanks, or click blank then click option'
Attempts:
3 left
💡 Hint
Common Mistakes
Using 'finalize' which is not a pytest method.
Trying to use 'add_cleanup' which does not exist in pytest.
✗ Incorrect
Use 'addfinalizer' to register the resource's close method for cleanup after the test.
3fill in blank
hardFix the error in the fixture by correctly adding a finalizer that prints 'Done' after the test.
PyTest
import pytest @pytest.fixture def sample(request): def fin(): print('Done') request.[1](fin) return 42
Drag options to blanks, or click blank then click option'
Attempts:
3 left
💡 Hint
Common Mistakes
Calling the finalizer function inside 'addfinalizer' instead of passing it.
Using a non-existent method like 'finalize'.
✗ Incorrect
The finalizer function should be passed without calling it. Use 'addfinalizer(fin)' not 'addfinalizer(fin())'.
4fill in blank
hardFill both blanks to create a fixture that opens a file and adds a finalizer to close it after the test.
PyTest
import pytest @pytest.fixture def file_resource(request): f = open('data.txt') request.[1](f.[2]) return f
Drag options to blanks, or click blank then click option'
Attempts:
3 left
💡 Hint
Common Mistakes
Using 'flush' instead of 'close' to clean up the file.
Using 'finalize' which is not a pytest method.
✗ Incorrect
Use 'addfinalizer' to register the 'close' method of the file for cleanup.
5fill in blank
hardFill all three blanks to create a fixture that sets up a database connection, adds a finalizer to disconnect, and returns the connection.
PyTest
import pytest class DBConnection: def connect(self): print('Connected') def disconnect(self): print('Disconnected') @pytest.fixture def db(request): conn = DBConnection() conn.[1]() request.[2](conn.[3]) return conn
Drag options to blanks, or click blank then click option'
Attempts:
3 left
💡 Hint
Common Mistakes
Using 'finalize' instead of 'addfinalizer'.
Calling 'disconnect' immediately instead of passing it to 'addfinalizer'.
✗ Incorrect
Call 'connect' to set up, use 'addfinalizer' to register 'disconnect' for cleanup.