python使用笔记29--代码驱动
1 import unittest 2 import requests 3 import jsonpath 4 import time 5 import nnreport 6 7 def get_value(d,key,expr=False,more=False): 8 if expr: 9 jp = jsonpath.jsonpath(d,key)#获取json字符串里某个key的值,返回的是[] 10 else: 11 jp = jsonpath.jsonpath(d, '$..%s' % key) # 获取json字符串里某个key的值,返回的是[] 12 13 if jp: 14 if more: 15 return jp 16 else: 17 return jp[0] 18 19 20 class LiteMallBase(unittest.TestCase): 21 username = "admin123" 22 password = username 23 host = "http://127.0.0.1:8080" 24 25 def login(self): 26 '''登录''' 27 url = self.host + '/admin/auth/login' 28 data = {'username': self.username, 'password': self.password} 29 r = requests.get(url, json=data) 30 token = get_value(r.json(), 'token') 31 self.assertIsNotNone(token, msg='获取不到token值') 32 return token 33 34 def create_coupon(self, name, token, money): 35 '''建券''' 36 url = self.host + "/admin/coupon/create" 37 38 data = {"name": name, "desc": "优惠券111", 39 "total": "999", "discount": 100, "min": money, 40 "limit": 1, "type": 0, "status": 0, "goodsType": 0, 41 "goodsValue": [], "timeType": 0, "days": "10", 42 "startTime": None, "endTime": None} 43 headers = {'X-Litemall-Admin-Token': token} 44 r = requests.get(url, json=data, headers=headers) 45 cid = get_value(r.json(), 'id') 46 cname = get_value(r.json(), 'name') 47 errno = get_value(r.json(), 'errno') 48 self.assertEqual(errno, 0, msg='创建券失败%s' % errno) 49 self.assertEqual(name, cname, msg='创建券名和返回的不一致') 50 return cid 51 52 def index_data(self): 53 '''查询首页数据''' 54 url = self.host + '/wx/home/index' 55 r = requests.get(url) 56 errno = get_value(r.json(), 'errno') 57 self.assertEqual(errno, 0, msg="首页数据查询失败") 58 return r.json() 59 60 class CouponCreate(LiteMallBase): 61 def test_create_coupon(self): 62 '''建券测试''' 63 name = "自动化测试%s-优惠券" % int(time.time()) 64 token = self.login() 65 cid = self.create_coupon(name,token,9999) 66 index_data = self.index_data() 67 coupon_ids = get_value(index_data,'$.data.couponList..id',True,True) 68 self.assertIn(cid,coupon_ids,msg='创建的券ID不存在,不存在的ID是%s'%cid) 69 70 71 suite = unittest.makeSuite(CouponCreate) 72 report = nnreport.BeautifulReport(suite) 73 report.report(description='建券测试报告',filename='建券测试报告.html')