将文件python_assert.py和cython_assert.pyx定义为相同,每个文件都包含一个引发AssertionError的简单函数:
def raise_assertionerror():
assert False
我希望以下两个测试都能在pytest下成功:
import pytest
import pyximport
pyximport.install()
from python_assert import raise_assertionerror as python_assert
from cython_assert import raise_assertionerror as cython_assert
def test_assertion():
with pytest.raises(AssertionError):
python_assert()
def test_cython_assertion():
with pytest.raises(AssertionError):
cython_assert()
但是,cython测试失败了:
===================================== FAILURES ======================================
_______________________________ test_cython_assertion _______________________________
def test_cython_assertion():
with pytest.raises(AssertionError):
> cython_assert()
test_pytest_assertion.py:15:
_ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _
> assert False
E AssertionError
cython_assert.pyx:2: AssertionError
======================== 1 failed, 1 passed in 0.61 seconds =========================
这似乎是pytest的一个问题,因为等效的单位测试成功了:
import unittest
import pyximport
pyximport.install()
from python_assert import raise_assertionerror as python_assert
from cython_assert import raise_assertionerror as cython_assert
class MyTestCase(unittest.TestCase):
def test_cython(self):
self.assertRaises(AssertionError, cython_assert)
def test_python(self):
self.assertRaises(AssertionError, python_assert)
if __name__ == "__main__":
unittest.main()
此外,如果我们拨打pytest.raises(Exception)
而不是pytest.raises(AssertionError)
,则pytest测试成功。
知道出了什么问题吗?