unittest 用例间数据共享参数传递.

 1 import unittest
 2 import requests
 3 import urllib3
 4 urllib3.disable_warnings()
 5 import warnings  # 解决错误 ResourceWarning: Enable tracemalloc to get the object allocation traceback
 6 from lxml import etree
 7 from loginfuction import login # 多个函数中间可用逗号隔开. from time import * 导入全部功能
 8 
 9 # 数据共享 #44 #50 本用例数据需在下一用例调用, 全局变量: globals()["result"] = userinfo_1_result
10 
11 class TestUserInfo(unittest.TestCase):
12 
13 
14     @classmethod # 所有的测试用例之前, 只执行一次.
15     def setUpClass(cls):    # 本函数内的变量如果需要在其它函数使用, 需要在变量名前加 cls.变量名
16         # 解决错误 ResourceWarning: Enable tracemalloc to get the object allocation traceback
17         warnings.simplefilter('ignore',ResourceWarning)
18         cls.s = requests.session()
19         cls.s.verify = False
20         # 解决InsecureRequestWarning: Unverified HTTPS request is being made. Adding certificate verification is strongly advised.
21         requests.packages.urllib3.disable_warnings()
22         cls.r = login(cls.s)
23 
24 
25     def setUp(self): #每个用例之前都会执行
26         self.newstr = "需要在其它函数调用, 需要在变量前加 self.newstr"
27 
28 
29     @classmethod
30     def tearDownClass(cls): # 所有测试用例之后, 只执行一次
31          cls.s.close() # 关闭会话
32 
33 
34     def test_userinfo_1(self):
35 
36         return_html = etree.HTML(self.r.text)
37         username_nodes = return_html.xpath('.//*[@class="username"]')
38         result = username_nodes[0].xpath('.//text()')[0]
39         exp_result = 'xx@hichina.com'
40         print(self.newstr)
41 
42         userinfo_1_result = "用例1获取到的结果"
43         # 数据共享 本用例数据需在下一用例调用, 全局变量: globals()["result"] = userinfo_1_result
44         globals()["result"] = userinfo_1_result
45         # 断言 实际结果 = 预期结果
46         assert result == exp_result
47 
48 
49     def test_userinfo_2(self):
50         userinfo_2_result = globals()["result"]
51         print('userinfo_2_result)  # 用例1获取到的结果
52 
53 
54 # 如果在当前脚本执行,执行下方的代码.  如果当前脚本是被其它代码导入,则不执行下列代码. __name__ 名字 __main__ 自己
55 if __name__ == '__main__':
56     unittest.main()

 

posted @ 2021-05-17 16:47  Aliwall  阅读(443)  评论(0编辑  收藏  举报