Bird
0
0

Which is the correct way to write this conditional parametrize in pytest?

hard🚀 Application Q15 of 15
PyTest - Parametrize
You want to run a test with parameters mode set to 'fast', 'slow', and 'medium'. However, you want to skip the 'slow' mode test only if an environment variable SKIP_SLOW is set to '1'. Which is the correct way to write this conditional parametrize in pytest?
Aimport os @pytest.mark.parametrize('mode', [ 'fast', pytest.param('slow', marks=pytest.mark.skipif('os.getenv("SKIP_SLOW") == "1"')), 'medium' ])
Bimport os @pytest.mark.parametrize('mode', [ 'fast', pytest.param('slow', skipif=os.getenv('SKIP_SLOW') == '1'), 'medium' ])
Cimport os @pytest.mark.parametrize('mode', [ 'fast', pytest.param('slow', marks=pytest.skipif(os.getenv('SKIP_SLOW') == '1')), 'medium' ])
Dimport os @pytest.mark.parametrize('mode', [ 'fast', pytest.param('slow', marks=pytest.mark.skipif(os.getenv('SKIP_SLOW') == '1', reason='Skip slow mode')), 'medium' ])
Step-by-Step Solution
Solution:
  1. Step 1: Use os.getenv to check environment variable

    os.getenv('SKIP_SLOW') returns the value of the environment variable as a string.
  2. Step 2: Apply skipif mark correctly

    Use pytest.mark.skipif with a boolean condition and a reason inside marks parameter of pytest.param.
  3. Step 3: Verify syntax correctness

    import os @pytest.mark.parametrize('mode', [ 'fast', pytest.param('slow', marks=pytest.mark.skipif(os.getenv('SKIP_SLOW') == '1', reason='Skip slow mode')), 'medium' ]) correctly uses marks=pytest.mark.skipif(condition, reason='...') and imports os.
  4. Final Answer:

    import os @pytest.mark.parametrize('mode', [ 'fast', pytest.param('slow', marks=pytest.mark.skipif(os.getenv('SKIP_SLOW') == '1', reason='Skip slow mode')), 'medium' ]) -> Option D
  5. Quick Check:

    Use marks=pytest.mark.skipif with env check and reason [OK]
Quick Trick: Use os.getenv and marks=pytest.mark.skipif with reason to skip params [OK]
Common Mistakes:
MISTAKES
  • Passing skipif as direct argument instead of marks
  • Using string condition instead of boolean
  • Omitting reason in skipif mark

Want More Practice?

15+ quiz questions · All difficulty levels · Free

Free Signup - Practice All Questions
More PyTest Quizzes