def setUp(self): print u'=======测试开始======' # self.load() # self.users = ReaderCsv('/Users/dabenchen/Documents/davdian_python/test_api_dvd/test_data/test_user.csv') #self.datafile.loadCsv() #self.datafile.randCsv() # 调用DavdianSession() self.session = DavdianSession()
def setUp(self): print u'=======测试开始======' print self.users # self.load() # 方式一 # user = self.randUser() # self.session = DavdianSession(user['mobile'], user['password']) # self.users = ReaderCsv('/Users/dabenchen/Documents/davdian_python/test_api_dvd/test_data/test_user.csv') # 方式二 self.session = DavdianSession()
class Login(unittest.TestCase): users = ReaderCsv( '/Users/dabenchen/Downloads/daben_chen_py/test_data/test_user.csv') ''' idx = 0 user = [] # 读取test_user.csv文件 def load(self): # print "Load" self.user = [] with open("/Users/dabenchen/Documents/davdian_python/test_api_dvd/test_data/test_user.csv", "rb") as fd: reader = csv.reader(fd) print reader for arr in reader: self.user.append({'mobile': arr[0], 'password': arr[1]}) # 取出test_user.csv文件 def randUser(self): self.load() return self.user ''' # ====================执行case==================== def setUp(self): print u'=======测试开始======' print self.users # self.load() # 方式一 # user = self.randUser() # self.session = DavdianSession(user['mobile'], user['password']) # self.users = ReaderCsv('/Users/dabenchen/Documents/davdian_python/test_api_dvd/test_data/test_user.csv') # 方式二 self.session = DavdianSession() #self.session.api('/api/mg/auth/user/login', {'mobile': arr['mobile'], 'password': arr['password']}) #self.test_01_login_success() def tearDown(self): print u'=======测试结束======' self.session.api('/api/mg/auth/user/logout') # =======================测试case=========================== def action_setting(self): print u'个人中心接口' data = self.session.api('/api/mg/user/center/index') self.assertEqual(int(data['code']), 0, data['data']) print data['code'] # print json.dumps(data) # 打印详细输出log # 请求设置页面 print u'设置页面' response = self.session.get('/settings.html') # print response return "退出登录" in response['body'] def test_01_seller_setting(self): print u'卖家身份: 登录 -> 个人中心 -> 设置页面 -> 退出登录' user = self.users.next() # print user # return self.session.api('/api/mg/auth/user/login', user) ret = self.action_setting() self.assertTrue(ret) def test_02_user_setting(self): print u'买家身份: 登录 -> 个人中心 -> 设置页面 -> 退出登录' user = self.users.next() # print user # return self.session.api('/api/mg/auth/user/login', user) ret = self.action_setting() self.assertTrue(ret) def test_03_no_setting(self): print u'游客身份: 登录 -> 个人中心 -> 设置页面 -> 退出登录' ret = self.action_setting() self.assertTrue(not ret, "not login user failed!")
class categoryGoods_getCart(unittest.TestCase): '''获取test_user.csv文件''' users = ReaderCsv('/Users/dabenchen/Downloads/daben_chen_py/test_data/test_user.csv') # goods = ReaderCsv('/Users/dabenchen/Downloads/daben_chen_py/test_data/test_goods_cart.csv') # ========执行测试========== def setUp(self): print u'-----测试开始-----' self.session = DavdianSession() def tearDown(self): print u'-----测试结束-----' self.session.api('/api/mg/auth/user/logout') # ===================测试case==================== def action_categoryGoods_getCart(self, goods_Id=None): # 请求分类页(图书0-2岁) print u"分类页(图书0-2岁)" response = self.session.get('/categorySync-8-14-2.html?sort=2&_t=1522657956463.7556&page_size=10&page=1') # data = json.loads(response['body']) # print response # 取出good_id,随机goods_id body = response['body'] body = json.loads(body) goodIds = [] # if 'data' not in body['data']: # return False if not body.has_key('data'): # 判断body中的key:data return False for item in body['data']: # 遍历key:data # if 'data' not in item: # continue # if len(item['data']) < 1 or 'goods_id' not in item['data'][0]: # continue # print item['data'][0]['goods_id'] goodIds.append(int(item['goods_id'])) print goodIds # 随机goods_id length = len(goodIds) randIndex = random.randint(0, length - 1) goodsId = goodIds[randIndex] print "DEBUG\t[%s][%s]" % (u'goodsId', goodsId) # 请求商品详情页 print u'商品详情页' print "DEBUG\t[%s][%s]" % (u'goodsId', goodsId) param = {'goodsId': goodsId} data = self.session.api('/api/mg/good/info/detail', param) self.assertEqual(int(data['code']), 0, data['data']) # 添加购物车 print u'添加购物车' param = {'goods': urllib.quote(json.dumps({"number":1, "goods_id":goodsId}))} # data_param = urllib.quote(json.dumps({"number":1, "goods_id":goodsId})); # print data_param print param['goods'] data = self.session.post('/index.php?c=cart&a=add_to_cart&m=default', urllib.urlencode(param)) # data = self.session.post('/index.php?c=cart&a=add_to_cart', 'goods=%257B%2522number%2522%253A%25201%252C%2520%2522goods_id%2522%253A%2520%2522562128%2522%257D') # print data # 请求购物车页面 print u'购物车页面' response = self.session.get('/cart.html?c=cart&a=load') # print response # 效验添加的商品是否在购物车中 data = json.loads(response['body']) cart_info = data['data']['cart_info'] goodsIds = {} activitys = cart_info['activitys'] for item in activitys: if 'goods' not in item: continue for goods in item['goods']: if 'goods_id' not in goods: continue goods_number = int(goods["goods_number"]) goodsIds[int(goods['goods_id'])] = goods_number self.assertTrue(goodsId in goodsIds.keys(), u'添加商品不在购物车中') # 修改商品数量+1 print u'购物车商品数量+1' # params = {'goodsId': goodsId} param = {'goods[' + str(goodsId) + '][act_id]':'0', 'goods[' + str(goodsId) + '][goods_id]': str(goodsId), 'goods[' + str(goodsId) + '][goods_number]':'2', 'goods[' + str(goodsId) + '][editCheck]':'false', 'goods[' + str(goodsId) + '][price_act_id]':'0', 'goods[' + str(goodsId) + '][price_act_type]':'0' } print urllib.urlencode(param) data = self.session.post('/index.php?c=cart&a=change', urllib.urlencode(param)) # print data # 效验添加的商品数量 body = data['body'] new_goodsIds= {} body = json.loads(body) if not body.has_key('data'): return False cart_info = body['data']['cart_info'] # body = response['body'] # body = json.loads(body) # print body activitys = cart_info['activitys'] for item in activitys: if 'goods' not in item: continue for goods in item["goods"]: if 'goods_id' not in goods: continue goods_number = int(goods["goods_number"]) new_goodsIds[int(goods["goods_id"])] = goods_number print "new goods_number: %d" % new_goodsIds.get(goodsId, 0) print "goods_number: %d" % goodsIds.get(goodsId, 0) self.assertTrue((new_goodsIds.get(goodsId, 0) - goodsIds.get(goodsId, 0))==1, u"商品数量不正确") # 修改商品数量-1 print u'购物车商品数量-1' # param = {'goods[1293][act_id]':'0', 'goods[1293][goods_id]': '1293', 'goods[1293][goods_number]':'1', 'goods[1293][editCheck]':'false', 'goods[1293][price_act_id]':'0', 'goods[1293][price_act_type]':'0' } param = {'goods[' + str(goodsId) + '][act_id]':'0', 'goods[' + str(goodsId) + '][goods_id]': str(goodsId), 'goods[' + str(goodsId) + '][goods_number]':'1', 'goods[' + str(goodsId) + '][editCheck]':'false', 'goods[' + str(goodsId) + '][price_act_id]':'0', 'goods[' + str(goodsId) + '][price_act_type]':'0' } print urllib.urlencode(param) data = self.session.post('/index.php?c=cart&a=change', urllib.urlencode(param)) # print data # 效验减少的商品数量 body = data['body'] new_goodsIds= {} body = json.loads(body) if not body.has_key('data'): return False cart_info = body['data']['cart_info'] activitys = cart_info['activitys'] for item in activitys: if 'goods' not in item: continue for goods in item["goods"]: if 'goods_id' not in goods: continue goods_number = int(goods["goods_number"]) new_goodsIds[int(goods["goods_id"])] = goods_number print "new goods_number: %d" % new_goodsIds.get(goodsId, 0) print "goods_number: %d" % goodsIds.get(goodsId, 0) self.assertTrue((new_goodsIds.get(goodsId, 0) == goodsIds.get(goodsId, 0)), u"商品数量不正确") # 删除商品 print u'删除商品' param = {'goods[' + str(goodsId) + '][act_id]':'0', 'goods[' + str(goodsId) + '][goods_id]': str(goodsId), 'goods[' + str(goodsId) + '][deleted]':'1', 'goods[' + str(goodsId) + '][editCheck]':'false', 'goods[' + str(goodsId) + '][price_act_id]':'0', 'goods[' + str(goodsId) + '][price_act_type]':'0' } # param = {'goods[94][act_id]':'0', 'goods[94][goods_id]': '94', 'goods[94][deleted]':'1', 'goods[94][editCheck]':'false', 'goods[94][price_act_id]':'0', 'goods[94][price_act_type]':'0' } print urllib.urlencode(param) data = self.session.post('/index.php?c=cart&a=change', urllib.urlencode(param)) # print data # 效验删除的商品 body = data['body'] new_goodsIds= {} body = json.loads(body) if not body.has_key('data'): return False cart_info = body['data']['cart_info'] '''-------*****这里判断是不是空删除后成空购物车(游客与卖家/买家返回的不一样)''' if len(cart_info) == 0: self.assertTrue(len(cart_info) == 0, u'删除商品失败123') return True # print cart_info activitys = cart_info['activitys'] for item in activitys: if 'goods' not in item: continue for goods in item['goods']: if 'goods_id' not in goods: continue goods_number = int(goods["goods_number"]) new_goodsIds[int(goods['goods_id'])] = goods_number print "new goods_number: %d" % new_goodsIds.get(goodsId, 0) print "goods_number: %d" % new_goodsIds.get(goodsId, 0) self.assertTrue(goodsId not in new_goodsIds.keys(), u'删除商品失败') return True # =============执行case=============== def test_01_seller_categoryGoods_getCart(self): print u'卖家身份: 登录 -> 分类 -> [随机取商品id] -> 商品详情页 -> 加入购物车 -> 购物车(增删查改) -> 退出登录' user = self.users.next() self.session.api('/api/mg/auth/user/login', user) #goods_Id = self.goods.random() ret = self.action_categoryGoods_getCart() self.assertTrue(ret) def test_02_user_categoryGoods_getCart(self): print u'买家身份: 登录 -> 分类 -> [随机取商品id] -> 商品详情页 -> 加入购物车 -> 购物车(增删查改) -> 退出登录' user = self.users.next() self.session.api('/api/mg/auth/user/login', user) ret = self.action_categoryGoods_getCart() self.assertTrue(ret) def test_03_no_categoryGoods_getCart(self): print u'游客身份: 分类 -> [随机取商品id] -> 商品详情页 -> 加入购物车 -> 购物车(增删查改) -> 退出登录' ret = self.action_categoryGoods_getCart() self.assertTrue(ret)
class groupList_goodsDetail(unittest.TestCase): '''获取test_user.csv文件''' users = ReaderCsv('/Users/dabenchen/Downloads/daben_chen_py/test_data/test_user.csv') '''获取test_groupList.csv文件''' groups = ReaderCsv('/Users/dabenchen/Downloads/daben_chen_py/test_data/test_groupList.csv') # =====执行测试====== def setUp(self): print u'-----测试开始-----' # 调用DavdianSession() self.session = DavdianSession() def tearDown(self): print u'-----测试结束-----' self.session.api('/api/mg/auth/user/logout') # ==============测试case================== '''以下是: 登录 -> 首页(第一屏/猜你喜欢) -> 组团[随机选择组团列表页商品id] -> 商品详情页 -> 退出登录【卖家/买家/游客】''' def action_groupList_goodsDetail(self, group_list=None): # 请求首页第一屏 print u'首页第一屏' data = self.session.api('/api/mg/sale/index/getPageFirst') # self.assertEqual(int(data['code']), 0, data['data']) # print json.dumps(data) # 请求首页猜你喜欢 print u'首页猜你喜欢' data = self.session.api('/api/mg/sale/index/getPageSecond') self.assertEqual(int(data['code']), 0, data['data']) # print json.dumps(data) # 请求组团团购精选接口 print u'组团列表' # print group_list print "DEBUG\t[%s][%s]" % (u'group_list', group_list) param = {'reverseType': group_list['reverseType'], 'pageIndex': group_list['pageIndex']} data = self.session.api('/api/mg/sale/reverse/getList', param) '''随机选择组团列表商品id''' reverseGroup = data['data']['reverseGroup'] goodsIds = [] dataList = reverseGroup['dataList'] for item in dataList: goodsIds.append((int)(item['goodsId'])) length = len(goodsIds) print length randIndex = random.randint(0, length - 1) goodsId = goodsIds[randIndex] print "DEBUG\t[%s][%s]" % (u'goodsId', goodsId) self.assertEqual(int(data['code']), 0, data['data']) # print json.dumps(data) # 请求商品详情页 print u'商品详情页' # print "DEBUG\t[%s][%s]" % (u'goodsId', goodsId) param = {'goodsId': goodsId} data = self.session.api('/api/mg/good/info/detail', param) self.assertEqual(int(data['code']), 0, data['data']) # print json.dumps(data) return True # ============执行case=============== def test_01_seller_groupList(self): print u'卖家身份: 登录 -> 首页(第一屏/猜你喜欢)-> 组团列表 -> 【随机选择组团列表商品id】 -> 商品详情页 -> 退出登录' user = self.users.next() self.session.api('/api/mg/auth/user/login', user) group_list = self.groups.random() ret = self.action_groupList_goodsDetail(group_list) self.assertTrue(ret) def test_02_user_groupList(self): print u'买家身份: 登录 -> 首页(第一屏/猜你喜欢)-> 组团列表 -> 【随机选择组团列表商品id】 -> 商品详情页 -> 退出登录' user = self.users.next() self.session.api('/api/mg/auth/user/login', user) group_list = self.groups.random() ret = self.action_groupList_goodsDetail(group_list) self.assertTrue(ret) def test_03_no_groupList(self): print u'游客身份: 登录 -> 首页(第一屏/猜你喜欢)-> 组团列表 -> 【随机选择组团列表商品id】 -> 商品详情页 -> 退出登录' # self.session.api('/api/mg/auth/user/login') group_list = self.groups.random() ret = self.action_groupList_goodsDetail(group_list) self.assertTrue(ret)
class categoryGoods_getCart_buy(unittest.TestCase): '''获取test_user.csv''' users = ReaderCsv('/Users/dabenchen/Downloads/daben_chen_py/test_data/test_user.csv') # ========执行测试========== def setUp(self): print u'-----测试开始-----' self.session = DavdianSession() def tearDown(self): print u'-----测试结束-----' self.session.api('/api/mg/auth/user/logout') # ===================测试case==================== def action_categoryGoods_getCart_buy(self, goods_Id=None): # 请求分类页(图书0-2岁) print u"分类页(图书0-2岁)" response = self.session.get('/categorySync-8-14-2.html?sort=2&_t=1522657956463.7556&page_size=10&page=1') # print response # 取出good_id,随机good_id body = response['body'] body = json.loads(body) goodIds = [] if not body.has_key('data'): return (False, '') for item in body['data']: goodIds.append(int(item['goods_id'])) print goodIds # 随机goods_id length = len(goodIds) randIndex = random.randint(0, length - 1) goodsId = goodIds[randIndex] print "DEBUG\t[%s][%s]" % (u'goodsId', goodsId) # 请求商品详情页 print u'商品详情页' print "DEBUG\t[%s][%s]" % (u'goodsId', goodsId) param = {'goodsId':goodsId} data = self.session.api('/api/mg/good/info/detail', param) self.assertEqual(int(data['code']), 0, data['data']) # 判断普通商品 basis = data['data']['basis'] goodsName = basis['goodsName'] print goodsName if not basis.has_key('childs'): return (False, '') if len(basis['childs']) > 0: return (False, '') extra = data['data']['extra'] if not extra.has_key('dataList') or len(extra['dataList']) == 0: return (False, '') dataList = extra['dataList'][0] sales = dataList['sales']['goodsStocks'] status = dataList['status']['onSale'] print sales,status # 加入购物车 print u'加入购物车' param = {'goods': urllib.quote(json.dumps({"number":1, "goods_id":goodsId}))} print param['goods'] data = self.session.post('/index.php?c=cart&a=add_to_cart&m=default', urllib.urlencode(param)) # 请求购物车页面 print u'购物车页面' response = self.session.get('/cart.html?c=cart&a=load') # print response # 校验购物车页面是否在购物车中 data = json.loads(response['body']) cart_info = data['data']['cart_info'] goodsIds = {} activitys = cart_info['activitys'] for item in activitys: if 'goods' not in item: continue for goods in item['goods']: if 'goods_id' not in goods: continue goods_number = int(goods['goods_number']) goodsIds[int(goods['goods_id'])] = goods_number self.assertTrue(goodsId in goodsIds.keys(), u'添加商品不在购物车中') # 点击结算,请求订单确认页 print u'订单确认页' if sales == 0 and status != 1: return (False, '') param = {'goods[0][id]': str(goodsId), 'goods[0][number]': '1'} response1 = self.session.get('/checkout.html?rp=goods_detail&rl=checkout' + '&' + urllib.urlencode(param)) print urllib.urlencode(param) # print response1['body'] # 判断:游客身份跳转到登录页面 if response1['body'].find('js/login.js') != -1: return (True, response1['body']) # 订单页取出addressId,获取addressId的值 value = 'window.addressId = ' index = response1['body'].find(value) if index == -1: return (False, '') # print index add_index = index+len(value) for i in response1['body'][add_index:]: if i == ';': break add_index += 1 # print response1['body'][(index+len(value)):add_index] addressId = response1['body'][(index+len(value)):add_index] print addressId # 订单确认页,取出身份证信息id value2 = 'idcard_id = ' index = response1['body'].find(value2) if index == -1: return (False, '') add_index = index + len(value2) for j in response1['body'][add_index:]: if j == ';': break add_index += 1 idcard = response1['body'][(index+len(value2)):add_index] print u'身份信息id:', idcard # 取出订单确认页,收货人姓名 result = False soup = BeautifulSoup(response1['body'], 'html.parser') base_name = soup.find_all("span", class_='name') # print base_name # 获取good_title里的值 if len(base_name) > 0: base_name = base_name[0].get_text().strip() print u'收货人姓名:', base_name # 订单确认页设置不使用红包 param = {'bonus_id':0} response = self.session.get('/checkoutBonus.html?' + urllib.urlencode(param)) print urllib.urlencode(param) # print response result = False # return (result, response1['body']) # 点击去支付,请求vdone页 print u'订单确认页生成订单' # http://18600967174.davdian.com/vdone.html?rp=checkout&rl=next&order_id=0&bonus_id=0&address_id=3652798&password=&commission=0&rp=cart&rl=checkout param = {'order_id':0, 'bonus_id':0, 'address_id':addressId, 'commission':0, 'idcard':idcard } response = self.session.get('/vdone.html?rp=checkout&rl=next' + '&' + urllib.urlencode(param)) print urllib.urlencode(param) print response['body'] ''' # 效验status值是否等于0 body = response['body'] statuss = [] if not body.has_key('status'): return (False, '') if len(body['status']) < 0: return (False, '') print status ''' # 效验status是否等于0,不等于0打印status,msg s = json.loads(response['body']) if 'status' in s: if s['status'] != 0: print "Failed! [status not 0][status:%s][message:%s]" % (s['status'], s['msg']) # response.("Failed! [status not 0][status:%s][message:%s]" % (s['status'], s['msg'])) return False print "SUCEESS! [status not 0][status:%s][message:%s]" % (s['status'], s['msg']) return True # =============执行case============== def test_01_seller_categoryGoods_getCart_buy(self): print u'卖家身份: 登录 -> 分类页 -> 商品详情页 -> 加入购物车 -> 购物车结算 -> 订单确认页 -> 去支付' user = self.users.next() self.session.api('/api/mg/auth/user/login', user) ret = self.action_categoryGoods_getCart_buy() self.assertTrue(ret) def test_02_user_categoryGoods_getCart_buy(self): print u'买家身份: 登录 -> 分类页 -> 商品详情页 -> 加入购物车 -> 购物车结算 -> 订单确认页 -> 去支付' user = self.users.next() self.session.api('/api/mg/auth/user/login', user) ret = self.action_categoryGoods_getCart_buy() self.assertTrue(ret) def test_03_no_categoryGoods_getCart_buy(self): print u'游客身份: 分类页 -> 商品详情页 -> 加入购物车 -> 购物车结算 -> 订单确认页 -> 登录(判断是否跳到登录页)' ret= self.action_categoryGoods_getCart_buy() print ret # 取出sess_key sess_key = self.session.session print sess_key self.assertTrue(ret)
class firstBanner_addCart(unittest.TestCase): '''获取test_user.csv文件''' users = ReaderCsv( '/Users/dabenchen/Downloads/daben_chen_py/test_data/test_user.csv') # users = ReaderCsv('/home/xiaoqiang.li/scripts/release_li/test_api_dvd/test_data/test_user.csv') topics = ReaderCsv( '/Users/dabenchen/Downloads/daben_chen_py/test_data/test_topic.csv') # =====执行测试====== def setUp(self): print u'-----测试开始-----' # 调用DavdianSession() self.session = DavdianSession() def tearDown(self): print u'-----测试结束-----' self.session.api('/api/mg/auth/user/logout') # ==============测试case=================== '''以下是: 新专题 -> 【随机选择商品id】-> 商品详情页 -> 加入购物车 -> 效验购物车 -> 退出登录【卖家/买家/游客】''' def action_firstBanner_addCart(self, topic_Id=None): # 请求首页banner专题页 print u'首页banner专题' print topic_Id param = {'topicId': topic_Id['topicId']} data = self.session.api('/api/mg/sale/topic/getTopicInfo', param) self.assertEqual(int(data['code']), 0, data['data']) # print json.dumps(data) # print type(data) # 取出专题页goodsId topicContent = data['data']['topicContent'] # print type(topicContent) # 返回的是字符串,先loads转换成对象 topicContent = json.loads(topicContent) print type(topicContent) # print topicContent # print type(topicContent) # 取下标第4个 # print topicContent['list'][4] goodsIds = [] goods_Ids = topicContent['list'][4]['goods'] # 转换成数组list goodsIds = goods_Ids.split(',') print goodsIds # 随机list length = len(goodsIds) randIndex = random.randint(0, length - 1) goodsId = goodsIds[randIndex] print goodsId # 请求商品详情页 print u'商品详情页' print "DEBUG\t[%s][%s]" % (u'goodsId', goodsId) param = {'goodsId': goodsId} data = self.session.api('/api/mg/good/info/detail', param) self.assertEqual(int(data['code']), 0, data['data']) # 添加购物车 print u'添加购物车' # 添加购物车的接口,需要goods: {"number":1,"goods_id":"550358"},用urllib.quote的方式 param = { 'm': 'default', 'c': 'cart', 'a': 'add_to_cart', 'goods': urllib.quote(json.dumps({ "number": 1, "goods_id": goodsId })) } print param['goods'] data = self.session.post('/cart.html', urllib.urlencode(param)) print data # 请求购物车页面 print u'购物车页面' response = self.session.get('/cart.html') # 请求购物车接口 print u'购物车接口' response = self.session.get('/cart.html?c=cart&a=load') # print response data = json.loads(response['body']) cart_info = data['data']['cart_info'] goodsIds = {} activitys = cart_info['activitys'] for item in activitys: if 'goods' not in item: continue for goods in item["goods"]: if 'goods_id' not in goods: continue goods_number = int(goods["goods_number"]) goodsIds[int(goods['goods_id'])] = goods_number # goodsIds.append((int)(goods['goods_id'])) # print goodsId # print goodsIds # self.assertTrue(goodsId in goodsIds.keys(), u"商品不在购物车中") return True # =============执行case=============== def test_01_seller_firstBanner_addCart(self): print u'卖家身份: 新专题 -> 【随机选择商品id】-> 商品详情页 -> 加入购物车 -> 效验购物车 -> 退出登录' user = self.users.next() self.session.api('/api/mg/auth/user/login', user) topic_Id = self.topics.random() ret = self.action_firstBanner_addCart(topic_Id) self.assertTrue(ret) def test_02_user_firstBanner_addCart(self): print u'买家身份: 新专题 -> 【随机选择商品id】-> 商品详情页 -> 加入购物车 -> 效验购物车 -> 退出登录' user = self.users.next() self.session.api('/api/mg/auth/user/login', user) topic_Id = self.topics.random() ret = self.action_firstBanner_addCart(topic_Id) self.assertTrue(ret) def test_03_no_firstBanner_addCart(self): print u'游客身份: 新专题 -> 【随机选择商品id】-> 商品详情页 -> 加入购物车 -> 效验购物车 -> 退出登录' topic_Id = self.topics.random() ret = self.action_firstBanner_addCart(topic_Id) self.assertTrue(ret)
class firstBanner(unittest.TestCase): '''获取test_user.csv文件''' users = ReaderCsv('/Users/dabenchen/Downloads/daben_chen_py/test_data/test_user.csv') # =====执行测试====== def setUp(self): print u'-----测试开始-----' # 调用DavdianSession() self.session = DavdianSession() def tearDown(self): print u'-----测试结束-----' self.session.api('/api/mg/auth/user/logout') # ==============测试case================== '''以下是: 登录 -> 首页(第一屏/猜你喜欢)-> 首页banner图 -> 【随机选择banner专题】 -> 专题页 -> 退出登录''' def action_firstBanner(self, topic_Id=None): # 请求首页第一屏 print u'首页第一屏' data = self.session.api('/api/mg/sale/index/getPageFirst') # self.assertEqual(int(data['code']), 0, data['data']) feedList = data['data']['feedList'] contents = [] for item in feedList: if not item.has_key('body') or not item['body'].has_key('dataList'): continue if len(item['body']['dataList']) < 0: continue dataList = item['body']['dataList'] for data in dataList: if not data.has_key('command'): continue m = re.match(r'^/.+\?topicId=(\d+)&', data['command']['content']) if m: topicId = m.group(1) contents.append(topicId) print "DEBUG\t[%s][%s]" % (u'contents', contents) length = len(contents) print "DEBUG\t[%s][%s]" % (u'length', length) randIndex = random.randint(0, length - 1) topicId = contents[randIndex] # topicIdurl = contents[randIndex] # topicId = re.findall(r"\d+\d*", topicIdurl)[0] print "DEBUG\t[%s][%s]" % (u'topicId', topicId) # print json.dumps(data) # 请求首页猜你喜欢 print u'首页猜你喜欢' data = self.session.api('/api/mg/sale/index/getPageSecond') self.assertEqual(int(data['code']), 0, data['data']) # print json.dumps(data) # return True # 请求首页banner专题页 print u'首页banner专题页' param = {'topicId': topicId} data = self.session.api('/api/mg/sale/topic/getTopicInfo', param) self.assertEqual(int(data['code']), 0, data['data']) # print json.dumps(data) return True # =============执行case=============== def test_01_seller_firstBanner(self): print u'卖家身份: 首页(第一屏/猜你喜欢)-> 首页banner图 -> 【随机选择banner专题】 -> 专题页 -> 退出登录' user = self.users.next() self.session.api('/api/mg/auth/user/login', user) ret = self.action_firstBanner() self.assertTrue(ret) def test_02_user_firstBanner(self): print u'买家身份: 首页(第一屏/猜你喜欢)-> 首页banner图 -> 【随机选择banner专题】 -> 专题页 -> 退出登录' user = self.users.next() self.session.api('/api/mg/auth/user/login', user) ret = self.action_firstBanner() self.assertTrue(ret) def test_03_no_firstBanner(self): print u'游客身份: 首页(第一屏/猜你喜欢)-> 首页banner图 -> 【随机选择banner专题】 -> 专题页 -> 退出登录' # self.session.api('/api/mg/auth/user/login') ret = self.action_firstBanner() self.assertTrue(ret)
class Search(unittest.TestCase): users = ReaderCsv( '/Users/dabenchen/Documents/davdian_python/test_api_dvd/test_data/test_user.csv' ) # ===========执行测试============= def setUp(self): print u'=====测试开始=====' # 调用DavdianSession() self.session = DavdianSession() def tearDown(self): print u'=====测试结束=====' self.session.api('/api/mg/auth/user/logout') # ==============测试case=============== def action_Search(self, user=None): # 请求首页第一屏接口 print u'首页第一屏' data = self.session.api('/api/mg/sale/index/getPageFirst') self.assertEqual(int(data['code']), 0, data['data']) print json.dumps(data) # 请求首页第二屏(猜你喜欢) print u'首页第二屏(猜你喜欢)' data = self.session.api('/api/mg/sale/index/getPageSecond') self.assertEqual(int(data['code']), 0, data['data']) print json.dumps(data) # 请求搜索建议词接口 print u'搜索建议词' # q:需要带的参数 param = {'q': user['q']} # print user data = self.session.api('/api/mg/sale/search/suggestKeywords', param) self.assertEqual(int(data['code']), 0, data['data']) # 取出keywords keywords = data['data']['keywords'] # 判断是否有结果;有返回Ture,否则返回False if user['expect'] == "true": self.assertTrue(keywords) for item in keywords: self.assertTrue(user['q'] in item) else: self.assertTrue(not keywords) print json.dumps(data) # 请求搜索热词 print u'搜索热词' data = self.session.api('/api/mg/sale/search/getHotwords') self.assertEqual(int(data['code']), 0, data['data']) print json.dumps(data) # return True # 请求搜索结果 print u'搜索结果' data = self.session.api('/api/mg/sale/search/getGoods') self.assertEqual(int(data['code']), 0, data['data']) print json.dumps(data) return True # ==========执行case=============== def test_01_seller_Search(self): print u'卖家身份: 登录 -> 首页(第一屏,第二屏[猜你喜欢]) -> 搜索建议词 -> 搜索热词 -> 搜索结果' user = self.users.next() #上面"搜索建议词"已经调用过user,这里再调用就会出现取第二个数据 # param = self.user.next() self.session.api('/api/mg/auth/user/login', user) ret = self.action_Search(user) self.assertTrue(ret) def test_02_user_Search(self): print u'买家身份: 登录 -> 首页(第一屏,第二屏[猜你喜欢]) -> 搜索建议词 -> 搜索热词 -> 搜索结果' user = self.users.next() # print "TEST2" # print user # return self.session.api('/api/mg/auth/user/login', user) ret = self.action_Search(user) self.assertTrue(ret) '''
class firstGuess_addCaet(unittest.TestCase): '''获取test_user.csv文件''' users = ReaderCsv( '/Users/dabenchen/Downloads/daben_chen_py/test_data/test_user.csv') # =====执行测试====== def setUp(self): print u'-----测试开始-----' # 调用DavdianSession() self.session = DavdianSession() def tearDown(self): print u'----测试结束-----' self.session.api('/api/mg/auth/user/logout') # ================测试case=================== '''以下是: 首页猜你喜欢 -> [随机获取猜你喜欢列表商品id] -> 商品详情页 -> 加入购物车(效验商品id是否加入) ->再次加入购物车(效验商品数量)''' def action_getCart(self): # 请求首页猜你喜欢 print u'首页猜你喜欢' data = self.session.api('/api/mg/sale/index/getPageSecond') feedList = data['data']['feedList'] contents = [] for item in feedList: if not item.has_key('body') or not item['body'].has_key( 'dataList'): continue if len(item['body']['dataList']) < 0: continue dataList = item['body']['dataList'] for data in dataList: if not data.has_key('command'): continue if not data['command'].has_key('content'): continue if re.match(r'^/\d+.html', data['command']['content']): contents.append(data['command']['content']) length = len(contents) randIndex = random.randint(0, length - 1) content = contents[randIndex] goodsIdurl = contents[randIndex] # re.findall是字符串类型,goodsId需要转换成int类型 goodsId = int(re.findall(r"\d+\d*", goodsIdurl)[0]) print "DEBUG\t[%s][%s]" % (u'goodsId', goodsId) ''' 第一次请求商品详情,添加商品id到购物车,效验goods_id、goods_number ''' # 请求商品详情页 print u'商品详情页' print "DEBUG\t[%s][%s]" % (u'goodsId', goodsId) param = {'goodsId': goodsId} data = self.session.api('/api/mg/good/info/detail', param) self.assertEqual(int(data['code']), 0, data['data']) print data['code'] # return True # 添加购物车 print u'添加购物车' # 添加购物车的接口,需要goods: {"number":1,"goods_id":"550358"},用urllib.quote的方式 param = { 'm': 'default', 'c': 'cart', 'a': 'add_to_cart', 'goods': urllib.quote(json.dumps({ "number": 1, "goods_id": goodsId })) } print param['goods'] # 购物车这里直接用post请求,**需要urlencode** data = self.session.post('/cart.html', urllib.urlencode(param)) print data # self.assertEqual(int(data['code']), 0, data['data']) # 请求购物车页面 print u'购物车页面' response = self.session.get('/cart.html') # print response # return "购物车" in response['body'] # 请求购物车接口 print u'购物车接口' response = self.session.get('/cart.html?c=cart&a=load') # print response data = json.loads(response['body']) # 以下:效验随机加入的商品id是不是在购物车中 cart_info = data['data']['cart_info'] goodsIds = {} activitys = cart_info['activitys'] for item in activitys: if 'goods' not in item: continue # goodsIds=[goods['goods_id'] for goods in item["goods"] if 'goods_id' in goods] for goods in item["goods"]: if 'goods_id' not in goods: continue goods_number = int(goods["goods_number"]) goodsIds[int(goods['goods_id'])] = goods_number # goodsIds.append((int)(goods['goods_id'])) # print goodsId # print goodsIds self.assertTrue(goodsId in goodsIds.keys(), u"商品不在购物车中") # return True ''' 第二次请求商品详情,添加商品id到购物车,效验goods_id、goods_number ''' # 再次请求商品详情页 print u'商品详情页' print "DEBUG\t[%s][%s]" % (u'goodsId', goodsId) param = {'goodsId': goodsId} data = self.session.api('/api/mg/good/info/detail', param) self.assertEqual(int(data['code']), 0, data['data']) # 添加购物车 print u'添加购物车' param = { 'm': 'default', 'c': 'cart', 'a': 'add_to_cart', 'goods': urllib.quote(json.dumps({ "number": 1, "goods_id": goodsId })) } print param['goods'] data = self.session.post('/cart.html', urllib.urlencode(param)) print data # 请求购物车页 print u'购物车页' response = self.session.get('/cart.html') # 购物车接口 print u'购物车接口' response = self.session.get('/cart.html?c=cart&a=load') data = json.loads(response['body']) # print data['data'] # 效验添加的商品数量 cart_info = data['data']['cart_info'] new_goodsIds = {} activitys = cart_info['activitys'] for item in activitys: if 'goods' not in item: continue for goods in item["goods"]: if 'goods_id' not in goods: continue goods_number = int(goods["goods_number"]) new_goodsIds[int(goods["goods_id"])] = goods_number # goods_numbers.append((int)(goods['goods_number'])) # print goodsId # print goodsIds print "new goods_number: %d" % new_goodsIds.get(goodsId, 0) print "goods_number: %d" % goodsIds.get(goodsId, 0) self.assertTrue( (new_goodsIds.get(goodsId, 0) - goodsIds.get(goodsId, 0)) == 1, u"商品数量不正确") return True # =============执行case=============== def test_01_seller_getCart(self): print u'卖家身份: 登录 -> 首页猜你喜欢 -> [随机获取猜你喜欢列表商品id] -> 商品详情页 -> 加入购物车(效验商品id是否加入) ->再次加入购物车(效验商品数量) -> 退出登录' user = self.users.next() self.session.api('/api/mg/auth/user/login', user) ret = self.action_getCart() self.assertTrue(ret) def test_02_user_getCart(self): print u'买家身份: 登录 -> 首页猜你喜欢 -> [随机获取猜你喜欢列表商品id] -> 商品详情页 -> 加入购物车(效验商品id是否加入) ->再次加入购物车(效验商品数量) -> 退出登录' user = self.users.next() self.session.api('/api/mg/auth/user/login', user) ret = self.action_getCart() self.assertTrue(ret) def test_03_no_getCart(self): print u'游客身份: 登录 -> 首页猜你喜欢 -> [随机获取猜你喜欢列表商品id] -> 商品详情页 -> 加入购物车(效验商品id是否加入) -> 再次加入购物车(效验商品数量) -> 退出登录' # self.session.api('/api/mg/auth/user/login') ret = self.action_getCart() self.assertTrue(ret)
class getChannel(unittest.TestCase): '''获取csv文件''' users = ReaderCsv( '/Users/dabenchen/Downloads/daben_chen_py/test_data/test_user.csv') menus = ReaderCsv( '/Users/dabenchen/Downloads/daben_chen_py/test_data/test_menu.csv') # ========执行测试========== def setUp(self): print u'-----测试开始------' # 调用DavdianSession() self.session = DavdianSession() def tearDown(self): print u'-----测试结束------' # ========测试case========== '''以下是:首页(第一屏、猜你喜欢) -> 二级菜单(第一屏、猜你喜欢) -> 退出登录''' def action_Channel(self, menu_id=None): # 请求首页第一屏 print u'首页第一屏' data = self.session.api('/api/mg/sale/index/getPageFirst') # self.assertEqual(int(data['code']), 0, data['data']) # print data['code'] # print json.dumps(data) # 请求首页第二屏(猜你喜欢) print u'首页第二屏(猜你喜欢)' data = self.session.api('/api/mg/sale/index/getPageSecond') self.assertEqual(int(data['code']), 0, data['data']) # print json.dumps(data) # 请求二级页第一屏 print u'二级页第一屏' # 需要上传参数:menuId print menu_id param = {'menuId': menu_id['menuId']} data = self.session.api('/api/mg/sale/channel/getPageFirst', param) # self.assertEqual(int(data['code']), 0, data['data']) # print json.dumps(data) # 请求二级页猜你喜欢 print u'二级页猜你喜欢' print menu_id param = { 'menuId': menu_id['menuId'], 'pageIndex': menu_id['pageIndex'] } # 设置页数 currentPage = 1 # lastPage(标识是否还有下一页) lastPage = 0 while lastPage == 0: param['pageIndex'] = currentPage # 打印页数 print "REQUEST PAGE %s" % currentPage data = self.session.api('/api/mg/sale/channel/getGuessBody', param) # print data lastPage = int(data['data']['feedList'][0]['body']['lastPage']) print('lastPage', lastPage) # 页数+1 currentPage += 1 self.assertEqual(int(data['code']), 0, data['data']) # print json.dumps(data) return True # ============执行case=============== def test_01_seller_getChannel(self): print u'卖家身份:登录 -> 首页(第一屏、猜你喜欢) -> 二级菜单(第一屏、猜你喜欢) -> 退出登录' user = self.users.next() self.session.api('/api/mg/auth/user/login', user) menu_id = self.menus.random() ret = self.action_Channel(menu_id) self.assertTrue(ret) def test_02_user_getChannel(self): print u'买家身份:登录 -> 首页(第一屏、猜你喜欢) -> 二级菜单(第一屏、猜你喜欢) -> 退出登录' user = self.users.next() self.session.api('/api/mg/auth/user/login', user) menu_id = self.menus.random() ret = self.action_Channel(menu_id) self.assertTrue(ret) def test_03_no_getChannel(self): print u'游客身份:登录 -> 首页(第一屏、猜你喜欢) -> 二级菜单(第一屏、猜你喜欢) -> 退出登录' self.session.api('/api/mg/auth/user/login') menu_id = self.menus.random() ret = self.action_Channel(menu_id) self.assertTrue(ret)
class Search(unittest.TestCase): users = ReaderCsv( '/Users/dabenchen/Downloads/daben_chen_py/test_data/test_user.csv') searchs = ReaderCsv( '/Users/dabenchen/Downloads/daben_chen_py/test_data/test_search.csv') # ===========执行测试============= def setUp(self): print u'=====测试开始=====' # 调用DavdianSession() self.session = DavdianSession() def tearDown(self): print u'=====测试结束=====' self.session.api('/api/mg/auth/user/logout') # ==============测试case=============== '''logic search with `search` 首页(第一屏,第二屏[猜你喜欢]) -> 搜索建议词 -> 搜索热词 -> 搜索结果''' def action_Search(self, query=None): # 请求首页第一屏接口 print u'首页第一屏' data = self.session.api('/api/mg/sale/index/getPageFirst') #self.assertEqual(int(data['code']), 0, data['data']) #print data['code'] #print json.dumps(data) # 请求首页第二屏(猜你喜欢) print u'首页第二屏(猜你喜欢)' data = self.session.api('/api/mg/sale/index/getPageSecond') self.assertEqual(int(data['code']), 0, data['data']) #print json.dumps(data) # 请求搜索建议词接口 print u'搜索建议词' # q:需要带的参数 print query param = {} # 搜索参数是{} # 判断query参数 if query: param = {'q': query['q']} # print user data = self.session.api('/api/mg/sale/search/suggestKeywords', param) self.assertEqual(int(data['code']), 0, data['data']) # 取出keywords keywords = data['data']['keywords'] # 判断是否有结果;有返回Ture,否则返回False if query and query['expect'] == "true": self.assertTrue(keywords) for item in keywords: self.assertTrue(query['q'] in item) else: self.assertTrue(not keywords) # print json.dumps(data) # 请求搜索热词 print u'搜索热词' data = self.session.api('/api/mg/sale/search/getHotwords') self.assertEqual(int(data['code']), 0, data['data']) # print json.dumps(data) # return True # 请求搜索结果 print u'搜索结果' data = self.session.api('/api/mg/sale/search/getGoods') self.assertEqual(int(data['code']), 0, data['data']) # print json.dumps(data) return True # ==========执行case=============== def test_01_seller_Search(self): print u'卖家身份: 登录 -> 首页(第一屏,第二屏[猜你喜欢]) -> 搜索建议词 -> 搜索热词 -> 搜索结果 -> 退出登录' user = self.users.next() # 取user参数 # param = self.user.next() self.session.api('/api/mg/auth/user/login', user) # 登录 # query = self.searchs.next() # 取search参数 query = self.searchs.random() ret = self.action_Search(query) self.assertTrue(ret) def test_02_user_Search(self): print u'买家身份: 登录 -> 首页(第一屏,第二屏[猜你喜欢]) -> 搜索建议词 -> 搜索热词 -> 搜索结果 -> 退出登录' user = self.users.next() self.session.api('/api/mg/auth/user/login', user) # print "TEST2" # print user # return # query = self.searchs.next() query = self.searchs.random() ret = self.action_Search(query) self.assertTrue(ret) def test_03_no_Search(self): print u'游客身份: 未登录 -> 首页(第一屏,第二屏[猜你喜欢]) -> 搜索建议词 -> 搜索热词 -> 搜索结果 -> 退出登录' # query = self.searchs.next(True) query = self.searchs.random() ret = self.action_Search(query) self.assertTrue(ret)
class firstGuess_goodsDetail(unittest.TestCase): '''获取user_csv文件''' users = ReaderCsv( '/Users/dabenchen/Downloads/daben_chen_py/test_data/test_user.csv') # =====执行测试===== def setUp(self): print u'-----测试开始-----' # 调用DavdianSession() self.session = DavdianSession() def tearDown(self): print u'-----测试结束-----' self.session.api('/api/mg/auth/user/logout') # ============测试case================ def action_firstGuess_goodsDetail(self): # 请求首页第一屏 print u'首页第一屏' data = self.session.api('/api/mg/sale/index/getPageFirst') # self.assertEqual(int(data['code']), 0, data['data']) # 请求首页猜你喜欢 print u'首页猜你喜欢' data = self.session.api('/api/mg/sale/index/getPageSecond') feedList = data['data']['feedList'] contents = [] for item in feedList: if not item.has_key('body') or not item['body'].has_key( 'dataList'): continue if len(item['body']['dataList']) < 0: continue dataList = item['body']['dataList'] for data in dataList: # print (data['command']['content']) if not data.has_key('command'): continue if not data['command'].has_key('content'): continue if re.match(r'^/\d+.html', data['command']['content']): contents.append(data['command']['content']) # print contents length = len(contents) # print length randIndex = random.randint(0, length - 1) content = contents[randIndex] # print "content:%s" %(content) goodsIdurl = contents[randIndex] goodsId = re.findall(r"\d+\d*", goodsIdurl)[0] print "DEBUG\t[%s][%s]" % (u'goodsId', goodsId) # self.assertEqual(int(data['code']), 0, data['data']) # print json.dumps(data) # 请求商品详情页 print u'商品详情页' print "DEBUG\t[%s][%s]" % (u'goodsId', goodsId) param = {'goodsId': goodsId} data = self.session.api('/api/mg/good/info/detail', param) # print json.dumps(data) return True # =============执行case=============== def test_01_seller_firstGuess_goodsDetail(self): print u'卖家身份:登录 -> 首页(第一屏) -> 首页(猜你喜欢) ->[随机选择猜你喜欢列表商品id] -> 商品详情页 -> 退出登录' user = self.users.next() self.session.api('/api/mg/auth/user/login', user) ret = self.action_firstGuess_goodsDetail() # print ret self.assertTrue(ret) def test_02_user_firstGuess_goodsDetail(self): print u'买家身份:登录 -> 首页(第一屏) -> 首页(猜你喜欢) ->[随机选择猜你喜欢列表商品id] -> 商品详情页 -> 退出登录' user = self.users.next() self.session.api('/api/mg/auth/user/login', user) ret = self.action_firstGuess_goodsDetail() self.assertTrue(ret) def test_03_no_firstGuess_goodsDetail(self): print u'游客身份:登录 -> 首页(第一屏) -> 首页(猜你喜欢) ->[随机选择猜你喜欢列表商品id] -> 商品详情页 -> 退出登录' #self.session.api('/api/mg/auth/user/login') ret = self.action_firstGuess_goodsDetail() self.assertTrue(ret)
class serach_addCart(unittest.TestCase): '''获取test_user.csv文件''' users = ReaderCsv( '/Users/dabenchen/Downloads/daben_chen_py/test_data/test_user.csv') '''获取test_search.csv文件''' searchs = ReaderCsv( '/Users/dabenchen/Downloads/daben_chen_py/test_data/test_search_goods.csv' ) # =======执行测试======== def setUp(self): print u'-----测试开始-----' # 调用DavdianSession() self.session = DavdianSession() def tearDown(self): print u'-----测试结束-----' self.session.api('/api/mg/auth/user/logout') # ===================测试case==================== '''以下: 搜索商品 -> 商品详情页 -> 加入购物车【效验商品id】 ''' def action_search_addCart(self, keywords=None): # 请求首页搜索接口 print u'首页搜索' data = self.session.api('/api/mg/sale/index/getSearch') self.assertEqual(int(data['code']), 0, data['data']) # print json.dumps(data) # 请求搜索结果 print u'搜索结果' param = { 'keywords': keywords['keywords'], 'h5Platform': keywords['h5Platform'], 'pageIndex': keywords['pageIndex'], 'pageSize': keywords['pageSize'], 'sort': keywords['sort'] } data = self.session.api('/api/mg/sale/search/getGoods', param) self.assertEqual(int(data['code']), 0, data['data']) # print json.dumps(data) # 取出goodsId,随机goodsId feedList = data['data']['feedList'] contents = [] for item in feedList: if not item.has_key('body') or not item['body'].has_key( 'dataList'): continue if len(item['body']['dataList']) < 0: continue dataList = item['body']['dataList'] for data in dataList: # print (data['command']['content']) if not data.has_key('command'): continue if not data['command'].has_key('content'): continue if re.match(r'^/\d+.html', data['command']['content']): contents.append(data['command']['content']) # print contents length = len(contents) randIndex = random.randint(0, length - 1) content = contents[randIndex] goodsIdurl = contents[randIndex] goodsId = int(re.findall(r"\d+\d*", goodsIdurl)[0]) print "DEBUG\t[%s][%s]" % (u'goodsId', goodsId) # 请求商品详情页 print u'商品详情页' print "DEBUG\t[%s][%s]" % (u'goodsId', goodsId) param = {'goodsId': goodsId} data = self.session.api('/api/mg/good/info/detail', param) # print json.dumps(data) # 添加购物车 print u'添加购物车' # 添加购物车的接口,需要goods: {"number":1,"goods_id":"550358"},用urllib.quote的方式 param = { 'm': 'default', 'c': 'cart', 'a': 'add_to_cart', 'goods': urllib.quote(json.dumps({ "number": 1, "goods_id": goodsId })) } print param['goods'] data = self.session.post('/cart.html', urllib.urlencode(param)) print data # 请求购物车页 print u'购物车页' response = self.session.get('/cart.html') # 请求购物车接口 print u'购物车接口' response = self.session.get('/cart.html?c=cart&a=load') data = json.loads(response['body']) # 以下:效验随机加入的商品id是不是在购物车中 cart_info = data['data']['cart_info'] goodsIds = [] activitys = cart_info['activitys'] for item in activitys: if 'goods' not in item: continue # goodsIds=[goods['goods_id'] for goods in item["goods"] if 'goods_id' in goods] for goods in item["goods"]: if 'goods_id' not in goods: continue goodsIds.append((int)(goods['goods_id'])) # print goodsId # print goodsIds self.assertTrue(goodsId in goodsIds, u"商品不在购物车中") return True # =============执行case=============== def test_01_seller_search_addCart(self): print u'卖家身份:登录 -> 搜索商品 -> 商品详情页 -> 加入购物车 -> [效验商品id] -> 退出登录' user = self.users.next() self.session.api('/api/mg/auth/user/login', user) query = self.searchs.random() ret = self.action_search_addCart(query) self.assertTrue(ret) def test_02_user_search_addCart(self): print u'买家身份:登录 -> 搜索商品 -> 商品详情页 -> 加入购物车 -> [效验商品id] -> 退出登录' user = self.users.next() self.session.api('/api/mg/auth/user/login', user) query = self.searchs.random() ret = self.action_search_addCart(query) self.assertTrue(ret) def test_03_no_search_addCart(self): print u'游客身份:登录 -> 搜索商品 -> 商品详情页 -> 加入购物车 -> [效验商品id] -> 退出登录' query = self.searchs.random() ret = self.action_search_addCart(query) self.assertTrue(ret)
class timeShop_getCart_buy(unittest.TestCase): '''获取user_csv''' users = ReaderCsv( '/Users/dabenchen/Downloads/daben_chen_py/test_data/test_user.csv') # =====执行测试===== def setUp(self): print u'----测试开始-----' # 调用DavdianSession() self.session = DavdianSession() def tearDown(self): print u'----测试结束-----' self.session.api('/api/mg/auth/user/logout') # ============测试case================ '''以下是: 登录 -> 首页限时购 -> [随机限时购商品] -> 商品详情页 -> 加入购物车 -> 订单确认 -> 去支付生成订单''' def action_timeShop_getCart_buy(self): # 请求首页限时购 print u'首页限时购' data = self.session.api('/api/mg/sale/index/getPageFirst') feedList = data['data']['feedList'] goodsIds = [] for item in feedList: if 'body' not in item or 'dataList' not in item['body']: continue if len(item['body']['dataList'] ) < 1 or 'goodsId' not in item['body']['dataList'][0]: continue goodsIds.append((int)(item['body']['dataList'][0]['goodsId'])) length = len(goodsIds) randIndex = random.randint(0, length - 1) goodsId = goodsIds[randIndex] print "DEBUG\t[%s][%s]" % (u'goodsId', goodsId) # 请求商品详情页 print u'商品详情页' print "DEBUG\t[%s][%s]" % (u'goodsId', goodsId) param = {'goodsId': goodsId} data = self.session.api('/api/mg/good/info/detail', param) # print data self.assertEqual(int(data['code']), 0, data['data']) # 判断普通商品 basis = data['data']['basis'] goodsName = basis['goodsName'] print goodsName if not basis.has_key('childs'): return (False, '') if len(basis['childs']) > 0: return (False, '') extra = data['data']['extra'] if not extra.has_key('dataList') or len(extra['dataList']) == 0: return (False, '') dataList = extra['dataList'][0] sales = dataList['sales']['goodsStocks'] status = dataList['status']['onSale'] print sales, status # 加入购物车 print u'加入购物车' param = { 'goods': urllib.quote(json.dumps({ "number": 1, "goods_id": goodsId })) } print param['goods'] data = self.session.post('/index.php?c=cart&a=add_to_cart&m=default', urllib.urlencode(param)) # 请求购物车页 print u'购物车页' response = self.session.get('/cart.html?c=cart&a=load') # print response # 效验添加商品是否在购物车中 data = json.loads(response['body']) cart_info = data['data']['cart_info'] goodsIds = {} activitys = cart_info['activitys'] for item in activitys: if 'goods' not in item: continue for goods in item['goods']: if 'goods_id' not in goods: continue goods_number = int(goods['goods_number']) goodsIds[int(goods['goods_id'])] = goods_number self.assertTrue(goodsId in goodsIds.keys(), u'添加的商品不在购物车中') # 请求订单确认页 print u'订单确认页' if sales == 0 and status != 1: return (False, '') param = {'goods[0][id]': str(goodsId), 'goods[0][number]': '1'} response1 = self.session.get( '/checkout.html?rp=goods_detail&rl=checkout' + '&' + urllib.urlencode(param)) print urllib.urlencode(param) # print response1['body'] # 判断: 游客身份跳转到登录页面 if response1['body'].find('js/login.js') != -1: return (True, response1['body']) # 订单页取出addressId,获取addressId的值 value = 'window.addressId = ' index = response1['body'].find(value) if index == -1: return (False, '') # print index add_index = index + len(value) for i in response1['body'][add_index:]: if i == ';': break add_index += 1 # print response1['body'][(index+len(value)):add_index] addressId = response1['body'][(index + len(value)):add_index] print addressId # 订单确认页,取出身份证信息id value2 = 'idcard_id = ' index = response1['body'].find(value2) if index == -1: return (False, '') add_index = index + len(value2) for j in response1['body'][add_index:]: if j == ';': break add_index += 1 idcard = response1['body'][(index + len(value2)):add_index] print u'身份信息id:', idcard # 取出订单确认页,收货人姓名 result = False soup = BeautifulSoup(response1['body'], 'html.parser') base_name = soup.find_all("span", class_='name') # print base_name # 获取good_title里的值 if len(base_name) > 0: base_name = base_name[0].get_text().strip() print u'收货人姓名:', base_name # 请求订单确认页,设置不使用红包 param = {'bonus_id': 0} response = self.session.get('/checkoutBonus.html?' + urllib.urlencode(param)) print urllib.urlencode(param) # print response result = False # 去支付,请求vode页 print u'订单确认页生成订单' param = { 'order_id': 0, 'bonus_id': 0, 'address_id': addressId, 'commission': 0, 'idcard': idcard } response = self.session.get('/vdone.html?rp=checkout&rl=next' + '&' + urllib.urlencode(param)) print urllib.urlencode(param) print response['body'] # 效验status是否等于0,不等于0打印status,msg s = json.loads(response['body']) if 'status' in s: if s['status'] != 0: print "Failed! [status not 0][status:%s][message:%s]" % ( s['status'], s['msg']) # response.("Failed! [status not 0][status:%s][message:%s]" % (s['status'], s['msg'])) return False print "SUCEESS! [status not 0][status:%s][message:%s]" % ( s['status'], s['msg']) return True # =============执行case============== def test_01_seller_timeShop_getCart_buy(self): print u'卖家身份: 登录 -> 首页限时购 -> [随机限时购商品] -> 商品详情页 -> 加入购物车 -> 订单确认 -> 去支付生成订单' user = self.users.next() self.session.api('/api/mg/auth/user/login', user) ret = self.action_timeShop_getCart_buy() self.assertTrue(ret) def test_02_user_timeShop_getCart_buy(self): print u'买家身份: 登录 -> 首页限时购 -> [随机限时购商品] -> 商品详情页 -> 加入购物车 -> 订单确认 -> 去支付生成订单' user = self.users.next() self.session.api('/api/mg/auth/user/login', user) ret = self.action_timeShop_getCart_buy() self.assertTrue(ret) def test_03_no_timeShop_getCart_buy(self): print u'游客身份: 首页限时购 -> [随机限时购商品] -> 商品详情页 -> 加入购物车 -> 订单确认 -> 登录(判断是否跳到登录页)' ret = self.action_timeShop_getCart_buy() print ret # 取出游客sess_key sess_key = self.session.session print sess_key
class search_buyGoods_pay(unittest.TestCase): '''获取test_user.csv''' users = ReaderCsv( '/Users/dabenchen/Downloads/daben_chen_py/test_data/test_user.csv') '''获取test_search_goods_buy.csv''' searchs = ReaderCsv( '/Users/dabenchen/Downloads/daben_chen_py/test_data/test_search_goods_buy.csv' ) # ======执行测试======= def setUp(self): print u'-----测试开始-----' # 调用DavdianSession() self.session = DavdianSession() def tearDown(self): print u'-----测试结束-----' self.session.api('/api/mg/auth/user/logout') ''' # 抽离下面的步骤成方法,下面调用 【多次用到的方法放在lib公用里,不是多次用到的放到tearDown下面】 def actionSearch(self): pass def actionDetail(self): pass def actionVdone(self): #need isSeller pass def action(self, handler): #search self.actionSearch() #detail self.actionDetail() #addCart #confirm #vdone self.actionVdone() #pay pass ''' # ============测试case================ '''以下是:搜索商品 -> 商品详情页 -> 立即购买 -> 订单确认页 -> 支付vdone -> 完成支付''' def action_search_buyGoods_pay(self, keywords=None, isSeller=None): # 请求首页搜索 print u'首页搜索' data = self.session.api('/api/mg/sale/index/getSearch') self.assertEqual(int(data['code']), 0, data['data']) # print json.dumps(data) print u'搜索结果' param = { 'keywords': keywords['keywords'], 'h5Platform': keywords['h5Platform'], 'pageIndex': keywords['pageIndex'], 'pageSize': keywords['pageSize'], 'sort': keywords['sort'] } data = self.session.api('/api/mg/sale/search/getGoods', param) self.assertEqual(int(data['code']), 0, data['data']) # print json.dumps(data) # 取出goodsId,随机goodsId feedList = data['data']['feedList'] contents = [] for item in feedList: if not item.has_key('body') or not item['body'].has_key( 'dataList'): continue if len(item['body']['dataList']) < 0: continue dataList = item['body']['dataList'] for data in dataList: if not data.has_key('command'): continue if not data['command'].has_key('content'): continue if re.match(r'^/\d+.html', data['command']['content']): contents.append(data['command']['content']) length = len(contents) randIndex = random.randint(0, length - 1) content = contents[randIndex] goodsIdurl = contents[randIndex] goodsId = int(re.findall(r"\d+\d*", goodsIdurl)[0]) print "DEBUG\t[%s][%s]" % (u'goodsId', goodsId) # 请求商品详情页 print u'商品详情页' print "DEBUG\t[%s][%s]" % (u'goodsId', goodsId) param = {'goodsId': goodsId} data = self.session.api('/api/mg/good/info/detail', param) # print json.dumps(data) # 判断普通商品 basis = data['data']['basis'] goodsName = basis['goodsName'] print goodsName if not basis.has_key('childs'): return (False, '') if len(basis['childs']) > 0: return (False, '') extra = data['data']['extra'] if not extra.has_key('dataList') or len(extra['dataList']) == 0: return (False, '') dataList = extra['dataList'][0] sales = dataList['sales']['goodsStocks'] status = dataList['status']['onSale'] print u'商品库存:', sales print u'是否在售:', status # 请求订单确认页 if sales == 0 and status != 1: return (False, '') param = {'goods[0][id]': str(goodsId), 'goods[0][number]': '1'} response1 = self.session.get( '/checkout.html?rp=goods_detail&rl=checkout' + '&' + urllib.urlencode(param)) print urllib.urlencode(param) # 游客身份跳转到登录 if response1['body'].find('js/login.js') != -1: return (True, response1['body']) # 订单页取出addressId,获取addressId的值 value = 'window.addressId = ' index = response1['body'].find(value) if index == -1: return (False, '') add_index = index + len(value) for i in response1['body'][add_index:]: if i == ';': break add_index += 1 addressId = response1['body'][(index + len(value)):add_index] print u'地址id:', addressId # 订单页取出身份证信息id value2 = 'idcard_id = ' index = response1['body'].find(value2) if index == -1: return (False, '') add_index = index + len(value2) for j in response1['body'][add_index:]: if j == ';': break add_index += 1 idcard = response1['body'][(index + len(value2)):add_index] print u'身份信息id:', idcard # 订单确认页取出收货人姓名 result = False soup = BeautifulSoup(response1['body'], 'html.parser') base_name = soup.find_all("span", class_='name') if len(base_name) > 0: base_name = base_name[0].get_text().strip() print u'收货人姓名:', base_name # 订单确认页,取出商品金额 result = False soup = BeautifulSoup(response1['body'], 'html.parser') good_price = soup.find_all("div", class_='good_price') #print good_price[0] dav_price = good_price[0].find_all("span", class_='dav-price') # print dav_price[0] dav_small = dav_price[0].find_all("span", class_='dav-small') small_price = dav_small[0].get_text() # print small_price dav_money = dav_price[0].get_text() # print dav_money # print dav_money[dav_money.find(small_price)+1:].strip() goods_price = dav_money[dav_money.find(small_price) + 1:].strip() print u'商品金额:', goods_price # 订单确认页,取出商品数量 result = False soup = BeautifulSoup(response1['body'], 'html.parser') goods_prices = soup.find_all("div", class_='good_price') # print goods_prices goods_price_spans = goods_prices[0].find_all("span") goods_number = goods_price_spans[-1].get_text().strip() number = 0 number_index = goods_number.find(' ') if number_index == -1: return False for char in goods_number[number_index + 1:]: if char == ' ': number_index += 1 else: break number = goods_number[number_index + 1:] print u'商品数量:', number # 订单确认页,取出goods里value result = False soup = BeautifulSoup(response1['body'], 'html.parser') confirm = soup.find_all("input", id='goods') value = confirm[0].attrs['value'] # 判断卖家/买家/游客 卖家有confirm_money、买家/游客没有confirm_money ''' if isSeller: confirm_money = confirm[0].find("span").get_text() print u'返现金额:', confirm_money else: confirm_money = 0 ''' # 订单确认页,设置不使用红包 param = {'bonus_id': 0} response = self.session.get('/checkoutBonus.html?' + urllib.urlencode(param)) print urllib.urlencode(param) # 去支付,请求vdone页 print u'订单确认页生成订单' #param = {'goods[0][id]': str(goodsId), 'goods[0][number]':number, 'goods[0][price]': goods_price, 'goods[0][act_id]':0, 'goods[0][act_stime]':0, 'goods[0][act_etime]':0, 'goods[0][price_act_id]':0, 'goods[0][price_act_type]':0, 'goods[0][income]':confirm_money, 'goods[0][pay_start_time]':0, 'goods[0][pay_start_time_format]':0, 'goods[0][pay_end_time]':0, 'goods[0][discount_price]':0, 'goods[0][advance_price]':0, 'goods[0][advance_price_one]':0,'goods[0][end_price]':0, 'goods[0][limit_num]':0, 'order_id':0, 'bonus_id':0, 'address_id':addressId, 'commission':0, 'idcard':idcard} response = self.session.get('/vdone.html?rp=checkout&rl=next' + '&' + value + '&address_id=' + addressId + '&password=&commission=0') print urllib.urlencode(param) print response['body'] # 效验status是否等于0,不等于0打印status,msg s = json.loads(response['body']) if 'status' in s: if s['status'] != 0: print "Failed! [status not 0][status:%s][message:%s]" % ( s['status'], s['msg']) return False print "SUCEESS! [status not 0][status:%s][message:%s]" % ( s['status'], s['msg']) # 取出vode页的跳转支付url p = json.loads(response['body']) # print pay if 'url' not in p: return False pay_url = p['url'] print pay_url # 请求跳转支付url url = pay_url response = requests.get(pay_url) print u'status_code:', response.status_code # print response.text # 取出pay_url,取出pay_url的order_id result = False soup = BeautifulSoup(response.text, 'html.parser') cashier_pay_type = soup.find_all('div', class_='cashier_pay_type') k = cashier_pay_type[0] for k in cashier_pay_type[0].find_all('a'): print(k['href']) url = k['href'] # https://18600967174.davdian.com/index.php?c=AgentPay&a=index&order_id=31342469 order_id = re.findall(r'\d+', url)[-1] print u'order_id:', order_id return True # ============执行case============== def test_01_seller_search_buyGoods_pay(self): print u'卖家身份: 登录 -> 搜索商品 -> 商品详情页 -> 立即购买 -> 订单确认页 -> 去支付 -> 生成订单(取出order_id)' user = self.users.next() self.session.api('/api/mg/auth/user/login', user) query = self.searchs.random() ret = self.action_search_buyGoods_pay(query, True) self.assertTrue(ret) def test_02_user_search_buyGoods_pay(self): print u'买家身份: 登录 -> 搜索商品 -> 商品详情页 -> 立即购买 -> 订单确认页 -> 去支付 -> 生成订单(取出order_id)' user = self.users.next() self.session.api('/api/mg/auth/user/login', user) query = self.searchs.random() ret = self.action_search_buyGoods_pay(query, False) self.assertTrue(ret) def test_03_no_search_buyGoods_pay(self): print u'游客身份: 搜索商品 -> 商品详情页 -> 立即购买 -> 订单确认页 -> 去支付 -> 登录(判断是否跳到登录页)' query = self.searchs.random() ret = self.action_search_buyGoods_pay(query, False) self.assertTrue(ret)
class channelGuess_goodsDetail(unittest.TestCase): '''获取test_user.csv文件''' users = ReaderCsv( '/Users/dabenchen/Downloads/daben_chen_py/test_data/test_user.csv') '''获取test_menu.csv文件''' menus = ReaderCsv( '/Users/dabenchen/Downloads/daben_chen_py/test_data/test_menu.csv') # =====执行测试===== def setUp(self): print u'-----测试开始-----' # 调用DavdianSession() self.session = DavdianSession() def tearDown(self): print u'-----测试结束-----' self.session.api('/api/mg/auth/user/logout') # ==============测试case=================== '''以下是: 登录 -> 二级菜单页(第一屏/猜你喜欢) -> [随机选择猜你喜欢列表商品id] -> 商品详情页 -> 退出登录''' def action_channelGuess_goodsDetail(self, menu_id=None): # 请求二级菜单页第一屏 print u'二级菜单页第一屏' # 业务上传参数:menuId print "DEBUG\t[%s][%s]" % (u'menu_id', menu_id) param = {'menuId': menu_id['menuId']} data = self.session.api('/api/mg/sale/channel/getPageFirst', param) # self.assertEqual(int(data['code']), 0, data['data']) # 请求二级菜单页猜你喜欢 print u'二级菜单页猜你喜欢' print menu_id param = { 'menuId': menu_id['menuId'], 'pageIndex': menu_id['pageIndex'] } data = self.session.api('/api/mg/sale/channel/getGuessBody', param) '''抽取猜你喜欢列表商品''' feedList = data['data']['feedList'] contents = [] for item in feedList: if not item.has_key('body') or not item['body'].has_key( 'dataList'): continue if len(item['body']['dataList']) < 0: continue dataList = item['body']['dataList'] for data in dataList: if not data.has_key('command'): continue if re.match('^/\d+.html', data['command']['content']): contents.append(data['command']['content']) print "DEBUG\t[%s][%s]" % (u'contents', contents) print contents length = len(contents) # print length print "DEBUG\t[%s][%s]" % (u'length', length) randIndex = random.randint(0, length - 1) content = contents[randIndex] goodsIdurl = contents[randIndex] goodsId = re.findall(r"\d+\d*", goodsIdurl)[0] print "DEBUG\t[%s][%s]" % (u'goodsId', goodsId) # self.assertEqual(int(data['code']), 0, data['data']) # 请求商品详情页 print u'商品详情页' param = {'goodsId': goodsId} data = self.session.api('/api/mg/good/info/detail', param) # print json.dumps(data) return True # =============执行case=============== def test_01_seller_channelGuess_goodsDetail(self): print u'卖家身份:登录 -> 二级菜单页(第一屏/猜你喜欢) -> [随机选择猜你喜欢商品id] -> 商品详情页 -> 退出登录' user = self.users.next() self.session.api('/api/mg/auth/user/login', user) menu_id = self.menus.random() ret = self.action_channelGuess_goodsDetail(menu_id) # print ret self.assertTrue(ret) def test_02_user_channelGuess_goodsDetail(self): print u'买家身份:登录 -> 二级菜单页(第一屏/猜你喜欢) -> [随机选择猜你喜欢商品id] -> 商品详情页 -> 退出登录' user = self.users.next() self.session.api('/api/mg/auth/user/login', user) menu_id = self.menus.random() ret = self.action_channelGuess_goodsDetail(menu_id) self.assertTrue(ret) def test_03_no_channelGuess_goodsDetail(self): print u'游客身份:登录 -> 二级菜单页(第一屏/猜你喜欢) -> [随机选择猜你喜欢商品id] -> 商品详情页 -> 退出登录' menu_id = self.menus.random() ret = self.action_channelGuess_goodsDetail(menu_id) self.assertTrue(ret)
def setUp(self): print u'=====测试开始=====' # 调用DavdianSession() self.session = DavdianSession()
class homePage(unittest.TestCase): users = ReaderCsv( '/Users/dabenchen/Downloads/daben_chen_py/test_data/test_user.csv') ''' # 读取test_user.csv def load(self): self.user = [] with open("/Users/dabenchen/Documents/davdian_python/test_api_dvd/test_data/test_user.csv", "rb") as fd: reader = csv.reader(fd) print reader for arr in reader: self.user.append({'mobile': arr[0], 'password':arr[1]}) # 取出test_user.csv文件 def randUser(self): self.load() return self.user ''' # ===================执行case=============== def setUp(self): print u'=======测试开始======' # self.load() # self.users = ReaderCsv('/Users/dabenchen/Documents/davdian_python/test_api_dvd/test_data/test_user.csv') #self.datafile.loadCsv() #self.datafile.randCsv() # 调用DavdianSession() self.session = DavdianSession() def tearDown(self): print u'=======测试结束======' self.session.api('/api/mg/auth/user/logout') # =======================测试case=========================== def action_pageFirst(self): # 请求首页第一屏接口 print u'首页第一屏' data = self.session.api('/api/mg/sale/index/getPageFirst') # self.assertEqual(int(data['code']), 0, data['data']) # print json.dumps(data) # 请求首页搜索接口 print u'首页搜索' data = self.session.api('/api/mg/sale/index/getSearch') self.assertEqual(int(data['code']), 0, data['data']) # print json.dumps(data) # 请求首页菜单接口 print u'首页菜单' data = self.session.api('/api/mg/sale/index/getMenu') self.assertEqual(int(data['code']), 0, data['data']) # print json.dumps(data) # 请求首页第二屏(猜你喜欢) print u'首页第二屏(猜你喜欢)' data = self.session.api('/api/mg/sale/index/getPageSecond') self.assertEqual(int(data['code']), 0, data['data']) # print json.dumps(data) return True # 不return,下面执行报错None def test_01_seller_pageFirst(self): print u'卖家身份: 登录 -> 首页(首页第一屏、首页搜索、首页菜单、首页猜你喜欢) -> 退出登录' user = self.users.next() self.session.api('/api/mg/auth/user/login', user) # ipdb.set_trace() ret = self.action_pageFirst() self.assertTrue(ret) def test_02_user_pageFirst(self): print u'买家身份: 登录 -> 首页(首页第一屏、首页搜索、首页菜单、首页猜你喜欢) -> 退出登录' user = self.users.next() self.session.api('/api/mg/auth/user/login', user) ret = self.action_pageFirst() self.assertTrue(ret) def test_03_no_pageFirst(self): print u'游客身份: 登录 -> 首页(首页第一屏、首页搜索、首页菜单、首页猜你喜欢) -> 退出登录' # self.session.api('/api/mg/auth/user/login', self.user[1]) ret = self.action_pageFirst() self.assertTrue(ret)
class timeShop_goodsDetail(unittest.TestCase): '''获取user_csv文件''' users = ReaderCsv( '/Users/dabenchen/Downloads/daben_chen_py/test_data/test_user.csv') # =====执行测试===== def setUp(self): print u'------测试开始------' # 调用DavdianSession() self.session = DavdianSession() def tearDown(self): print u'-----测试结束------' self.session.api('/api/mg/auth/user/logout') # ============测试case================ '''以下是:登录 -> 首页(第一屏) ->[随机选择限时购列表商品id] -> 商品详情页 -> 退出登录''' def action_timeShop_goodsDetail(self): # 请求首页第一屏 print u'首页第一屏' data = self.session.api('/api/mg/sale/index/getPageFirst') feedList = data['data']['feedList'] goodsIds = [] for item in feedList: if 'body' not in item or 'dataList' not in item['body']: continue if len(item['body']['dataList'] ) < 1 or 'goodsId' not in item['body']['dataList'][0]: continue goodsIds.append((int)(item['body']['dataList'][0]['goodsId'])) length = len(goodsIds) randIndex = random.randint(0, length - 1) goodsId = goodsIds[randIndex] print "DEBUG\t[%s][%s]" % (u'goodsId', goodsId) # self.assertEqual(int(data['code']), 0, data['data'] # print json.dumps(data) # 请求首页猜你喜欢 print u'首页猜你喜欢' data = self.session.api('/api/mg/sale/index/getPageSecond') self.assertEqual(int(data['code']), 0, data['data']) # print json.dumps(data) # 请求商品详情页 print u'商品详情页' print "DEBUG\t[%s][%s]" % (u'goodsId', goodsId) param = {'goodsId': goodsId} data = self.session.api('/api/mg/good/info/detail', param) # print data self.assertEqual(int(data['code']), 0, data['data']) # print json.dumps(data) return True # =============执行case=============== def test_01_seller_timeShop_goodsDetail(self): print u'卖家身份:登录 -> 首页(第一屏) ->[随机选择限时购列表商品id] -> 商品详情页 -> 退出登录' user = self.users.next() self.session.api('/api/mg/auth/user/login', user) ret = self.action_timeShop_goodsDetail() # print ret self.assertTrue(ret) def test_02_user_timeShop_goodsDetail(self): print u'买家身份:登录 -> 首页(第一屏) ->[随机选择限时购列表商品id] -> 商品详情页 -> 退出登录' user = self.users.next() self.session.api('/api/mg/auth/user/login', user) ret = self.action_timeShop_goodsDetail() self.assertTrue(ret) def test_03_no_timeShop_goodsDetail(self): print u'游客身份:登录 -> 首页(第一屏) ->[随机选择限时购列表商品id] -> 商品详情页 -> 退出登录' #self.session.api('/api/mg/auth/user/login') ret = self.action_timeShop_goodsDetail() self.assertTrue(ret)
class timeShop_addCart(unittest.TestCase): '''获取test_user.csv文件''' users = ReaderCsv( '/Users/dabenchen/Downloads/daben_chen_py/test_data/test_user.csv') # '''获取test_cart.csv文件''' # carts = ReaderCsv('/Users/dabenchen/Documents/davdian_python/test_api_dvd/test_data/test_cart.csv') # =====执行测试====== def setUp(self): print u'-----测试开始-----' # 调用DavdianSession() self.session = DavdianSession() def tearDown(self): print u'-----测试结束-----' self.session.api('/api/mg/auth/user/logout') # ==============测试case================== '''以下是:登录 -> 首页(第一屏) -> 【随机获取第一屏/限时购列表商品id】 -> 商品详情页 -> 加入购物车 -> 退出登录''' def action_getCart(self): # 请求首页第一屏 print u'首页第一屏' data = self.session.api('/api/mg/sale/index/getPageFirst') feedList = data['data']['feedList'] goodsIds = [] for item in feedList: if 'body' not in item or 'dataList' not in item['body']: continue if len(item['body']['dataList'] ) < 1 or 'goodsId' not in item['body']['dataList'][0]: continue goodsIds.append((int)(item['body']['dataList'][0]['goodsId'])) length = len(goodsIds) randIndex = random.randint(0, length - 1) goodsId = goodsIds[randIndex] print "DEBUG\t[%s][%s]" % (u'goodsId', goodsId) # self.assertEqual(int(data['code']), 0, data['data']) # print json.dumps(data) # 请求商品详情页 print u'商品详情页' print "DEBUG\t[%s][%s]" % (u'goodsId', goodsId) param = {'goodsId': goodsId} data = self.session.api('/api/mg/good/info/detail', param) self.assertEqual(int(data['code']), 0, data['data']) # return True # 添加购物车 print u'添加购物车' # 添加购物车的接口,需要goods: {"number":1,"goods_id":"550358"},用urllib.quote的方式 param = { 'm': 'default', 'c': 'cart', 'a': 'add_to_cart', 'goods': urllib.quote(json.dumps({ "number": 1, "goods_id": goodsId })) } print param['goods'] # 购物车这里直接用post请求,**需要urlencode** data = self.session.post('/cart.html', urllib.urlencode(param)) print data # self.assertEqual(int(data['code']), 0, data['data']) # 请求购物车页面 print u'购物车页面' response = self.session.get('/cart.html') # print response # return "购物车" in response['body'] # 请求购物车接口 print u'购物车接口' response = self.session.get('/cart.html?c=cart&a=load') # print response data = json.loads(response['body']) # 以下:效验随机加入的商品id是不是在购物车中 cart_info = data['data']['cart_info'] goodsIds = [] activitys = cart_info['activitys'] for item in activitys: if 'goods' not in item: continue # goodsIds=[goods['goods_id'] for goods in item["goods"] if 'goods_id' in goods] for goods in item["goods"]: if 'goods_id' not in goods: continue goodsIds.append((int)(goods['goods_id'])) # print goodsId # print goodsIds self.assertTrue(goodsId in goodsIds, u"商品不在购物车中") return True # =============执行case=============== def test_01_seller_getCart(self): print u'卖家身份: 登录 -> 首页(第一屏) -> 【随机获取限时购商品id】 -> 商品详情页 -> 加入购物车(效验添加的商品id)-> 退出登录' user = self.users.next() self.session.api('/api/mg/auth/user/login', user) # cart = self.carts.random() ret = self.action_getCart() self.assertTrue(ret) def test_02_user_addCart(self): print u'买家身份: 登录 -> 首页(第一屏) -> 【随机获取限时购商品id】 -> 商品详情页 -> 加入购物车(效验添加的商品id)-> 退出登录' user = self.users.next() self.session.api('/api/mg/auth/user/login', user) ret = self.action_getCart() self.assertTrue(ret) def test_03_no_addCart(self): print u'游客身份: 登录 -> 首页(第一屏) -> 【随机获取限时购商品id】 -> 商品详情页 -> 加入购物车(效验添加的商品id)-> 退出登录' # self.session.api('/api/mg/auth/user/login') # self.assertEqual(int(data['code']), 0, data['data']) ret = self.action_getCart() # print ret self.assertTrue(ret)
class getChannel_getCart_buy(unittest.TestCase): '''获取user_csv''' users = ReaderCsv( '/Users/dabenchen/Downloads/daben_chen_py/test_data/test_user.csv') '''获取test_menu.csv''' menus = ReaderCsv( '/Users/dabenchen/Downloads/daben_chen_py/test_data/test_menu.csv') # ======执行测试======= def setUp(self): print u'-----测试开始-----' # 调用DavdianSession() self.session = DavdianSession() def tearDown(self): print u'-----测试结束-----' self.session.api('/api/mg/auth/user/logout') # ============测试case================ '''以下是: 二级菜单 -> [随机商品] -> 商品详情页 -> 加入购物车 -> 订单确认页 -> 去支付 -> 生成订单''' def action_getChannel_getCart_buy(self, menu_id=None): # 请求二级菜单页第一屏 print u'二级菜单页' param = {'menuId': menu_id['menuId']} data = self.session.api('/api/mg/sale/channel/getPageFirst', param) feedList = data['data']['feedList'] contents = [] for item in feedList: if not item.has_key('body') or not item['body'].has_key( 'dataList'): continue if len(item['body']['dataList']) < 0: continue dataList = item['body']['dataList'] for data in dataList: if not data.has_key('command'): continue if re.match(r'^/\d+.html', data['command']['content']): contents.append(data['command']['content']) print "DEBUG\t[%s][%s]" % (u'contents', contents) length = len(contents) print "DEBUG\t[%s][%s]" % (u'length', length) randIndex = random.randint(0, length - 1) content = contents[randIndex] goodsIdurl = contents[randIndex] goodsId = re.findall(r"\d+\d*", goodsIdurl)[0] print "DEBUG\t[%s][%s]" % (u'goodsId', goodsId) # 请求商品详情页 print u'商品详情页' param = {'goodsId': goodsId} data = self.session.api('/api/mg/good/info/detail', param) self.assertEqual(int(data['code']), 0, data['data']) # 判断普通商品 basis = data['data']['basis'] goodsName = basis['goodsName'] print goodsName if not basis.has_key('childs'): return (False, '') if len(basis['childs']) > 0: return (False, '') extra = data['data']['extra'] if not extra.has_key('dataList') or len(extra['dataList']) == 0: return (False, '') dataList = extra['dataList'][0] sales = dataList['sales']['goodsStocks'] status = dataList['status']['onSale'] print sales, status ''' # 判断sales大于0,字符串需要转换成int if int(sales) > 0: print sales break # 多规格商品拼接: goodsName + title goodsNames = goodsName + '_' + title print goodsNames ''' # 加入购物车 print u'加入购物车' param = { 'goods': urllib.quote(json.dumps({ "number": 1, "goods_id": goodsId })) } print param['goods'] data = self.session.post('/index.php?c=cart&a=add_to_cart&m=default', urllib.urlencode(param)) # 请求购物车页面 print u'购物车页面' response = self.session.get('/cart.html?c=cart&a=load') # print response # 请求订单确认页 print u'订单确认页' if sales == 0 and status != 1: return (False, '') param = {'goods[0][id]': str(goodsId), 'goods[0][number]': '1'} response1 = self.session.get( '/checkout.html?rp=goods_detail&rl=checkout' + '&' + urllib.urlencode(param)) print urllib.urlencode(param) # 判断: 游客身份跳转到登录页面 if response1['body'].find('js/login.js') != -1: return (True, response1['body']) # print response1['body'] # 订单页取出addressId,获取addressId的值 value = 'window.addressId = ' index = response1['body'].find(value) if index == -1: return (False, '') # print index, len(value) add_index = index + len(value) for i in response1['body'][add_index:]: if i == ';': break add_index += 1 # print add_index # print response1['body'][(index+len(value)):add_index] addressId = response1['body'][(index + len(value)):add_index] print u'地址id:', addressId # 订单确认页, 取出身份证信息id value2 = 'idcard_id = ' index = response1['body'].find(value2) if index == -1: return (False, '') add_index = index + len(value2) for j in response1['body'][add_index:]: if j == ';': break add_index += 1 idcard = response1['body'][(index + len(value2)):add_index] print u'身份信息id:', idcard # 取出订单确认页,收货人姓名 result = False soup = BeautifulSoup(response1['body'], 'html.parser') base_name = soup.find_all("span", class_='name') # print base_name # 获取good_title里的值 if len(base_name) > 0: base_name = base_name[0].get_text().strip() print u'收货人姓名:', base_name ''' if goodsNames == content: result = True self.assertTrue(result, u'商品不存在!') ''' # return (result, response1['body']) # 订单确认页,设置不使用红包 param = {'bonus_id': 0} response = self.session.get('/checkoutBonus.html?' + urllib.urlencode(param)) print urllib.urlencode(param) # print response result = False # 去支付,请求vdone页 print u'订单确认页生成订单' param = { 'order_id': 0, 'bonus_id': 0, 'address_id': addressId, 'commission': 0, 'idcard': idcard } response = self.session.get('/vdone.html?rp=checkout&rl=next' + '&' + urllib.urlencode(param)) print urllib.urlencode(param) print response['body'] # 效验status是否等于0,不等于0打印status,msg s = json.loads(response['body']) if 'status' in s: if s['status'] != 0: print "Failed! [status not 0][status:%s][message:%s]" % ( s['status'], s['msg']) # response.("Failed! [status not 0][status:%s][message:%s]" % (s['status'], s['msg'])) return False print "SUCEESS! [status not 0][status:%s][message:%s]" % ( s['status'], s['msg']) return True # =============执行case============== def test_01_seller_getChannel_getCart_buy(self): print u'卖家身份: 二级菜单 -> 随机商品 -> 商品详情页 -> 加入购物车 -> 购物车结算 -> 订单确认 -> 生成订单' user = self.users.next() self.session.api('/api/mg/auth/user/login', user) menu_id = self.menus.random() ret = self.action_getChannel_getCart_buy(menu_id) self.assertTrue(ret) def test_02_user_getChannel_getCart_buy(self): print u'买家身份: 二级菜单 -> 随机商品 -> 商品详情页 -> 加入购物车 -> 购物车结算 -> 订单确认 -> 生成订单' user = self.users.next() self.session.api('/api/mg/auth/user/login', user) menu_id = self.menus.random() ret = self.action_getChannel_getCart_buy(menu_id) self.assertTrue(ret) def test_03_no_getChannel_getCart_buy(self): print u'游客身份: 二级菜单 -> 随机商品 -> 商品详情页 -> 加入购物车 -> 购物车结算 -> 订单确认 -> 登录(判断是否跳到登录页)' menu_id = self.menus.random() ret = self.action_getChannel_getCart_buy(menu_id) self.assertTrue(ret) print ret # 取出sess_key sess_key = self.session.session print sess_key
class single_getChecout(unittest.TestCase): # 获取test_user.csv users = ReaderCsv( '/Users/dabenchen/Downloads/daben_chen_py/test_data/test_user.csv') # 获取test_search_single_goods.csv searchs = ReaderCsv( '/Users/dabenchen/Downloads/daben_chen_py/test_data/test_search_single_goods.csv' ) # 设置初始化 def setUp(self): print u'-----测试开始-----' self.session = DavdianSession() def tearDown(self): print u'-----测试结束-----' self.session.api('/api/mg/auth/user/logout') # ===================测试case==================== '''以下: 搜索商品 -> 商品详情页 -> 立即购买 -> 订单确认页 ''' def action_single_getCheckout(self, keywords=None): # 请求搜索接口 print u'首页搜索' data = self.session.api('/api/mg/sale/index/getSearch') self.assertEqual(int(data['code']), 0, data['data']) # 搜索结果 print u'搜索结果' param = { 'keywords': keywords['keywords'], 'h5Platform': keywords['h5Platform'], 'pageIndex': keywords['pageIndex'], 'pageSize': keywords['pageSize'], 'sort': keywords['sort'] } data = self.session.api('/api/mg/sale/search/getGoods', param) self.assertEqual(int(data['code']), 0, data['data']) # 搜索结果取出goodsId -> 随机goodsId(商品详情) feedList = data['data']['feedList'] contents = [] for item in feedList: if not item.has_key('body') or not item['body'].has_key( 'dataList'): continue if len(item['body']['dataList']) < 0: continue dataList = item['body']['dataList'] for data in dataList: if not data.has_key('command'): continue if not data['command'].has_key('content'): continue if re.match(r'^/\d+.html', data['command']['content']): contents.append(data['command']['content']) length = len(contents) # randIndex = 0 随机固定第一个 randIndex = random.randint(0, length - 1) content = contents[randIndex] goodsIdurl = contents[randIndex] goodsId = int(re.findall(r"\d+\d*", goodsIdurl)[0]) print "DEBUG\t[%s][%s]" % (u'goodsId', goodsId) # 请求商品详情页 print u'商品详情页' print "DEBUG\t[%s][%s]" % (u'goodsId', goodsId) param = {'goodsId': goodsId} data = self.session.api('/api/mg/good/info/detail', param) # print json.dumps(data) # 判断普通商品 basis = data['data']['basis'] goodsName = basis['goodsName'] print goodsName # print json.dumps(basis) if not basis.has_key('childs'): return (False, '') if len(basis['childs']) > 0: return (False, '') extra = data['data']['extra'] # print len(extra['dataList']) if not extra.has_key('dataList') or len(extra['dataList']) == 0: return (False, '') dataList = extra['dataList'][0] sales = dataList['sales']['goodsStocks'] status = dataList['status']['onSale'] print sales, status # 请求订单确认页 if sales == 0 and status != 1: return (False, '') param = {'goods[0][id]': str(goodsId), 'goods[0][number]': '1'} # print param['goods[0][id]'] # print param['goods[0][number]'] response = self.session.get( '/checkout.html?rp=goods_detail&rl=checkout' + '&' + urllib.urlencode(param)) print urllib.urlencode(param) # print response['body'] # 判断确认订单页商品名称 # 取出response['body']里的商品名称 result = False soup = BeautifulSoup(response['body'], 'html.parser') content = soup.find_all("div", class_='good_title') print content # 获取good_title里的值 if len(content) > 0: content = content[0].get_text().strip() print "content************" print content print "content************" if goodsName == content: result = True self.assertTrue(result, u'商品不存在!') return (result, response['body']) # =============执行case============== def test_01_seller_single_getCheckout(self): print u'卖家身份: 搜索商品 -> 商品详情页 -> 立即购买 -> 订单确认页 -> 退出登录' user = self.users.next() # print "------------user1-------------" # print user # print "------------user1-------------" self.session.api('/api/mg/auth/user/login', user) query = self.searchs.random() # print query ret, body = self.action_single_getCheckout(query) self.assertTrue(ret) def test_02_user_single_getCheckout(self): print u'买家身份: 搜索商品 -> 商品详情页 -> 立即购买 -> 订单确认页 -> 退出登录' user = self.users.next() # print "------------user2-----------" # print user # print "------------user2-----------" self.session.api('/api/mg/auth/user/login', user) query = self.searchs.random() # print query ret, body = self.action_single_getCheckout(query) self.assertTrue(ret) def test_03_no_single_getCheckout(self): print u'游客身份: 搜索商品 -> 商品详情页 -> 立即购买 -> 订单确认页 -> 登录(判断是否跳到登录页)' query = self.searchs.random() ret, body = self.action_single_getCheckout(query) # 取出sess_key sess_key = self.session.session print sess_key # 截取最后8位 # sek = sess_key # print sek[32:] result = False if "js/login.js" in body: # print body result = True self.assertTrue(result)
def setUp(self): print u'-----测试开始-----' self.session = DavdianSession()
class getGoodsdetail(unittest.TestCase): '''获取csv文件''' users = ReaderCsv( '/Users/dabenchen/Documents/davdian_python/test_api_dvd/test_data/test_user.csv' ) # =====执行测试===== def setUp(self): print u'------测试开始------' # 调用DavdianSession() self.session = DavdianSession() def tearDown(self): print u'-----测试结束------' # ============测试case================ '''以下是:首页(第一屏、猜你喜欢) -> 随机取出商品id -> 各自商品详情页''' def action_Detail(self): # 请求首页第一屏 print u'首页第一屏' data = self.session.api('/api/mg/sale/index/getPageFirst') # 取feedList feedList = data['data']['feedList'] # 设定goodsIds goodsIds = [] # 遍历feedList for item in feedList: if 'body' not in item or 'dataList' not in item['body']: continue if len(item['body']['dataList'] ) < 1 or 'goodsId' not in item['body']['dataList'][0]: continue goodsIds.append((int)(item['body']['dataList'][0]['goodsId'])) # 最后包含了,所以要length - 1 length = len(goodsIds) randIndex = random.randint(0, length - 1) # 随机取goodsid,还包含了一层['body']['dataList'] #goodsidIndex = random.randint(0, len(feedList[randIndex]['body']['dataList']) - 1) #print feedList[randIndex] # 给定一个goodsId,判断,因为feedList里前几个没有goodsId goodsId = goodsIds[randIndex] # 取出goodsid # goodsId = int(data['data']['feedList'][]['body']['dataList']['goodsId']) print goodsId self.assertEqual(int(data['code']), 0, data['data']) # print json.dumps(data) # 请求商品详情页 print u'商品详情' print goodsId param = {'goodsId': goodsId} data = self.session.api('/api/mg/good/info/detail', param) # print data self.assertEqual(int(data['code']), 0, data['data']) # print json.dumps(data) return True # =============执行case=============== def test_01_seller_getGoodsdetail(self): print u'卖家身份:登录 -> 首页(随机取限时购/猜你喜欢商品) -> 商品详情页' user = self.users.next() self.session.api('/api/mg/auth/user/login', user) ret = self.action_Detail() # print ret self.assertTrue(ret)