You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何使用Pytest检测自定义异常抛出?(含具体代码场景)

How to Test Custom Exception Raised by 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 in pytest.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.raises but 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 like from ..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 use pytest.raises(Exception)—if you ever switch to a custom exception class (like InvalidFileTypeError), replace Exception with 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

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.11 07:45:17