Commit 57fd14e1de4c238ace43aed43a97a2f85e822b38

Authored by SuperPC
Committed by liujiqiang
1 parent 8f3f2bcf

删除冗余的代码和注释

src/commons/ConfigDB.py
1   -#!/usr/bin/python
2   -# -*- coding: UTF-8 -*-
3   -import MySQLdb
4   -import commons.common as ca
5   -import json
6   -from commons.Logging import Logger
7   -# import chardet
8   -log=Logger()
9   -
10   -
11   -dbhost=ca.get_global_config('global_data','Database','dbhost')
12   -dbport=ca.get_global_config('global_data','Database','dbport')
13   -dbname=ca.get_global_config('global_data','Database','dbname')
14   -dbuser=ca.get_global_config('global_data','Database','dbuser')
15   -dbpassword=ca.get_global_config('global_data','Database','dbpassword')
16   -#dbcharset=get_global_config('Database','dbcharset')
17   -
18   -def mysql_selectOne(select_action):
19   - action=select_action
20   - db = MySQLdb.connect(dbhost, dbuser, dbpassword, dbname, charset='utf8' )
21   - cursor = db.cursor()
22   - # 使用cursor()方法获取操作游标
23   - try:
24   - # 使用execute方法执行SQL语句
25   - cursor.execute(action)
26   - # 使用 fetchone() 方法获取一条数据
27   - data = cursor.fetchone()
28   -# print data
29   - return data
30   - except Exception as e:
31   - print("数据库操作异常:%s" % str(e))
32   - log.error("数据库操作异常:%s" % str(e))
33   - assert False
34   - finally:
35   - # 关闭数据库连接
36   - db.close()
37   -
38   -def mysql_selectAll(select_action):
39   - action=select_action
  1 +#!/usr/bin/python
  2 +# -*- coding: UTF-8 -*-
  3 +import MySQLdb
  4 +import commons.common as ca
  5 +import json
  6 +from commons.Logging import Logger
  7 +# import chardet
  8 +log=Logger()
  9 +
  10 +
  11 +dbhost=ca.get_global_config('global_data','Database','dbhost')
  12 +dbport=ca.get_global_config('global_data','Database','dbport')
  13 +dbname=ca.get_global_config('global_data','Database','dbname')
  14 +dbuser=ca.get_global_config('global_data','Database','dbuser')
  15 +dbpassword=ca.get_global_config('global_data','Database','dbpassword')
  16 +#dbcharset=get_global_config('Database','dbcharset')
  17 +
  18 +def mysql_selectOne(select_action):
  19 + action=select_action
