Commit 636d41688769a51e5550ff5eda38bf1727218c4a

Authored by lixi
1 parent f960ecf0

1

Showing 2 changed files with 83 additions and 70 deletions
commons/MySession.py
1 #!/usr/bin/python 1 #!/usr/bin/python
2 # -*- coding: UTF-8 -*- 2 # -*- coding: UTF-8 -*-
3 import requests 3 import requests
  4 +import re
4 from commons import common as com 5 from commons import common as com
5 from commons.Logging import log 6 from commons.Logging import log
6 from commons.clientSession import cliSession 7 from commons.clientSession import cliSession
@@ -36,16 +37,17 @@ class mysession(requests.Session): @@ -36,16 +37,17 @@ class mysession(requests.Session):
36 body = "userName=sg_wenze&password=111111" 37 body = "userName=sg_wenze&password=111111"
37 body_client= {"userName":"sg_wenze","password":"111111"} 38 body_client= {"userName":"sg_wenze","password":"111111"}
38 39
39 - def __init__(self): 40 + def __init__(self,host=None):
40 "如下代码,可以通过配置文件来控制测试环境和灰度环境,http和https" 41 "如下代码,可以通过配置文件来控制测试环境和灰度环境,http和https"
41 super().__init__() 42 super().__init__()
  43 + self.user={}
42 self.url = mysession.url.replace("http://test.", com.get_global_config("global_data", "environment", "en")) 44 self.url = mysession.url.replace("http://test.", com.get_global_config("global_data", "environment", "en"))
43 self.header = mysession.header 45 self.header = mysession.header
44 self.body = mysession.body 46 self.body = mysession.body
45 self.url_client = mysession.url_client.replace("http://test.", com.get_global_config("global_data", "environment", "en")) 47 self.url_client = mysession.url_client.replace("http://test.", com.get_global_config("global_data", "environment", "en"))
46 self.header_client = mysession.header_client 48 self.header_client = mysession.header_client
47 self.body_client = mysession.body_client 49 self.body_client = mysession.body_client
48 - self.timeout = (6,6) 50 + self.timeout = (10,10)
49 self.max_retries = 3 51 self.max_retries = 3
50 self.keep_alive = False 52 self.keep_alive = False
51 self.ssl_verify = False 53 self.ssl_verify = False
@@ -55,36 +57,48 @@ class mysession(requests.Session): @@ -55,36 +57,48 @@ class mysession(requests.Session):
55 self.allow_redirects = False 57 self.allow_redirects = False
56 self.firmid={"group":"1","hd":"2","cd":"3","qqhe":"4","mdj":"5","gy":"6","cc":"7","sg":"8","sy":"9"} 58 self.firmid={"group":"1","hd":"2","cd":"3","qqhe":"4","mdj":"5","gy":"6","cc":"7","sg":"8","sy":"9"}
57 self.market={"sy":"沈阳","heb":"哈尔滨","sg":"寿光","gy":"贵阳","cc":"长春","hs":"杭水","hg":"杭果"} 59 self.market={"sy":"沈阳","heb":"哈尔滨","sg":"寿光","gy":"贵阳","cc":"长春","hs":"杭水","hg":"杭果"}
58 - self.user={} 60 + self.host= None if host==None else eval(com.get_global_config("global_data", "host_ip", host))
  61 +
