Bird
0
0

Identify the error in this pytest fixture usage:

medium📝 Debug Q14 of 15
PyTest - Fixtures
Identify the error in this pytest fixture usage:
import pytest

@pytest.fixture
def resource():
    return open('file.txt', 'r')

def test_read(resource):
    data = resource.read()
    assert data != ''
    resource.close()
AThe fixture should close the file after test automatically
BThe fixture is missing the @pytest.fixture decorator
CThe test should not use the fixture as a parameter
DThe assert statement is invalid syntax
Step-by-Step Solution
Solution:
  1. Step 1: Analyze resource fixture and test

    The fixture opens a file but does not close it. The test closes it manually.
  2. Step 2: Understand best practice for cleanup

    Fixtures should handle cleanup automatically using yield or finalizers to avoid resource leaks if test fails before close.
  3. Final Answer:

    The fixture should close the file after test automatically -> Option A
  4. Quick Check:

    Fixtures manage setup and cleanup [OK]
Quick Trick: Use fixture finalizers or yield for cleanup [OK]
Common Mistakes:
MISTAKES
  • Not closing resources in fixtures
  • Closing resources only in tests
  • Ignoring cleanup causing leaks

Want More Practice?

15+ quiz questions · All difficulty levels · Free

Free Signup - Practice All Questions
More PyTest Quizzes