40 20 db = MySQLdb.connect(dbhost, dbuser, dbpassword, dbname, charset='utf8' )
41   - #游标加上cursorclass=MySQLdb.cursors.DictCursor后,返回值会变成字典,不加时返回数据格式如:(("001","test"),)加了后变成({'name': test, 'id': 001L,})
42   - #cursor = db.cursor(cursorclass=MySQLdb.cursors.DictCursor)
43 21 cursor = db.cursor()
44   - # 使用cursor()方法获取操作游标
45   - try:
46   - # 使用execute方法执行SQL语句
47   - cursor.execute(action)
48   - # 使用 fetchall() 方法获取所有数据
49   - data = cursor.fetchall()
50   -# print data
51   - return data
52   - except Exception as e:
53   - print("数据库操作异常:%s" % str(e))
54   - log.error("数据库操作异常:%s" % str(e))
55   - assert False
56   - finally:
57   - # 关闭数据库连接
58   - db.close()
59   -
60   -def mysql_delete(delete_action):
61   - action=delete_action
62   - db = MySQLdb.connect(dbhost, dbuser, dbpassword, dbname, charset='utf8' )
63   - cursor = db.cursor()
64   - # 使用cursor()方法获取操作游标
65   - try:
66   - # 使用execute方法执行SQL语句
67   - cursor.execute(action)
68   - # 提交
69   - db.commit()
70   - except Exception as e:
71   - print("数据库操作异常:%s" % str(e))
72   - log.error("数据库操作异常:%s" % str(e))
73   - # 错误回滚
74   - db.rollback()
75   - finally:
76   - # 关闭数据库连接
77   - db.close()
78   -
79   -def mysql_update(update_action):
80   - action=update_action
81   - db = MySQLdb.connect(dbhost, dbuser, dbpassword, dbname, charset='utf8' )
82   - cursor = db.cursor()
83   - # 使用cursor()方法获取操作游标
84   - try:
85   - # 使用execute方法执行SQL语句
86   - cursor.execute(action)
87   - # 提交
88   - db.commit()
89   - except Exception as e:
90   - print("数据库操作异常:%s" % str(e))
91   - log.error("数据库操作异常:%s" % str(e))
92   - # 错误回滚
93   - db.rollback()
94   - finally:
95   - # 关闭数据库连接
96   - db.close()
97   -
98   -def mysql_insert(insert_action):
99   - action=insert_action
100   - db = MySQLdb.connect(dbhost, dbuser, dbpassword, dbname, charset='utf8' )
101   - cursor = db.cursor()
102   - # 使用cursor()方法获取操作游标
103   - try:
104   - # 使用execute方法执行SQL语句
105   - cursor.execute(action)
106   - # 提交
107   - db.commit()
108   - except Exception as e:
109   - print("数据库操作异常:%s" % str(e))
110   - log.error("数据库操作异常:%s" % str(e))
111   - # 错误回滚
112   - db.rollback()
113   - finally:
114   - # 关闭数据库连接
115   - db.close()
116   -
117   -def mysql_check_insert(api,section,check_sql,delete_sql,insert_sql):
118   - log.info(u"======测试数据准备======")
119   - check=ca.get_api_config(api, section, check_sql)
120   - delete=ca.get_api_config(api, section, delete_sql)
121   - insert=ca.get_api_config(api, section, insert_sql)
122   -# print check
123   -# print delete
124   -# print insert
125   - try:
126   - db = MySQLdb.connect(dbhost, dbuser, dbpassword, dbname, charset='utf8' )
127   - cursor = db.cursor()
128   - # 使用cursor()方法获取操作游标
129   - # 使用execute方法执行SQL语句
130   - cursor.execute(check)
131   - result=cursor.fetchall()
132   - # 提交
133   - db.commit()
134   - if result:
135   - log.info(u"检查到数据库有重复数据%r"%str(result))
136   - log.info(u"删除查询到的重复数据%r"%str(delete))
137   - cursor.execute(delete)
138   - log.info(u"删除数据完成")
139   - log.info(u"向数据库中插入测试数据%r"%str(insert))
140   - cursor.execute(insert)
141   - log.info(u"插入数据完成")
142   - result=cursor.fetchall()
143   - db.commit()
144   - return result
145   - else:
146   - log.info(u"数据库没有重复数据直接插入自定义数据%r"%str(insert))
147   - result=cursor.execute(insert)
148   - log.info(u"插入数据完成,返回结果为为%r"%str(result))
149   -# cursor.fetchall()
150   - db.commit()
151   - return result
152   -
153   - except Exception as e:
154   - print(u"数据库操作异常:%r" % str(e))
155   - log.error(u"数据库操作异常:%r" % str(e))
156   - # 错误回滚
157   - db.rollback()
158   - assert False
159   - finally:
160   - # 关闭数据库连接
161   - db.close()
162   -
163   -
164   -
165   -def mysql_select_order(orderNum):
166   - return mysql_selectOne("SELECT * FROM `order`.orders WHERE code = '%s';"%orderNum)
167   -
168   -def mysql_delete_order(orderNum):
169   - mysql_delete("DELETE FROM `order`.orders WHERE code = '%s';"%orderNum)
170   -
171   -def mysql_select_coupon(couponNum):
172   - return mysql_selectOne("SELECT * FROM `customer`.customer_coupon WHERE id = '%s';"%couponNum)
173   -
174   -def mysql_delete_coupon(couponNum):
175   - mysql_delete("DELETE FROM `customer`.customer_coupon WHERE id = '%s';"%couponNum)
176   -
177   -
178   -def Check_in_Mysql(in_data,sql_spm):
179   - log.info(u"======从数据库中查询传入数据======")
180   - result=mysql_selectAll(sql_spm)
181   - log.info(u"传入in_data为: %s"%in_data)
182   - log.info(u"数据库查询到的结果为 %s"%result)
183   -
184   - result=str(result)
185   -# print "1111111",result.decode("utf-8")
186   - if len(str(in_data)) == 0 and len(result)!=0:
187   - log.error(u"传入数据为空!!\n")
188   - assert False
189   - return
190   - elif len(str(in_data)) == 0 and len(result)==0:
191   - log.error(u"传入数据与数据库查询结果都为空!!\n")
192   - assert False
193   - return
194   - elif len(str(in_data)) != 0 and len(result)==0:
195   - log.error(u"数据库查询结果为空\n")
196   - assert False
197   - return
198   - elif isinstance(in_data,(list)):
199   - log.info(u'检查的数据格式 为list类型')
200   - for i in range(0,len(in_data)):
201   - #由于数据库查询的数据中,中文的格式为unicode-escape,所以传入的数据需要进行encode
202   - in_data[i]=str(in_data[i]).decode("utf-8").encode("unicode-escape")
203   -# log.info(u"正在检查输入数据:%s"%in_data[i])
204   - if in_data[i] in result:
205   - assert True
206   - log.info(u"遍历list第%d次,插入数据%r与数据库查询结果一致"%(i,in_data[i]))
207   - else:
208   - log.error(u"#########ERROR#########:\n in_data与数据库查询结果不一致%r"%in_data[i])
209   - assert False
210   - return True
211   -
212   - elif str(in_data).decode("utf-8").encode("unicode-escape") in result:
213   - assert True
214   - log.info(u"in_data与数据库查询结果一致!!%r"%in_data)
215   - return True
216   - else:
217   - log.info(u"#########ERROR#########:\n in_data与数据库查询结果不一致!!%r"%in_data)
218   - assert False
219   -
220   -def Check_in_Response(check_data,src_data):
221   - #check_data必须为列表形式,src_data必须为r.json()的数据类型
222   - log.info(u"======从响应Body中查询传入数据======")
223   - src_data=json.dumps(src_data)
224   - src_data=src_data.replace(" ","")
225   - log.info(u"传入check_data为: %s"%check_data)
226   - log.info(u"对比的响应数据为 %s"%src_data)
227   - if len(check_data) == 0 or len(src_data)==0:
228   - log.error(u"传入数据为空!!\n")
229   - assert False
230   - return
231   - elif isinstance (check_data,str) :
232   - check_data=check_data.replace(" ","").replace("[","").replace("]","").decode("utf-8").split(",")
233   - for i in range(0,len(check_data)):
234   - #由于数据库查询的数据中,中文的格式为unicode-escape,所以传入的数据需要进行encode
235   - check_data[i]=check_data[i].decode("utf-8").encode("unicode-escape")
236   -# print type(check_data),check_data[i]
237   - if check_data[i] in src_data:
238   - assert True
239   - log.info(u"遍历list第%d次,字段%s在请求响应结果中"%((i+1),check_data[i].decode("unicode-escape")))
240   - else:
241   - log.error(u"#########ERROR#########:\n check_data不在请求响应结果中%s"%check_data[i].decode("unicode-escape"))
242   - assert False
243   - return True
244   - elif isinstance (check_data,list) and len(check_data) > 0:
245   - for i in range(0,len(check_data)):
246   - #由于数据库查询的数据中,中文的格式为unicode-escape,所以传入的数据需要进行encode
247   - check_data[i]=check_data[i].decode("utf-8").encode("unicode-escape")
248   - print(type(check_data),check_data[i],str(check_data[i]))
249   - print(type(src_data),src_data)
250   - if check_data[i] in src_data:
251   - assert True
252   - log.info(u"遍历list第%d次,插入数据%r与数据库查询结果一致"%(i,check_data[i]))
253   - else:
254   - log.error(u"#########ERROR#########:\n check_data数据库查询结果不一致%r"%check_data[i])
255   - assert False
256   - return True
257   - else:
258   - log.info(u"#########ERROR#########:\n 检查数据有问题,请检查!!!!!%r")
259   - assert False
260   -
261   -
262   -# test=ca.get_api_config('listCoupon', 'RequstHeader', 'testlist')
263   -# print type(test),test
264   -# print test.replace(" ","").replace("[","").replace("]","").decode("utf-8").split(",")
265   -# test1=test.replace(" ","").replace("[","").replace("]","").decode("utf-8").split(",")
266   -#
267   -# a='couponBizType'
268   -# b='code'
269   -# data1=[a,b:"200"]
270   -# data2={"code":"200","data":{"code":u"你好","data":[{"couponBizType":1,"couponCode":"004","couponCode123":"004"}],"result":"OK","success":2},"result":"OK","success":2}
271   -#
272   -# print Check_in_Response(data1, data2)
273   -
274   -# d=mysql_selectAll("select id as ddd,created_id,name from `product`.tag where id =1")
275   -# d1=mysql_selectOne("select id,created_id,name from `product`.tag where id =1111")
276   -# print d
277   -# print d1
278   -# print d[0][0]
279   -# print chardet.detect(str(d))
280   -# print chardet.detect(str(d[0][2]))
281   -# mysql_insert(ca.get_api_config('submitOrder', 'coupon', 'insert'))
282   -# d=ca.get_api_config('submitOrder', 'coupon', 'insert')
283   -# d=d.decode("utf-8")
284   -# print d
285   -# mysql_insert(d)
286   -
287   -# c={"couponBizType":1,"couponCode":"004"}
288   -# a={"code":"200","data":{"code":"200","data":[],"result":"OK","success":1},"result":"OK","success":2}
289   -# b={"code":"200","data":{"code":"200","data":[{"couponBizType":1,"couponCode":"004","couponCode123":"004"}],"result":"OK","success":2},"result":"OK","success":2}
290   -# # print json_cmp(a, b)
291   -# print json_cmp(a, b)
292   -# print 123
293   -# mysql_check_insert('listCoupon', 'listCoupon01',1,2,3)
294   -# a=mysql_selectAll("select * from `order`.orders where id =271")
295   -# print a
296   -# if a:
297   -# print 111
298   -
299   -# def string(str1):
300   -# a=[]
301   -# b=[]
302   -# str1= list(str1)
303   -# print type(str1[0]),type(str1[1]),len(str1)
304   -# for i in range(len(str1)):
305   -# if str1[i] in '0123456789':
306   -# b.append(str1[i])
307   -# else:
308   -# a.append(str1[i])
309   -# a= "".join(a)
310   -# b= "".join(b)
311   -# c=a+b
312   -# return c
313   -#
314   -# print string("A1B2c3")
315   -#
316   -# assert None, "add assert message"
317 22 \ No newline at end of file
  23 + try:
  24 + # 使用execute方法执行SQL语句
  25 + cursor.execute(action)
  26 + data = cursor.fetchone()
  27 + return data
  28 + except Exception as e:
  29 + print("数据库操作异常:%s" % str(e))
  30 + log.error("数据库操作异常:%s" % str(e))
  31 + assert False
  32 + finally:
  33 + # 关闭数据库连接
  34 + db.close()
  35 +
  36 +def mysql_selectAll(select_action):
  37 + action=select_action
  38 + db = MySQLdb.connect(dbhost, dbuser, dbpassword, dbname, charset='utf8')
  39 + cursor = db.cursor()
  40 + try:
  41 + # 使用execute方法执行SQL语句
  42 + cursor.execute(action)
  43 + # 使用 fetchall() 方法获取所有数据
  44 + data = cursor.fetchall()
  45 +# print data
  46 + return data
  47 + except Exception as e:
  48 + print("数据库操作异常:%s" % str(e))
  49 + log.error("数据库操作异常:%s" % str(e))
  50 + assert False
  51 + finally:
  52 + # 关闭数据库连接
  53 + db.close()
  54 +
  55 +def mysql_delete(delete_action):
  56 + action=delete_action
  57 + db = MySQLdb.connect(dbhost, dbuser, dbpassword, dbname, charset='utf8' )
  58 + cursor = db.cursor()
  59 + try:
  60 + # 使用execute方法执行SQL语句
  61 + cursor.execute(action)
  62 + # 提交
  63 + db.commit()
  64 + except Exception as e:
  65 + print("数据库操作异常:%s" % str(e))
  66 + log.error("数据库操作异常:%s" % str(e))
  67 + # 错误回滚
  68 + db.rollback()
  69 + finally:
  70 + # 关闭数据库连接
  71 + db.close()
  72 +
  73 +def mysql_update(update_action):
  74 + action=update_action
  75 + db = MySQLdb.connect(dbhost, dbuser, dbpassword, dbname, charset='utf8' )
  76 + cursor = db.cursor()
  77 + try:
  78 + # 使用execute方法执行SQL语句
  79 + cursor.execute(action)
  80 + # 提交
  81 + db.commit()
  82 + except Exception as e:
  83 + print("数据库操作异常:%s" % str(e))
  84 + log.error("数据库操作异常:%s" % str(e))
  85 + # 错误回滚
  86 + db.rollback()
  87 + finally:
  88 + # 关闭数据库连接
  89 + db.close()
  90 +
  91 +def mysql_insert(insert_action):
  92 + action=insert_action
  93 + db = MySQLdb.connect(dbhost, dbuser, dbpassword, dbname, charset='utf8' )
  94 + cursor = db.cursor()
  95 + try:
  96 + # 使用execute方法执行SQL语句
  97 + cursor.execute(action)
  98 + # 提交
  99 + db.commit()
  100 + except Exception as e:
  101 + print("数据库操作异常:%s" % str(e))
  102 + log.error("数据库操作异常:%s" % str(e))
  103 + # 错误回滚
  104 + db.rollback()
  105 + finally:
  106 + # 关闭数据库连接
  107 + db.close()
  108 +
  109 +def mysql_check_insert(api,section,check_sql,delete_sql,insert_sql):
  110 + log.info(u"======测试数据准备======")
  111 + check=ca.get_api_config(api, section, check_sql)
  112 + delete=ca.get_api_config(api, section, delete_sql)
  113 + insert=ca.get_api_config(api, section, insert_sql)
  114 +
  115 + try:
  116 + db = MySQLdb.connect(dbhost, dbuser, dbpassword, dbname, charset='utf8' )
  117 + cursor = db.cursor()
  118 + # 使用execute方法执行SQL语句
  119 + cursor.execute(check)
  120 + result=cursor.fetchall()
  121 + # 提交
  122 + db.commit()
  123 + if result:
  124 + log.info(u"检查到数据库有重复数据%r"%str(result))
  125 + log.info(u"删除查询到的重复数据%r"%str(delete))
  126 + cursor.execute(delete)
  127 + log.info(u"删除数据完成")
  128 + log.info(u"向数据库中插入测试数据%r"%str(insert))
  129 + cursor.execute(insert)
  130 + log.info(u"插入数据完成")
  131 + result=cursor.fetchall()
  132 + db.commit()
  133 + return result
  134 + else:
  135 + log.info(u"数据库没有重复数据直接插入自定义数据%r"%str(insert))
  136 + result=cursor.execute(insert)
  137 + log.info(u"插入数据完成,返回结果为为%r"%str(result))
  138 +# cursor.fetchall()
  139 + db.commit()
  140 + return result
  141 +
  142 + except Exception as e:
  143 + print(u"数据库操作异常:%r" % str(e))
  144 + log.error(u"数据库操作异常:%r" % str(e))
  145 + # 错误回滚
  146 + db.rollback()
  147 + assert False
  148 + finally:
  149 + # 关闭数据库连接
  150 + db.close()
  151 +
  152 +def mysql_select_order(orderNum):
  153 + return mysql_selectOne("SELECT * FROM `order`.orders WHERE code = '%s';"%orderNum)
  154 +
  155 +def mysql_delete_order(orderNum):
  156 + mysql_delete("DELETE FROM `order`.orders WHERE code = '%s';"%orderNum)
  157 +
  158 +def mysql_select_coupon(couponNum):
  159 + return mysql_selectOne("SELECT * FROM `customer`.customer_coupon WHERE id = '%s';"%couponNum)
  160 +
  161 +def mysql_delete_coupon(couponNum):
  162 + mysql_delete("DELETE FROM `customer`.customer_coupon WHERE id = '%s';"%couponNum)
  163 +
  164 +
  165 +def Check_in_Mysql(in_data,sql_spm):
  166 + log.info(u"======从数据库中查询传入数据======")
  167 + result=mysql_selectAll(sql_spm)
  168 + log.info(u"传入in_data为: %s"%in_data)
  169 + log.info(u"数据库查询到的结果为 %s"%result)
  170 +
  171 + result=str(result)
  172 + if len(str(in_data)) == 0 and len(result)!=0:
  173 + log.error(u"传入数据为空!!\n")
  174 + assert False
  175 + return
  176 + elif len(str(in_data)) == 0 and len(result)==0:
  177 + log.error(u"传入数据与数据库查询结果都为空!!\n")
  178 + assert False
  179 + return
  180 + elif len(str(in_data)) != 0 and len(result)==0:
  181 + log.error(u"数据库查询结果为空\n")
  182 + assert False
  183 + return
  184 + elif isinstance(in_data,(list)):
  185 + log.info(u'检查的数据格式 为list类型')
  186 + for i in range(0,len(in_data)):
  187 + in_data[i]=str(in_data[i]).decode("utf-8").encode("unicode-escape")
  188 +
  189 + if in_data[i] in result:
  190 + assert True
  191 + log.info(u"遍历list第%d次,插入数据%r与数据库查询结果一致"%(i,in_data[i]))
  192 + else:
  193 + log.error(u"#########ERROR#########:\n in_data与数据库查询结果不一致%r"%in_data[i])
  194 + assert False
  195 + return True
  196 +
  197 + elif str(in_data).decode("utf-8").encode("unicode-escape") in result:
  198 + assert True
  199 + log.info(u"in_data与数据库查询结果一致!!%r"%in_data)
  200 + return True
  201 + else:
  202 + log.info(u"#########ERROR#########:\n in_data与数据库查询结果不一致!!%r"%in_data)
  203 + assert False
  204 +
  205 +def Check_in_Response(check_data,src_data):
  206 + #check_data必须为列表形式,src_data必须为r.json()的数据类型
  207 + log.info(u"======从响应Body中查询传入数据======")
  208 + src_data=json.dumps(src_data)
  209 + src_data=src_data.replace(" ","")
  210 + log.info(u"传入check_data为: %s"%check_data)
  211 + log.info(u"对比的响应数据为 %s"%src_data)
  212 + if len(check_data) == 0 or len(src_data)==0:
  213 + log.error(u"传入数据为空!!\n")
  214 + assert False
  215 + return
  216 + elif isinstance (check_data,str) :
  217 + check_data=check_data.replace(" ","").replace("[","").replace("]","").decode("utf-8").split(",")
  218 + for i in range(0,len(check_data)):
  219 + #由于数据库查询的数据中,中文的格式为unicode-escape,所以传入的数据需要进行encode
  220 + check_data[i]=check_data[i].decode("utf-8").encode("unicode-escape")
  221 +# print type(check_data),check_data[i]
  222 + if check_data[i] in src_data:
  223 + assert True
  224 + log.info(u"遍历list第%d次,字段%s在请求响应结果中"%((i+1),check_data[i].decode("unicode-escape")))
  225 + else:
  226 + log.error(u"#########ERROR#########:\n check_data不在请求响应结果中%s"%check_data[i].decode("unicode-escape"))
  227 + assert False
  228 + return True
  229 + elif isinstance (check_data,list) and len(check_data) > 0:
  230 + for i in range(0,len(check_data)):
  231 + check_data[i]=check_data[i].decode("utf-8").encode("unicode-escape")
  232 + print(type(check_data),check_data[i],str(check_data[i]))
  233 + print(type(src_data),src_data)
  234 + if check_data[i] in src_data:
  235 + assert True
  236 + log.info(u"遍历list第%d次,插入数据%r与数据库查询结果一致"%(i,check_data[i]))
  237 + else:
  238 + log.error(u"#########ERROR#########:\n check_data数据库查询结果不一致%r"%check_data[i])
  239 + assert False
  240 + return True
  241 + else:
  242 + log.info(u"#########ERROR#########:\n 检查数据有问题,请检查!!!!!%r")
  243 + assert False
