def get_college_detail(self, url, list_items, detail_info={}, mod='college_detail'): send_url = self.request.get_url(url, mod) try: res = Request().set_request(send_url) res.encoding = 'gbk' soup = BeautifulSoup(res.text, "html.parser") dom = soup.find('div', {'class': 'scores_List'}) dl = dom.find_all('dl') for dl_item in dl: dt = dl_item.find('dt') college_name = dt.get_text().strip() if college_name in list_items: continue img = dt.find('img').get('src') img_url = Utils().savePic(img, path_in='logo/' + college_name + '-') list_items[college_name] = {'logo': img_url} print 'ok: ', send_url, len(dl) except IOError: print 'failed: ', send_url finally: print json.dumps(list_items, encoding='UTF-8', ensure_ascii=False) time.sleep(5) return list_items, detail_info
def test_register(self,case): # 使用正则,首先从数据库查找到最大手机号加1,通过正则替换excel中的参数---还需再改!!! # if case.case_id == 1: # # 从数据库找到最大手机号+1 # max_phone_old = mysql.fetch_one(sql)['mobilephone'] # max_phone = int(max_phone_old) + 1 # print("最大手机号是:",max_phone) # # 新的手机号替换excel中的手机号 # phone = re.findall(pattern='\d{11}', string=case.data)[0] # 先从excel中取出手机号 # case.data = case.data.replace(phone,str(max_phone)) # replace替换 # 也可以不用正则,取出case.data字典里的手机号,直接赋值替换 data = json.loads(case.data) # 从excel中取到的data是一个字符串,loads() 把字符串序列化为字典 if data['mobilephone'] == '${register}': # 判断是否需要进行参数化 max_phone_new = int(max_phone_old) + 1 # 取到数据库里面最大的手机号码,进行加1 data['mobilephone'] = max_phone_new # 赋值替换excel中的手机号 resp = Request(method=case.method, url=case.url, data=data) # request请求时,data一定要是字典类型 print("status_code:", resp.get_status_code()) # 打印响应码 resp_dict = resp.get_json() # 获取请求响应,字典 self.assertEqual(case.expected, resp.get_text()) # 数据库校验 if resp_dict['code'] == 10001: # 注册成功的数据校验,判断数据库member表有这条数据 sql = 'select * from future.member where mobilephone = "{0}"'.format(max_phone_new) member = self.mysql.fetch_one(sql) # member是字典类型 expected = max_phone_new if member is not None: # 正常注册成功,不应该返回None self.assertEqual(expected, member['mobilephone']) else: # 返回None,代表注册成功之后但是数据库里面没有插入数据 print("注册失败,数据库没有插入数据")
def __init__(self): self.dt = Data() readIni = ReadIni() self.base_url = readIni.get_value('base_url', 'api') self.schoolweb_url = readIni.get_value('schoolweb_url', 'api') self.req = Request() self.row_total = self.dt.row_total()
def test_recharge(self, case): # 参数化处理 data = DoRegex.replace(case.data) # 将字符串序列化成字典 data = json.loads(data) if hasattr(Context, 'cookies'): # 判断是否有cookies cookies = getattr(Context, 'cookies') # 获取放到上下文里面的cookies else: cookies = None resp = Request(method=case.method, url=case.url, data=data, cookies=cookies) # 通过封装的Request类来完成接口的调用 # 判断有没有cookie if resp.get_cookies(): # 判断返回里面是否有cookies setattr(Context, 'cookies', resp.get_cookies()) # 放入到上下文中 resp_dict = resp.get_json() # 获取请求响应,字典 self.assertEqual(case.expected, int(resp_dict['code'])) # 判断响应返回的code 是否与期望结果一致 actual = self.mysql.fetch_one(self.sql)['LeaveAmount'] # 再次获取账户余额 print("测试{0}后的金额".format(case.title), actual) # 充值成功,判断余额增加 if resp_dict['code'] == '10001' and resp_dict['msg'] == "充值成功": amount = float(data['amount']) # 充值金额 print('充值金额', amount) expect = float(self.before_amount) + amount # 充值成功,期望的账户余额= 原来余额 + 充值金额 self.assertEqual(expect, actual) # 判断期望结果与实际结果是否一致 elif resp_dict['code'] != '10001': expect = self.before_amount # 充值失败,期望结果:余额未增加 self.assertEqual(expect, actual) # 判断期望结果与实际结果是否一致
def __init__(self): self.is_to_excel = cfg.IS_TO_EXCEL self.is_email = cfg.IS_EMAIL self.request = Request() self.html = HtmlController() self.excel = ExcelController()
def test_login(self, case): data = json.loads(case.data) resp = Request(method=case.method, url=case.url, data=data) # 通过封装的Request类来完成接口的调用 print('test data:', data) print('status_code:', resp.get_status_code()) # 打印响应码 resp_dict = resp.get_json() # 获取请求响应,字典 self.assertEqual(case.expected, resp.get_json_code())
def test_login(self, case): # 必须传输一条case data = json.loads(case.data) res = Request(method=case.method, url=case.url, data=data) print(res.get_json()) try: self.assertEqual(eval(case.expected), res.get_json()) except AssertionError as e: print("{} not found".format(e)) raise e
def test_recharge(self, case): # 必须传输一条case my_logger = MyLog() data = DoRegex.replace(case.data) # 首先从excel中取出来,然后做正则 data = json.loads(data) # 然后在loads if hasattr(Context, 'cookies'): # 第一次登陆没有cookies,所以要判断 # 参数化处理 cookies = getattr(Context, 'cookies') else: cookies = None res = Request(method=case.method, url=case.url, data=data, cookies=cookies) # 判断有没有cookies if res.get_cookies(): setattr(Context, 'cookies', res.get_cookies()) my_logger.debug(res.get_json()) try: self.assertEqual(str(case.expected), res.get_json()['code']) except AssertionError as e: my_logger.error("{} not found".format(e)) raise e if res.get_json()['msg'] == '充值成功': try: self.assertEqual(str(self.leaveamount + 10), res.get_json()['data']['leaveamount']) except AssertionError as a: my_logger.error("余额不正确,报错{}".format(a))
def test_case(self, **args): # module,case_name,case_num,case_imp,request_type,request_url,request_param,case_except,case_author self.model_name = args.get('Model') self.case_name = args.get('Case') self._testMethodDoc = self.model_name + '_' + self.case_name # 单个文件运行时请注释此行 self.url = args.get('Url') self.login_state = args.get('Login_State') self.method = args.get('Method') self.data = args.get('Data') self.status_code = args.get('Status_Code') self.expect_type = args.get('Expect_Type') self.expect = args.get('Expect') test = assertion.Assertions() request = Request() if self.method == 'post': my_log.info("开始执行post请求!模块名称为: %s ,用例名称为 %s" % (self.model_name, self.case_name)) r = request.post_request(url=self.url, data=self.data, login_state=self.login_state) assert test.assert_code(r['code'], self.status_code) if self.expect_type == 'body': assert test.assert_in_text(r['body'], self.expect) elif self.expect_type == 'text': assert self.expect in r['text'] elif self.expect_type == 'time_consuming': assert test.assert_in_text(r['time_consuming'], self.expect) elif self.expect_type == 'time_total': assert test.assert_in_text(r['time_total'], self.expect) else: my_log.error('excel文件中设置的预期类型不符合格式!') elif self.method == 'get': my_log.info("开始执行get请求!模块名称为: %s ,用例名称为 %s" % (self.model_name, self.case_name)) r = request.get_request(url=self.url, data=self.data, login_state=self.login_state) assert test.assert_code(r['code'], self.status_code) if self.expect_type == 'body': assert test.assert_in_text(r['body'], self.expect) elif self.expect_type == 'text': assert self.expect in r['text'] elif self.expect_type == 'time_consuming': assert test.assert_time(r['time_consuming'], self.expect) elif self.expect_type == 'time_total': assert test.assert_time(r['time_total'], self.expect) else: my_log.error('excel文件中设置的预期类型不符合格式!') else: my_log.error("暂不支持此种请求方式!")
def __init__(self): #打开用例获取login_sheet 中的第一行用例 self.login_case = Read_Excel('../data/smile_tasks.xlsx', 'login') self.login_case.open_excel() self.table = self.login_case.get_sheet_table() self.ncols = self.login_case.get_ncols(self.table) self.login_case_data = self.login_case.get_test_case( self.table, self.ncols) #定义一个request self.request = Request() #定义log self.log = Log()
def test_login(self, case): data = json.loads(case.data) logger1.my_logger.info('测试用例名称:{0}'.format(case.title)) logger1.my_logger.info('测试用例数据:{0}'.format(case.data)) resp = Request(method=case.method, url=case.url, data=data) # 通过封装的Request类来完成接口的调用 logger1.my_logger.debug('status_code:{0}'.format( resp.get_status_code())) # 打印响应码 resp_dict = resp.get_json() # 获取请求响应,字典 try: self.assertEqual(case.expected, resp.get_text()) except AssertionError as e: logger1.my_logger.error('测试失败')
def test_list(self, case): my_logger = MyLog() if case.data != None: data = DoRegex.replace(case.data) # 正则调用,替换正则表达式的数据 data = json.loads(data) if hasattr(Context, 'cookies'): cookies = getattr(Context, 'cookies') else: cookies = None res = Request(method=case.method, url=case.url, data=data, cookies=cookies) print(res.get_json()) if res.get_cookies(): setattr(Context, 'cookies', res.get_cookies())
def test_add(self, case): data = DoRegex.replace(case.data) data = json.loads(data) if hasattr(Context, 'cookies'): cookies = Context.cookies else: cookies = None #请求成功后,返回response resp = Request(method=case.method, url=case.url, data=data, cookies=cookies) if resp.get_cookies(): # 将cookies动态写入上下文管理器中 setattr(Context, 'cookies', resp.get_cookies()) print("用例名称:", case.title) resp_dict = resp.get_json() print(resp.get_text()) self.assertEqual(str(case.expected), resp_dict['code']) # check the response code firstly # Check that the login case is successful if case.title == '管理员正常登录': try: self.assertEqual(str(case.expected), resp_dict['code']) TestResult = 'PASS' do_excel.write_result_by_case_id('add', case.case_id, resp.get_text(), TestResult) except AssertionError as e: TestResult = 'Fail' do_excel.write_result_by_case_id('add', case.case_id, resp.get_text(), TestResult) raise e
class Common(): def __init__(self): #打开用例获取login_sheet 中的第一行用例 self.login_case = Read_Excel('../data/smile_tasks.xlsx', 'login') self.login_case.open_excel() self.table = self.login_case.get_sheet_table() self.ncols = self.login_case.get_ncols(self.table) self.login_case_data = self.login_case.get_test_case( self.table, self.ncols) #定义一个request self.request = Request() #定义log self.log = Log() def login(self): #request所需要的参数 method = self.login_case_data['method'] url = self.login_case_data['url'] username = self.login_case_data['username'] password = self.login_case_data['password'] param = {'username': username, 'password': password} #发送请求 try: r = self.request.request(method, url, param) r_json = r.json() token = r_json['token'] except: self.log.error('get token failed') return token
class Set_pattern(unittest.TestCase): def setUp(self): self.request = Request() self.token = get_antelope_token() def test_set_pattern(self): global test_data test_data = test_data[0] #print(test_data) #请求参数 para = test_data['para'] #print(para) #请求头 header = { 'Content-Type': 'application/x-www-form-urlencoded', 'token': self.token } print(header) #请求头 r = self.request.request(test_data['method'], test_data['url'], para, header) actual_result = r.json() #断言 self.assertEqual(actual_result['code'], test_data['code']) def tearDown(self): pass
class LoginTest(unittest.TestCase): do_excel = DoExcel(constants.case_file) # 读取cases.xlsx cases = do_excel.get_cases('login') # 指定读取login测试数据 request = Request() # 实例化对象 def setUp(self): pass def tearDown(self): pass @data(*cases) def test_login(self, case): logger.info("开始执行第{0}用例".format(case.id)) # 使用封装好的request 来完成请求 resp = self.request.request(case.method, case.url, case.data) try: # 将返回结果和期望结果进行匹配 self.assertEqual(case.expected, resp.text, 'login error') # 一致就写入Excel的结果为Pass self.do_excel.write_result('login', case.id + 1, resp.text, 'Pass') logger.info("第{0}用例执行结果:PASS".format(case.id)) except AssertionError as e: # 不一致就写入Excel的结果为Fail,并抛出异常 self.do_excel.write_result('login', case.id + 1, resp.text, 'Fail') logger.error("第{0}用例执行结果:FAIL".format(case.id)) raise e
def test_register(self, case): # 必须传输一条case data = json.loads(case.data) if data['mobilephone'] == '${register}': data['mobilephone'] = str(int(self.max_phone) + 1) print(data) res = Request(method=case.method, url=case.url, data=data) print(res.get_json()) self.assertEqual(str(case.expected), res.get_json()['code']) # 数据库数据校验 sql = "select l.MobilePhone from future.member l where l.MobilePhone ={}".format( int(self.max_phone) + 1) # print(sql) expected = int(self.max_phone) + 1 member = self.mysql.fetch_one(sql) if member is not None: self.assertEqual(expected, member['MobilePhone'])
def schedule_and_build_instances(self, context, build_requests, request_specs, image, admin_password, injected_files, requested_networks, block_device_mapping): index = 0 for build_request in build_requests: request_spec = request_specs[index] index += 1 data = { 'build_requests': [build_request], 'request_specs': [request_spec], 'image': image, 'admin_password': admin_password, 'injected_files': injected_files, 'requested_networks': requested_networks, 'block_device_mapping': block_device_mapping } req = { "context": context, "data": data, "action": "schedule_and_build_instances" } request = Request.fromDict(req) self.nova_manager.notify(event_type="SERVER_CREATE", request=request)
class RechargeTest(unittest.TestCase): cases = doexcel.DoExcel(contants.case_file, "recharge").get_data("recharge") request = Request() def setUp(self): pass def tearDown(self): pass @data(*cases) def test_login(self, case): print("开始执行第{}个测试用例:".format(case.case_id)) resp = self.request.request(method=case.method, url=case.url, data=case.data) doexcels = doexcel.DoExcel(contants.case_file, "recharge") try: self.assertEqual(case.expected, resp.text) doexcels.write_back(row=case.case_id + 2, col=8, value="PASS", sheet_name="recharge") except AssertionError as e: doexcels.write_back(row=case.case_id + 2, col=8, value="FAIlED", sheet_name="recharge") raise e doexcels.write_back(case.case_id + 2, 7, resp.text, sheet_name="recharge") print(resp.text)
class InvestTest(unittest.TestCase): cases = doexcel.DoExcel(contants.case_file, "invest").get_data("invest") request = Request() @classmethod def setUpClass(cls): cls.mysql = MysqlUtil() @classmethod def tearDownClass(cls): cls.mysql.close() @data(*cases) def test_invest(self,case): readconfig = ReadConfig() pre_url = readconfig.get("api","pre_url") print("开始执行第{}个测试用例:".format(case.case_id)) case.data = replace(case.data) resp = self.request.request(method=case.method,url = pre_url+case.url,data=case.data) doexcels = doexcel.DoExcel(contants.case_file, "invest") try: self.assertEqual(case.expected,resp.text) doexcels.write_back(row=case.case_id + 2, col=8, value="PASS", sheet_name="invest") #加一层判断,判断加标是否成功,如果成功,就把标的的ID查出来反射给类的属性,以便下一条用例取 if resp.json()["msg"] == "加标成功": load_member_id = getattr(Context,"loan_member_id") mysql = MysqlUtil() sql = "select Id from future.loan where MemberID={} order by CreateTime desc limit 1".format(load_member_id) loan_id = mysql.fetchone(sql)[0] setattr(Context,"loan_id",str(loan_id)) except AssertionError as e: doexcels.write_back(row=case.case_id + 2, col=8, value="FAIlED", sheet_name="invest") doexcels.write_back(case.case_id + 2,7,resp.text,sheet_name="invest") print(resp.text)
class LoginTest(unittest.TestCase): # 可类里,也可模块外 do_excel = DoExcel(contants.case_file) # 传入cases.xlsx cases = do_excel.read('login') request = Request() # 实例化一个对象 # 可类里,也可模块外 def setUp(self): pass @data(*cases) # 此处传入数据,so读数据就要从test_login()方法移到方法外面,for case in cases:也需删掉 def test_login(self, case): # 加case接收解包数据 print("开始执行第{0}行用例".format(case.case_id)) # 使用分装好的request来完成请求 resp = self.request.request(case.method, case.url, case.data) # 实例对象已移到外面,这里要加self. # 将返回结果与期望结果对比 # 当用unittest时,比对用断言,不用if恒等==手动了 try: self.assertEqual(case.expected, resp.text, 'login error') # 一致就写入Excel的结果PASS self.do_excel.write_back(case.case_id+1, resp.text, 'PASS') # 实例对象已放外面,类变量加self. print("第{0}行用例执行结果:PASS".format(case.case_id)) except AssertionError as e: self.do_excel.write_back(case.case_id, resp.text, 'FAIL') # 实例对象已放外面,类变量加self.调用 print("第{0}行用例执行结果:FAIL".format(case.case_id)) raise e def tearDown(self): pass
class LoginTest(unittest.TestCase): cases = doexcel.DoExcel(contants.case_file, "login").get_data("login") request = Request() def setUp(self): pass def tearDown(self): pass @data(*cases) def test_login(self, case): logg.info("开始执行第{}个测试用例:".format(case.case_id)) resp = self.request.request(method=case.method, url=case.url, data=case.data) doexcels = doexcel.DoExcel(contants.case_file, "login") try: self.assertEqual(case.expected, resp.text) doexcels.write_back(row=case.case_id + 1, col=8, value="PASS", sheet_name="login") except AssertionError as e: doexcels.write_back(row=case.case_id + 1, col=8, value="FAIlED", sheet_name="login") logg.error("第{}个用例执行结果:failed".format(case.case_id)) doexcels.write_back(case.case_id + 1, 7, resp.text, sheet_name="login") logg.info(resp.text)
class LoginTest(unittest.TestCase): do_excel = DoExcel(contants.case_file) # 传入test.xlsx cases = do_excel.get_data('login') #定位表单 request = Request() #实例化request def setUp(self): pass @data(*cases) def test_login(self, item): #用一个变量来解释data传递的数据 # 使用封装好的request 来完成请求 logger.info("开始执行第{}用例".format(item.id)) resp = self.request.request(item.method, item.url, item.data) # 将返回结果和期望结果进行匹配 try: self.assertEqual(item.expected, resp.text, "login error") self.do_excel.write_result('login', item.id + 1, resp.text, 'PASS') logger.info("第{}用例执行结果:PASS".format(item.id)) except AssertionError as e: self.do_excel.write_result('login', item.id + 1, resp.text, 'FAIL') logger.error("第{}用例执行结果:FAIL".format(item.id)) raise e def tearDown(self): pass
class APITest(unittest.TestCase): do_excel = DoExcel(contants.case_file) # 传入cases.xlsx login_cases = do_excel.read('login') # 一个就够,不需要重复写多个对象 request = Request() # 实例化一个对象 def setUp(self): pass @unittest.skip("忽略测试,不要运行") # 暂时不运行此用例 @data(*login_cases) def test_login(self, case): print("开始执行第{0}行用例".format(case.case_id)) # 使用分装好的request来完成请求 resp = self.request.request(case.method, case.url, case.data) # 实例对象已移到外面,这里要加self. # 将返回结果与期望结果对比 try: self.assertEqual(case.expected, resp.text, 'login error') # 一致就写入Excel的结果PASS self.do_excel.write_back(case.case_id+1, resp.text, 'PASS') # 实例对象已放外面,类变量加self. print("第{0}行用例执行结果:PASS".format(case.case_id)) except AssertionError as e: self.do_excel.write_back(case.case_id+1, resp.text, 'FAIL') # 实例对象已放外面,类变量加self.调用 print("第{0}行用例执行结果:FAIL".format(case.case_id)) raise e register_cases = do_excel.read('register') # 增加了一个方法 # mysql = MysqlUtil() # 实例化对象(进行了一次数据库的连接) # sql = "SELECT MAX(MobilePhone) FROM future.member WHERE MobilePhone LIKE '152%';" # 传一条sql进来 # max = mysql.fetch_one(sql)[0] # 找到最大手机号码, 元组里取第1个值 # print(type(max), max) @data(*register_cases) def test_register(self, case): mysql = MysqlUtil() # 实例化对象(进行了一次数据库的连接) sql = "SELECT MAX(MobilePhone) FROM future.member WHERE MobilePhone LIKE '152%';" # 传一条sql进来 max = mysql.fetch_one(sql)[0] # 找到最大手机号码, 元组里取第1个值 print("开始执行第{0}行用例".format(case.case_id)) import json data_dict = json.loads(case.data) # Excel字符串转成字典 if data_dict['mobilephone'] == '${register_mobile}': # 判断是否等于标记 data_dict['mobilephone'] = int(max) + 1 # 将最大手机号码+1 赋值给mobilephone # 使用封装好的request来完成请求 resp = self.request.request(case.method, case.url, data_dict) # 实例对象已移到外面,这里要加self. # 将返回结果与期望结果对比 try: self.assertEqual(case.expected, resp.text, 'register error') # 一致就写入Excel的结果PASS,并且 self.do_excel.write_back(case.case_id+1, resp.text, 'PASS') # 实例对象已放外面,类变量加self. print("第{0}行用例执行结果:PASS".format(case.case_id)) except AssertionError as e: self.do_excel.write_back(case.case_id+1, resp.text, 'FAIL') # 实例对象已放外面,类变量加self.调用 print("第{0}行用例执行结果:FAIL".format(case.case_id)) raise e def tearDown(self): pass
class AddloanTest(unittest.TestCase): cases = doexcel.DoExcel(contants.case_file, "addloan").get_data("addloan") request = Request() def setUp(self): pass def tearDown(self): pass @data(*cases) def test_addloan(self, case): readconfig = ReadConfig() pre_url = readconfig.get("api", "pre_url") print("开始执行第{}个测试用例:".format(case.case_id)) resp = self.request.request(method=case.method, url=pre_url + case.url, data=case.data) doexcels = doexcel.DoExcel(contants.case_file, "addloan") try: self.assertEqual(case.expected, resp.text) doexcels.write_back(row=case.case_id + 2, col=8, value="PASS", sheet_name="addloan") except AssertionError as e: doexcels.write_back(row=case.case_id + 2, col=8, value="FAIlED", sheet_name="addloan") doexcels.write_back(case.case_id + 2, 7, resp.text, sheet_name="addloan") print(resp.text)
def test_longin(self, case): url = getattr(contex, 'url') + case.url mylog = MyLog() mylog.debug('判断有无初始化的cookies值') if hasattr(contex, 'cookies'): cookies = getattr(contex, 'cookies') else: cookies = None mylog.debug('获取到的cookies值是:{}'.format(cookies)) params = json.loads(DoRegex().replace(case.params)) resp = Request(method=case.method, url=url, data=params, cookies=cookies) mylog.info('执行{}的用例'.format(case.title)) mylog.info('请求数据{}'.format(params)) if resp.cookies(): setattr(contex, 'cookies', resp.cookies()) mylog.info('本次请求获取到的cookies是:{}'.format(resp.cookies())) actual = resp.get_txt() result = None try: self.assertEqual(actual, case.expected) result = 'PASS' mylog.info('执行{}的用例:{}'.format(case.title, result)) except Exception as e: result = 'FAILED' mylog.error('执行{}的用例,错误信息是:{}'.format(case.title, e)) raise e finally: read.write_result(case.caseid + 1, 7, resp.get_txt()) read.write_result(case.caseid + 1, 8, result) mylog.info('写入测试结果完成')
def schedule_and_build_instances(self, context, build_requests, request_specs, image, admin_password, injected_files, requested_networks, block_device_mapping): index = 0 for build_request in build_requests: request_spec = request_specs[index] index += 1 data = {'build_requests': [build_request], 'request_specs': [request_spec], 'image': image, 'admin_password': admin_password, 'injected_files': injected_files, 'requested_networks': requested_networks, 'block_device_mapping': block_device_mapping} req = {"context": context, "data": data, "action": "schedule_and_build_instances"} request = Request.fromDict(req) self.nova_manager.notify(event_type="SERVER_CREATE", request=request)
class LoginTest(unittest.TestCase): do_excel = DoExcel(contants.case_file) # 传入cases.xlsx cases = do_excel.get_cases('login') request = Request() # 实例化对象 def setUp(self): pass @data(*cases) def test_login(self,case): logger.info("开始执行第{0}用例".format(case.id)) # 使用封装好的request 来完成请求 resp = self.request.request(case.method, case.url, case.data) # 将返回结果和期望结果进行匹配 try: self.assertEqual(case.expected, resp.text, "login error ") # 一致就写入Excel的结果为PASS,并且 self.do_excel.write_result('login',case.id + 1, resp.text, 'PASS') logger.info("第{0}用例执行结果:PASS".format(case.id)) except AssertionError as e: self.do_excel.write_result('login',case.id + 1, resp.text, 'FAIL') logger.error("第{0}用例执行结果:FAIL".format(case.id)) raise e def tearDown(self): pass
def get_task_id(token): request = Request() method = 'post' param = {"task_type": 400, "ignore_sub_task_error": 1} para = json.dumps(param) url = readconfig.agv_url + '/tasks/task/' header = { "Content-Type": "application/x-www-form-urlencoded", "token": token } r = request.request(method, url, para, header) result = r.json() return result['data']['rows'][0]['id']
class RegisterTest(unittest.TestCase): do_excel = DoExcel(constants.case_file) # 读取cases.xlsx register_cases = do_excel.get_cases('register') request = Request() # 实例化对象 mysql = MysqlUtil(return_dict=True) sql = 'select max(mobilephone) as max_mobilephone from future.member' def setUp(self): self.max_mobilephone = self.mysql.fetch_one( self.sql)['max_mobilephone'] @data(*register_cases) def test_register(self, case): logger.info("开始执行第{0}用例".format(case.id)) import json data_dict = json.loads(case.data) if data_dict['mobilephone'] == '${register_mobile}': data_dict['mobilephone'] = int( self.max_mobilephone) + 1 # 数据库中最大手机号+1 if 'regname' in data_dict.keys(): regname = data_dict['regname'] else: regname = None # print(regname) # 使用封装好的request 来完成请求 resp = self.request.request(case.method, case.url, data_dict) # print(resp.json()) try: # 将返回结果和期望结果进行匹配 self.assertEqual(case.expected, resp.text, 'register error') # 一致就写入Excel的结果为Pass self.do_excel.write_result('register', case.id + 1, resp.text, 'Pass') if resp.json()['msg'] == '注册成功': sql = "select * from future.member where mobilephone = '{0}'".format( data_dict['mobilephone']) result = self.mysql.fetch_all(sql) # 首先判断是否有成功插入数据 self.assertEqual(1, len(result), '注册成功时,仅在数据库中插入一条数据') # 判断注册成功余额应该是0 self.assertEqual(0, result[0]['LeaveAmount'], '注册成功后,初始余额应该是0') # 判断regname if regname: self.assertEqual(regname, result[0]['RegName']) else: self.assertEqual('小蜜蜂', result[0]['RegName']) logger.info("第{0}用例执行结果:PASS".format(case.id)) except AssertionError as e: # 不一致就写入Excel的结果为Fail,并抛出异常 self.do_excel.write_result('register', case.id + 1, resp.text, 'Fail') logger.error("第{0}用例执行结果:FAIL".format(case.id)) raise e @classmethod def tearDownClass(cls): cls.mysql.close()
class TestApiMethod(unittest.TestCase): '这是测试接口的类' do_excel = DoExcel(contants.excel_file) # 传入excel cases_login = do_excel.read_excel("login") cases_register = do_excel.read_excel("register") request = Request() def setUp(self): # self.write_register = do_excel.write_excel("register") # 创建一个对象写入 # self.write_register = do_excel.write_excel("login") # 创建一个对象写入 my_log.info("开始执行用例") def tearDown(self): my_log.info("用例执行结束") @data(*cases_register) def test_register(self, case): # 测试注册 my_log.info("开始执行第{}条用例: {}".format(case.case_id, case.title)) my_log.info('url:{}'.format(case.url)) my_log.info('data:{}'.format(case.data)) my_log.info('method:{}'.format(case.method)) my_log.info('expected:{}'.format(case.expected)) result = self.request.request(case.method, case.url, case.data) try: self.assertEqual(case.expected, result.text) self.do_excel.write_excel(case.case_id + 1, result.text, "Pass") # 写入测试实际结果 # TestResult = "Pass" except AssertionError as e: self.do_excel.write_excel(case.case_id + 1, result.text, "Failed") # 写入测试实际结果 # TestResult = "Failed" my_log.error("断言出错了".format(e)) raise e # finally: # self.do_excel.write_excel(case.case_id+1, result.text, TestResult) # 写入测试实际结果 # my_log.info('注册的结果:{}'.format(result)) @data(*cases_login) def test_login(self, case): # 测试登陆 my_log.info("开始执行第{}条用例: {}".format(case.case_id, case.title)) my_log.info('url:{}'.format(case.url)) my_log.info('data:{}'.format(case.data)) my_log.info('method:{}'.format(case.method)) my_log.info('expected:{}'.format(case.expected)) result = self.request.request(case.method, case.url, case.data) try: self.assertEqual(case.expected, result.text) self.do_excel.write_excel(case.case_id + 1, result.text, "Pass") # 写入测试实际结果 # TestResult = "Pass" except AssertionError as e: self.do_excel.write_excel(case.case_id + 1, result.text, "Failed") # 写入测试实际结果 # TestResult = "Failed" my_log.error("断言出错了".format(e)) raise e
def save_img(url): """ save image """ try: image = Request.request('GET', url) if image.content: with open('{}/{}.jpg'.format(PATH, hashlib.md5(url).hexdigest()), 'wb') as f: for chunk in image.iter_content(chunk_size=1024): f.write(chunk) except Exception as e: logger.error('save image error, url [{}], error message [{}]'.format(url, e))
def build_instances(self, context, instances, image, filter_properties, admin_password, injected_files, requested_networks, security_groups, block_device_mapping=None, legacy_bdm=True): for instance in instances: data = {'instances': [instance], 'image': image, 'filter_properties': filter_properties, 'admin_password': admin_password, 'injected_files': injected_files, 'requested_networks': requested_networks, 'security_groups': security_groups, 'block_device_mapping': block_device_mapping, 'legacy_bdm': legacy_bdm} req = {"context": context, "data": data, "action": "build_instances"} try: request = Request.fromDict(req) self.nova_manager.notify(event_type="SERVER_CREATE", request=request) except Exception as ex: LOG.info(ex)
def run(self): LOG.info("Worker %s running!" % self.name) queue_items = [] last_release_time = SharedQuota.getLastReleaseTime() while not self.exit and not self.queue.isClosed(): try: if last_release_time < SharedQuota.getLastReleaseTime(): last_release_time = SharedQuota.getLastReleaseTime() while queue_items: self.queue.restore(queue_items.pop(0)) for project in self.project_manager.getProjects(): for user in project.getUsers(): self.queue.updatePriority(user) if len(queue_items) >= self.backfill_depth: SharedQuota.wait() continue queue_item = self.queue.dequeue(block=False) if queue_item is None: if self.queue.getSize(): SharedQuota.wait() continue else: queue_item = self.queue.dequeue(block=True) if queue_item is None: continue request = Request.fromDict(queue_item.getData()) user_id = request.getUserId() prj_id = request.getProjectId() context = request.getContext() server = request.getServer() server_id = server.getId() quota = None try: s = self.nova_manager.getServer(server_id, detail=True) if s.getState() != "building": # or server["OS-EXT-STS:task_state"] != "scheduling": self.queue.delete(queue_item) continue except SynergyError as ex: LOG.warn("the server %s is not anymore available!" " (reason=%s)" % (server_id, ex)) self.queue.delete(queue_item) continue project = self.project_manager.getProject(id=prj_id) if not project: raise SynergyError("project %r not found!" % prj_id) quota = project.getQuota() blocking = False if server.isEphemeral() and not SharedQuota.isEnabled(): blocking = True if quota.allocate(server, blocking=blocking): found = False try: km = self.keystone_manager trust = km.getTrust(context["trust_id"]) token = trust.getToken(km.getToken().getId()) context["auth_token"] = token.getId() context["user_id"] = token.getUser().getId() except SynergyError as ex: LOG.error("error on getting the token for server " "%s (reason=%s)" % (server.getId(), ex)) raise ex try: self.nova_manager.buildServer(request) LOG.info("building server %s user_id=%s prj_id=%s quo" "ta=shared" % (server_id, user_id, prj_id)) found = True except Exception as ex: LOG.error("error on building the server %s (reason=%s)" % (server.getId(), ex)) if found: self.queue.delete(queue_item) else: quota.release(server) queue_items.append(queue_item) else: queue_items.append(queue_item) except Exception as ex: LOG.error("Exception has occured", exc_info=1) LOG.error("Worker %s: %s" % (self.name, ex)) self.queue.delete(queue_item) LOG.info("Worker %s destroyed!" % self.name)
def fetch(url): """ fetch html """ html = Request.request('GET', url).text parse_html(html)
import random import sys import os params={} params['Data'] = [{'dimensions':{'lanip':myaddr},'value':mem_usage,'metricName':metricName}] print params params['Nonce'] = random.randint(1, sys.maxint) params['Timestamp'] = currentTime params['Region'] = region params['Namespace'] = namespace params['SecretId'] = secretId print params sys.path.append(os.path.split(os.path.realpath(__file__))[0] + os.sep) print sys.path from common.request import Request request = Request(secretId, secretKey) url = request.generateUrl(requestHost, requestUri , params) print 'end url: ' + url import urllib2 req = urllib2.Request(url) print req res_data = urllib2.urlopen(req) res = res_data.read() print res
def generateUrl(self, action, params): self._checkParams(action, params) request = Request(self.secretId, self.secretKey) return request.generateUrl(self.requestHost, self.requestUri, self._params, self.method)
def call(self, action, params, files = {}): self._checkParams(action, params) request = Request(self.secretId, self.secretKey) return request.send(self.requestHost, self.requestUri, self._params, files, self.method, self.debug)
def test_some_method(self): request = Request() self.assertEqual(request.some_method(2, 2), 4)