Warning: file_get_contents(/data/phpspider/zhask/data//catemap/3/apache-spark/5.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python 将unittest assertRaise()与对象实例化一起使用_Python_Python Unittest - Fatal编程技术网

Python 将unittest assertRaise()与对象实例化一起使用

Python 将unittest assertRaise()与对象实例化一起使用,python,python-unittest,Python,Python Unittest,我有一个类FilePlay,它接受三个参数host\u dic,PATH,group,所有参数都带有默认值。当给出主机dic时,对象实例化将创建一个文件。当没有给出对象实例化时,将检查文件是否存在,如果不存在将引发错误。代码如下: class FilePlay(object): def __init__(self, host_dic=None, PATH='/foo/', group='bar'): self.host_dic = host_dic sel

我有一个类FilePlay,它接受三个参数
host\u dic
PATH
group
,所有参数都带有默认值。当给出主机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)
当我尝试在路径位置使用文件运行测试时,它工作正常。但当文件不存在时,我得到:

======================================================================
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)

如果调用
FilePlay
引发异常,为什么需要指定名称?
play=
部分不起作用。通过直接调用
FilePlay
,可以在调用
assertRaises()
方法之前引发异常。不要让你的测试以文件的存在为条件。测试两种方案。感谢您的评论。举个例子会很有帮助。。你已经有了下面的答案。@Martijn Pieters你建议删除if/else,然后一个接一个地使用self.assert*语句吗?谢谢,我把它分成了两个测试;一个是路径不存在的,另一个是使用模拟的
os.path.isfile()
函数(和其他模拟)来测试要加载文件的情况。谢谢,这很好!我不知道上下文管理器。我会查的