如何使用Pytest检测自定义异常抛出?(含具体代码场景)
convert_file Function with Pytest I get it, as a Pytest newbie it's easy to trip up on exception testing—let's fix this for you. Your convert_file function raises a generic Exception with a specific message when given a non-list input, and we need to verify both that the exception is thrown and that the message is correct.
First, let's break down why your previous attempts failed:
- If you just called
convert_file("some string")without wrapping it inpytest.raises, Pytest will treat the uncaught exception as a test failure (which makes sense—you have to explicitly tell Pytest you expect that exception to occur). - If your second attempt used
pytest.raisesbut didn't pass, you might have missed accessing the exception object properly, or had a tiny typo in the message string you were asserting against.
Here's the correct test code you need, saved as test_converter.py (assuming your converter.py is in the same directory):
import pytest from converter import convert_file def test_convert_file_rejects_non_list_input(): # Use pytest.raises as a context manager to catch the expected exception with pytest.raises(Exception) as exc_context: # Pass any non-list input (string, int, dict, etc.) to trigger the error convert_file("single_file.txt") # Assert that the exception message matches exactly what your function throws assert str(exc_context.value) == "The file type is not a list"
Alternatively, you can use the match parameter directly in pytest.raises for cleaner code—this also supports regex if you ever need partial message matching later:
def test_convert_file_rejects_non_list_input_with_match(): # The match parameter verifies the exception message matches the provided string with pytest.raises(Exception, match="The file type is not a list"): convert_file(12345) # Using an integer as a non-list test input
A few quick checks to ensure this works smoothly:
- Double-check your import path for
convert_file—if your test file is in a subdirectory, adjust the import to something likefrom ..converter import convert_file. - Make sure you're passing a genuine non-list input to trigger the exception branch—avoid accidentally passing a list (that would skip the error handling you're trying to test).
- Since you're raising a generic
Exception, we usepytest.raises(Exception)—if you ever switch to a custom exception class (likeInvalidFileTypeError), replaceExceptionwith that class name for stricter, more precise testing.
Run the test with pytest test_converter.py -v and it should pass now!
内容的提问来源于stack exchange,提问作者Danish Xavier

