I need to write a unit test using Mock module for a Python code with different functions:
_read_file()
: opens a URL and then parse the xml using Element tree and return element tree instance.validate_field
: this filed takes arguments as field_value and order.
tree.findall
function is used to get allfields_values
in a list and then using the order exact value of that field is stored in a field. this file is then compared with the received argument and based on comparison either true of false is returned.
I have written unit test for above function. I have mocked urllib.urlopen
and the return value of the called function, but it's giving error as:
IndexError: list index out of range
Please guide me on this.
Code below:
class test:
def __init__(self, host, service_path='/policy/test.xml'):
self.base_url = 'https://' +host + service_path
self.service_path = service_path
self.host = host
def _read_policy(self, url):
policy_xml = urllib.urlopen(url)
self.tree = ElementTree.parse(policy_xml)
return self.tree
def compare(self, arg1, arg2):
if arg1 == arg2:
return 'true'
else:
return 'false'
def validate_email(self, email, order):
index = int(order) - 1
email_list = self.tree.findall("testList/test/email")
xml_email = email_list[index].text
_resp = self.compare(xml_email, email)
return(_resp)
Test class:
class test_validate_email(unittest.TestCase):
def test_validate_email(self):
myMock = Mock( return_value = StringIO.StringIO("""<?xml version="1.0" encoding="utf-8"?><email>*@test.com</email>"""))
urllib.urlopen = myMock
print 'urllib.urlopen', urllib.urlopen()
cp = test(DEFAULT_HOST)
tree = cp._read_policy("some data")
ElementTree.dump(tree)
myMock2 = Mock(return_value = 'true')
_resp = myMock2
print 'test_resp', _resp()
resp = cp.validate_email('*@ashishtest.com','1')
print 'resp', resp
self.assertEqual(resp, 'true')
if __name__ == '__main__':
unittest.main()