Bird
Raised Fist0
PyTesttesting~20 mins

Testing custom exceptions in PyTest - Practice Problems & Coding Challenges

Choose your learning style10 modes available
Challenge - 5 Problems
🎖️
Custom Exception Testing Master
Get all challenges correct to earn this badge!
Test your skills under time pressure!
❓ Predict Output
intermediate
2:00remaining
Output of pytest test for custom exception
What is the test result when running this pytest code that checks for a custom exception?
PyTest
import pytest

class MyError(Exception):
    pass

def func():
    raise MyError("fail")

def test_func_raises():
    with pytest.raises(MyError):
        func()
ATest fails with MyError uncaught
BTest fails with AssertionError
CTest passes with no errors
DTest raises TypeError during execution
Attempts:
2 left
💡 Hint
pytest.raises expects the specified exception to be raised inside the with block.
❓ assertion
intermediate
2:00remaining
Correct assertion to test exception message
Which assertion correctly tests that the exception message contains the word 'timeout'?
PyTest
import pytest

def func():
    raise TimeoutError("Connection timeout occurred")

def test_func():
    with pytest.raises(TimeoutError) as exc_info:
        func()
    # Which assertion below is correct here?
Aassert exc_info.value.args[0] == 'timeout'
Bassert 'timeout' in str(exc_info.value)
Cassert exc_info.value.message == 'timeout'
Dassert exc_info.message == 'timeout'
Attempts:
2 left
💡 Hint
Exception message is accessed by converting exc_info.value to string.
🔧 Debug
advanced
2:00remaining
Identify the error in this pytest exception test
Why does this pytest test fail with an error instead of passing?
PyTest
import pytest

class CustomError(Exception):
    pass

def func():
    raise CustomError("error")

def test_func():
    with pytest.raises(CustomError):
        func
Afunc is referenced without parentheses, so exception is never raised
Bpytest.raises expects a string, not an exception class
CCustomError is not derived from Exception
DThe exception message must be checked inside pytest.raises
Attempts:
2 left
💡 Hint
Check how func is called inside the with block.
🧠 Conceptual
advanced
2:00remaining
Why use custom exceptions in testing?
What is the main advantage of defining and testing custom exceptions in your code?
AThey make the code run faster by skipping error checks
BThey automatically fix bugs without extra code
CThey reduce the need for writing test cases
DThey allow more precise error handling and clearer test failure reasons
Attempts:
2 left
💡 Hint
Think about how custom exceptions help in identifying specific problems.
❓ framework
expert
2:00remaining
Best pytest pattern for testing multiple custom exceptions
You want to test that a function raises either CustomErrorA or CustomErrorB depending on input. Which pytest pattern correctly tests this in one test function?
AUse pytest.raises with a tuple of exceptions: with pytest.raises((CustomErrorA, CustomErrorB)): func(x)
BWrite two separate test functions, each with pytest.raises for one exception
CUse try-except inside the test and assert exception type manually
DUse pytest.raises with a list of exceptions: with pytest.raises([CustomErrorA, CustomErrorB]): func(x)
Attempts:
2 left
💡 Hint
Check pytest documentation for multiple exceptions in raises.

Practice

(1/5)
1. What is the main purpose of using pytest.raises() in testing custom exceptions?
easy
A. To check if a specific exception is raised during a function call
B. To skip a test when an exception occurs
C. To automatically fix exceptions in the code
D. To print the exception message to the console

Solution

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

    This function is used to verify that a specific exception is raised when running a block of code.
  2. Step 2: Identify the purpose in testing

    It helps confirm that error handling works as expected by catching the intended exception type.
  3. Final Answer:

    To check if a specific exception is raised during a function call -> Option A
  4. Quick Check:

    pytest.raises() checks exceptions [OK]
Hint: Remember: pytest.raises() tests if code throws an error [OK]
Common Mistakes:
  • Thinking pytest.raises() fixes errors
  • Using pytest.raises() to skip tests
  • Expecting pytest.raises() to print messages