... ...
src/commons/Logging.py
1   -#!/usr/bin/python
2   -# -*- coding: UTF-8 -*-
3   -import logging,os
4   -
5   -class Logger():
6   -
7   - def __init__(self, path=__name__,clevel = logging.ERROR,Flevel = logging.DEBUG,test = 'w'):
8   - #test = 'w'时每次日志文件都重新写入,test = 'a'时为追加模式,在原来日志文件上追加日志
9   - #重写模式的时,发送test.log没有信息,用追加模式可以(注意如果为a时日志可能出现重复,为w时没有这个现象)
10   - #设置日志路径
11   - current_path=os.path.dirname(os.path.dirname(__file__))
12   - path=current_path+"/report"+"/test.log"
13   -
14   - self.logger = logging.getLogger(path)
15   -
16   - self.logger.setLevel(logging.DEBUG)
17   -
18   - fmt = logging.Formatter('[%(asctime)s] [%(levelname)s] : %(message)s', '%Y-%m-%d %H:%M:%S')
19   -# fmt = logging.Formatter('[%(asctime)s] %(levelname)s [%(name)s,%(funcName)s: %(filename)s, %(lineno)d] %(message)s', '%Y-%m-%d %H:%M:%S')
20   - #设置CMD日志
21   -
22   - sh = logging.StreamHandler()
23   -
24   - sh.setFormatter(fmt)
25   -
26   - sh.setLevel(clevel)
27   -
28   - #设置文件日志
29   -
30   - fh = logging.FileHandler(path,mode=test,encoding="utf-8")
31   -
32   - fh.setFormatter(fmt)
33   -
34   - fh.setLevel(Flevel)
35   -
36   - self.logger.addHandler(sh)
37   -
38   - self.logger.addHandler(fh)
39   -
40   -
41   - def debug(self,message):
42   - #初始化得时候self.logger = logging.getLogger(path)
43   - self.logger.debug(message)
44   -
45   - def info(self,message):
46   -
47   - self.logger.info(message)
48   -
49   -
50   - def warn(self,message):
51   -
52   - self.logger.warn(message)
53   -
54   -
55   - def error(self,message):
56   -
57   - self.logger.error(message)
58   -
59   -
60   - def critical(self,message):
61   -
62   - self.logger.critical(message)
63   -
64   -
65   -
66   -
67   -# a=Logger()
68   -# a.info("123")
69   -# from Case_Method.Logging import *
70   -
71   -# logcommonsonfig(level=logging.DEBUG, # log level
72   -# format='[%(asctime)s] %(levelname)s [%(funcName)s: %(filename)s, %(lineno)d] %(message)s', # log格式
73   -# datefmt='%Y-%m-%d %H:%M:%S', # 日期格式
74   -# filename='test.log', # 日志输出文件
75   -# filemode='a') # 追加模式
76 1 \ No newline at end of file
  2 +#!/usr/bin/python
  3 +# -*- coding: UTF-8 -*-
  4 +import logging,os
  5 +
  6 +class Logger():
  7 +
  8 + def __init__(self, path=__name__,clevel = logging.ERROR,Flevel = logging.DEBUG,test = 'w'):
  9 + current_path=os.path.dirname(os.path.dirname(__file__))
  10 + path=current_path+"/report"+"/test.log"
  11 +
  12 + self.logger = logging.getLogger(path)
  13 +
  14 + self.logger.setLevel(logging.DEBUG)
  15 +
  16 + fmt = logging.Formatter('[%(asctime)s] [%(levelname)s] : %(message)s', '%Y-%m-%d %H:%M:%S')
  17 +
  18 + sh = logging.StreamHandler()
  19 +
  20 + sh.setFormatter(fmt)
  21 +
  22 + sh.setLevel(clevel)
  23 +
  24 + #设置文件日志
  25 +
  26 + fh = logging.FileHandler(path,mode=test,encoding="utf-8")
  27 +
  28 + fh.setFormatter(fmt)
  29 +
  30 + fh.setLevel(Flevel)
  31 +
  32 + self.logger.addHandler(sh)
  33 +
  34 + self.logger.addHandler(fh)
  35 +
  36 +
  37 + def debug(self,message):
  38 +
  39 + self.logger.debug(message)
  40 +
  41 + def info(self,message):
  42 +
  43 + self.logger.info(message)
  44 +
  45 +
  46 + def warn(self,message):
  47 +
  48 + self.logger.warn(message)
  49 +
  50 +
  51 + def error(self,message):
  52 +
  53 + self.logger.error(message)
  54 +
  55 +
  56 + def critical(self,message):
  57 +
  58 + self.logger.critical(message)
