Pytest 'pytest.raises(ValueError)' 似乎没有检测到 'ValueError'



EDIT.问题是每次我导入该功能时,它都不会随着更新而改变。为此我需要做

import sys, importlib
importlib.reload(sys.modules['foo'])
from foo import bar

它开始工作


我正在尝试使用 Pytest 编写一个测试,以检测 ValueError 如果传递给函数的 json 文件无效。但是,当我遵循该示例时,测试不会检测到引发 ValueError。

这是我想要测试的功能

import pytest
import json 
def read_file(input_file):
try: 
with open(input_file, "r", encoding='utf-8') as reader:
pre_input_data = json.load(reader)
except ValueError: 
raise ValueError

这是我的测试功能

def test_read_file():
with pytest.raises(ValueError):
read_file("invalidJsonFile.json")

如果我只是运行原始函数,它会引发 ValueError

read_file("invalidJsonFile.json"(

无效的 json 文件:期望值:第 1 行第 1 列(字符 0(

但是,当我运行测试时,它说它没有收到 ValueError

test_read_file((

Invalid json file: Expecting value: line 1 column 1 (char 0)
---------------------------------------------------------------------------
Failed                                    Traceback (most recent call last)
<ipython-input-47-c42b81670a67> in <module>()
----> 1 test_read_file()
2 frames
<ipython-input-46-178e6c645f01> in test_read_file()
1 def test_read_file():
2     with pytest.raises(Exception):
----> 3         read_file("invalidJsonFile.json")
/usr/local/lib/python3.6/dist-packages/_pytest/python_api.py in __exit__(self, *tp)
727         __tracebackhide__ = True
728         if tp[0] is None:
--> 729             fail(self.message)
730         self.excinfo.__init__(tp)
731         suppress_exception = issubclass(self.excinfo.type, self.expected_exception)
/usr/local/lib/python3.6/dist-packages/_pytest/outcomes.py in fail(msg, pytrace)
115     """
116     __tracebackhide__ = True
--> 117     raise Failed(msg=msg, pytrace=pytrace)
118 
119 
Failed: DID NOT RAISE <class 'Exception'>

您确定运行的代码与此处发送的代码相同吗? 因为在堆栈跟踪中,您似乎正在读取不同的文件(该文件可能是有效的,然后不会引发异常,例如,如果它为空(。

----> 3 read_file("sampleData.csv"(

此外,您不需要仅仅为了引发 ValueError 而排除 ValueError,当您使用 pytest 时pytest.raises(ValueError):pytest 将检查异常是否是 ValueError 的实例。

最新更新