Bird
Raised Fist0
PyTesttesting~15 mins

pytest.raises context manager - Build an Automation Script

Choose your learning style10 modes available
Verify that dividing by zero raises a ZeroDivisionError
Preconditions (2)
Step 1: Write a function that divides two numbers
Step 2: Call the function with divisor as zero inside pytest.raises context manager
Step 3: Check that ZeroDivisionError is raised
✅ Expected Result: Test passes confirming ZeroDivisionError is raised when dividing by zero
Automation Requirements - pytest
Assertions Needed:
Verify ZeroDivisionError is raised when divisor is zero
Best Practices:
Use pytest.raises as a context manager
Keep test function simple and focused
Do not catch exceptions manually inside the test
Automated Solution
PyTest
import pytest

def divide(a, b):
    return a / b

def test_divide_by_zero_raises():
    with pytest.raises(ZeroDivisionError):
        divide(10, 0)

The divide function simply divides two numbers.

The test test_divide_by_zero_raises uses pytest.raises as a context manager to check that calling divide(10, 0) raises a ZeroDivisionError.

This is the correct way to test exceptions in pytest because it clearly shows the expected error and keeps the test clean.

Common Mistakes - 3 Pitfalls
Catching the exception manually with try-except inside the test
Not specifying the exception type in pytest.raises
Placing code outside the pytest.raises block that raises the exception
Bonus Challenge

Now add data-driven testing with 3 different pairs of inputs where division by zero should raise ZeroDivisionError

Show Hint

Practice

(1/5)
1. What is the main purpose of using pytest.raises in a test?
easy
A. To skip a test when an error occurs
B. To check if a specific error is raised by the code inside the block
C. To automatically fix errors in the tested code
D. To print error messages during test execution

Solution

  1. Step 1: Understand the role of pytest.raises

    pytest.raises is used to verify that a certain error is raised when running code inside its context.
  2. Step 2: Compare options with this purpose

    Only To check if a specific error is raised by the code inside the block correctly states that pytest.raises checks for expected errors. Other options describe unrelated behaviors.
  3. Final Answer:

    To check if a specific error is raised by the code inside the block -> Option B
  4. Quick Check:

    pytest.raises checks errors = A [OK]
Hint: Remember: pytest.raises expects an error inside its with block [OK]
Common Mistakes:
  • Thinking pytest.raises fixes errors automatically
  • Confusing pytest.raises with test skipping
  • Using pytest.raises to print errors
2. Which of the following is the correct syntax to use pytest.raises to check for a ValueError?
easy
A. with pytest.raises(ValueError):\n function_call()
B. pytest.raises(ValueError):\nfunction_call()
C. with pytest.raises('ValueError'):\n function_call()
D. pytest.raises(ValueError)\n function_call()

Solution

  1. Step 1: Recall correct context manager syntax

    pytest.raises must be used with the with keyword and the exception class without quotes.
  2. Step 2: Evaluate each option

    with pytest.raises(ValueError):\n function_call() correctly uses with pytest.raises(ValueError):. Options A and B miss the with keyword. with pytest.raises('ValueError'):\n function_call() incorrectly uses quotes around the exception.
  3. Final Answer:

    with pytest.raises(ValueError):\n function_call() -> Option A
  4. Quick Check:

    Use with + exception class (no quotes) = D [OK]
Hint: Always use 'with' and exception class without quotes [OK]
Common Mistakes:
  • Omitting the 'with' keyword
  • Putting exception name in quotes
  • Not indenting code inside the block
3. What will be the result of this test code?
import pytest

def test_divide():
    with pytest.raises(ZeroDivisionError):
        x = 1 / 0
medium
A. Test fails because no error is raised
B. Test passes but warns about division
C. Test fails due to syntax error
D. Test passes because ZeroDivisionError is raised

Solution

  1. Step 1: Analyze the code inside pytest.raises

    The code divides 1 by 0, which raises a ZeroDivisionError as expected.
  2. Step 2: Understand pytest.raises behavior

    Since the expected error occurs, pytest.raises catches it and the test passes.
  3. Final Answer:

    Test passes because ZeroDivisionError is raised -> Option D
  4. Quick Check:

    Expected error raised = test passes = B [OK]
Hint: If expected error occurs inside with block, test passes [OK]
Common Mistakes:
  • Thinking test fails when error is raised
  • Confusing ZeroDivisionError with other exceptions
  • Assuming syntax error without checking code
4. Identify the error in this test code using pytest.raises:
import pytest

def test_key_error():
    with pytest.raises(KeyError):
    d = {'a': 1}
    x = d['b']
medium
A. Indentation error inside the with block
B. Wrong exception type used
C. Missing import of pytest
D. No error; code is correct

Solution

  1. Step 1: Check indentation inside the with block

    The lines inside the with block must be indented. Here, d = {'a': 1} and x = d['b'] are not indented properly.
  2. Step 2: Verify other aspects

    pytest is imported, and KeyError is the correct exception for missing key access. So no other errors.
  3. Final Answer:

    Indentation error inside the with block -> Option A
  4. Quick Check:

    Indent code inside with block = C [OK]
Hint: Indent all code inside the with block properly [OK]
Common Mistakes:
  • Not indenting code inside the with block
  • Using wrong exception type
  • Forgetting to import pytest
5. You want to test a function parse_int(s) that should raise ValueError when given a non-integer string. Which of these test snippets correctly uses pytest.raises to check this behavior and also verifies the error message contains 'invalid'?
hard
A. with pytest.raises('ValueError') as e: parse_int('abc') assert 'invalid' in e
B. with pytest.raises(ValueError): parse_int('abc') assert 'invalid' in str(ValueError)
C. with pytest.raises(ValueError) as excinfo: parse_int('abc') assert 'invalid' in str(excinfo.value)
D. pytest.raises(ValueError): parse_int('abc') assert 'invalid' in str(excinfo.value)

Solution

  1. Step 1: Use pytest.raises as context manager with 'as' to capture exception info

    with pytest.raises(ValueError) as excinfo: parse_int('abc') assert 'invalid' in str(excinfo.value) correctly uses as excinfo to capture the exception object for later inspection.
  2. Step 2: Check the error message from excinfo.value

    with pytest.raises(ValueError) as excinfo: parse_int('abc') assert 'invalid' in str(excinfo.value) asserts that 'invalid' is in the string form of the exception value, which is the correct way to check the error message.
  3. Final Answer:

    with pytest.raises(ValueError) as excinfo: parse_int('abc') assert 'invalid' in str(excinfo.value) -> Option C
  4. Quick Check:

    Use 'as excinfo' and check excinfo.value message = A [OK]
Hint: Use 'as excinfo' to check error message inside pytest.raises [OK]
Common Mistakes:
  • Putting exception name in quotes
  • Not capturing exception info with 'as'
  • Checking error message outside the context incorrectly
Recommended

Ready to prove it?

Pass the test and this pattern moves unknown strong while earning +1 Grip toward your certificate.

10 questions~5 mineasy hard