我需要使用Mock模块为具有不同功能的Python代码编写单元测试:
_read_file()
:打开一个URL,然后使用Element树解析xml并返回元素树实例。validate_field
:此字段将参数作为field_value和order
tree.findall
函数用于获取列表中的所有fields_values
,然后使用该字段的顺序精确值存储在字段中。然后将此文件与接收的参数进行比较,并根据比较返回true或false。我已经为上述功能编写了单元测试。我已经模拟了urllib.urlopen
和被调用函数的返回值,但它给出了错误:
IndexError: list index out of range
请指导我。
以下代码:
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)
测试类:
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()