gpt4 book ai didi

python - 将unittest的assertRaise()与对象实例化结合使用

转载 作者:太空宇宙 更新时间:2023-11-03 15:56:08 25 4
gpt4 key购买 nike

我有一个 FilePlay 类,它接受三个参数 host_dicPATHgroup,所有参数均具有默认值。当给定 host_dic 时,对象实例化将创建一个文件。如果没有给出,对象实例化将检查文件是否存在,如果不存在将引发错误。这是代码:

class FilePlay(object):
def __init__(self, host_dic=None, PATH='/foo/', group='bar'):
self.host_dic = host_dic
self.PATH = PATH
self.group = group # this changes with the instantiation

if isinstance(hosts_dic, dict):
# create a file
# change self.group
else:
if os.path.isfile(self.PATH+'hosts'):
# read the file
# change self.group
else:
raise IOError("Neither hosts file found nor host_dic parameter given, cannot instantiate.")

现在我想用 unittest 来测试它。这是我的代码:

import unittest
from top.files import FilePlay
import os.path


class Test_FilePlay(unittest.TestCase):

def test_init_PATH(self):
'''It tests FilePlay instatiation when:
PATH parameter is given
'''
test_PATH='/foo/'

if not os.path.isfile(test_PATH+'hosts'): # If there is no hosts file at PATH location
self.assertRaises(IOError,play = FilePlay(PATH=test_PATH)) #Here is the problem!
else: # if there is the hosts file at PATH location
play = FilePlay(PATH=test_PATH)

self.assertEqual(play.group, 'bar')
self.assertEqual(play.hosts_dic, None)

当我尝试使用 PATH 位置的文件运行测试时,它工作正常。但是当文件不存在时我得到:

======================================================================
ERROR: test_init_PATH (top.tests.test_test_file)
It tests FilePlay instatiation when:
----------------------------------------------------------------------
Traceback (most recent call last):
File "top/tests/test_file.py", line 14, in test_init_PATH
self.assertRaises(IOError,play = FilePlay(PATH=test_PATH))
File "top/ansible_shared.py", line 88, in __init__
raise IOError("Neither hosts file found nor host_dic parameter given, cannot instantiate.")
IOError: Neither hosts file found nor host_dic parameter given, cannot instantiate.

----------------------------------------------------------------------
Ran 1 test in 0.001s

FAILED (errors=1)

当文件不存在时如何通过测试?

最佳答案

您没有正确使用assertRaises。您直接调用该对象,以便在断言有机会捕获错误之前引发错误。

您需要分别传递类本身及其参数:

self.assertRaises(IOError, FilePlay, PATH=test_PATH)

或使用上下文管理器版本:

with self.assertRaises(IOError):
FilePlay(PATH=test_PATH)

关于python - 将unittest的assertRaise()与对象实例化结合使用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40760719/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com