59 62
60 def cliLogin(self,user="sy_userName_01"): 63 def cliLogin(self,user="sy_userName_01"):
61 self.webHeaders, self.clientHeaders, self.userInfo = cliSession().loginUser(user=user) 64 self.webHeaders, self.clientHeaders, self.userInfo = cliSession().loginUser(user=user)
62 return self 65 return self
63 66
64 - def get_session(self, account, **kwargs):  
65 - "如下代码,可以通过配置文件来控制登录的账户session"  
66 - self.body = self.body.replace("sg_wenze",  
67 - com.get_global_config("global_data", "account", account).split("&")[0])  
68 - self.body = self.body.replace("111111",  
69 - com.get_global_config("global_data", "account", account).split("&")[1])  
70 - self.se = requests.session()  
71 - co = requests.cookies.RequestsCookieJar()  
72 - #加入UAP_firmId属性  
73 - firm=account.split("_")[0]  
74 - co.set("UAP_firmId", self.firmid[firm])  
75 - self.se.cookies.update(co)  
76 - # 进行登录请求  
77 - re = self.se.post(url=self.url, headers=self.header, data=self.body, proxies=self.proxies, **kwargs)  
78 - self.UAP_accessToken=self.se.cookies["UAP_accessToken"]  
79 - self.UAP_refreshToken=self.se.cookies["UAP_refreshToken"]  
80 - return self.se 67 + # def get_session(self, account, **kwargs):
  68 + # "如下代码,可以通过配置文件来控制登录的账户session"
  69 + # self.body = self.body.replace("sg_wenze",
  70 + # com.get_global_config("global_data", "account", account).split("&")[0])
  71 + # self.body = self.body.replace("111111",
  72 + # com.get_global_config("global_data", "account", account).split("&")[1])
  73 + # self.se = requests.session()
  74 + # co = requests.cookies.RequestsCookieJar()
  75 + # #加入UAP_firmId属性
  76 + # firm=account.split("_")[0]
  77 + # co.set("UAP_firmId", self.firmid[firm])
  78 + # self.se.cookies.update(co)
  79 + # # 进行登录请求
  80 + # re = self.se.post(url=self.url, headers=self.header, data=self.body, proxies=self.proxies, **kwargs)
  81 + # self.UAP_accessToken=self.se.cookies["UAP_accessToken"]
  82 + # self.UAP_refreshToken=self.se.cookies["UAP_refreshToken"]
  83 + # return self.se
  84 + #
  85 + # def get_login_info(self, account, **kwargs):
  86 + # "用于获取用户信息"
  87 + # self.body_client.update({"userName":com.get_global_config("global_data", "account", account).split("&")[0]})
  88 + # self.body_client.update({"password":pwdCry(com.get_global_config("global_data", "account", account).split("&")[1])})
  89 + # tmp = requests.post(url=self.url_client, headers=self.header_client, json=self.body_client, proxies=self.proxies, **kwargs)
  90 + # return tmp
81 91
82 - def get_login_info(self, account, **kwargs):  
83 - "用于获取用户信息"  
84 - self.body_client.update({"userName":com.get_global_config("global_data", "account", account).split("&")[0]})  
85 - self.body_client.update({"password":pwdCry(com.get_global_config("global_data", "account", account).split("&")[1])})  
86 - tmp = requests.post(url=self.url_client, headers=self.header_client, json=self.body_client, proxies=self.proxies, **kwargs)  
87 - return tmp 92 + def url_pro(self, url, host):
  93 + # url = url.replace(" ", "")
  94 + if host!=None:
  95 + if "http:" in url:
  96 + d1 = re.match(r"http://(.+?)/", url).group(1).split(":")[0]
  97 + url = re.sub(r"http://(.+?)/", r"http://" + host[d1] + "/", url)
  98 + elif "https:" in url:
  99 + d1 = re.match(r"https://(.+?)/", url).group(1).split(":")[0]
  100 + url = re.sub(r"https://(.+?)/", r"https://" + host[d1] + "/", url)
  101 + return url
88 102
89 def get_session_client(self, account, **kwargs): 103 def get_session_client(self, account, **kwargs):
90 "get_session和get_session_client的方法只能用一个" 104 "get_session和get_session_client的方法只能用一个"
@@ -151,6 +165,8 @@ class mysession(requests.Session): @@ -151,6 +165,8 @@ class mysession(requests.Session):
151 """ 165 """
152 # 记录日志 166 # 记录日志
153 log.info("{0:=^86}".format('')) 167 log.info("{0:=^86}".format(''))
  168 + log.info(url)
  169 + url=self.url_pro(url,self.host)
