def login(self, usr=None, pwd=None): # 下面全是服务于登录 if self._type == 'android': device_info = g.get_info('android_params', 'device_id') elif self._type == 'ios': device_info = g.get_info('ios_params', 'device_id') else: raise AttributeError('params必须为android_params或ios_params') salt = g.get_info('env_info', 'salt') ts = str(int(time.time())) # 获取_gm_token _gm_token = hashlib.md5((device_info + ts + salt).encode()).hexdigest()[6:12] + ts self.headers.update({ 'Cookie': '_gm_token=' + _gm_token }) phone = usr if usr else self._user password = pwd if pwd else self._pwd rep = self.post( url=self.host + '/api/accounts/login/password', data={'phone': phone, 'password': password} ) try: return rep.json() except: pass finally: if rep.json().get('error') == 0: self.uid = rep.json().get('data').get('user_id') sessionid = re.search(r'sessionid=(\w+);.*', rep.headers.get('Set-Cookie')).groups() if sessionid: self.headers.update({"Cookie": "sessionid=" + sessionid[0]})
def __init__(self): self.host = g.host self.android_params = g.android_params user_telephone = g.get_info('user_info', 'telephone') password = g.get_info('user_info', 'password') from common.getcookie import create_header self.header = create_header(user_telephone, password, 'android_params').get('header')
def __init__(self, ostype='android', *args, **kwargs): self._type = ostype self._params = g.params(ostype) self.params = deepcopy(self._params) self.verify = False self.headers = {'User-Agent': GmHttp.user_agent} self._user = kwargs.get('user', g.get_info('user_info', 'telephone')) self._pwd = kwargs.get('pwd', g.get_info('user_info', 'password')) self.host = g.host self.uid = None
def zone_my_get(): r = gmhttp.get(url=g.host + g.get_info('api_info', 'zone_my')).json() if not r['data']['my_tags']: _, zone_id = question_id_get() post_data = {'tag_id': zone_id} gmhttp.post(url=g.host + g.get_info('api_info', 'zone_follow'), data=post_data).json() r = gmhttp.get(url=g.host + g.get_info('api_info', 'zone_my')).json() tag_name = r['data']['my_tags'][0]['name'] tag_id = r['data']['my_tags'][0]['tag_id'] return tag_id, tag_name
def create_diary(): tag_id1 = g.get_info('env_info', 'tag_id1') api_step1 = g.get_info('api_info', 'diary_additional_info_v2') url = g.host + api_step1 r = gmhttp.post(url, data={ 'tag_ids': '[{}]'.format(tag_id1), 'operation_timestamp': int(time.time()), 'cover': '', 'images': [] }).json() diary_id = r.get('data').get('id') return diary_id
def maidan_id_get(): *_, doctor_id, _ = service_id_get() data = {'tag_ids': "[0]", "payment": 0, "doctor_id": doctor_id} url = g.host + g.get_info('api_info', 'maidan_create') r = gmhttp.post(url=url, data=data).json() maidan_id = r.get('data').get('id') return maidan_id
def face_token_get(file): url = g.host + g.get_info('api_info', 'face_analyze') if not file: file = face_file_name_get() r = gmhttp.post(url, data={"filename": file}).json() token = r.get('data').get('token') return token
def create_live(self): url = self.host + '/files/upload/' + "?" + self.android_params with open(os.path.join(BASE_DIR, 'common', 'test.jpg'), 'rb') as f: info = f.read() files = {"file": ('test.jpg', info, 'image/jpg')} r = requests.post(url, files=files, headers=self.header, verify=False) self.file_name = r.json().get('data').get('file') push_live = g.get_info('api_info', 'live_push_live_info') tag_id = g.get_info('env_info', 'tag_id1') url = self.host + push_live + "?" + 'title={}&cover_url={}&tag_id={}'.format( '直播测试', self.file_name, tag_id) + '&' + self.android_params r = requests.get(url, verify=False, headers=self.header) r = r.json() self.channel = r.get('data').get('channel') return self.channel
def shopcart_info_get(): url = g.host + g.get_info('api_info', 'shopcart_list_v2') gmhttp.params.update({'count_only': 0}) r = gmhttp.get(url).json() if not r['data']['cart']: *_, service_item_id = service_id_get() post_data = {'number': '1', 'service_item_id': service_item_id} gmhttp.post(url=g.host + g.get_info('api_info', 'shopcart_add_v1'), data=post_data).json() r = gmhttp.get(url).json() gmhttp.reset() service_item_id = r['data']['cart'][0]['services'][0]['service_item_id'] myid = r['data']['cart'][0]['services'][0]['id'] # 获取购物车物品id service_id = r['data']['cart'][0]['services'][0]['service_id'] transparent_key = r['data']['interesting'][0]['gm_url'].split('=')[2] return myid, service_item_id, service_id, transparent_key
def live_topic_id_get(): uri = g.get_info('api_info', 'live_list') url = g.host + uri r = gmhttp.get(url).json() topic_list = list( map(lambda x: x.get('topic_id'), filter(lambda x: x.get('status') == 0, r.get('data'))))[0] return topic_list
def diary_id_get(): api_setup_1 = g.get_info('api_info', 'user_my_diary_v2') url = g.host + api_setup_1 r = gmhttp.get(url).json() diary_id = r['data']['diaries'][0]['id'] if r['data']['diaries'] else False # ============================================= if not diary_id: diary_id = create_diary() return diary_id
def sign_activity_id_get(): url = g.host + g.get_info('api_info', 'sign_detail') r = gmhttp.get(url).json() activity_id = r.get('data').get('id') status = r.get('data').get('is_remind') sign_status = r.get('data').get('sign_status') total_days = r.get('data').get('total_days') return activity_id, status, sign_status, total_days
def draft_id_get(): # 创建草稿 add_draft = g.get_info('api_info', 'draft_create') url = g.host + add_draft tag_id1 = g.get_info('env_info', 'tag_id1') r = gmhttp.post( url, data={ 'draft_type': 0, # 类型为1需要后期添加 'content': '草稿测试', 'cover': '', 'diary_id': diary_id_get(), 'images': [], 'tag_ids': '[' + tag_id1 + ']' }).json() draft_id = r.get('data').get('draft_id') return draft_id
def get_live(self): url = self.host + g.get_info('api_info', 'index_v6') params = g.params() params.update({'tabtype': 'live'}) r = requests.get(url, params=params, verify=False).json() d_live = r.get('data').get('data_live') dlive_list = [ item.get('topic_id') for item in d_live if item['status'] in [0, 1] ] return dlive_list[0] if dlive_list else None
def order_settlement_id_get(): # 订单和付款单 uri = g.get_info('api_info', 'orders_my_v2') url = g.host + uri r = gmhttp.get(url).json() order_id = settlement_id = None for item in r['data']['orders']: order_id = item['order']['order_id'] settlement_id = item['order']['settlement_id'] break return order_id, settlement_id
def service_id_get(): service_id = 5450353 # 获取医生id和医院id gmhttp.params.update({"service_id": service_id}) url = g.host + g.get_info('api_info', 'service_detail_v1') r = gmhttp.get(url).json() gmhttp.reset() doctor_id = r.get('data').get('service_hospital').get('doctor_id') hospital_id = r.get('data').get('service_hospital').get('hospital_id') sku_id = r.get('data').get('normal_sku_list')[0].get('service_item_id') return service_id, hospital_id, doctor_id, sku_id
def settlement_id_get(): data = { "service_item_id": "78123", "number": "1", "phone": "77777777777", "platform_coupon_id": "", "doctor_coupon_id": "", "use_point": "0", "is_doctor_see": "1", "insurance_info": "[]" } r = gmhttp.post(url=g.host + g.get_info('api_info', 'settlement_create_v1'), data=data).json() st_id = r.get('data').get('id') return st_id
def question_id_get(): r = gmhttp.get(url=g.host + g.get_info('api_info', 'question_index_v2')).json() question_id = r['data']['topics'][0]['question_id'] zone_id = r['data']['recommend_zones'][0]['zone_id'] return question_id, zone_id
def diary_id_others_get(): url = g.host + g.get_info('api_info', 'index_v6') r = gmhttp.get(url).json() diary_id = r.get('data').get('features')[0].get('id') return diary_id
def uid_get(): url = g.host + g.get_info('api_info', 'user_info') r = gmhttp.get(url).json() user_id = r.get('data').get('uid') return user_id
def reason_id_get(): url = g.host + g.get_info('api_info', 'report_reason') r = gmhttp.get(url).json() reason_id = r.get('data')[0].get('reason_id') return reason_id
def run_test(path: str = 'testCase'): """ :param path: With default path testcase, the method will execute all testcases, otherwise it only execute the cases which in the specific path :return: test report """ host = g.host method = g.get_info('config_info', 'method') testsuits = TestSuite() report_name = "{}_{}".format(path, str(datetime.now().strftime("%Y%m%d%H%M%S"))) copyname = 'testReport/test_api_ressult.html' # 保证连接正常,testdata做了断网简单兼容,此处也做兼容 if host == "http://backend.pre.igengmei.com": host = "https://backend.igengmei.com" try: a = requests.get(f"http://{g.server_host}/testapi/checkedapi/", params={ 'env': host, "method": method }).json() with open(case_file, 'w', encoding='utf-8') as f: f.write(json.dumps(a)) except Exception: with open(case_file, 'r', encoding='utf-8') as f: _data = f.read() a = eval(_data) _a = copy.deepcopy(a) for case in a: _unit = unittest.defaultTestLoader.discover(path, pattern=case + '_test.py', top_level_dir='testCase') # print(_unit.__dict__) if case=='account_login_login_vfc' else None if _unit.__dict__.get('_tests'): testsuits.addTest(_unit) _a.remove(case) result = BeautifulReport(testsuits) result.report(filename=report_name, description="API接口", log_path='testReport') shutil.copy('testReport/%s.html' % report_name, copyname) result_list = [item for item in result.result_list if item[4] != '成功'] # 我们需要获取已经记录但是没有写脚本的接口和case,收录在_a中 from PIL import Image, ImageDraw, ImageFont length, weight_unit = 1000, 20 back_img = Image.new(mode='RGB', size=(length, weight_unit * ((len(result_list) or 1) + len(_a) + 2)), color=(255, 255, 255)) draw_img = ImageDraw.ImageDraw(back_img) font = ImageFont.truetype('arial.ttf', size=weight_unit, encoding='gbk') num = 0 if len(result_list) == 0: draw_img.text((0, weight_unit * num), 'ALL PASS!', font=font, fill='green') num += 1 for item in result_list: draw_img.text((0, weight_unit * num), item[0] + ':' + item[1], font=font, fill='red') num += 1 if _a: draw_img.text((0, weight_unit * num), 'The following interface scripts are missing!!', font=font, fill='red') num += 1 for item in _a: draw_img.text((0, weight_unit * num), item, font=font, fill='blue') num += 1 back_img.save('testReport/error.jpg') if len(result_list) > 0: #主动跑错 raise Exception('有接口没有执行通过!')