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

使用pyhamcrest raises匹配器时Pytest测试失败问题咨询

Why PyHamcrest's raises Matcher Fails in Pytest (But Works in Unittest)

The core issue is how you're using PyHamcrest's raises matcher—it requires a callable that it executes internally to catch the exception, not the result of running the function directly.

The Problem with Your Original Code

When you write:

assert_that(self.target.do(), raises(FileNotFoundError))

You immediately run self.target.do() before assert_that even starts. The FileNotFoundError gets thrown outside the matcher's control, so pytest sees it as an uncaught exception and marks the test as failed.

Why It Might Seem to Work in Unittest

Strictly speaking, this code should fail in unittest too, since the exception is thrown before the matcher can handle it. If it's passing for you, it’s likely due to one of these edge cases:

  • Your unittest runner is configured to swallow uncaught exceptions (uncommon but possible).
  • A try/except block in your do() method or test setup is masking the exception.
  • You’re confusing PyHamcrest’s raises with unittest’s built-in assertRaises method.

Correct PyHamcrest Usage

To make the matcher work in both frameworks, pass a callable that the matcher will execute. Use a lambda to wrap your method call:

def test_foo(self):
    assert_that(lambda: self.target.do(), raises(FileNotFoundError))

Or use functools.partial as an alternative:

from functools import partial

def test_foo(self):
    assert_that(partial(self.target.do), raises(FileNotFoundError))

This way, the matcher controls execution of the function, allowing it to catch and verify the exception properly.

Why pytest.raises Works

pytest.raises uses a context manager to wrap your code in a block that catches the exception. This is a different mechanism than PyHamcrest’s matcher, which relies on receiving a callable to execute. Both are valid approaches but require distinct syntax.

内容的提问来源于stack exchange,提问作者Kingamajick

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.11 14:05:25