0

编辑。问题是每次我导入该函数时,它都不会随着更新而改变。为此我需要做

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'>
4

1 回答 1

2

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

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

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

于 2019-11-29T10:05:38.963 回答