【问题标题】:Pytest `pytest.raises(ValueError)` does not seem to detect a `ValueError`Pytest `pytest.raises(ValueError)` 似乎没有检测到`ValueError`
【发布时间】:2019-11-30 05:03:54
【问题描述】:

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

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 列 (char 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'>

【问题讨论】:

    标签: python unit-testing pytest


    【解决方案1】:

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

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

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

    【讨论】:

    • 抱歉,为了便于阅读,我更改了变量,但错误地忘记更改它们。但问题是每次我重新加载它时该功能都没有改变。原来我需要一个特殊的程序,请参阅编辑后的问题。
    猜你喜欢
    • 1970-01-01
    • 2012-05-10
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-04-01
    • 2015-06-27
    • 2015-08-04
    相关资源
    最近更新 更多