编辑。问题是每次我导入该函数时,它都不会随着更新而改变。为此我需要做
import sys, importlib
importlib.reload(sys.modules['foo'])
from foo import bar
它开始工作
如果传递给函数的 json 文件无效,我正在尝试使用 Pytest 编写测试来检测 ValueError。但是,当我按照示例进行操作时,测试没有检测到引发了 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'>