unittest - assertRaises返回错误而不是传递

时间:2016-07-27 10:53:29

标签: python python-unittest

我编写了一段使用配置文件的代码(采用JSON格式)

def test_read_config_file(self):
   self.assertRaises(ValueError, self.read_config_file('no_json.txt')

原始函数如下所示:

def read_config_file(file_name)
    config_data = None

    try:
       with open(file_name, 'r') as infile:
         config_data = json.load(infile)
    except ValueError as err:
       LOGGER.error(str(err))

    return config_data

当我运行我的测试用例时,我得到了这个:

2016-07-27 12:41:09,616 ERROR read_config_file(158) No JSON object could be decoded
2016-07-27 12:41:09,616 ERROR read_config_file(158) No JSON object could be decoded
2016-07-27 12:41:09,616 ERROR read_config_file(158) No JSON object could be decoded
2016-07-27 12:41:09,616 ERROR read_config_file(158) No JSON object could be decoded

no_json.txt只包含"嗨"。为什么我在这里得到4个错误?

谢谢,

2 个答案:

答案 0 :(得分:0)

您没有正确使用def test_read_config_file(self): self.assertRaises(ValueError, self.read_config_file('no_json.txt')) # Btw. there was a missing closing `)` 库。当你这样写:

self.read_config_file()

self.assertRaises方法在self.assertRaises之前执行。如果失败,则永远不会调用self.assertRaises。相反,异常会在其他东西捕获之前冒泡。

您希望self.read_config_file方法执行ValueError方法。因为那时它才能捕获潜在的self.assertRaises(ValueError, self.read_config_file, "no_json.txt") 。为此,您有两种选择:

将方法分别传递给test和参数:

self.assertRaises

像这样self.assertRaises将使用指定的参数调用您传递给它的函数。然后在def test_read_config_file(self): with self.assertRaises(ValueError): self.read_config_file("no_json.txt") 内发生异常,可以捕获它并让测试成功。

第二个选项是使用上下文管理器:

with

这样的异常将在ValueError语句中发生。在上下文管理器的清理步骤中,这样的异常的存在可以再次让测试成功。

修改 在您的编辑中,我可以看到您已经在self.read_config_file方法中处理了self.assertRaises。所以任何self.read_config_file方法都会失败。让response引发错误或更改您的测试。

答案 1 :(得分:0)

问题是你的函数捕获ValueError引发的json.load异常,执行日志记录,然后继续返回config_data的值。您的测试断言该函数应该引发异常,但是没有代码可以确保该函数执行此操作。

解决此问题的最简单方法是通过添加raise语句来修改代码,以确保重新引发ValueError以被assertRaises调用捕获:< / p>

def read_config_file(file_name)
    config_data = None

    try:
        with open(file_name, 'r') as infile:
            config_data = json.load(infile)
    except ValueError as err:
        LOGGER.error(str(err))
        raise

    return config_data