154 log.info("{}\n{}\n".format(url, kwargs)) 170 log.info("{}\n{}\n".format(url, kwargs))
155 # 进行请求 171 # 进行请求
156 re = super().request(method , url, **kwargs,timeout=self.timeout) 172 re = super().request(method , url, **kwargs,timeout=self.timeout)
@@ -262,15 +278,15 @@ class mysession(requests.Session): @@ -262,15 +278,15 @@ class mysession(requests.Session):
262 278
263 my = mysession() 279 my = mysession()
264 my.set_mark() 280 my.set_mark()
265 -  
266 # 沈阳客户端session 281 # 沈阳客户端session
267 sessionSy = mysession().cliLogin("sy_userName_01") 282 sessionSy = mysession().cliLogin("sy_userName_01")
268 # 哈尔滨客户端session 283 # 哈尔滨客户端session
269 sessionHeb = mysession().cliLogin("hd_userName_01") 284 sessionHeb = mysession().cliLogin("hd_userName_01")
270 -# print(sessionSy.userInfo)  
271 -# print(sessionHeb.userInfo)  
272 -  
273 -sy1=mysession().get_session_client("sy_user01")  
274 -heb=mysession().get_session_client("heb_user01")  
275 -# sg=mysession().get_session_client("sg_user01")  
276 - 285 +#获取对应市场session
  286 +sy1=mysession("host1").get_session_client("sy_user01")
  287 +heb=mysession("host1").get_session_client("heb_user01")
  288 +hg=mysession("host2").get_session_client("hg_user01")
  289 +# 检测登录接口
  290 +sy1.check_login("sy_user01")
  291 +# 检测登录接口
  292 +hg.check_login("hg_user01")
277 \ No newline at end of file 293 \ No newline at end of file
1 #!/usr/bin/python 1 #!/usr/bin/python
2 # -*- coding: UTF-8 -*- 2 # -*- coding: UTF-8 -*-
3 -import os,time 3 +import os, time
4 import sys 4 import sys
5 import unittest 5 import unittest
6 import re 6 import re
@@ -13,72 +13,69 @@ from commons.MySession import my @@ -13,72 +13,69 @@ from commons.MySession import my
13 from commons.scripts import delReport 13 from commons.scripts import delReport
14 14
15 15
16 -  
17 def Create_Testcase_suite(path=""): 16 def Create_Testcase_suite(path=""):
18 '''创建测试套件''' 17 '''创建测试套件'''
19 - if path!="":  
20 - path+="/" 18 + if path != "":
  19 + path += "/"
21 print(path) 20 print(path)
22 - testunit=unittest.TestSuite() 21 + testunit = unittest.TestSuite()
23 test_Loader = DiscoveringTestLoader() 22 test_Loader = DiscoveringTestLoader()
24 - discover=test_Loader.discover("./testcase/{}".format(path),pattern='test_*.py',top_level_dir=None) 23 + discover = test_Loader.discover("./testcase/{}".format(path), pattern='test_*.py', top_level_dir=None)
25 # print(discover) 24 # print(discover)
26 for test_suite in discover: 25 for test_suite in discover:
27 testunit.addTests(test_suite) 26 testunit.addTests(test_suite)
28 -# print(testunit) 27 + # print(testunit)
29 return testunit 28 return testunit
30 29
31 -  
32 -def Run_Testcase(testsuit,head=""): 30 +
  31 +def Run_Testcase(testsuit, head=""):
33 '''运行测试用例并生成报告''' 32 '''运行测试用例并生成报告'''
34 if (head in my.market.keys()): 33 if (head in my.market.keys()):
35 - head="["+ my.market[head] + "]"  
36 - now = time.strftime("%Y-%m-%d %H_%M_%S",time.localtime())  
37 - path=os.path.dirname(os.path.abspath(sys.argv[0]))  
38 - report_file=path+"/report/"+now+"_result.html"  
39 - #创建报告文件  
40 - fp=open(report_file,'wb') 34 + head = "[" + my.market[head] + "]"
  35 + now = time.strftime("%Y-%m-%d %H_%M_%S", time.localtime())
  36 + path = os.path.dirname(os.path.abspath(sys.argv[0]))
  37 + report_file = path + "/report/" + now + "_result.html"
  38 + # 创建报告文件
  39 + fp = open(report_file, 'wb')