... ...
src/commons/SendEmail.py
1   -#!/usr/bin/python
2   -# -*- coding: UTF-8 -*-
3   -import os
4   -import smtplib # 用于建立smtp连接
5   -from email.mime.multipart import MIMEMultipart # 混合MIME格式,支持上传附件
6   -from email.header import Header # 用于使用中文邮件主题
7   -from email.mime.text import MIMEText # 邮件需要专门的MIME格式
8   -from email.mime.image import MIMEImage
9   -from email.mime.application import MIMEApplication
10   -from commons.Logging import Logger
11   -log=Logger()
12   -
13   -def send_email_text():
14   - # 1. 编写邮件内容(Email邮件需要专门的MIME格式)
15   - msg = MIMEText('this is a test email', 'plain', 'utf-8') # plain指普通文本格式邮件内容
16   -
17   - # 2. 组装Email头(发件人,收件人,主题)
18   - msg['From'] = '328351418@qq.com' # 发件人
19   - msg['To'] = '328351418@qq.com' # 收件人
20   - msg['Subject'] = 'Api Test Report' # 邮件主题
21   -
22   - # 3. 连接smtp服务器并发送邮件
23   - smtp = smtplib.SMTP_SSL('smtp.qq.com') # smtp服务器地址 使用SSL模式
24   - smtp.login('328351418@qq.com', 'apebatdwkggkbiee') # 用户名和密码
25   - smtp.sendmail("328351418@qq.com", "328351418@qq.com", msg.as_string())
26   - smtp.quit()
27   -
28   -
29   -def send_email(send_file,send_to=["lixi@diligrp.com","328351418@qq.com"]):
30   -
31   - log_path=os.path.dirname(os.path.dirname(__file__))
32   - log_path=log_path+"/report/test.log"
33   - msg = MIMEMultipart() # 混合MIME格式
34   - msg['From'] = '328351418@qq.com' # 发件人
35   - msg['To'] = '175930106@qq.com' # 收件人
36   - msg['Subject'] = Header('接口测试报告', 'utf-8') # 中文邮件主题,指定utf-8编码
37   -
38   - text = MIMEText('this is a test email', 'plain', 'utf-8')
39   - msg.attach(MIMEText(open(send_file,'rb' ).read(), 'html', 'utf-8')) # 邮件正文添加html格式内容(会丢失css格式)
40   -
41   - att1 = MIMEText(open(send_file, 'rb').read(), 'base64', 'utf-8') # 二进制格式打开需要添加的附件
42   - att1["Content-Type"] = 'application/octet-stream'
43   - att1["Content-Disposition"] = 'attachment; filename="report.html"' # filename为邮件中附件显示的名字
44   -
45   -# att2 = MIMEText(open("../Case_Report/test.log", 'rb').read(), 'base64', 'utf-8') # 二进制格式打开需要添加的附件
46   - att2 = MIMEText(open(log_path, 'rb').read(), 'base64', 'utf-8') # 二进制格式打开需要添加的附件
47   - att2["Content-Type"] = 'application/octet-stream'
48   - att2["Content-Disposition"] = 'attachment; filename="test.log"' # filename为邮件中附件显示的名字
49   - msg.attach(text)
50   - msg.attach(att1)
51   - msg.attach(att2)
52   -
53   - #一下发送日志不会在test.log上,因为提前msg.attach了
54   - log.info("发送邮件")
55   - try:
56   - smtp = smtplib.SMTP_SSL('smtp.qq.com') # smtp服务器地址 使用SSL模式
57   - re=smtp.login('328351418@qq.com', 'wveicahctcizbghh') # 用户名和密码
58   - smtp.sendmail("328351418@qq.com", send_to, msg.as_string())
59   - print(re)
60   -# smtp.sendmail("328351418@qq.com", "328351418@qq.com", msg.as_string()) # 发送给另一个邮箱
61   -# logging.info("邮件发送完成!")
62   - except Exception as e:
63   - log.error(str(e))
64   - print(e)
65   - finally:
66   - smtp.quit()
67   - log.info("邮件发送完毕")
68   -
69   -
70   -#
71   -# f='E:\\EclipseWorkspace\\\WorksapceDemo\\Request-demo\\src\\report\\2019-11-28 15_39_01_result.html'
72   -# send_email(send_file=f)
73   -# fromaddr = '328351418@qq.com'
74   -# password = 'apebatdwkggkbiee'
75   -# toaddrs = ['328351418@qq.com', '328351418@qq.com']
76   -#
77   -# content = 'hello, this is email content.'
78   -# textApart = MIMEText(content)
79   -#
80   -# imageFile = 'E:\\EclipseWorkspace\\nong12test\\Request-fresh\\src\\Case_Report\\report.html'
81   -# imageApart = MIMEApplication(open(imageFile, 'rb').read())
82   -# imageApart.add_header('Content-Disposition', 'attachment', filename='report.html')
83   -#
84   -# # pdfFile = '算法设计与分析基础第3版PDF.pdf'
85   -# # pdfApart = MIMEApplication(open(pdfFile, 'rb').read())
86   -# # pdfApart.add_header('Content-Disposition', 'attachment', filename=pdfFile)
87   -# #
88   -# #
89   -# # zipFile = '算法设计与分析基础第3版PDF.zip'
90   -# # zipApart = MIMEApplication(open(zipFile, 'rb').read())
91   -# # zipApart.add_header('Content-Disposition', 'attachment', filename=zipFile)
92   -#
93   -# m = MIMEMultipart()
94   -# m.attach(textApart)
95   -# m.attach(imageApart)
96   -# # m.attach(pdfApart)
97   -# # m.attach(zipApart)
98   -# m['Subject'] = 'TEST REPORT'
99   -# m['From'] = '328351418@qq.com'
100   -# m['to'] = '175930106@qq.com'
101   -#
102   -# try:
103   -# server = smtplib.SMTP('smtp.qq.com')
104   -# server.login(fromaddr,password)
105   -# server.sendmail(fromaddr, toaddrs, m.as_string())
106   -# print('success')
107   -# server.quit()
108   -# except smtplib.SMTPException as e:
109   -# print('error:',e) #打印错误
110   -#
111   -#
112   -# # file='E:\\EclipseWorkspace\\nong12test\\Request-fresh\\src\\Case_Report\\2019-01-28 17_54_18_result.html'
113   -# #
114   -# # email(file)
115 1 \ No newline at end of file
  2 +#!/usr/bin/python
  3 +# -*- coding: UTF-8 -*-
  4 +import os
  5 +import smtplib
  6 +from email.mime.multipart import MIMEMultipart
  7 +from email.header import Header
  8 +from email.mime.text import MIMEText
  9 +from email.mime.image import MIMEImage
  10 +from email.mime.application import MIMEApplication
  11 +from commons.Logging import Logger
  12 +log=Logger()
  13 +
  14 +def send_email_text():
  15 + # 1. 编写邮件内容(Email邮件需要专门的MIME格式)
  16 + msg = MIMEText('this is a test email', 'plain', 'utf-8')
  17 +
  18 + # 2. 组装Email头(发件人,收件人,主题)
  19 + msg['From'] = '328351418@qq.com' # 发件人
  20 + msg['To'] = '328351418@qq.com' # 收件人
  21 + msg['Subject'] = 'Api Test Report' # 邮件主题
  22 +
  23 + # 3. 连接smtp服务器并发送邮件
  24 + smtp = smtplib.SMTP_SSL('smtp.qq.com')
  25 + smtp.login('328351418@qq.com', 'apebatdwkggkbiee')
  26 + smtp.sendmail("328351418@qq.com", "328351418@qq.com", msg.as_string())
  27 + smtp.quit()
  28 +
  29 +
  30 +def send_email(send_file,send_to=["lixi@diligrp.com","328351418@qq.com"]):
  31 +
  32 + log_path=os.path.dirname(os.path.dirname(__file__))
  33 + log_path=log_path+"/report/test.log"
  34 + msg = MIMEMultipart() # 混合MIME格式
  35 + msg['From'] = '328351418@qq.com' # 发件人
  36 + msg['To'] = '175930106@qq.com' # 收件人
  37 + msg['Subject'] = Header('接口测试报告', 'utf-8') # 中文邮件主题,指定utf-8编码
  38 +
  39 + text = MIMEText('this is a test email', 'plain', 'utf-8')
  40 + msg.attach(MIMEText(open(send_file,'rb' ).read(), 'html', 'utf-8'))
  41 +
  42 + att1 = MIMEText(open(send_file, 'rb').read(), 'base64', 'utf-8')
  43 + att1["Content-Disposition"] = 'attachment; filename="report.html"'
  44 +
  45 + att2 = MIMEText(open(log_path, 'rb').read(), 'base64', 'utf-8')
  46 + att2["Content-Type"] = 'application/octet-stream'
  47 + att2["Content-Disposition"] = 'attachment; filename="test.log"'
  48 + msg.attach(text)
  49 + msg.attach(att1)
  50 + msg.attach(att2)
  51 +
  52 + #一下发送日志不会在test.log上,因为提前msg.attach了
  53 + log.info("发送邮件")
  54 + try:
  55 + smtp = smtplib.SMTP_SSL('smtp.qq.com') # smtp服务器地址 使用SSL模式
  56 + re=smtp.login('328351418@qq.com', 'wveicahctcizbghh') # 用户名和密码
  57 + smtp.sendmail("328351418@qq.com", send_to, msg.as_string())
  58 + print(re)
  59 + except Exception as e:
  60 + log.error(str(e))
  61 + print(e)
  62 + finally:
  63 + smtp.quit()
  64 + log.info("邮件发送完毕")
