0
0
PyTesttesting~10 mins

Fixture finalization (request.addfinalizer) 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 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'
Aadd_cleanup
Bfinalize
Caddfinalizer
Dregister_finalizer
Attempts:
3 left
💡 Hint
Common Mistakes
Using 'finalize' instead of 'addfinalizer'.
Trying to call 'register_finalizer' which does not exist.
2fill in blank
medium

Complete 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'
Aaddfinalizer
Badd_cleanup
Cregister_cleanup
Dfinalize
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.
3fill in blank
hard

Fix 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'
Afinalize
Baddfinalizer
Cadd_cleanup
Dregister_finalizer
Attempts:
3 left
💡 Hint
Common Mistakes
Calling the finalizer function inside 'addfinalizer' instead of passing it.
Using a non-existent method like 'finalize'.
4fill in blank
hard

Fill 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'
Aaddfinalizer
Bclose
Cflush
Dfinalize
Attempts:
3 left
💡 Hint
Common Mistakes
Using 'flush' instead of 'close' to clean up the file.
Using 'finalize' which is not a pytest method.
5fill in blank
hard

Fill 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'
Aconnect
Baddfinalizer
Cdisconnect
Dfinalize
Attempts:
3 left
💡 Hint
Common Mistakes
Using 'finalize' instead of 'addfinalizer'.
Calling 'disconnect' immediately instead of passing it to 'addfinalizer'.