diegus diegus - 12 days ago 5
Python Question

Use unittest assertRaise() with object instantiation

I have a class FilePlay that accepts three parameters

host_dic
,
PATH
,
group
all with default values. When the host_dic is given the object instantiation will create a file. When not given the object instantiation will check if the file exists, if not will raise an error. Here is the code:

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.")


Now I would like to test this with
unittest
. So here is my code:

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)


When i try to run the test with the file at the PATH location it works ok. But when the file is NOT present I get:

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


How could pass the test when the file is NOT present?

Answer

You're not using assertRaises correctly. You're calling the object directly, so that the error is raised before the assertion has a chance to capture it.

You need to either pass the class itself and its parameters separately:

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

or use the context manager version:

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