... ...
src/commons/common.py
1   -#!/usr/bin/python
2   -# -*- coding: UTF-8 -*-
3   -import os
4   -import operator
5   -import configparser
6   -import requests
7   -import json
8   -from commons.Logging import Logger
9   -import urllib3
10   -urllib3.disable_warnings(urllib3.exceptions.InsecureRequestWarning)
11   -log=Logger()
12   -
13   -
14   -def get_global_config(file,section, key):
15   -
16   - current_path=os.path.dirname(__file__)
17   - src_path=os.path.dirname(current_path)
18   -# global_setting_path=src_path+'/config/global_data.conf'
19   - global_setting_path=src_path+'/config/'+file+".conf"
20   - #验证文件是否存在
21   - file_path = os.path.exists(global_setting_path)
22   - if file_path:
23   - #获取文件的数据
24   - if isinstance(key,int):
25   - log.error("key of section cannot be int Type :<%r> "%str(key))
26   - raise Exception("key of section cannot be int Type :<%r> "%str(key))
27   - else:
28   - config = configparser.ConfigParser()
29   - config.read(global_setting_path,encoding="utf-8")
30   - return config.get(section, key)
31   - else:
32   - log.error("File Not Exist :<%r> "%str(global_setting_path))
33   - raise Exception("File Not Exist :<%r> "%str(global_setting_path))
34   -
35   -
36   -def get_api_config(api,section,key):
37   - current_path=os.path.dirname(__file__)
38   - src_path=os.path.dirname(current_path)
39   - api_path=src_path+"/config/api/"
40   - api_config_path=api_path+api+".conf"
41   - #验证文件是否存在
42   - file_path = os.path.exists(api_config_path)
43   - if file_path:
44   - #获取文件的数据
45   - if isinstance(key,int):
46   - log.error("key of section cannot be int Type :<%r> "%str(key))
47   - raise Exception("key of section cannot be int Type :<%r> "%str(key))
48   - else:
49   - config = configparser.ConfigParser()
50   - config.read(api_config_path,encoding="utf-8")
51   - return config.get(section, key)
52   - else:
53   - log.error("File Not Exist :<%r> "%str(api_config_path))
54   - raise Exception("File Not Exist :<%r> "%str(api_config_path))
55   -
56   -def set_global_config(file,section, key,value):
57   - current_path=os.path.dirname(__file__)
58   - src_path=os.path.dirname(current_path)
59   -# global_setting_path=src_path+'/config/global_data.conf'
60   - global_setting_path=src_path+'/config/'+file+".conf"
61   - #验证文件是否存在
62   - file_path = os.path.exists(global_setting_path)
63   - if file_path:
64   - #获取文件的数据
65   - if isinstance(key,int):
66   - log.error("key of section cannot be int Type :<%r> "%str(key))
67   - raise Exception("key of section cannot be int Type :<%r> "%str(key))
68   - else:
69   - config = configparser.ConfigParser()
70   - config.read(global_setting_path,encoding="utf-8")
71   - config.set(section, key, value)
72   - config.write(open(global_setting_path, "w"))
73   -
74   - return config.get(section, key)
75   - else:
76   - log.error("File Not Exist :<%r> "%str(global_setting_path))
77   - raise Exception("File Not Exist :<%r> "%str(global_setting_path))
78   -
79   -def set_priority(priority_list):
80   - #用户自定义优先级方法,设定有需要运行的用例优先级
81   - #方法内定义global全局变量可以真正通过这个方法设置一个全局的值,如果global放在外面,方法内的变量都是临时的,
82   - #接上面:即使名称和外面的全局变量相同,方法内的变量和外面的全局变量完全是两码事,外面的全局变量不会受干扰
83   - global _global_priority
84   - if priority_list:
85   - _global_priority=priority_list
86   - return _global_priority
87   - else:
88   - _global_priority=[1,2,3]
89   - return _global_priority
90   -
91   -def set_mark(case_mark):
92   - #用户自定义优先级方法,设定有需要运行的用例优先级
93   - global _global_mark
94   - if case_mark:
95   - _global_mark=case_mark
96   - return _global_mark
97   - else:
98   - _global_mark=False
99   - return _global_mark
100   -
101   -def read_priority_list():
102   - #需要重新设定一个方法来读取配置的全局优先级变量,且必须在全局变量初始化后使用,不然会报错
103   - #如果直接再py文件中加入类似p=set_priority_list()的代码,之前用户自定义的优先级配置将会失效
104   - priority_list=[1,2,3]
105   - try:
106   - return _global_priority
107   - except Exception as e:
108   - return priority_list
109   -
110   -def read_case_mark():
111   - #需要重新设定一个方法来读取配置的全局优先级变量,且必须在全局变量初始化后使用,不然会报错
112   - #如果直接再py文件中加入类似p=set_priority_list()的代码,之前用户自定义的优先级配置将会失效
113   - casemark=False
114   - try:
115   - return _global_mark
116   - except Exception as e:
117   - return casemark
118   -
119   -def mark(tag=None,p=None):
120   - #此处的try主要用于,当用户需要直接运行单个用例文件时,没提前_global_priority和_global_mark初始化
121   - #如果不加try处理,那么_global_priority和_global_mark没有初始化时,单独运行一个引用了mark方法的用例文件会报错
122   - try:
123   - #用户没有输入任何值
124   - if _global_priority == [1,2,3] and _global_mark == False :
125   - return True
126   - #只指定用例标签
127   - elif _global_priority == [1,2,3] and _global_mark != False:
128   - if tag == _global_mark:
129   - return True
130   - else:
131   - return False
132   - #只指定用例优先级
133   - elif _global_priority != [1,2,3] and _global_mark == False:
134   - if p in _global_priority:
135   - return True
136   - else:
137   - return False
138   - #同时指定优先级和标签
139   - elif _global_priority != [1,2,3] and _global_mark != False:
140   - if p in _global_priority and tag == _global_mark:
141   - return True
142   - else:
143   - return False
144   - #若直接在用例文件中运行那么_global_mark和_global_priority都不会被定义,会导致异常
145   - #这里的try用来当上述两个变量未定义时,默认跑当前文件的用例
146   - except Exception as e:
147   - return True
148   -
149   -
150   -def get_session(name,password):
151   - pass
152   - return "header"
153   -
154   -def get_token(name,password):
155   - pass
156   - return "token"
157   -
158   -def get_request_Url(api):
159   - return get_api_config(api,'RequestUrl', 'url')
160   -
161   -def get_request_Json(api):
162   - return get_api_config(api,'JsonStructrue', 'requestJson')
163   -
164   -# def post_request(api_url, argu, headers):
165   -# #传值前最好要进行一个类型判断,以免数据类型没有转换正确,或者重复转换,导致调用接口时失败
166   -# test_headers=json.loads(headers)
167   -# r = requests.post(api_url, data=argu, headers=test_headers)
168   -# return r
169   -
170   -def dict_diff(a1,b1):
171   - #提取出dict与str或list的异常对比场景
172   - if type(a1)!= type(b1):
173   - print("实际响应json的元素{}的类型{}和期望响应json元素{}的类型{}不一致".format(a1,type(a1),b1,type(b1)))
174   - return False
175   - d1=list(set(a1.keys()).difference(set(b1.keys())))
176   - d2=list(set(b1.keys()).difference(set(a1.keys())))
177   - if len(d1)==0 and len(d2)==0:
178   - return True
179   - else:
180   - print("实际json比期望json多了键值",d1)
181   - print("实际json比期望json少了键值",d2)
182   - return False
183   -
184   -def list_diff(a1,b1):
185   - #提取出list与str或dict的异常对比场景
186   - if type(a1)!= type(b1):
187   - print("实际响应json的元素{}的类型{}和期望响应json元素{}的类型{}不一致".format(a1,type(a1),b1,type(b1)))
188   - return False
189   - elif len(a1)!=len(b1):
190   - print("实际响应json列表长度{}和期望响应json列表长度{}不一致".format(a1,b1))
191   - return False
192   - else:
193   - return True
194   -
195   -#无法判断[[1],[2]]和[[1],[1]]的区别,只能判断列表长度和字典键值是否一致
196   -#a为实际对比的json数据,b为期望的json数据
197   -def compare_json(a,b):
198   - #判断检查数据是否为列表格式的数据
199   - if isinstance(a,list):
200   - if list_diff(a,b)==True:
201   - #为列表时必须进行排序,否则可能出现列表对比的位置不一致
202   - a.sort()
203   - b.sort()
204   - for i in range(len(a)):
205   - #判断列表中的指定的元素是否为字典格式
206   - if compare_json(a[i],b[i]) == False:
207   - return False
208   - else:
209   - return False
210   - #判断检查数据是否为字典格式的数据
211   - elif isinstance(a,dict):
212   - if dict_diff(a,b)==True:
213   - #如果第一层键值相同时,遍历检查内层所有键值
214   - for key in a.keys():
215   - #内层键值为列表数据类型时
216   - if compare_json(a[key],b[key]) == False:
217   - return False
218   - else:
219   - return False
220   - #期望数据非dict和list类型时,直接进行对比,可能会导致{"code":"200"},{"code":"201"}出现不同的情况,所以注释下面的结果
221   -# elif operator.eq(a, b)==False:
222   -# print("实际数据的{}和期望数据的{}不一致".format(a,b))
223   -# return False
224   -
225   -#接口返回值是可控的情况可以用下面这个方法
226   -def cmp_json(actual_data,expect_data):
227   - log.info("======对比期望和实际响应Json格式======")
228   - try:
229   - if len(expect_data)!=0 and len(actual_data)!=0:
230   - expect_data=json.loads(expect_data)
231   - result=compare_json(actual_data,expect_data)
232   - if result==None:
233   - log.info("响应数据和期望数据的Json格式一致")
234   - return True
235   - else:
236   - log.error("66响应数据和期望数据的Json格式不一致")
237   - return False
238   - elif len(expect_data)!=0 and len(actual_data)==0:
239   - log.error("对比数据中,实际响应数据为空")
240   - assert False
241   - elif len(expect_data)==0 and len(actual_data)!=0:
242   - log.error("对比数据中,期望响应数据为空,请检查配置文件")
243   - assert False
244   - elif len(expect_data)==0 and len(actual_data)==0:
245   - log.error("对比数据都为空")
246   - assert False
247   - except Exception as e:
248   - log.error("对比响应数据和期望数据的Json格式 ERROR == %s"%e)
249   - return False
250   -
251   -def get_to_post(data):
252   - #需要传入get格式的请求,如:id=638&driver=好司机&licensePlate=车辆信息,返回字典类型数据
253   - if isinstance(data, str):
254   - test={i.split("=",1)[0]:i.split("=")[1] for i in data.split("&")}
255   - return test
256   - else:
257   - raise Exception("transformation data must be str type")
258   -
259   -def post_to_get(data):
260   - if isinstance(data, dict):
261   - #字典类型,格式如{'id':'668','driver':'好司机'}或者{"id":"668","driver":"好司机"}
262   - test=json.dumps(data)
263   - test=test.replace(" ","").replace('":"', '=').replace('","', "&").replace('"', '').replace("{", "").replace("}", "")
264   - return test.encode('utf_8').decode("unicode_escape")
265   - elif isinstance(data, str):
266   - if '"' in data:
267   - #字符串类型,格式如str({'id':'668','driver':'好司机'})
268   - test=data.replace(" ","").replace('":"', '=').replace('","', "&").replace('"', '').replace("{", "").replace("}", "")
269   - return test
270   - elif "'" in data:
271   - #json字符串类型,格式如str({"id":"668","driver":"好司机"})
272   - test=data.replace(" ","").replace("':'", "=").replace("','", "&").replace("'", "").replace("{", "").replace("}", "")
273   - return test
274   - else:
275   - raise Exception("pls check your transformation data")
276   -
277   -def get_request(api,caseNum):
278   - #传值前最好要进行一个类型判断,以免数据类型没有转换正确,或者重复转换,导致调用接口时失败
279   - if 'http' in api.replace(' ',''):
280   - log.info(u"======直接调用GET请求%s======"%api)
281   - r = requests.post(api, headers=caseNum,verify=False)
282   - else:
283   - URL=get_api_config(api,'RequstURL', 'url')
284   - #获取header
285   - headers=get_api_config(api,'RequstHeader', 'header')
286   - if 'none' == headers:
287   - #header=str(获取有session和token的header)
288   - pass
289   - headers=json.loads(headers)
290   - #获取URI
291   - params=get_api_config(api,caseNum, 'URL_params')
292   - params=params.replace("[","").replace("]","")
293   - URI=URL+params
294   - #进行get请求
295   - r = requests.get(URI,headers=headers)
296   - if r.status_code == 200:
297   - # 关闭请求 释放内存
298   - r.close()
299   - return r
300   - else:
301   - r.close()
302   - log.error(u"Request code==%s ! Response Code is not 200,Pls Check Your Request Datas"%(r.status_code))
303   - raise Exception(u"Request Fail! Response Code is not 200,Pls Check Your Request Datas")
304   - return r
305   -
306   -
307   -def post_request(api,caseNum,requestBody):
308   - #设置重连次数
309   - requests.adapters.DEFAULT_RETRIES = 5
310   - # 设置连接活跃状态为False
311   - s = requests.session()
312   - s.keep_alive = False
313   - #判断post方法使用方式
314   - if 'http' in api.replace(' ',''):
315   - log.info(u"======直接调用POST请求%s======"%api)
316   - r = requests.post(api, headers=caseNum,data=requestBody,verify=False)
317   - else:
318   - log.info(u"======配置相关参数,调用POST请求%s======"%caseNum)
319   - #传值前最好要进行一个类型判断,以免数据类型没有转换正确,或者重复转换,导致调用接口时失败
320   - #获取请求地址数据
321   - url=get_api_config(api,'RequstURL', 'url')
322   - #获取请求header数据
323   - header=get_api_config(api,'RequstHeader', 'header')
324   - if 'none' == header:
325   - #header=str(获取有session和token的header)
326   - pass
327   - #获取请求body数据
328   - body=get_api_config(api,caseNum,requestBody)
329   - #获取请求备注内容
330   - notes=get_api_config(api,caseNum,'notes')
331   - #获取请求期望json格式
332   - expect_Response=get_api_config(api,caseNum,'expect_Response')
333   - #把转换header类型
334   - test_headers=json.loads(header)
335   - #避免日志中的中文乱码,进行编码转换
336   - test_body=json.dumps(json.loads(body)).decode('unicode_escape')
337   - #调用post请求
338   - r = requests.post(url, data=body, headers=test_headers,verify=False)
339   - #进行日志记录
340   - log.info(u"NUM:%s | 请求备注 ==%s"%(caseNum,notes))
341   - log.info(u"NUM:%s | 请求URL==%s"%(caseNum,url))
342   - log.info(u"NUM:%s | 请求body==%s"%(caseNum,test_body))
343   - log.info(u"NUM:%s | 请求实际响应格式 ==%s"%(caseNum,r.content))
344   - log.info(u"NUM:%s | 请求期望响应格式 ==%s"%(caseNum,expect_Response))
345   - #判断请求是否成功
346   - if r.status_code == 200:
347   - # 关闭请求 释放内存
348   - r.close()
349   - return r
350   - else:
351   - r.close()
352   - log.error(u"Request code==%s ! Response Code is not 200,Pls Check Your Request Datas"%(r.status_code))
353   - raise Exception(u"Request Fail! Response Code is not 200,Pls Check Your Request Datas")
354   -
355   -
356   -
357   -
358   -# def my
359   -
360   -# a='https://gateway.fresh.nong12.com/getCityByPosition?lat=30.661286&lng=104.067624'
361   -# b={
362   -# "Host": "gateway.fresh.nong12.com",
363   -# "Content-Type": "application/json",
364   -# "referer": "https://servicewechat.com/wxd1405e5c40ff05db/0/page-frame.html",
365   -# "apiusertoken": "dili-fresh-token",
366   -# "charset": "utf-8",
367   -# "Accept-Encoding": "gzip",
368   -# "User-Agent": "Mozilla/5.0 (Linux; Android 7.0; HUAWEI NXT-AL10 Build/HUAWEINXT-AL10; wv) AppleWebKit/537.36 (KHTML, like Gecko) Version/4.0 Chrome/59.0.3071.125 Mobile Safari/537.36 MicroMessenger/6.7.3.1360(0x2607033D) NetType/WIFI Language/zh_CN Process/appbrand2"
369   -# }
370   -# print get_request('getCityByPosition','getCityByPosition01').json()
371   -# a= get_api_config('submitOrder', 'RequstHeader', 'header')
372   -# b= get_global_config('basic_data_prepare', 'instert_customer')
373   -# print(a)
374   -# print(b)
375   -# print type(a)
376   -# a=json.loads(a)
377   -# print a
378   -# a=json.dumps(a)
379   -# print a
380   -# print a
381   -# a=post_request('nearBy', 'nearBy01', 'requestBody')
382   -# # b=get_api_config('listCoupon', 'listCoupon01', 'expect_Response')
383   -# print a.json()
384   -# print json_compare(b, a.json())
385   -# a=['code', 'data', 'result', 'success']
386   -# b=['code', 'data', 'result', 'success']
387   -# print str(b)
388   -# print json_compare(str(b), a)
389   -
390   -# print a.content
391   -# a=post_request('www.baidu.com/',"" ,"" )
392   -# print a.headers
393   -# print type(a)
394   -# b=json.loads(a)
395   -# c=json.dumps(json.loads(a)).decode('unicode_escape')
396   -# print c
397   -# a={"code":"200","data":{"code":"200","data":[],"result":"OK","success":1},"result":"OK","success":2}
398   -# b={"code":"200","data":{"code":"200","data":[{"couponBizType":1,"couponCode":"004","couponConditionValue":0,"couponDescription":"auto","couponDiscount":1000,"couponDuration":10,"couponName":"成勇测试01","couponTimeEnd":"2025-01-26 23:59:59","couponTimeSt":"2019-01-17 00:00:00","couponType":2,"created":"2019-01-17 15:14:15","customerCode":"00010966","id":10000,"isUsable":2,"state":1,"version":1}],"result":"OK","success":2},"result":"OK","success":2}
399   -# print type(a),type(b)
400   -# prjson_cmp(a, b)
401 1 \ No newline at end of file
  2 +#!/usr/bin/python
  3 +# -*- coding: UTF-8 -*-
  4 +import os
  5 +import operator
  6 +import configparser
  7 +import requests
  8 +import json
  9 +from commons.Logging import Logger
  10 +import urllib3
  11 +urllib3.disable_warnings(urllib3.exceptions.InsecureRequestWarning)
  12 +log=Logger()
  13 +
  14 +
  15 +def get_global_config(file,section, key):
  16 +
  17 + current_path=os.path.dirname(__file__)
  18 + src_path=os.path.dirname(current_path)
  19 +# global_setting_path=src_path+'/config/global_data.conf'
  20 + global_setting_path=src_path+'/config/'+file+".conf"
  21 + #验证文件是否存在
  22 + file_path = os.path.exists(global_setting_path)
  23 + if file_path:
  24 + #获取文件的数据
  25 + if isinstance(key,int):
  26 + log.error("key of section cannot be int Type :<%r> "%str(key))
  27 + raise Exception("key of section cannot be int Type :<%r> "%str(key))
  28 + else:
  29 + config = configparser.ConfigParser()
  30 + config.read(global_setting_path,encoding="utf-8")
  31 + return config.get(section, key)
  32 + else:
  33 + log.error("File Not Exist :<%r> "%str(global_setting_path))
  34 + raise Exception("File Not Exist :<%r> "%str(global_setting_path))
  35 +
  36 +
  37 +def get_api_config(api,section,key):
  38 + current_path=os.path.dirname(__file__)
  39 + src_path=os.path.dirname(current_path)
  40 + api_path=src_path+"/config/api/"
  41 + api_config_path=api_path+api+".conf"
  42 + #验证文件是否存在
  43 + file_path = os.path.exists(api_config_path)
  44 + if file_path:
  45 + #获取文件的数据
  46 + if isinstance(key,int):
  47 + log.error("key of section cannot be int Type :<%r> "%str(key))
  48 + raise Exception("key of section cannot be int Type :<%r> "%str(key))
  49 + else:
  50 + config = configparser.ConfigParser()
  51 + config.read(api_config_path,encoding="utf-8")
  52 + return config.get(section, key)
  53 + else:
  54 + log.error("File Not Exist :<%r> "%str(api_config_path))
  55 + raise Exception("File Not Exist :<%r> "%str(api_config_path))
  56 +
  57 +
  58 +def set_priority(priority_list):
  59 + #用户自定义优先级方法,设定有需要运行的用例优先级
  60 + global _global_priority
  61 + if priority_list:
  62 + _global_priority=priority_list
  63 + return _global_priority
  64 + else:
  65 + _global_priority=[1,2,3]
  66 + return _global_priority
  67 +
  68 +def set_mark(case_mark):
  69 + #用户自定义优先级方法,设定有需要运行的用例优先级
  70 + global _global_mark
  71 + if case_mark:
  72 + _global_mark=case_mark
  73 + return _global_mark
  74 + else:
  75 + _global_mark=False
  76 + return _global_mark
  77 +
  78 +def read_priority_list():
  79 + #需要重新设定一个方法来读取配置的全局优先级变量,且必须在全局变量初始化后使用,不然会报错
  80 + priority_list=[1,2,3]
  81 + try:
  82 + return _global_priority
  83 + except Exception as e:
  84 + return priority_list
  85 +
  86 +def read_case_mark():
  87 + #需要重新设定一个方法来读取配置的全局优先级变量,且必须在全局变量初始化后使用,不然会报错
  88 + casemark=False
  89 + try:
  90 + return _global_mark
  91 + except Exception as e:
  92 + return casemark
  93 +
  94 +def mark(tag=None,p=None):
  95 + #此处的try主要用于,当用户需要直接运行单个用例文件时,没提前_global_priority和_global_mark初始化
  96 + try:
  97 + #用户没有输入任何值
  98 + if _global_priority == [1,2,3] and _global_mark == False :
  99 + return True
  100 + #只指定用例标签
  101 + elif _global_priority == [1,2,3] and _global_mark != False:
  102 + if tag == _global_mark:
  103 + return True
  104 + else:
  105 + return False
  106 + #只指定用例优先级
  107 + elif _global_priority != [1,2,3] and _global_mark == False:
  108 + if p in _global_priority:
  109 + return True
  110 + else:
  111 + return False
  112 + #同时指定优先级和标签
  113 + elif _global_priority != [1,2,3] and _global_mark != False:
  114 + if p in _global_priority and tag == _global_mark:
  115 + return True
  116 + else:
  117 + return False
  118 + except Exception as e:
  119 + return True
  120 +
  121 +
  122 +def get_session(name,password):
  123 + pass
  124 + return "header"
  125 +
  126 +def get_token(name,password):
  127 + pass
  128 + return "token"
  129 +
  130 +def get_request_Url(api):
  131 + return get_api_config(api,'RequestUrl', 'url')
  132 +
  133 +def get_request_Json(api):
  134 + return get_api_config(api,'JsonStructrue', 'requestJson')
  135 +
  136 +
  137 +def dict_diff(a1,b1):
  138 + #提取出dict与str或list的异常对比场景
  139 + if type(a1)!= type(b1):
  140 + print("实际响应json的元素{}的类型{}和期望响应json元素{}的类型{}不一致".format(a1,type(a1),b1,type(b1)))
  141 + return False
  142 + d1=list(set(a1.keys()).difference(set(b1.keys())))
  143 + d2=list(set(b1.keys()).difference(set(a1.keys())))
  144 + if len(d1)==0 and len(d2)==0:
  145 + return True
  146 + else:
  147 + print("实际json比期望json多了键值",d1)
  148 + print("实际json比期望json少了键值",d2)
  149 + return False
  150 +
  151 +def list_diff(a1,b1):
  152 + #提取出list与str或dict的异常对比场景
  153 + if type(a1)!= type(b1):
  154 + print("实际响应json的元素{}的类型{}和期望响应json元素{}的类型{}不一致".format(a1,type(a1),b1,type(b1)))
  155 + return False
  156 + elif len(a1)!=len(b1):
  157 + print("实际响应json列表长度{}和期望响应json列表长度{}不一致".format(a1,b1))
  158 + return False
  159 + else:
  160 + return True
  161 +
  162 +#无法判断[[1],[2]]和[[1],[1]]的区别,只能判断列表长度和字典键值是否一致
  163 +#a为实际对比的json数据,b为期望的json数据
  164 +def compare_json(a,b):
  165 + #判断检查数据是否为列表格式的数据
  166 + if isinstance(a,list):
  167 + if list_diff(a,b)==True:
  168 + #为列表时必须进行排序,否则可能出现列表对比的位置不一致
  169 + a.sort()
  170 + b.sort()
  171 + for i in range(len(a)):
  172 + #判断列表中的指定的元素是否为字典格式
  173 + if compare_json(a[i],b[i]) == False:
  174 + return False
  175 + else:
  176 + return False
  177 + #判断检查数据是否为字典格式的数据
  178 + elif isinstance(a,dict):
  179 + if dict_diff(a,b)==True:
  180 + #如果第一层键值相同时,遍历检查内层所有键值
  181 + for key in a.keys():
  182 + #内层键值为列表数据类型时
  183 + if compare_json(a[key],b[key]) == False:
  184 + return False
  185 + else:
  186 + return False
  187 + #期望数据非dict和list类型时,直接进行对比,可能会导致{"code":"200"},{"code":"201"}出现不同的情况,所以注释下面的结果
  188 +# elif operator.eq(a, b)==False:
  189 +# print("实际数据的{}和期望数据的{}不一致".format(a,b))
  190 +# return False
  191 +
  192 +#接口返回值是可控的情况可以用下面这个方法
  193 +def cmp_json(actual_data,expect_data):
  194 + log.info("======对比期望和实际响应Json格式======")
  195 + try:
  196 + if len(expect_data)!=0 and len(actual_data)!=0:
  197 + expect_data=json.loads(expect_data)
  198 + result=compare_json(actual_data,expect_data)
  199 + if result==None:
  200 + log.info("响应数据和期望数据的Json格式一致")
  201 + return True
  202 + else:
  203 + log.error("66响应数据和期望数据的Json格式不一致")
  204 + return False
  205 + elif len(expect_data)!=0 and len(actual_data)==0:
  206 + log.error("对比数据中,实际响应数据为空")
  207 + assert False
  208 + elif len(expect_data)==0 and len(actual_data)!=0:
  209 + log.error("对比数据中,期望响应数据为空,请检查配置文件")
  210 + assert False
  211 + elif len(expect_data)==0 and len(actual_data)==0:
  212 + log.error("对比数据都为空")
  213 + assert False
  214 + except Exception as e:
  215 + log.error("对比响应数据和期望数据的Json格式 ERROR == %s"%e)
  216 + return False
  217 +
  218 +
  219 +
... ...