diff --git a/TestCase/account/test_account_01.py b/TestCase/account/test_account_01.py index 6e76ed516c0ce86d46fe0f049307a0f6ff684213..f76135de7071532d5c05589128a2a1177d1cc1d4 100644 --- a/TestCase/account/test_account_01.py +++ b/TestCase/account/test_account_01.py @@ -9,6 +9,5 @@ class TestAccount: yaml_data = yaml_handler.yaml_handler.get_case(yaml_path) @pytest.mark.parametrize('case',yaml_data) def test_account(self,case): - # case = req_handler.ReqHandler.params_handler(case=case,var_class=accountData) #替换变量 req_handler.ReqHandler.send_requests(case=case,var_class=accountData) print(case) \ No newline at end of file diff --git a/TestCase/billing/test_buyPlan_01.py b/TestCase/billing/test_buyPlan_01.py index 4e2be5d1c9a09543344cd67576795e563dc1bb84..c785471f571ac1d5e5ae2b300de3f7bee1a9ba93 100644 --- a/TestCase/billing/test_buyPlan_01.py +++ b/TestCase/billing/test_buyPlan_01.py @@ -9,6 +9,5 @@ class TestBuyPlan: yaml_data = yaml_handler.yaml_handler.get_case(yaml_path) @pytest.mark.parametrize('case',yaml_data) def test_buy_plan(self,case): - case = req_handler.ReqHandler.params_handler(case=case,var_class=buyPlanData) #替换变量 req_handler.ReqHandler.send_requests(case=case,var_class=buyPlanData) print(case) \ No newline at end of file diff --git a/Utils/req_handler.py b/Utils/req_handler.py index 69f4535d79703f73746fe50f5f8d1c212d631e18..5291650dd15c725184c37359a03fb7e7d9a7e2dc 100644 --- a/Utils/req_handler.py +++ b/Utils/req_handler.py @@ -60,7 +60,7 @@ class ReqHandler: encoding='utf8') as f: content = f.read() exec(content) - return + return 1 url = case['url'] if 'http' in case['url'] else config_handler.base_config.get_value('url','test_address') + case['url'] #判断是否有域名,没有的话给config文件中的默认测试域名 method = case['method'] expected = case['expected'] @@ -72,7 +72,6 @@ class ReqHandler: if case.get('headers'): for key,value in case['headers'].items(): headers[key] = value - if method == 'post': if headers.get('content-type') == 'application/x-www-form-urlencoded' or headers.get('content-type') == 'text/xml': res = requests.request(url=url,method=method,data=data,headers=headers) @@ -84,31 +83,6 @@ class ReqHandler: res = requests.request(url=url,method=method,data=data,headers=headers) self.assert_handler(self,res=res,expected=expected) if case.get('set_value'): - import random - async def test_recv(): - data = json.dumps({ - 'action': "sendmsg", - 'data': { - 'avatar': "https://img.willdesk.com/${picUrl}", - 'clientId': websocket_handler.ws_willdesk.client_id, - 'fromId': '35948', #c端userId - 'isNote': False, - 'message': '{\"contentList\":\"testtesttest
\",\"attachmentList\":[]}', - 'msgType': 'newstext', - 'platform': 1, - 'roomChannelType': 'wk', - 'roomId': '502856393624136484', - 'roomPlatform': 'willdesk', - 'siteId': '7238', #店铺id - 'uType': 2, - 'uid': '5746', #userId - 'username': 'zhs' #品牌名称 - }, - 'seq': str(random.randint(1000000000000000, 9999999999999999)) - }) - await websocket_handler.ws_willdesk.send_message(data) - # await websocket_handler.ws_willdesk.receive_message() - asyncio.run(test_recv()) self.set_value_handler(self,res=res,item=case['set_value'],var_class=var_class) if case.get('after_sql'): sql = case['after_sql'] @@ -129,8 +103,9 @@ class ReqHandler: ws = case['ws'] # 操作端 if ws not in ['willdesk', 'customer']: raise Exception('websocket操作端填写有误') - websocket = websocket_handler.ws_willdesk if ws == 'willdesk' else websocket_handler.ws_customer - websocket_handler.ws_run(ws=websocket,case=case) + websocket = websocket_handler.ws_willdesk if ws == 'willdesk' else websocket_handler.ws_client + # websocket_handler.ws_run(ws=websocket,case=case) + websocket_handler.loop.run_until_complete(websocket_handler.ws_run(ws=websocket, case=case)) def assert_handler(self,res,expected): ''' diff --git a/Utils/websocket_handler.py b/Utils/websocket_handler.py index 4748cbacb24c2d65975a3831b29d66007ddc3e39..7b2652d7695ca2b6e5d08acb9920e53740a41271 100644 --- a/Utils/websocket_handler.py +++ b/Utils/websocket_handler.py @@ -2,6 +2,10 @@ import asyncio import websockets import time,random,json,jsonpath from Utils.global_variate import Global +from TestData.inbox.livechat_test_data import livechatData + +loop = asyncio.get_event_loop() #异步主线 + class ws: def __init__(self, url, attr): @@ -9,20 +13,25 @@ class ws: self.websocket = None self.loop = asyncio.get_event_loop() self.client_id = '' + self.attr = attr + async def get_client_id(self): + if not self.websocket: + self.websocket = await websockets.connect(self.url) + enter_res = json.loads(await self.websocket.recv()) + if enter_res.get('action'): + if enter_res['action'] in ['readMsg', 'tipmsg']: + self.client_id = enter_res['data']['clientId'] + elif enter_res['action'] == 'sendmsg': + self.client_id = enter_res['data']['response']['clientId'] + else: # action是heartbeat的情况 + self.client_id = enter_res['data']['cliend'] + else: # action是enter的情况 + self.client_id = enter_res['data']['clientId'] async def connect(self): try: self.websocket = await websockets.connect(self.url) - enter_res = eval(await self.websocket.recv()) - if enter_res.get('action'): - if enter_res['action'] in ['readMsg','tipmsg']: - self.client_id = enter_res['data']['clientId'] - elif enter_res['action'] =='sendmsg': - self.client_id = enter_res['data']['response']['clientId'] - else: #action是heartbeat的情况 - self.client_id = enter_res['data']['cliend'] - else: #action是enter的情况 - self.client_id = enter_res['data']['clientId'] + await self.get_client_id() # print(f"Connected to {self.url}") except websockets.ConnectionClosed as e: await self.close() @@ -37,9 +46,8 @@ class ws: await self.close() except Exception: print('error') - else: - # print('send重新链接') + print('send重新链接') await self.connect() await self.send_message(message) @@ -54,14 +62,13 @@ class ws: await self.close() except NameError: return message + except Exception as e: + print(e) else: print('receive重新链接') await self.connect() return await self.receive_message() - def ws_sendmsg(self,case): - pass - async def close(self): if self.websocket: await self.websocket.close() @@ -74,42 +81,36 @@ async def ws_action(ws,case): :param case: 传入用例数据 ''' action = case['action'] #操作 - expected = case['expected'] #断言 if action == 'sendmsg': - response = ws_send_handler(case=case,ws=ws) + response = await ws_send_handler(case=case,ws=ws) assert response['response']['code'] == 200 assert response['action'] == 'sendmsg' elif action == 'receive': + expected = case['expected'] # 断言 + if ws.client_id == '': + await ws.get_client_id() + msg = json.loads(await ws.receive_message()) + ws_assert(expected=expected,msg=msg) - msg = await ws.receive_message() - while msg['action'] == 'heartbeat': - time.sleep(0.1) - msg = await ws.receive_message() - result = ws_assert(expected=expected,msg=msg) - assert result - -def ws_send_handler(case,ws): - if case.get('file'): - '''预留文件处理区''' +async def ws_send_handler(case,ws): data = case['data'] # 消息数据 msgType = 'newstext' if data['type'] in ['text', 'emoji']: content = r'{"contentList":"%s","attachmentList":[]}' % data['content'] - elif data['type'] == 'picture': - content = r'{"contentList":"

