def session_post(self, account, third, url, post_data): # 共用 session post方式 (Pc) try: r = self.SESSION.post(self._post_url + url, headers=self._header, data=json.dumps(post_data)) if 'Balance' in url: print(f'{third}, 餘額: {r.json()["balance"]}') elif 'transfer' in url: if r.json()['status']: print( f'帳號 kerrthird001 轉入 {third} ,金額:1, 狀態碼:{r.json()["status"]}' ) else: print(f'{third} 轉帳失敗') elif 'getuserbal' in url: print(f'4.0 餘額: {r.json()["data"]}') # print(title)#強制便 unicode, 不燃顯示在html報告 會有誤 # print('result: '+statu_code+"\n"+'---------------------') except requests.exceptions.ConnectionError: print(f'{third} 轉帳失敗') print(u'連線有問題,請稍等') except Exception as e: print(f'{third} 轉帳失敗') from utils.TestTool import trace_log trace_log(e)
def test_PcTransferout(self): # 第三方轉回 """第三方轉出""" status_dict = {} # 存放 第三方狀態 post_data = {"amount": 1} errors = {} for third in self._third_list: url = f'/{third}/transferToFF' try: r = self.SESSION.post(self._post_url + url, data=json.dumps(post_data), headers=self._header) if r.json()['status']: print( f'帳號 {self._user}, {third} 轉回4.0 ,金額:1, 狀態碼:{r.json()["status"]}' ) else: logger.error(f'轉帳接口失敗 : errors[{third}] = {r.json()}') errors[third] = r.json() print(f'{third} 轉帳接口失敗') status_dict[third] = r.json()['status'] except Exception as e: print(f'{third} 轉帳接口失敗') from utils.TestTool import trace_log trace_log(e) logger.debug(f'status_dict = {status_dict.items()}') for third in status_dict.keys(): if status_dict[third]: logger.debug( f'status_dict[{third}]: # 判斷轉帳的狀態, 才去要 單號 = {status_dict[third]}' ) tran_result = ["", 0] count = 0 while tran_result[1] != '2': # 確認轉帳狀態, 2為成功 ,最多做10次 tran_result = self._conn_mysql.thirdly_tran( tran_type=1, third=third, user=self._user) sleep(2) count += 1 # print(f'驗證{third}中 : tran_result = {tran_result}') if tran_result[1] == '2': logger.info(f'轉帳狀態成功 : [{third}] = {tran_result}') print(f'狀態成功. {third} ,sn 單號: {tran_result[0]}') break if count == 15: logger.error( f'轉帳狀態失敗 : errors[{third}] = {tran_result}') errors[third] = tran_result # print(f'{third} : 轉帳狀態失敗') # 如果跑道9次 需確認 break else: pass for key, value in errors.items(): print(f'三方: {key} 轉帳失敗. 接口返回: {value}') self.test_PcThirdBalance() if errors: self.fail('部分轉帳失敗')
def check_driver_state(self): try: self.driver.execute(Command.STATUS) return True except Exception as e: self.logger.error(trace_log(e)) return False
def _add_all_random(self, index_m=0, index_g=0): _temp_m = index_m # 紀錄當前method _temp_g = index_g # 紀錄當前game try: methods = self.get_current_methods() for method in range(index_m, len(methods)): _temp_m = method # self.logger.debug("_temp_m:%s" % _temp_m) methods[method].click() # self.logger.info(">>>%s method clicked" % methods[method].get_attribute('innerHTML')) sleep(self._waitTime) # 供JS運行時間 games = self.get_current_games() for game in range(index_g, len(games)): _temp_g = game # self.logger.debug("_temp_g:%s" % _temp_g) if self.link == '/gameBet/jlffc': methods[method].click() # 為配合吉利分分彩新增 # self.logger.info(">>>%s method clicked." % methods[method].get_attribute('innerHTML')) games[game].click() # self.logger.info(">%s game clicked." % games[game].get_attribute('innerHTML')) sleep(0.1) self.add_random_bet_1() sleep(self._waitTime) index_g = 0 # 當本輪皆添加後需初始話避免後續短少 except Exception as e: self.logger.error(trace_log(e)) self.check_period_popup() # 排除臨時顯示彈窗 self.logger.warning("Retry bet all with method:%s, game:%s" % (index_m, index_g)) if self._retry_times < self._max_retry: self._retry_times += 1 self._add_all_random(_temp_m, _temp_g) # 從中斷點再次運行 else: raise e
def add_all_random(self, index_t=0, index_m=0, index_g=0): """ 投注所有彩種,考量因跨期導致彈窗中段的可能,添加三個參數供接續測試。 :param index_t: 起始type **呼叫時不需帶參** :param index_m: 起始method **呼叫時不需帶參** :param index_g: 起始game **呼叫時不需帶參** """ _temp_t = index_t # 紀錄當前type _temp_m = index_m # 紀錄當前method _temp_g = index_g # 紀錄當前game self.get_types() print('self.game_types = {}'.format(self.game_types)) try: if len(self.game_types) > 0: # self.logger.debug("len(self.gameTypes) : %s" % len(self.game_types)) for gType in range(index_t, len(self.game_types)): _temp_t = gType # self.logger.debug("_temp_t:%s" % _temp_t) # self.logger.info(">>>>>%s" % self.game_types[gType].get_attribute('innerHTML')) self.game_types[gType].click() self._add_all_random(index_m, index_g) index_m = 0 # 當本輪皆添加後需初始話避免後續短少 else: self._add_all_random(index_m, index_g) except Exception as e: self.logger.error(trace_log(e)) self.check_period_popup() # 排除臨時顯示彈窗 self.logger.warning( "Retry bet all with type:%s, method:%s, game:%s" % (index_t, index_m, index_g)) if self._retry_times < self._max_retry: self._retry_times += 1 self.add_all_random(_temp_t, _temp_m, _temp_g) # 從中斷點再次運行 else: raise e
def submit_bet(self): self.driver.find_element_by_id(self.id_submit).click() self.driver.find_element_by_xpath(self.xpath_submit_bet).click() try: WebDriverWait(self.driver, 30).until( expected_conditions.presence_of_element_located( (By.XPATH, self.xpath_bet_success))) print('投注結果驗證通過') except Exception as e: logger.error(trace_log(e)) print('取得投注結果失敗') raise e
def get_driver(self) -> webdriver: self.logger.info('BasePage.get_driver : self.driver = {}'.format( self.driver)) if self.driver is None: try: if 'ChromeDriver' in locals() or 'ChromeDriver' in globals(): self.driver = webdriver.Chrome( chrome_options=Config.chrome_options) else: self.driver = webdriver.Chrome( Config.chromeDriver_Path, chrome_options=Config.chrome_options) self.driver.implicitly_wait(10) self.driver.set_page_load_timeout(30) except Exception as e: self.logger.error(trace_log(e)) return self.driver
def add_random_bet_5(self): try: self.driver.find_element_by_id(self.id_random_five) except Exception as e: self.logger.error(trace_log(e))
def pc_submit(self, account: str, envs: int, em_url: str, header: dict, lottery: str, award_mode: int, trace_issue_num: int, win_stop: bool = True, red_mode: bool = False, money_unit: float = 1.0): """ PC投注/追號共用功能. 首先判斷當前彩種是否有紅包模式、獎金模式、元角模式限制並調整。 後續透過 FF_().submit_json 取得投注注單內容。 於發送投注後回傳投注結果。 :param red_mode: 紅包模式,預設為關 :param money_unit: 單位模式,預設為元 :param account: 用戶帳號 :param envs: 環境物件 :param em_url: 投注網域 :param header: header內容 :param lottery: 彩種名稱 :param award_mode: 獎金組模式 :param trace_issue_num: 追號期數,>2則判定為追號,否則為一般投注 :param win_stop: 是否追中即停 :return: 若投置請求成功,回傳None。若請求報錯,回傳 [彩種名稱, 錯誤訊息] """ if lottery in LotteryData.lottery_force_bonus: # 強制高獎金 award_mode = 2 elif lottery in LotteryData.lottery_no_bonus: # 無高獎金 award_mode = 1 if lottery in LotteryData.lottery_no_trace: # 不支援追號彩種 trace_issue_num = 0 if lottery in LotteryData.lottery_no_red: # 不支援紅包彩種 red_mode = False if lottery in LotteryData.lottery_dollar: # 強制元模式 money_unit = 1 elif money_unit == 0.01 and lottery in LotteryData.lottery_dime: money_unit = 0.1 if trace_issue_num <= 1: # 若非追號單,追中即停更改為False win_stop = False logger.info(f'pc_submit: account={account}, envs={envs}, em_url={em_url}, header={header}, lottery={lottery},' f'award_mode={award_mode}, trace_issue_num={trace_issue_num}, win_stop={win_stop}') postData = FF_().submit_json(em_url=em_url, account=account, lottery=lottery, award_mode=award_mode, trace_issue_num=trace_issue_num, is_trace_win_stop=win_stop, envs=envs, header=header, money_unit=money_unit) assert len(postData) > 0 # 確保彩種有成功取得投注內容 logger.info(f'postData = {postData}') for data in postData: if red_mode: # 取得投注內容後,若為紅包投注則添加紅包參數 data['redDiscountAmount'] = data['amount'] # 呼叫各彩種 投注data api r = FF_().session_post(em_url, f'/gameBet/{lottery}/submit', json.dumps(data), header) print(f'{account}投注, 彩種: {self.lottery_dict[lottery][0]}\n') try: print(r.json()['msg'] + '\n') if r.json()['isSuccess'] == 0: # 若投注結果為失敗 return [self.lottery_dict[lottery][0], r.json()['msg']] print(f'投注方案: {r.json()["data"]["projectId"]}\n') except KeyError as k: print(r.text) print(k) return [self.lottery_dict[lottery][0], r.text] except Exception as e: from utils.TestTool import trace_log trace_log(e) return [self.lottery_dict[lottery][0], r.text] return None
def suite_test(test_cases, user_name, test_env, is_use_red: bool, money_unit: float, award_mode: int, lottery_name): """ autoTest 初始化 :param lottery_name: 彩種列表 :param award_mode: 獎金模式 (0:預設 / 1:高獎金 / 2:高獎金) :param money_unit: 元角分模式 (1 / 0.1 / 0.01) :param test_cases: Array[][]; 測試項目,為二維矩陣。第一維區分測試類型(PC_API、APP_API、PC整合),二維紀錄測試method名稱 :param user_name: String; 就是個用戶名 :param test_env: String; 網域名稱,用於Config.encConfig初始化 :param is_use_red: String; yse or no; 目前未使用 :return: """ logger = create_logger(r'\AutoTest', 'auto_test') logger.info("suite_test 初始化") _env_config = Config.EnvConfig(test_env) _env_config_app = Config.EnvConfigApp(test_env) _suite_list = [] _web_test_list = [ 'cqssc', 'xjssc', 'hljssc', 'shssl', 'tjssc', 'txffc', 'fhjlssc', 'fhcqc', 'fhxjc', '3605fc', 'btcffc', 'llssc', '360ffc', 'jlffc', 'v3d' ] logger.debug(f'autoTest test_cases : {test_cases}') try: suite = unittest.TestSuite() _conn = None _conn2 = None logger.info(f"suite_test with test_cases : {test_cases}") if lottery_name == 'all': lottery_name = LotteryData.lottery_dict.keys( ) # 頁面選全部, 從config取lottery資訊 else: lottery_name = [ lottery_name ] # test_PCLotterySubmit , loop取出lottery , 所以寫在list裡 if _env_config.get_env_id() in (0, 1): _conn = OracleConnection(_env_config.get_env_id()) _conn2 = MysqlConnection(_env_config.get_env_id()) for case in test_cases[0]: # PC接口測試 _suite_list.append( ApiTestPC(case=case, env_config=_env_config, _user=user_name, red_type=is_use_red, money_unit=money_unit, award_mode=award_mode, oracle=_conn, mysql=_conn2, lottery_name=lottery_name)) for case in test_cases[1]: # App接口測試 _suite_list.append( ApiTestApp(case_=case, env_config=_env_config_app, user=user_name, red_type=is_use_red, oracle=_conn, mysql=_conn2)) for case in test_cases[2]: # Web交互測試 if case == 'test_plan': for lottery in _web_test_list: _suite_list.append( IntegrationTestWeb(case=f'test_{lottery}', env_config=_env_config, user=user_name, red_type=is_use_red)) else: _suite_list.append( IntegrationTestWeb(case=case, env_config=_env_config, user=user_name, red_type=is_use_red)) elif _env_config.get_env_id() == 11: # 若為YFT測試案例 _conn = PostgresqlConnection() # 建立共用的DB連線 for case in test_cases[0]: _suite_list.append( ApiTestPC_YFT(case=case, env_config=_env_config, user=user_name, money_unit=money_unit, _award_mode=award_mode, conn=_conn)) for case in test_cases[1]: _suite_list.append( ApiTestAPP_YFT(case=case, env_config=_env_config, user=user_name, money_unit=money_unit, award_mode=award_mode, conn=_conn)) logger.info(f"測試內容 suite_list : {_suite_list}") suite.addTests(_suite_list) logger.info(f"測試內容Suite suite_api_pc : {suite}") filename = Config.reportHtml_Path # now + u'自動化測試' + '.html' fp = open(filename, 'wb') runner = HTMLTestRunner.HTMLTestRunner( stream=fp, title=u'測試報告', description=f'環境: {_env_config.get_domain()}, 帳號: {user_name}', ) logger.debug(">>>>>>>>Test Start.<<<<<<<<") runner.run(suite) logger.debug(">>>>>>>>Test End.<<<<<<<<") fp.close() _conn.close_conn() if _conn2 is not None: _conn2.close_conn() except Exception as e: logger.error(trace_log(e))