41 40
42 - runner=HTMLTestRunner_cn.HTMLTestRunner( 41 + runner = HTMLTestRunner_cn.HTMLTestRunner(
43 stream=fp, 42 stream=fp,
44 title=u'进门收费{}--接口测试报告'.format(head), 43 title=u'进门收费{}--接口测试报告'.format(head),
45 description=u'用例简要执行情况如下:(注:报告详细信息需要下载report.html并用浏览器打开)', 44 description=u'用例简要执行情况如下:(注:报告详细信息需要下载report.html并用浏览器打开)',
46 - verbosity = 2)  
47 - #执行用例 45 + verbosity=2)
  46 + # 执行用例
48 runner.run(testsuit) 47 runner.run(testsuit)
49 - #关闭文件 48 + # 关闭文件
50 fp.close() 49 fp.close()
51 delReport.delReport(path) 50 delReport.delReport(path)
52 return report_file 51 return report_file
53 - 52 +
  53 +
54 def Send_email(filename): 54 def Send_email(filename):
55 '''判断邮件发送逻辑''' 55 '''判断邮件发送逻辑'''
56 - l=eval(com.get_global_config("global_data", "email","to_list").lower())  
57 - c=eval(com.get_global_config("global_data", "email","cc_list").lower())  
58 - if type(l)!=type([]): 56 + l = eval(com.get_global_config("global_data", "email", "to_list").lower())
  57 + c = eval(com.get_global_config("global_data", "email", "cc_list").lower())
  58 + if type(l) != type([]):
59 raise Exception("error,pls input list type send-email address") 59 raise Exception("error,pls input list type send-email address")
60 - elif len(l)==0: 60 + elif len(l) == 0:
61 print("\n To_list of send-email is null,won't send email!") 61 print("\n To_list of send-email is null,won't send email!")
62 - elif len(l)!=0: 62 + elif len(l) != 0:
63 for i in l: 63 for i in l:
64 print("\n check send-email format : {}".format(i)) 64 print("\n check send-email format : {}".format(i))
65 - if re.match(r'^[0-9a-zA-Z_]{1,19}@[0-9a-zA-Z]{1,13}\.[com,cn,net]{1,3}$',i): 65 + if re.match(r'^[0-9a-zA-Z_]{1,19}@[0-9a-zA-Z]{1,13}\.[com,cn,net]{1,3}$', i):
66 pass 66 pass
67 else: 67 else:
68 raise Exception("error,pls check your send-email format") 68 raise Exception("error,pls check your send-email format")
69 - #发送邮件  
70 - em.send_email(filename,send_to=l,cc_to=c) 69 + # 发送邮件
  70 + em.send_email(filename, send_to=l, cc_to=c)
71 else: 71 else:
72 print("\n Haven't sent the email,pls check send-email address!") 72 print("\n Haven't sent the email,pls check send-email address!")
73 -  
74 73
75 74
76 if __name__ == "__main__": 75 if __name__ == "__main__":
77 - #检测数据库 76 + # 检测数据库
78 db.mysql_conn_test() 77 db.mysql_conn_test()
79 - #检测登录接口  
80 - my.check_login("sy_user01")  
81 - #创建测试套,运行测试用例,生成报告  
82 - report=Run_Testcase(Create_Testcase_suite("sy"))  
83 - #发送邮件  
84 - Send_email(report) 78 + # 创建测试套,运行测试用例,生成报告
  79 + report = Run_Testcase(Create_Testcase_suite())
  80 + # 发送邮件
  81 + Send_email(report)
85 \ No newline at end of file 82 \ No newline at end of file