","attachmentList":[]}' + elif data['type'] == 'image': + content = "{\"contentList\":\"

\",\"attachmentList\":[]}"%livechatData.imgSrc elif data['type'] == 'file': - content = r'{"contentList":"","attachmentList":[{"src":"https://img.willdesk.com/test/chat/5973/2024/03/06/6e7d5240ef4f8ecec7430851f764b2ee/新建_文本文档.txt","blobSrc":"https://img.willdesk.com/test/chat/5973/2024/03/06/6e7d5240ef4f8ecec7430851f764b2ee/新建_文本文档.txt","name":"新建 文本文档.txt","size":0,"type":"text/plain"}]}' + content = r'{"contentList":"","attachmentList":[{"src":"%s","blobSrc":"%s","name":"新建 文本文档.txt","size":0,"type":"text/plain"}]}'%(livechatData.fileSrc,livechatData.fileSrc) elif data['type'] == 'article': - content = r'{"contentList":"
article title

article_detail

View all →
","attachmentList":[]}' % \ - data['content'] + content = r'{"contentList":"
article title

article_detail

View all →
","attachmentList":[]}' %data['content'] elif data['type'] == 'rate': - content = r'[&*{"reviewContent":"

Would you mind sharing your feedback on your experience so fa222r?

","thumbsReviews":{"good":"","bad":"FeedbackURL"},"startReviews":{"one_start":"FeedbackURL","two_start":"FeedbackURL","three_start":"FeedbackURL","four_start":"","five_start":"www.baidu.com"},"reviewTitle":"How was your chat with {AgentName}222?","reviewChoose":"thumbs","askSendReview":"true","autoSendReview":"false","primaryColor":"#2C23E5"}]' + content = r'[&*{"reviewContent":"%s","thumbsReviews":{"good":"","bad":"FeedbackURL"},"startReviews":{"one_start":"FeedbackURL","two_start":"FeedbackURL","three_start":"FeedbackURL","four_start":"","five_start":"www.baidu.com"},"reviewTitle":"%s","reviewChoose":"thumbs","askSendReview":"true","autoSendReview":"false","primaryColor":"#2C23E5"}]'%(livechatData.rateContent,livechatData.rateTitle) msgType = 'rate' elif data['type'] == 'link': - content = r'{"contentList":"test","attachmentList":[]}' + content = "{\"contentList\":\"%s\",\"attachmentList\":[]}"%(livechatData.linkHref,livechatData.linkTitle) elif data['type'] == 'product': - content = r'{"contentList":"
Selling Plans Ski Wax
","attachmentList":[]}' + content = "{\"contentList\":\"
Selling Plans Ski Wax
\",\"attachmentList\":[]}" elif data['type'] == 'coupon': content = r'{"contentList":"优惠券","attachmentList":[]}' fromId = data['fromId'] if data.get('fromId') else getattr(Global, 'customerId') @@ -117,13 +118,16 @@ def ws_send_handler(case,ws): uid = data['uid'] if data.get('uid') else getattr(Global, 'userId') username = data['username'] if data.get('username') else getattr(Global, 'name') isNote = data['isNote'] if data.get('isNote') else False - roomId = data['roomId'] - messageData = { - 'action': 'sendmsg', - 'data': { - 'avatar': "https://img.willdesk.com/${picUrl}", - 'clientId': ws.client_id, - 'fromId': fromId, # c端userId + roomId = str(data['roomId']) if ws.attr == 'willdesk' else '' + avatar = 'https://img.willdesk.com/${picUrl}' if ws.attr == 'willdesk' else '' + if ws.client_id == '': + await ws.get_client_id() + client_id = ws.client_id + if ws.attr == 'willdesk': + data = { + 'avatar': avatar, + 'clientId': client_id, + 'fromId': str(fromId), # c端userId 'isNote': isNote, 'message': content, 'msgType': msgType, @@ -131,15 +135,34 @@ def ws_send_handler(case,ws): 'roomChannelType': 'wk', 'roomId': roomId, 'roomPlatform': 'willdesk', - 'siteId': siteId, # 店铺id + 'siteId': str(siteId), # 店铺id 'uType': 2, - 'uid': uid, # userId + 'uid': str(uid), # userId 'username': username # 品牌名称 - }, + } + else: + data = { + 'avator': avatar, + 'clientId': client_id, + 'isNote': isNote, + 'message': content, + 'msgType': msgType, + 'pageUrl': 'https://zhs-test.myshopify.com/', + 'platform': 1, + 'roomId': roomId, + 'sendTime': int(time.time()), + 'siteId': str(siteId), # 店铺id + 'uType': 1, + 'uid': str(fromId), # userId + 'username': Global.customerName # 品牌名称 + } + messageData = { + 'action': 'sendmsg', + 'data': data, 'seq': str(random.randint(1000000000000000, 9999999999999999)) } await ws.send_message(message=json.dumps(messageData)) - response = eval(await ws.receive_message()) + response = json.loads(await ws.receive_message()) return response def ws_assert(expected,msg): @@ -148,10 +171,6 @@ def ws_assert(expected,msg): :param res: 返回的信息 :return: ''' - try: - msg = eval(msg) - except Exception: - return 0 for item in expected: # 循环每一个断言场景 for item_key, item_value in item.items(): assert_way = item_key @@ -169,39 +188,45 @@ def ws_assert(expected,msg): elif assert_way == 'ain': assert res_path_value in value -def ws_run(ws,case): + +async def ws_run(ws,case): ''' :param ws: 传入websocket服务 :param case: 传入用例数据 ''' - loop = asyncio.get_event_loop() - loop.run_until_complete(ws_action(ws=ws,case=case)) + # asyncio.run(ws_action(ws=ws,case=case)) + task = asyncio.ensure_future(ws_action(ws=ws,case=case)) + await asyncio.wait_for(task,timeout=10) + # loop.run_until_complete(ws_action(ws=ws,case=case)) # 使用示例 # async def main(): # data = json.dumps({ # 'action': "sendmsg", # 'data': { -# 'avatar': "https://img.willdesk.com/${picUrl}", -# 'clientId': 'cnk14g7fot40rbaaqa20', -# 'fromId': '35948', +# 'avator': "", +# 'clientId': 'cnkm29etjph80j73niq0', # 'isNote': False, # 'message': '{"contentList":"testtesttest
","attachmentList":[]}', # 'msgType': 'newstext', # 'platform': 1, -# 'roomChannelType': 'wk', -# 'roomId': '502856393624136484', -# 'roomPlatform': 'willdesk', +# 'roomId': '', # 'siteId': '7238', -# 'uType': 2, -# 'uid': '5746', +# 'uType': 1, +# 'sendTime': int(time.time()), +# 'uid': '36202', # 'username': 'zhs' # }, # 'seq' : str(random.randint(1000000000000000, 9999999999999999)) # }) -# webs = ws(url=f'wss://atestws.sealapps.com/ws?platform=1&authorization=eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJpYXQiOjE3MDk3MDc4NDAsImlzcyI6IndpbGxkZXNrLmNvbSIsInN1YiI6IkxvZ2luQXV0aFRva2VuIiwidXNlcl9pbmZvIjp7ImNvbXBhbnlJZCI6NjA1OSwiYnJhbmRJZCI6NjA1MiwiY3VzdG9tZXJTZXJ2aWNlSWQiOjU3NDYsImxvZ2luUm9sZSI6MSwiY2xpZW50SWQiOiJjbmsxNGc3Zm90NDByYmFhcWEyMCIsImxvZ2luVGltZSI6MTcwOTcwNzg0MH0sImtleSI6ImFsbHBsYXRmb3JtLXdpbGxkZXNrLXVzZXIifQ.XcTxOOmKaSQDGSiZIHfx6AB83c0qlo8kzs2zQpV-XDw&t=1709710166112',attr='willdesk') +# webs = ws(url=f'wss://atestws.sealapps.com/ws?platform=1&authorization=eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJpYXQiOjE3MDk3NzY4OTgsImlzcyI6IndpbGxkZXNrLmNvbSIsInN1YiI6IkxvZ2luQXV0aFRva2VuIiwidXNlcl9pbmZvIjp7ImNvbXBhbnlJZCI6NjA1OSwiYnJhbmRJZCI6NjA1MiwiY3VzdG9tZXJTZXJ2aWNlSWQiOjU3NDYsImxvZ2luUm9sZSI6MSwiY2xpZW50SWQiOiJjbmtpMDBnNmxnY2M3MWNxZHM1ZyIsImxvZ2luVGltZSI6MTcwOTc3Njg5OH0sImtleSI6ImFsbHBsYXRmb3JtLXdpbGxkZXNrLXVzZXIifQ.EllFwfirKFTB88BzBigz64tBz1SJQFFwFp0tWlQzWVU&t=1709802959971',attr='willdesk') # await asyncio.create_task(webs.send_message(message=data)) # msg = await asyncio.create_task(webs.receive_message()) +# print(msg) # + + + + # loop = asyncio.get_event_loop() # loop.run_until_complete(main()) diff --git a/YamlCase/account/account.yaml b/YamlCase/account/account.yaml index 8ef4c555caea3d0293a6c2acde8ab3215d16fc26..bcd98bdf55a353f9501981f499d78f6fa37433c3 100644 --- a/YamlCase/account/account.yaml +++ b/YamlCase/account/account.yaml @@ -6,77 +6,77 @@ api1: set_value: {"picUrl" : "$.data.list[?(@.id == '${userId}')].profile"} expected: - eq: {"$.code" : 0} -# -#api2: -# title: 更改账户名 -# url: /api/v1/customerService/updateCustomerServiceAccount -# method: post -# data: {"id" : "${userId}" , "localLang" : "zh-CN" ,"name" : "${new_name}" , "profile" : "${picUrl}", "v" : "${v}"} -# expected: -# - eq: {"$.code" : 0} -# - eq: {"$.msg" : "success"} -# -#api3: -# title: 检查用户名 -# url: /api/v1/customerService/listCustomerService -# method: post -# data: {"isActivation" : -1,"isDelete" : -1,"v" : "${v}"} -# expected: -# - eq: {"$.code" : 0} -# - eq: {"$.data.list[?(@.id == '${userId}')].name" : "${new_name}"} -# -#api4: -# title: 检查用户名 - 首页查询账户信息接口 -# url: /api/v1/customerService/getCustomerServiceInfo?v=${v} -# method: get -# expected: -# - eq: { "$.code": 0 } -# - eq: { "$.data.name": "${new_name}" } -# -#api5: -# title: 检查用户名 - inbox页面检查资源列表接口 -# url: /api/v1/resource/getResourceItemList -# method: post -# data: {"resourceType" : "teammates" , "v" : "${v}"} -# expected: -# - eq: {"$.code" : 0} -# - eq: {"$.data.list[?(@.relId == '${userId}')].name" : "${new_name}"} -# -#api6: -# title: 更改用户的设置语言 -# url: /api/v1/customerService/updateCustomerServiceAccount -# method: post -# data: {"id" : "${userId}" , "localLang" : "${target_language}" , "profile" : "${picUrl}", "v" : "${v}"} -# after_sql: /account/account_selectLanguage.py -# expected: -# - eq: {"$.code" : 0} -# - eq: {"$.msg" : "success"} -# -#api8: -# title: 检查翻译文本接口 -# url: /api/v1/translate/transKeyValue -# before_sql: /account/account_selectTransResult.py -# method: post -# data: {"keyValue" : {"${trans_key}" : "${originValue}"},"targetLang" : "${target_language}","transType" : 1,"v" : "${v}"} -# expected: -# - eq: {"$.code": 0 } -# - eq: {"$.data.translated" : {"${trans_key}" : "${transValue}"}} -# -#api9: -# title: 检查翻译文本接口 - 2 -# url: /api/v1/translate/transText -# method: post -# data: {"targetLang" : "English","text" : ["${originValue}"]} -# expected: -# - eq: {"$.code": 0 } -# - eq: {"$.data.translated" : ["${originValue}"]} -# -# -#api10: -# title: 还原设置 -# url: /api/v1/customerService/updateCustomerServiceAccount -# method: post -# data: {"id" : "${userId}" , "localLang" : "${origin_language}" ,"name" : "${old_name}", "profile" : "${picUrl}", "v" : "${v}"} -# expected: -# - eq: {"$.code" : 0} -# - eq: {"$.msg" : "success"} + +api2: + title: 更改账户名 + url: /api/v1/customerService/updateCustomerServiceAccount + method: post + data: {"id" : "${userId}" , "localLang" : "zh-CN" ,"name" : "${new_name}" , "profile" : "${picUrl}", "v" : "${v}"} + expected: + - eq: {"$.code" : 0} + - eq: {"$.msg" : "success"} + +api3: + title: 检查用户名 + url: /api/v1/customerService/listCustomerService + method: post + data: {"isActivation" : -1,"isDelete" : -1,"v" : "${v}"} + expected: + - eq: {"$.code" : 0} + - eq: {"$.data.list[?(@.id == '${userId}')].name" : "${new_name}"} + +api4: + title: 检查用户名 - 首页查询账户信息接口 + url: /api/v1/customerService/getCustomerServiceInfo?v=${v} + method: get + expected: + - eq: { "$.code": 0 } + - eq: { "$.data.name": "${new_name}" } + +api5: + title: 检查用户名 - inbox页面检查资源列表接口 + url: /api/v1/resource/getResourceItemList + method: post + data: {"resourceType" : "teammates" , "v" : "${v}"} + expected: + - eq: {"$.code" : 0} + - eq: {"$.data.list[?(@.relId == '${userId}')].name" : "${new_name}"} + +api6: + title: 更改用户的设置语言 + url: /api/v1/customerService/updateCustomerServiceAccount + method: post + data: {"id" : "${userId}" , "localLang" : "${target_language}" , "profile" : "${picUrl}", "v" : "${v}"} + after_sql: /account/account_selectLanguage.py + expected: + - eq: {"$.code" : 0} + - eq: {"$.msg" : "success"} + +api8: + title: 检查翻译文本接口 + url: /api/v1/translate/transKeyValue + before_sql: /account/account_selectTransResult.py + method: post + data: {"keyValue" : {"${trans_key}" : "${originValue}"},"targetLang" : "${target_language}","transType" : 1,"v" : "${v}"} + expected: + - eq: {"$.code": 0 } + - eq: {"$.data.translated" : {"${trans_key}" : "${transValue}"}} + +api9: + title: 检查翻译文本接口 - 2 + url: /api/v1/translate/transText + method: post + data: {"targetLang" : "English","text" : ["${originValue}"]} + expected: + - eq: {"$.code": 0 } + - eq: {"$.data.translated" : ["${originValue}"]} + + +api10: + title: 还原设置 + url: /api/v1/customerService/updateCustomerServiceAccount + method: post + data: {"id" : "${userId}" , "localLang" : "${origin_language}" ,"name" : "${old_name}", "profile" : "${picUrl}", "v" : "${v}"} + expected: + - eq: {"$.code" : 0} + - eq: {"$.msg" : "success"} diff --git a/main.py b/main.py index ba06f4662d7856d7dada92e5feda5da2c6c7be5d..a68b5ba9c524280de36c99e786217d6b93c6099d 100644 --- a/main.py +++ b/main.py @@ -1,13 +1,17 @@ import pytest -import time +import asyncio import os from Utils.sql_handler import test_env_conn +from Utils import websocket_handler if __name__ == '__main__': - tims_str = int(time.time()) - pytest.main(['-vs','TestCase/account',f'--alluredir=./allureReports','--clean-alluredir']) - os.system(f'allure generate ./allureReports -c') + try: + pytest.main(['-vs','TestCase/inbox',f'--alluredir=./allureReports','--clean-alluredir']) + os.system(f'allure generate ./allureReports -c') # os.system('allure open ./allureReports') - test_env_conn.close_db() + finally: + print('finally') + # test_env_conn.close_db() +