Bird
0
0

You want to create a pytest fixture that opens a file before a test and closes it after. Which fixture code correctly uses yield for this purpose?

hard🚀 Application Q15 of 15
PyTest - Fixtures
You want to create a pytest fixture that opens a file before a test and closes it after. Which fixture code correctly uses yield for this purpose?
Adef file_fixture(): yield open('data.txt') f.close()
Bdef file_fixture(): f = open('data.txt') yield f f.close()
Cdef file_fixture(): f = open('data.txt') f.close() yield f
Ddef file_fixture(): f = open('data.txt') yield f.close()
Step-by-Step Solution
Solution:
  1. Step 1: Open file before yield and yield file object

    def file_fixture(): f = open('data.txt') yield f f.close() opens the file, yields the file object to the test, allowing test to use it.
  2. Step 2: Close file after yield

    After test finishes, code after yield closes the file, ensuring cleanup.
  3. Final Answer:

    def file_fixture(): f = open('data.txt') yield f f.close() -> Option B
  4. Quick Check:

    Open before yield, yield resource, close after yield [OK]
Quick Trick: Yield resource to test, cleanup after yield [OK]
Common Mistakes:
MISTAKES
  • Closing file before yield
  • Yielding without resource variable
  • Not closing file after test

Want More Practice?

15+ quiz questions · All difficulty levels · Free

Free Signup - Practice All Questions
More PyTest Quizzes