class AddLearnRecord(unittest.TestCase): def setUp(self): self.s = requests.session() self.lgin = LG(self.s) #实例化登录类 self.uid_token = self.lgin.login() #直接取第二部登录 self.header = { 'User-Agent': 'LanTingDoctor/1.3.1 (iPad; iOS 10.1.1; Scale/2.00)', 'Accept-Encoding': 'gzip, deflate', 'Accept-Language': 'zh-Hans-CN;q=1', 'Content-Type': 'application/json', 'requestApp': '3', 'requestclient': '2', 'versionForApp': '2.0', 'Authorization': 'Basic YXBpTGFudGluZ0BtZWRsYW5kZXIuY29tOkFwaVRobWxkTWxkQDIwMTM=', 'Connection': 'keep-alive' } self.log = Log() def test_addlearn_record(self): u'测试增加学习记录接口' self.log.info('--------开始测试增加学习记录接口---------') url = 'http://api.lesson.sunnycare.cc/v1/learn/chapadd' L = ['J00201'] for i in L: #加入nonce json_data = { "chap_code": i, "timestamp": str(int(time.time())), "token": self.uid_token, "nonce": get_digit() } #加入sign json_data['sign'] = get_sign(json_data) r = self.s.post(url, headers=self.header, json=json_data) try: self.log.info('请求返回的数据是%s' % r.json()) self.assertEqual('请求成功', r.json()['note']) except Exception as e: raise AssertionError self.log.error('增加章节学习记录请求失败,原因是:%s' % e) ''' #数据库查询出章节code,循环加入学习 i = 0 while i < len(chapters): json_data = {"chap_code":chapters[i][0].__str__(), "timestamp":str(time.time()), "token":self.uid_token} r = self.s.post(url,headers = self.header,json=json_data) try: self.log.info('请求返回的数据是%s' % r.json()) self.assertEqual('请求成功',r.json()['note']) except Exception as e: self.log.error('增加'+ chapters[i][0].__str__() +'章节学习记录请求失败,原因是:%s' % e ) i += 1 ''' def tearDown(self): self.s.close()
class Read_Cases(unittest.TestCase): def setUp(self): get_config = Read_Excel('../data/test_cases.xlsx', 'config') get_config.open_excel() self.table = get_config.get_sheet_table() self.nrows = get_config.get_nrows(self.table) self.ncols = get_config.get_ncols(self.table) self.test_name = get_config.get_test_name(self.table, self.nrows) self.test_mothod = get_config.get_test_method(self.table, self.nrows) self.test_url = get_config.get_test_url(self.table, self.nrows) self.test_data = get_config.get_test_data(self.table, self.nrows) self.status_code = get_config.get_test_code(self.table, self.nrows) self.except_result = get_config.get_except_result( self.table, self.nrows) self.log = Log() def test_read(self): for i in range(self.nrows - 1): self.log.info('---start----') r = requests.request(self.test_mothod[i], self.test_url[i]) try: if str(r.status_code) == self.status_code[i]: self.assertEqual(len(r.json()), int(self.except_result[i])) print('pass') except: print('test failed') def tearDown(self): pass
class ConnectSqLServer: """连接SqlServer数据库封装""" def __init__(self): self.log = Log() """判断是否连接成功""" try: self.conn = pymssql.connect(host=read_config.SQLServer_host, user=read_config.SQLServer_user, password=read_config.SQLServer_pwd, port=read_config.SQLServer_port, database='sharebuy_test', charset='utf8') self.log.info('数据库连接成功') except Exception as e: self.log.error('数据库链接异常! {}'.format(e)) def execute_sql(self, sql): """ 执行查询语句 返回的是一个包含tuple的list,list的元素是记录行,tuple的元素是每行记录的字段 """ cur = self.conn.cursor() with cur as cur: try: cur.execute(sql) except Exception as e: self.log.error('执行SQL语句出现异常:{}'.format(e)) return False else: if 'select' in sql: # 查询 resList = cur.fetchall() return resList else: self.conn.commit()
class ConnectMySqL: """ 连接mysql数据库封装 """ def __init__(self): self.log = Log() """判断是否连接成功""" try: self.conn = pymysql.connect(host=read_config.MySQL_host, database=read_config.MySQL_database, user=read_config.MySQL_user, password=read_config.MySQL_pwd, port=int(read_config.MySQL_port), charset='utf8') self.log.info('数据库连接成功') except Exception as e: self.log.error('数据库链接异常! {}'.format(e)) def execute_sql(self, sql, dict_type=False, num=1): """返回查询结果集 sql: 执行的sql语句; dict_type: 是否返回的数据是字典类型; num: 返回的数据是一个还是多个 """ if dict_type: # 返回数据字典类型 cur = self.conn.cursor(cursor=pymysql.cursors.DictCursor) else: cur = self.conn.cursor() try: with cur as cur: cur.execute(sql) # 执行sql if 'delete' in sql: self.conn.commit() # 提交 else: if num == 1: # 返回一条数据 data = cur.fetchone() if dict_type: return data else: return data[0] else: # 返回多条数据 data_str = '' data = cur.fetchall() if dict_type: return data else: for i in data: for j in i: data_str += str(j) + ',' # 拼接返回数据 return data_str except Exception as e: self.conn.rollback() self.log.error('执行SQL语句出现异常:{}'.format(e)) return None def __del__(self): self.conn.close()
def start_baidu(project_session_start): logger = Log() global driver logger.info('百度输入测试开始......{0}'.format(sys._getframe().f_code.co_name)) driver = project_session_start driver.get('http://www.baidu.com') lg = BaiduPage(driver) yield lg logger.info('百度输入测试结束......{0}'.format(sys._getframe().f_code.co_name))
class ColumnList(unittest.TestCase): def setUp(self): self.s = requests.session() self.lgin = LG(self.s) #实例化登录类 self.uid_token = self.lgin.login() self.header = { 'User-Agent': 'LanTingDoctor/1.3.1 (iPad; iOS 10.1.1; Scale/2.00)', 'Accept-Encoding': 'gzip, deflate', 'Accept-Language': 'zh-Hans-CN;q=1', 'Content-Type': 'application/json', 'requestApp': '3', 'requestclient': '2', 'versionForApp': '2.0', 'Authorization': 'Basic YXBpTGFudGluZ0BtZWRsYW5kZXIuY29tOkFwaVRobWxkTWxkQDIwMTM=', 'Connection': 'keep-alive' } self.EXCEL = Excel_util( r'C:\Users\Administrator\Desktop\Interface_testcase.xls') self.log = Log() def test_ColumnList(self): u'测试专栏列表接口' self.log.info('开始测试专栏列表接口....') url = 'http://api.lesson.sunnycare.cc/v1/spe/list' json_data = { "timestamp": str(int(time.time())), "token": self.uid_token, "time": "0" } #加入nonce参数 json_data['nonce'] = get_digit() json_data['sign'] = get_sign(json_data) print(json_data) r = self.s.post(url, headers=self.header, json=json_data, verify=False) self.EXCEL.write_value(4, 5, r.json()) print(r.json()) self.assertEqual('请求成功.', r.json()['note']) data = r.json()['data'] content = data['list'] #专栏列表的内容 self.assertTrue(len(content) >= 1, msg='专栏列表为空,肯定有问题!') spe_codes = {} n = 1 for i in r.json()['data']['list']: spe_codes['spe_code' + str(n)] = i['spe_code'] n += 1 self.EXCEL.write_value(4, 6, (spe_codes)) self.log.info('专栏列表接口测试结束!!') def tearDown(self): self.s.close()
class Login(unittest.TestCase): def setUp(self): self.log = Log() self.request = Request() @ddt.data(*testdata) def test_login(self, data): #获取requests 的post/get方法 post_method = data['method'] #获取需要提交的参数 post_data = { 'username': data['username'], 'password': data['password'] } #获取请求的url post_url = data['url'] #获取请求头 post_header = {} #记录日志 self.log.info('----login %s start----' % data['testname']) #请求 r = self.request.request(post_method, post_url, post_data) result = r.json() #断言 if r.status_code == 200: try: self.assertEqual(result['username'], data['username']) except Exception as e: raise e elif r.status_code == 400: try: self.assertEqual(str(result['code']), data['code']) self.assertEqual(result['msg'], data['msg']) except Exception as e: raise e elif r.status_code == 401: try: self.assertEqual(str(result['code']), data['code']) self.assertEqual(result['msg'], data['msg']) except Exception as e: raise e self.log.info('----login %s end----' % data['testname']) def tearDown(self): pass
def get(self, url, **dataset): params = dataset.get('params') headers = dataset.get('headers') lg = Log() try: resp = requests.get(url, params=params, headers=headers, timeout=5) text = resp.json() status_code = resp.status_code return text, status_code except Exception as e: lg.info(u'get请求错误:%s' % e)
class Baidu(unittest.TestCase): def setUp(self): self.log = Log() def tearDown(self): pass def test_baidu(self): self.log.info('----start----') r = requests.get('http://www.baidu.com') self.log.info('----end----')
def get_response(self,url,method,**dataset): resp = None code = None if method == 'get': resp,code = HTTPService().get(url,**dataset) elif method == 'post': resp,code = HTTPService().post(url,**dataset) else: lg = Log() lg.info(u'暂不支持该请求方法') return resp,code
def run(): def resolution(string): p = string.split('x') if len(p) != 2: raise argparse.ArgumentTypeError('not a valid resolution') try: p[0] = int(p[0]) p[1] = int(p[1]) except: raise argparse.ArgumentTypeError('not a valid resolution') return tuple(p) parser = argparse.ArgumentParser(description='Yamosg Client') parser.add_argument('-u', '--username', default='foo') parser.add_argument('-p', '--password', default='bar') parser.add_argument('-r', '--resolution', type=resolution, default=(800, 600)) parser.add_argument('-c', '--logconfig', default=resources.realpath('client.conf')) parser.add_argument('host', metavar='HOST', nargs='?', default='localhost') parser.add_argument('port', metavar='PORT', nargs='?', type=int, default='1234') args = parser.parse_args() if os.path.exists(args.logconfig): print args.logconfig logging.config.fileConfig(args.logconfig) else: print >> sys.stderr, 'logconfig', args.logconfig, 'not found, logging disabled' log = Log() log.info('Yamosg starting (%s)', pf.system()) pygame.display.init() client = Client(args.resolution, args.host, args.port, args.username, args.password) signal(SIGINT, quit) # create "superglobal" access to the client- and game instances __builtins__['client'] = client __builtins__['game'] = client._game # hack client.run() log.info('Yamosg stopping')
class TestTwo(): def __init__(self): self.data = OperationData() self.data.op_data('test2') self.ya = OperationYaml('test2') self.run = RunMethon() self.log = Log() def testTaobao(self): self.log.info('-----开始执行第二个文件,第一个用例-----') data = self.ya.get_data('test2_1') rel = self.run.run_main(self.data.method[0], self.data.url[0], data) print(rel) return rel
class ZipMethod(object): """压缩文件的公共方法""" def __init__(self, file_path): self.file_path = file_path self.log = Log() def zip_files(self, zip_name): """将路径下的所有文件压缩成zip包""" data = os.listdir(self.file_path) zip_file = zipfile.ZipFile(zip_name, 'w', zipfile.ZIP_DEFLATED) for file in data: self.log.info('%s正在压缩中......' % file) zip_file.write(os.path.join(self.file_path, file)) zip_file.close() self.log.info('压缩完成') def zip_path(self, zip_name, zip_file): """指定具体文件按照全路径进行压缩""" data = os.listdir(self.file_path) if len(data) == None or len(data) < 1: self.log.warning('待压缩的文件目录:%s' % self.file_path + '里面不存在文件,不需要压缩') else: zip = zipfile.ZipFile(zip_name, "w", zipfile.ZIP_DEFLATED) if zip_file not in data: self.log.info('您所要压缩的文件不存在,请再次确认!') else: zip.write(os.path.join(self.file_path, zip_file)) self.log.info('压缩完成') zip.close()
class TestBaidu(unittest.TestCase): def setUp(self): self.driver = get_driver() self.log = Log() self.driver.get("https://www.baidu.com") self.driver.maximize_window() self.SearchPage = SearchPage(self.driver) def test_search(self): self.SearchPage.action("pageObject设计模式") self.log.info("百度搜索成功") handles = self.driver.window_handles self.driver.switch_to.window(handles[1]) self.log.info("切换句柄成功")
class Register(unittest.TestCase): def setUp(self): self.log = Log() self.request = Request() @ddt.data(*testdata) def test_register(self, data): #获取请求方法 post_method = data['method'] #获取请求的URL post_url = data['url'] #需要传递的参数 post_data = { 'username': data['username'], 'password': data['password'], 'password_confirmation': data['password_confirmation'] } #记录日志 self.log.info('----register test start----') #请求 r = self.request.request(post_method, post_url, post_data) result = r.json() #断言 if r.status_code == 200: try: self.assertEqual(data['username'], result['username']) except Exception as e: raise e elif r.status_code == 400: try: self.assertEqual(int(data['code']), result['code']) self.assertEqual(data['msg'], result['msg']) except Exception as e: raise e self.log.info('----register test end----') def tearDown(self): pass
class CreateTasks(unittest.TestCase): def setUp(self): self.log = Log() self.common = Common() self.request = Request() @ddt.data(*testdata) def test_create_task(self, data): #获取请求方法 method = data['method'] #获取请求URL url = data['url'] #获取请求参数 desc = data['desc'] title = data['title'] param = {'title': title, 'desc': desc} #获取token token = self.common.login() header = {'Authorization': 'Bearer ' + token} #记录日志 self.log.info('----createtask test start----') #请求 r = self.request.request(method, url, param, header) r_json = r.json() #断言 if data['result'] == 1: try: self.assertEqual(r_json['desc'], data['desc']) self.assertEqual(r_json['title'], data['title']) except Exception as e: raise e elif data['result'] == 0: try: self.assertEqual(r_json['msg']['name'], 'SequelizeValidationError') except Exception as e: raise e self.log.info('----createtask test end----') def tearDown(self): pass
class TestOne(unittest.TestCase): def setUp(self): self.log = Log() print('TestOne_setup!!!!') def testOne_01(self): u'''TestOne测试用例01!!!''' # browser = webdriver.Chrome() # browser.get('https://www.baidu.com/') self.assertEquals(1, 2) self.log.info('测试用例01') #browser.quit() def testOne_02(self): u'''TestOne测试用例02!!!''' self.assertEquals(2, 2) self.log.info('测试用例02')
class Feedback(unittest.TestCase): def setUp(self): self.s = requests.session() self.lgin = LG(self.s) #实例化登录类 self.uid_token = self.lgin.get_token() #直接取账号登录的token self.auto_login_token = self.lgin.get_autologin_token() #取自动登录的token self.header = { 'User-Agent': 'LanTingDoctor/2.0.2 (iPad; iOS 10.1.1; Scale/2.00)', 'Accept-Encoding': 'gzip, deflate', 'Accept-Language': 'zh-Hans-CN;q=1', 'Content-Type': 'application/json', 'requestApp': '3', 'requestclient': '2', 'versionForApp': '2.0', 'Authorization': 'Basic YXBpTGFudGluZ0BtZWRsYW5kZXIuY29tOkFwaVRobWxkTWxkQDIwMTM=', 'Connection': 'keep-alive' } self.log = Log() @unittest.skip('无理由跳过!') def test_feedback(self): u'测试一键反馈接口' self.log.info('测试意见反馈只反馈文字') url = 'http://api.rih.medohealth.com/API/V1/UserFeedBack/addAUserFeedBack' json_data = { "ufbTitle": "反馈信息", "ufbUIUID": "IKxSa8XhbiJH1CYlwQvkW50oLefZ62uB", "ufbDesc": "urjrjfjfjfjfjfjrjrjjffjj", "token": self.auto_login_token, "ufbImages": "[]", } r = self.s.post(url, headers=self.header, json=json_data) print(r.json()) self.assertEqual('反馈成功', r.json()['msg'], msg='只反馈文字出错了') self.log.info('意见反馈只反馈文字成功!') self.log.info('测试意见反馈反馈图片和文字:') json_data2 = { "ufbTitle": "反馈信息", "ufbUIUID": "IKxSa8XhbiJH1CYlwQvkW50oLefZ62uB", "ufbDesc": "南京今天", "ufbImages": "[\"feedbackimages\/23411.png\"]", "token": "" } r2 = self.s.post(url, headers=self.header, json=json_data2) print('r2', r2.json()) self.assertEqual('反馈成功', r.json()['msg'], msg='反馈出错了') self.log.info('测试意见反馈反馈图片和文字成功!') def tearDown(self): self.s.close()
def post(self, url, **kwargs): '''封装yyj方法''' # 获取请求参数 log = Log() params = kwargs.get("params") data = kwargs.get("data") json = kwargs.get("json") files = kwargs.get("files") headers = kwargs.get("headers") try: result = requests.post(url, params=params, data=data, json=json, files=files, headers=headers) log.info(result.content.decode('utf-8')) return result except Exception as e: print("post请求错误: %s" % e)
def post(self, url, **dataset): params = dataset.get('params') headers = dataset.get('headers') data = dataset.get('data') json = dataset.get('json') files = dataset.get('files') lg = Log() try: resp = requests.post(url, params=params, headers=headers, data=data, json=json, files=files, timeout=5) status_code = resp.status_code text = resp.json() return text, status_code except Exception as e: lg.info(u'post请求错误:%s' % e)
class SendMail: def __init__(self): self.config = Config() self.log = Log() def sendMail(self): msg = MIMEMultipart() # body = """ # <h3>Hi,all</h3> # <p>本次接口自动化测试报告如下。</p> # """ arset='utf-8') stress_body = [] result_body = [] body2 = 'Hi,all\n本次接口自动化测试报告如下:\n 接口响应时间集:%s\n 接口运行结果集:%s' % (stress_body, result_body) mail_body2 = MIMEText(body2, _subtype='plain', _charset='utf-8') tm = time.strftime("%Y-%m-%d %H:%M:%S", time.localtime(time.time())) msg['Subject'] = Header("接口自动化测试报告"+"_"+tm, 'utf-8') msg['From'] = self.config.get('email','sender') receivers = self.config.get('email','receiver') toclause = receivers.split(',') msg['To'] = ",".join(toclause) # msg.attach(mail_body) msg.attach(mail_body2) try: smtp = smtplib.SMTP() smtp.connect(self.config.get('email','smtpserver')) smtp.login(self.config.get('email','username'), self.config.get('email','password')) smtp.sendmail(self.config.get('email','sender'), toclause, msg.as_string()) except Exception as e: print(e) print("发送失败") self.log.error("邮件发送失败,请检查邮件配置") else: print("发送成功") self.log.info("邮件发送成功") finally: smtp.quit()
def run(): def resolution(string): p = string.split('x') if len(p) != 2: raise argparse.ArgumentTypeError('not a valid resolution') try: p[0] = int(p[0]) p[1] = int(p[1]) except: raise argparse.ArgumentTypeError('not a valid resolution') return tuple(p) parser = argparse.ArgumentParser(description='Yamosg Client') parser.add_argument('-u', '--username', default='foo') parser.add_argument('-p', '--password', default='bar') parser.add_argument('-r', '--resolution', type=resolution, default=(800,600)) parser.add_argument('-c', '--logconfig', default=resources.realpath('client.conf')) parser.add_argument('host', metavar='HOST', nargs='?', default='localhost') parser.add_argument('port', metavar='PORT', nargs='?', type=int, default='1234') args = parser.parse_args() if os.path.exists(args.logconfig): print args.logconfig logging.config.fileConfig(args.logconfig) else: print >> sys.stderr, 'logconfig', args.logconfig, 'not found, logging disabled' log = Log() log.info('Yamosg starting (%s)', pf.system()) pygame.display.init() client = Client(args.resolution, args.host, args.port, args.username, args.password) signal(SIGINT, quit) # create "superglobal" access to the client- and game instances __builtins__['client'] = client __builtins__['game'] = client._game # hack client.run() log.info('Yamosg stopping')
def yyy(r_type, parameter_type, sheet, row_name, ip, field=[], valu=[]): global result cfg = ConfigParser() cfg.read('../yyyTest/common/config.ini') ip1 = (cfg.get('server', 'ip1')) ip2 = (cfg.get('server', 'ip2')) port = (cfg.get('server', 'port')) excel_path = (cfg.get('excel', 'excel_path')) tokenId = (cfg.get('token', 'tokenId')) x = Test_Requests() log = Log() update_excel(excel_path, sheet) Test_data = read_excel_row(excel_path, sheet, row_name, field=field, valu=valu) log.info(type(Test_data)) api_url = Test_data[0]['url'] if ip == 'ip1': ip = ip1 elif ip == 'ip2': ip = ip2 if parameter_type == 'webForms': result = x.run_main(r_type, url=ip + api_url, data=Test_data[0]) elif parameter_type == 'json': j = Test_data[0]['data'] k = json.loads(j) if 'header' in k: k["header"]["tokenId"] = tokenId else: pass result = x.run_main(r_type, url=ip + api_url, json=k) # log.info(result) else: print('传参类型错误') result = str(result.status_code) expected = Test_data[0]['expect'] write_excel(excel_path, sheet, result, row_name) return expected, result
class Test_Pytest(): log = Log() def setup_class(self): print('类前面,我爱你') self.obj = Method() self.p = IsContent() self.execl = OperationExcel() self.operationJson = OperationJson() self.log = Log() def teardown_class(self): print('类之后') def setup_method(self): print('方法前面') # def teardown_method(self): print('方法后') # def isContent(self,r,row): # # self.statusCode(r=r) # assert self.p.isContent(row=row, str2=r.text) @pytest.mark.usefixtures("del_title") def test_addCategory_001(self): """添加商品分类校验""" print("test_laGou_001方法执行") self.log.info("-------添加商品分类:start!---------") r = self.obj.post(row=1, data=self.operationJson.getRequestsData(row=1)) print("添加商品分类 is:", r.text) self.log.info("获取请求结果:%s" % r.text) # self.isContent(r=r, row=1) self.execl.writeResult(1, 'pass') assert r.status_code == 200 assert str(r.json()["msg"]) == "成功" print("test_addCategory_0000001 is:", r.json()["data"]["id"])
class TestOne(): def __init__(self): self.data = OperationData() self.data.op_data('test1') #需要请求地址和方法 self.ya = OperationYaml('test1') self.run = RunMethon() self.log = Log() def testLogistics(self): self.log.info('-----开始执行第一个文件,第一个用例-----') data = self.ya.get_data('test1_1') rel = self.run.run_main(self.data.method[0],self.data.url[0],data) print(rel) return rel def testLongude(self): self.log.info('-----开始执行第一个文件,第二个用例-----') data = self.ya.get_data('test1_2') rel = self.run.run_main(self.data.method[1],self.data.url[1],data) print(rel) return rel
class getJsonStr: """ 解析接口返回加密数据 """ def __init__(self, value): self.value = value # 要解析的数据 self.log = Log() # 日志 self.test_data = get_test_data('test_data.xlsx', 'common', 0) self.url = self.test_data['url'] self.headers = self.test_data['header'] self.method = self.test_data['method'] self.payload = {'value': self.value} def get_json_str(self): try: res = get_response(self.url, method=self.method, headers=json.loads(self.headers), data=json.dumps(self.payload)).json() self.log.info('正在解析加密数据==========') # self.log.info('解析结果为: {}'.format(res)) return res except Exception as e: print('请求错误{}'.format(e))
class Con(unittest.TestCase): def setUp(self): self.s = requests.session() self.lgin = LG(self.s) #实例化登录类 self.uid_token = self.lgin.login() #直接取第二部登录 self.header = { 'User-Agent': 'LanTingDoctor/1.3.1 (iPad; iOS 10.1.1; Scale/2.00)', 'Accept-Encoding': 'gzip, deflate', 'Accept-Language': 'zh-Hans-CN;q=1', 'Content-Type': 'application/json', 'requestApp': '3', 'requestclient': '2', 'versionForApp': '2.0', 'Authorization': 'Basic YXBpTGFudGluZ0BtZWRsYW5kZXIuY29tOkFwaVRobWxkTWxkQDIwMTM=', 'Connection': 'keep-alive' } self.log = Log() #实例化日志的类 self.exel = Excel_util( r'C:\Users\Administrator\Desktop\interface_testcase.xls') def test_delete_contacts(self): u'删除联系人接口' self.log.info('删除联系人接口测试开始!') url = 'http://api.meet.sunnycare.cc/v2/contact/del' #读取contact_code code = self.exel.read_value(15, 6) be_code = json.loads(code) #如果非空 if code: for v in be_code.values(): json_data = { "token": self.uid_token, "contact_code": v, #读取excel中的code, "timestamp": str(int(time.time())), "nonce": get_digit() } #入参加密 json_data['sign'] = get_sign(json_data) r = self.s.post(url, headers=self.header, json=json_data) self.log.info('删除该条联系人返回结果是:%s' % r.json()) self.assertEqual('请求成功.', r.json()['note']) else: self.log.warning('参会人code为空') self.log.info('删除联系人接口测试结束!!') def tearDown(self): self.s.close()
class Tickets(unittest.TestCase): def setUp(self): self.s = requests.session() self.lgin = LG(self.s) #实例化登录类 self.uid_token = self.lgin.login() #直接取第二部登录 self.header = { 'User-Agent': 'LanTingDoctor/1.3.1 (iPad; iOS 10.1.1; Scale/2.00)', 'Accept-Encoding': 'gzip, deflate', 'Accept-Language': 'zh-Hans-CN;q=1', 'Content-Type': 'application/json', 'requestApp': '3', 'requestclient': '2', 'versionForApp': '2.0', 'Authorization': 'Basic YXBpTGFudGluZ0BtZWRsYW5kZXIuY29tOkFwaVRobWxkTWxkQDIwMTM=', 'Connection': 'keep-alive' } self.log = Log() #实例化日志的类 self.excel = Excel_util( r'C:\Users\Administrator\Desktop\Interface_testcase.xls') def test_ticke_info(self): u'会议门票详情接口' self.log.info('开始测试会议门票详情接口') url = 'http://api.meet.sunnycare.cc/v2/ticket/order' #读取ticket_order_code read_code = self.excel.read_value(16, 6) be_use_code = json.loads(read_code) for v in be_use_code.values(): json_data = { "token": self.uid_token, "ticket_order_code": v, "timestamp": str(int(time.time())), "nonce": get_digit() } #入参加密 json_data['sign'] = get_sign(json_data) r = self.s.post(url, headers=self.header, json=json_data) self.log.info('%s的门票详情返回的结果是:%s' % (v, r.json())) self.assertEqual('请求成功.', r.json()['note']) self.log.info('会议门票详情接口测试结束!') def tearDown(self): self.s.close()
class LaGou(unittest.TestCase): # log = Log() def setUp(self): self.obj = Method() self.p = IsContent() self.execl = OperationExcel() self.operationJson = OperationJson() self.log = Log() def tearDown(self): pass def statusCode(self, r): self.assertEqual(r.status_code, 200) print(r.status_code) # print(r.json()['code']) # self.assertEqual(r.json ()['code'], 200) def isContent(self, r, row): self.statusCode(r=r) self.assertTrue(self.p.isContent(row=row, str2=r.text)) def test_post_001(self): """测试post接口-直接请求""" print("test_laGou_001方法执行") self.log.info("------测试post接口-直接请求:start!---------") # print(check_user(user=jp_user,name=18821768014)) "sign为空" r = self.obj.post(row=1, data=self.operationJson.getRequestsData(row=1)) print("test_laGou_001 is:", r.text) self.log.info("获取请求结果:%s" % r.text) self.isContent(r=r, row=1) self.execl.writeResult(1, 'pass') def test_post_002(self): print("test_laGou_002方法执行") "测试post接口-参数化请求" self.log.info("------测试post接口-参数化请求:start!---------") r = self.obj.post(row=1, data=set_so_keyword1(phone='18821768014')) print("test_laGou_002 is:", r.text) self.isContent(r=r, row=1) self.execl.writeResult(1, 'pass')
class ColumnInfo(unittest.TestCase): def setUp(self): self.s = requests.session() self.lgin = LG(self.s) #实例化登录类 self.uid_token = self.lgin.login() #直接取第二部登录 self.header = { 'User-Agent': 'LanTingDoctor/1.3.1 (iPad; iOS 10.1.1; Scale/2.00)', 'Accept-Encoding': 'gzip, deflate', 'Accept-Language': 'zh-Hans-CN;q=1', 'Content-Type': 'application/json', 'requestApp': '3', 'requestclient': '2', 'versionForApp': '2.0', 'Authorization': 'Basic YXBpTGFudGluZ0BtZWRsYW5kZXIuY29tOkFwaVRobWxkTWxkQDIwMTM=', 'Connection': 'keep-alive' } self.log = Log() #实例化日志的类 def testAvailabelCoupon(self): u'测试可领用优惠券列表接口' self.log.info('-----开始测试可领的优惠券列表接口-------') url = 'http://api.lesson.sunnycare.cc/v1/coupon/canget' json_DATA = { "where_code": "K00112", "timestamp": str(int(time.time())), "for_where": "2", "token": self.uid_token, "nonce": get_digit() } json_DATA['sign'] = get_sign(json_DATA) r = self.s.post(url, headers=self.header, json=json_DATA) try: self.log.info('开始断言请求该接口返回的状态是否成功') self.assertEqual('请求成功.', r.json()['note']) except Exception as e: raise AssertionError self.log.error('请求接口返回不成功,原因:%s' % e) self.log.info('---------------测试接口结束--------------------') print(r.json()) def tearDown(self): self.s.close()
class Contact(unittest.TestCase): def setUp(self): self.s = requests.session() self.lgin = LG(self.s) #实例化登录类 self.uid_token = self.lgin.login() #直接取第二部登录 self.header = {'User-Agent': 'LanTingDoctor/1.3.1 (iPad; iOS 10.1.1; Scale/2.00)', 'Accept-Encoding': 'gzip, deflate', 'Accept-Language': 'zh-Hans-CN;q=1', 'Content-Type': 'application/json', 'requestApp': '3', 'requestclient': '2', 'versionForApp': '2.0', 'Authorization': 'Basic YXBpTGFudGluZ0BtZWRsYW5kZXIuY29tOkFwaVRobWxkTWxkQDIwMTM=', 'Connection': 'keep-alive'} self.log = Log()#实例化日志的类 self.excel = Excel_util(r'C:\Users\Administrator\Desktop\interface_testcase.xls') def test_contact_list(self): u'联系人列表接口' self.log.info('参会人列表接口测试开始') url = 'http://api.meet.sunnycare.cc/v2/contact/records' json_data = { "token":self.uid_token, "nonce": get_digit(), "timestamp": str(int(time.time())) } #入参加密 json_data['sign'] = get_sign(json_data) r = self.s.post(url,headers = self.header,json=json_data) self.log.info('参会人列表返回内容是:%s' % r.json()) conten = r.json()['data']['content'] contact_code = {} j = 1 for i in conten: contact_code['contact_code'+str(j)] = i['contact_code'] j += 1 #将contact_code写入excel供其他借口调用 self.excel.write_value(15,6,contact_code) self.log.info('参会人列表接口测试结束!') def tearDown(self): self.s.close()
class Client: cursor_default = None cursor_capture = None def __init__(self, resolution, host, port, username, password, split="\n"): global network_log self.log = Log('client') network_log = Log('network') # must have at least one handler self.log.logger.addHandler(logging.NullHandler()) network_log.logger.addHandler(logging.NullHandler()) # opengl must be initialized first self.log.info("Initializing display (windowed at %(resolution)s)", dict(resolution='%dx%d'%resolution)) self._screen = pygame.display.set_mode(resolution, OPENGL|DOUBLEBUF) pygame.display.set_caption('yamosg') self.log.debug("OpenGL setup (version=\"%(version)s\", vendor=\"%(vendor)s\")", dict(version=glGetString(GL_VERSION), vendor=glGetString(GL_VENDOR))) setup_opengl() Client.cursor_default = pygame.cursors.arrow Client.cursor_capture = pygame.cursors.diamond self._resolution = Vector2i(resolution) self._username = username self._password = password self._split = split self._running = False self._state = StateManager() self._game = GameWidget(self, self._resolution) self._container = Composite(Vector2i(0,0), self._resolution, children=[self._game]) self._toolbar = Toolbar(self._game) self._window = VBox() self._window.add(self._toolbar, size=LayoutAttachment(Vector2i(1,0), Vector2i(0,25))) self._window.add(self._container) self._state.push(GameState(self._resolution, self._window)) self._network = Network(self, host, port) self._command_store = {} self._command_queue = [] self._command_lock = threading.Lock() self._playerid = None self._players = {} self._capture_position = None self._timer = 0 # resizing must be done after state has been created so the event is propagated proper. self._resize(self._resolution) def add_window(self, win): self._container.add(win) @event(pygame.QUIT) def quit(self, event=None): self._running = False def is_running(self): return self._running def resolution(self): return self._resolution def run(self): self._running = True self._network.start() while self._running: try: self._flush_queue() self._logic() self._render() except GLError: traceback.print_exc() self.quit() except: traceback.print_exc() @event(pygame.VIDEORESIZE, lambda event: Vector2i(event.w, event.h)) def _resize(self, resolution): self.log.debug("Resolution changed to %dx%d", resolution.x, resolution.y) #self._screen = pygame.display.set_mode(resolution.xy(), OPENGL|DOUBLEBUF|RESIZABLE) setup_opengl() self._resolution = resolution glMatrixMode(GL_PROJECTION) glLoadIdentity() glOrtho(0, resolution.x, 0, resolution.y, -1.0, 1.0); glMatrixMode(GL_MODELVIEW) glLoadIdentity() self._state.resize(resolution) self._game.on_resize(resolution, True) def _flush_queue(self): while True: self._command_lock.acquire() if len(self._command_queue) == 0: self._command_lock.release() break command, args = self._command_queue.pop(0) self._command_lock.release() try: self._dispatch(command, args) except: traceback.print_exc() def _logic(self): global event_table for event in pygame.event.get(): func, adapter = event_table.get(event.type, (None,None)) if func is None: continue func(self, adapter(event)) t = time() if t-self._timer > 1.0: self._toolbar.invalidate() self._timer = t @event(pygame.MOUSEMOTION) def _mousemotion(self, event): pos = Vector2i(event.pos) pos.y = self._resolution.y - pos.y self._state.on_mousemove(pos) @event(pygame.MOUSEBUTTONDOWN) def _mousebuttondown(self, event): pos = Vector2i(event.pos) pos.y = self._resolution.y - pos.y if self._capture_position is not None: if event.button == 1: callback, args, kwargs = self._capture_position try: callback(pos, *args, **kwargs) except: traceback.print_exc() self._capture_position = None pygame.mouse.set_cursor(*Client.cursor_default) return self._state.on_buttondown(pos, event.button) @event(pygame.MOUSEBUTTONUP) def _mousebuttonup(self, event): pos = Vector2i(event.pos) pos.y = self._resolution.y - pos.y self._state.on_buttonup(pos, event.button) def _render(self): glClearColor(1,0,0,0) glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT) self._state.render() pygame.display.flip() def _dispatch(self, cmd, args): """ Run command """ global network_log network_log.debug('got %s(%s)', cmd, ', '.join([str(x) for x in args])) try: # Try to get function func = getattr(self, cmd) # See if it is exposed, so a malicious cannot run any func. if not getattr(func, 'exposed'): raise AttributeError # raised to get same handling as a non-existing func. except AttributeError: print 'Malformed or bad command:', cmd, args return except: print 'Unhandled exception when running command:', cmd, args traceback.print_exc() return func(*args) def push_command(self, line): # Run from network thread try: self._command_lock.acquire() tokens = parse_tokens(line) id = tokens[0] if id == 'UNICAST' or id == 'BROADCAST': id, command, args = parse(line) self._command_queue.append((command, args)) elif id in self._command_store: status = tokens[1] args = tuple(tokens[2:]) data = line[len(id)+len(status)+2:] self._command_store[id].reply(status, args, data) else: raise RuntimeError, 'Got a reply for ID ' + id + ' but no matching request' except: traceback.print_exc() finally: self._command_lock.release() def call(self, command, *args): """ Synchronously call and get reply """ cmd = Command(command, *args) # send command with self._command_lock: self._command_store[cmd.id] = cmd self._network.send(str(cmd) + self._split) # await reply reply = cmd.wait() # delete command with self._command_lock: del self._command_store[cmd.id] return reply @server_call('LIST_OF_ENTITIES', decode=True) def list_of_entities(self, descriptions): self._game.set_entities([Entity(**x) for x in descriptions]) @expose def NEWENT(self, data): decoded = json.loads(data) self._game.add_entity(Entity(**decoded)) @server_call('ENTINFO', 'id', decode=True) def entity_info(self, info): return info @server_call('ENTACTION', 'id', 'action', decode=True) def entity_action(self, info): return info @server_call('PLAYERINFO', 'id', decode=True) def playerinfo(self, info): self._toolbar.set_cash(info['cash']) @expose def CASH(self, amount): self._toolbar.set_cash(int(amount)) @server_call('LOGIN', 'username', 'password', decode=True) def login(self, info): self.playerid = info['id'] self.log.debug('player id is %s', self.playerid) self.playerinfo(self.playerid) @server_call('PLAYERS', decode=True) def players(self, players): return players def player_by_id(self, id): return self._players.get(unicode(id), None) @expose def Hello(self): self.call('SET', 'ENCODER', 'json') try: self.login(username=self._username, password=self._password) except RuntimeError, e: self.log.error(e) self.quit() return self._players = self.players() self.list_of_entities()