Bird
0
0

Identify the error in this fixture code and how to fix it:

medium📝 Debug Q14 of 15
PyTest - Fixtures
Identify the error in this fixture code and how to fix it:
import pytest

@pytest.fixture
def resource():
    setup = open('file.txt')
    yield setup
    setup.close()
AFile 'file.txt' may not exist causing runtime error
BNo error; code is correct
CMissing parentheses in yield statement
DFixture must return value, not yield
Step-by-Step Solution
Solution:
  1. Step 1: Analyze fixture code

    The fixture opens a file and yields the file object, then closes it after test.
  2. Step 2: Identify potential runtime issue

    If 'file.txt' does not exist, open() will raise an error before yield. This is a runtime error, not syntax.
  3. Final Answer:

    File 'file.txt' may not exist causing runtime error -> Option A
  4. Quick Check:

    File open can fail if file missing [OK]
Quick Trick: Check external resources exist before opening in fixture [OK]
Common Mistakes:
MISTAKES
  • Thinking yield needs parentheses
  • Believing fixtures cannot use yield
  • Ignoring file existence errors

Want More Practice?

15+ quiz questions · All difficulty levels · Free

Free Signup - Practice All Questions
More PyTest Quizzes