2. Which of the following is the correct syntax to test if a function foo() raises a custom exception MyError using pytest?
easy
A. assert pytest.raises(MyError, foo)
B. pytest.raises(MyError, foo())
C. with pytest.raises(MyError): foo()
D. pytest.check_exception(MyError, foo())

Solution

  1. Step 1: Recall pytest.raises() usage

    The correct way is to use it as a context manager with with and call the function inside the block.
  2. Step 2: Analyze each option

    with pytest.raises(MyError): foo() uses the context manager correctly. Options B and C misuse the function call or assert. pytest.check_exception(MyError, foo()) uses a non-existent function.
  3. Final Answer:

    with pytest.raises(MyError): foo() -> Option C
  4. Quick Check:

    Use context manager with pytest.raises() [OK]
Hint: Use 'with pytest.raises(Exception):' before calling function [OK]
Common Mistakes:
  • Calling function inside pytest.raises() without 'with'
  • Using assert with pytest.raises() incorrectly
  • Using non-existent pytest functions
3. Given the code below, what will be the test result?
class MyError(Exception):
    pass

def func():
    raise MyError("Error happened")

def test_func():
    with pytest.raises(MyError) as exc_info:
        func()
    assert str(exc_info.value) == "Error happened"
medium
A. Test raises a syntax error
B. Test fails because the exception type is wrong
C. Test fails because the exception message is incorrect
D. Test passes because the exception and message match

Solution

  1. Step 1: Check exception type raised by func()

    func() raises MyError with message "Error happened".
  2. Step 2: Verify test assertions

    The test uses pytest.raises(MyError) to catch the exception and asserts the message matches exactly.
  3. Final Answer:

    Test passes because the exception and message match -> Option D
  4. Quick Check:

    Exception type and message match = pass [OK]
Hint: Match both exception type and message for success [OK]
Common Mistakes:
  • Ignoring exception message in assertion
  • Catching wrong exception type
  • Forgetting to call the function inside the context
4. Identify the error in the following pytest test for a custom exception:
def test_error():
    with pytest.raises(ValueError):
        raise TypeError("Wrong type")
medium
A. The test will pass because any exception is accepted
B. The test will fail because the raised exception type does not match the expected
C. The test has a syntax error due to missing colon
D. The test will raise an error because ValueError is not imported

Solution

  1. Step 1: Compare expected and raised exceptions

    The test expects a ValueError but raises a TypeError instead.
  2. Step 2: Understand pytest.raises() behavior

    pytest.raises() fails the test if the raised exception type does not match the expected one.
  3. Final Answer:

    The test will fail because the raised exception type does not match the expected -> Option B
  4. Quick Check:

    Exception type mismatch causes test failure [OK]
Hint: Expected and raised exception types must match exactly [OK]
Common Mistakes:
  • Assuming any exception passes the test
  • Ignoring exception type differences
  • Confusing syntax errors with logic errors
5. You have a custom exception MyError that can be raised with different messages. How can you write a pytest test that checks the exception is raised and the message contains the word "timeout" regardless of other text?
hard
A. Use with pytest.raises(MyError, match="timeout"): to match substring
B. Use with pytest.raises(MyError) as e: then assert str(e.value) == "timeout"
C. Use assertRaises(MyError, "timeout") to check message
D. Use pytest.raises(MyError, message_contains="timeout")

Solution

  1. Step 1: Recall pytest.raises() match parameter

    pytest.raises() accepts a match argument to check if the exception message matches a regex or substring.
  2. Step 2: Compare options for message checking

    with pytest.raises(MyError, match="timeout"): correctly uses the match parameter to verify the message contains "timeout". with pytest.raises(MyError) as e: followed by assert str(e.value) == "timeout" only checks for exact match, failing if there is extra text. Options C and D use invalid syntax.
  3. Final Answer:

    Use with pytest.raises(MyError, match="timeout"): -> Option A
  4. Quick Check:

    Use match parameter to check message substring [OK]
Hint: Use pytest.raises(..., match="text") to check message content [OK]
Common Mistakes:
  • Using exact match instead of substring check for the message
  • Using non-existent pytest.raises() parameters
  • Not checking message content at all
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