Bird
0
0

You want to write a PyTest test that checks if a list nums contains only positive numbers. Which assert statement best uses PyTest's core mechanism to do this?

hard🚀 Application Q15 of 15
PyTest - Writing Assertions
You want to write a PyTest test that checks if a list nums contains only positive numbers. Which assert statement best uses PyTest's core mechanism to do this?
Aassert nums == [n for n in nums if n > 0]
Bassert nums > 0
Cassert len(nums) > 0
Dassert all(n > 0 for n in nums)
Step-by-Step Solution
Solution:
  1. Step 1: Understand the test goal

    The test should confirm every number in nums is greater than zero (positive).
  2. Step 2: Evaluate each assert option

    assert all(n > 0 for n in nums) uses all() with a generator to check all numbers are positive, which is correct. assert nums > 0 compares list to 0, invalid. assert len(nums) > 0 checks list length, not positivity. assert nums == [n for n in nums if n > 0] compares list to filtered list, which passes if all positive but less clear.
  3. Final Answer:

    assert all(n > 0 for n in nums) -> Option D
  4. Quick Check:

    Use all() to check every item condition [OK]
Quick Trick: Use all() with assert to check all items meet condition [OK]
Common Mistakes:
MISTAKES
  • Comparing list directly to a number
  • Checking only list length instead of values
  • Using filtered list equality which is less clear

Want More Practice?

15+ quiz questions · All difficulty levels · Free

Free Signup - Practice All Questions
More PyTest Quizzes