def test_008_exit_message(self): # self.fp.write('=' * 100 + '\n') userInfos = random.choice(read_file(self.tokenfile)) username = userInfos['username'] token = "Bearer % s" % (userInfos['token']) memberId = Mysql().reslut_replace( f'select id from user where username={username}') to_userId = str( random.choice(list(range(5152, 5201)) + list(range(5248, 5297)))) if int(to_userId) > int(memberId): rex = f'{memberId}:{to_userId}' else: rex = f'{to_userId}:{memberId}' sql = {"_id": re.compile(rex)} db = return_mgdb('userMessage:%s.' % memberId) messageList = db.find(sql).distinct('_id') ids = [] for mid in messageList: ids.append(mid.split(":")[-1]) if len(ids) == 0: pass else: messageId = random.choice(ids) req = User_Controller(self.clientType, self.version).exit_message( token, to_userId, memberId) self.assertEqual(req.status_code, 200)
def test_006_delete_session_withuser(self): self.fp.write('=' * 100 + '\n') userInfos = random.choice(read_file(self.tokenfile)) username = userInfos['username'] token = "Bearer % s" % (userInfos['token']) memberId = Mysql().reslut_replace( f'select id from user where username={username}') mgresult = return_mgdb('userMessage:%s.' % memberId) # 聊条记录session sessionList = mgresult.distinct("sessionId") to_userId = str( random.choice(list(range(5152, 5201)) + list(range(5248, 5297)))) if int(to_userId) > int(memberId): rex = f'{memberId}:{to_userId}' else: rex = f'{to_userId}:{memberId}' req = User_Controller(self.clientType, self.version).delete_session_withuser( token, to_userId) try: assert req.status_code == 200 self.fp.write(f'======删除和某个用户的会话框:True======\n') except: self.fp.write(f'======删除和某个用户的会话框:False======\n') self.fp.write('=' * 100 + '\n')
def test_005_User_Controller_delete_message(self): self.fp.write('=' * 100 + '\n') userInfos = random.choice(read_file(self.tokenfile)) username = userInfos['username'] token = "Bearer % s" % (userInfos['token']) memberId = Mysql().reslut_replace( f'select id from user where username={username}') mgresult = mgdb('userMessage:%s.' % memberId, None, '_id', 1) messageIds = [] for data in mgresult: messageIds.append(data['_id']) InMessage = random.sample( messageIds, random.randint(1, math.ceil(len(messageIds) / 10))) newMessageIds = [] for data in messageIds: if data not in InMessage: newMessageIds.append(data) ErrorMessage = [newMessageIds[0], f'-1:{int(memberId)+1}:1'] testData = [InMessage, ErrorMessage] try: for data in testData: req = User_Controller(self.clientType, self.version).delete_message( token, data) if len(data) != 0: self.assertEqual(req.status_code, 200) for messageid in data: sql = {'_id': messageid} mgr = mgdb('userMessage:%s.' % memberId, sql, '_id', 1) self.assertEqual(len(mgr), 0) self.fp.write(f'======用户删除某条私聊消息:True======\n') except: self.fp.write(f'======用户删除某条私聊消息:False======\n') self.fp.write('=' * 100 + '\n')
def test_004_User_Controller_delete_withuser(self): self.fp.write('=' * 100 + '\n') userInfos = random.choice(read_file(self.tokenfile)) username = userInfos['username'] token = "Bearer % s" % (userInfos['token']) memberId = Mysql().reslut_replace( f'select id from user where username={username}') to_userId = str( random.choice(list(range(5152, 5201)) + list(range(5248, 5297)))) req = User_Controller(self.clientType, self.version).delete_withuser(token, to_userId) try: self.assertEqual(req.status_code, 200, msg="接口正常调通") if int(to_userId) > int(memberId): rex = f'{memberId}:{to_userId}' else: rex = f'{to_userId}:{memberId}' sql = {"_id": re.compile(rex)} mgresult = mgdb('userMessage:%s.' % memberId, sql, "createTime", -1) self.assertEqual(len(mgresult), 0, msg="删除与他人得私聊信息功能正常") self.fp.write(f'======删除和某个用户的私聊信息:True======\n') except: self.fp.write(f'======删除和某个用户的私聊信息:False======\n') self.fp.write('=' * 100 + '\n')
def test_007_user_withuser(self): """ 只要ids存在则查询出对应得结果, 如果不存在时,则不返回 :return: """ self.fp.write('=' * 100 + '\n') userInfos = random.choice(read_file(self.tokenfile)) username = userInfos['username'] token = "Bearer % s" % (userInfos['token']) memberId = Mysql().reslut_replace( f'select id from user where username={username}') to_userId = str( random.choice(list(range(5152, 5201)) + list(range(5248, 5297)))) if int(to_userId) > int(memberId): rex = f'{memberId}:{to_userId}' else: rex = f'{to_userId}:{memberId}' sql = {"_id": re.compile(rex)} db = return_mgdb('userMessage:%s.' % memberId) messageList = db.find(sql).distinct('_id') ids = [] for messageid in messageList: ids.append(messageid.split(":")[-1]) rightId = random.sample(ids, math.ceil(len(ids) / 5)) datas = [None, rightId, rightId + ["-1"]] for data in datas: req = User_Controller(self.clientType, self.version).withUserId( token, to_userId, data) if data == None: self.assertNotEqual(req.status_code, 200) elif len(data) == 0: pass else: self.assertEqual(req.status_code, 200) for mid in data: indx = data.index(mid) if mid in ids: content = db.find({ "_id": f"%s:{mid}" % rex }).distinct('content') self.assertEqual(f"u'{req.json()[indx]['content']}'", f"u'{content[0]}'") self.fp.write('=' * 100 + '\n')
def test_001_Message_Controller_chat(self): self.fp.write('=' * 100 + '\n') userInfos = random.choice(read_file(self.tokenfile)) username = userInfos['username'] token = "Bearer % s" % (userInfos['token']) req = Message_Controller(self.clientType, self.version).chat(token) try: self.assertEqual(req.status_code, 200, msg="接口请求调用成功") datas = Mysql().sql_result\ (f'SELECT friend_id FROM im_user_friend WHERE user_id=' f'(select id from user where username={username}) ORDER BY id ASC') self.assertEqual(len(req.json()), len(datas), msg="查询结果和数据库保持一致") rdatas = [] for result in req.json(): rdatas.append((int(result['id']), )) self.assertEqual(sorted(datas), sorted(rdatas)) self.fp.write(f'======查询某用户的聊天列表测试结果:True======\n') except: self.fp.write(f'======查询某用户的聊天列表测试结果:False======\n') self.fp.write('=' * 100 + '\n')
def test_002_User_Controller_backward(self): self.fp.write('=' * 100 + '\n') userInfos = random.choice(read_file(self.tokenfile)) username = userInfos['username'] token = "Bearer % s" % (userInfos['token']) memberId = Mysql().reslut_replace( f'select id from user where username={username}') to_userId = str( random.choice(list(range(5152, 5201)) + list(range(5248, 5297)))) if int(to_userId) > int(memberId): rex = f'{memberId}:{to_userId}' else: rex = f'{to_userId}:{memberId}' systime = datetime.datetime.now() systime_timestamp = int(systime.timestamp() * 1000) sqljson = { "$and": [{ "_id": re.compile(rex) }, { "createTime": { "$lte": systime } }] } req = User_Controller(self.clientType, self.version).backward(token, to_userId, systime_timestamp) mbresult = mgdb('userMessage:%s.' % memberId, sqljson, "createTime", -1) try: for i in range(len(req.json())): self.assertEqual(req.json()[i]['id'], mbresult[i]['_id'], msg='消息记录id保持一致') self.assertEqual(u'%s' % req.json()[i]["content"], u'%s' % mbresult[i]['content']) self.fp.write(f'======查询与某人的历史聊天记录(给定时间之前的消息):True======\n') except: self.fp.write(f'======查询与某人的历史聊天记录(给定时间之前的消息):False======\n') self.fp.write('=' * 100 + '\n')
def Result_concurrent_testing(threadnum, internTime, duration): with open(send_result_file, 'w') as sf: sf.truncate() with open(recv_result_file, 'w') as rf: rf.truncate() with open(result_file, 'w') as ref: ref.truncate() systime = datetime.datetime.now() endtime = systime + datetime.timedelta(seconds=duration) while (systime <= endtime): Function_thread_testing(threadnum, internTime, duration) systime = datetime.datetime.now() data_send = read_file(send_result_file) data_recv = read_file(recv_result_file) data_send_success_list = [] recv_send_success_list = [] recvTimeList = [] sendTimeList = [] heartTimeList = [] for data in data_send: if data['Code'] == 200: data_send_success_list.append(data) sendTimeList.append((data['content']['MessageId'], round(float(data['Responsetime']), 2))) destinationId = data_send_success_list[0]['destinationId'] LinkData = [] RecvMessage = [] for data in data_recv: if "HEARTBEAT_ACK" in list(data.values()): heartTimeList.append(data) elif data['messageType'] == 'MESSAGE': RecvMessage.append(data) recvTimeList.append((data['content']['MessageId'], round(float(data['Responsetime']), 2))) else: pass RECVLIST = [] for recv in recvTimeList: if recv[0] not in str(RECVLIST): RECVLIST.append(recv) # 是否漏发漏收 isintegrity = (len(data_send_success_list) == len(RECVLIST)) # 发送消息成功百分比 successrate = '%.2f' % (len(data_send_success_list) / len(data_send) * 100) # 发送消息失败百分比 errorrate = '%.2f' % ( (len(data_send) - len(data_send_success_list)) / len(data_send) * 100) # 接发收总时间 totalList = [] for Sdata in sendTimeList: for Rdata in RECVLIST: if Sdata[0] == Rdata[0]: totalList.append((Sdata[0], round(Sdata[1] + Rdata[1], 2))) # 发送数据结果 header = ['messgId', 'responseTime'] sendDF = pd.DataFrame(np.array(sendTimeList), columns=header) sendDF[['responseTime']] = sendDF[['responseTime']].apply(pd.to_numeric) sendResult = sendDF.describe() send_sumTime = sendDF['responseTime'].sum() sendResult = (sendResult.rename(columns={'responseTime': ''})) # 接收数据结果 recvDF = pd.DataFrame(np.array(RECVLIST), columns=header) recvDF[['responseTime']] = recvDF[['responseTime']].apply(pd.to_numeric) recvResult = recvDF.describe() recv_sumTime = recvDF['responseTime'].sum() recvResult = (recvResult.rename(columns={'responseTime': ''})) t1 = [] t2 = [] lowrecv = [] for data in sendTimeList: t1.append(data[0]) for data in recvTimeList: t2.append(data[0]) for data in t1: if data not in t2: lowrecv.append(data) # 发送和接受总数据结果 totalDF = pd.DataFrame(np.array(totalList), columns=header) totalDF[['responseTime']] = totalDF[['responseTime']].apply(pd.to_numeric) TotalResult = totalDF.describe() total_sumTime = totalDF['responseTime'].sum() TotalResult = (TotalResult.rename(columns={'responseTime': ''})) with open(result_file, 'w+') as f: f.write( f'EXECUTE TIME:{datetime.datetime.now()}\n' f'When thread is: {threadnum}, Duration is:{duration} seconds, WaitTime is: {internTime} seconds and send area is txt.\n' f'Message sent successfully: {len(data_send_success_list)}; Message received successfully: {len(RECVLIST)}\n' f'Whether messages sent and received are lost: {isintegrity}\n' f'The total running time is: {total_sumTime} ms\n' f'The total sending time is {send_sumTime} ms\n' f'The total time accepted is {recv_sumTime} ms.') f.write('\n') f.write( f'Because of thread receiving problem (data receiving after heartbeat is sent misses), ' f'the missed message is always: {len(lowrecv)} \n,the missed message id is:' f"{'; '.join(lowrecv)}") f.write('\n') f.write( 'Data analysis of receiving, sending and receiving information is as follows:' ) f.write(str(TotalResult)) f.write('\n') f.write('Send message data is analyzed as follows:') f.write(str(sendResult)) f.write('\n') f.write('Recv message data is analyzed as follows:') f.write(str(recvResult)) f.write('\n')
import qiniu from urllib import request from urllib import response import random from until.readTxt import read_file host = "http://139.196.57.60:9090" url = '/im/qiniu/getQiniuToken' headers = { 'Content-Type': 'application/x-www-form-urlencoded', 'clientType': 'IOS', 'User-Agent': f'Auction/5.0.0 (iPhone; iOS 10.3.3; Scale/2.00)', 'Connection': 'keep - alive' } tokenfile = rootPath + r'\TestData\token.txt' def qiniu_get_token(Authorization): qiniuurl = host + url headers.update(Authorization=Authorization) req = request.Request(qiniuurl, headers=headers) print(req.headers, req.full_url) RE = request.urlopen(req) print(RE.read()) userInfos = random.choice(read_file(tokenfile)) username = userInfos['username'] token = "Bearer % s" % (userInfos['token']) qiniu_get_token(token)