Пример #1
0
 def test_data_analysis(self):
     #登录
     self.login_page.login()
     #获取实际结果
     re=self.data_analysis.main()
     #期望结果
     log.info("re")
Пример #2
0
 def main(self,coupon_name,money,liveTime,introductions,notices,number,instructions):
     log.info("begin creat coupon page")
     self.click(CreatCouponPage.collector_tools_loc)#点击“集客工具”
     self.click(CreatCouponPage.coupon_loc)#点击优惠券菜单
     time.sleep(5)
     self.click(CreatCouponPage.creat_loc)#点击创建
     time.sleep(5)
     self.click(CreatCouponPage.new_coupon_loc)#点击新增优惠券按钮
     time.sleep(5)
     self.sendKeys(CreatCouponPage.input_coupon_name,coupon_name)#输入优惠券名称
     time.sleep(2)
     self.sendKeys(CreatCouponPage.input_money,money)#输入金额
     time.sleep(2)
     self.sendKeys(CreatCouponPage.live_time,liveTime)#输入到期日
     time.sleep(2)
     js1 = "document.documentElement.scrollTop=5000"
     self.driver.execute_script(js1)
     self.sendKeys(CreatCouponPage.coupon_introduction,introductions)#输入优惠说明
     time.sleep(2)
     self.sendKeys(CreatCouponPage.use_notice,notices)#输入使用须知
     time.sleep(2)
     self.sendKeys(CreatCouponPage.input_num,number)#输入数量
     self.sendKeys(CreatCouponPage.apply_instruction,instructions)#输入申请说明
     self.click(CreatCouponPage.save_loc)#保存并提交审核
     time.sleep(2)
     self.click(CreatCouponPage.sure_loc)#确定
     log.info("end creat coupon page")
Пример #3
0
    def main(self):

        log.info("begin grant coupon page")
        self.click(GrantCouponPage.wechat_grant_loc)# 点击微信发放
        self.click(GrantCouponPage.peculiar_msend_loc)#点击特异群发
        self.click(GrantCouponPage.msend_loc)#点击群发消息
        log.info("end grant coupon page")
Пример #4
0
def youzhan_task_parser(taskcontent):
    all_info = []
    room_list = []

    result = {}
    result['para'] = None
    result['error'] = 0

    taskcontent = taskcontent.encode('utf-8').strip()

    try:
        hotel_id = taskcontent.split('&')[0]
        star = taskcontent.split('&')[2]
        ipathid = taskcontent.split('&')[1]
        city = taskcontent.split('&')[3]
        country = taskcontent.split('&')[4]
        from_date_temp = taskcontent.split('&')[5]
        from_date = from_date_temp[:4] + '-' + from_date_temp[4:6] + '-' \
                    + from_date_temp[6:]
        to_date_temp = datetime.datetime(int(from_date_temp[:4]), int(from_date_temp[4:6]), \
                                         int(from_date_temp[6:8]))
        to_date = str(to_date_temp + datetime.timedelta(days = 1))[:10]
    except Exception,e:
        logger.info('youzhanHotel: Wrong Content Format with %s'%taskcontent)
        result['error'] = TASK_ERROR
        return result
Пример #5
0
 def test_add_smsTemplate(self):
     tem_title=u"双11活动"
     tem_detail=u"活动当天消费双倍积分"
     #获取实际结果
     res = self.add_smsTemplate(tem_title, tem_detail)
     #期望结果
     log.info(res)
Пример #6
0
def get_search_id(url,proxy):
    hdr = {'User-Agent': 'Mozilla/5.0 (Windows NT 6.1) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/27.0.1453.116',
       'Accept': 'text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8',
       'Accept-Charset': 'ISO-8859-1,utf-8;q=0.7,*;q=0.3',
       'Accept-Encoding': 'none',
       'Referer':'http://www.wego.cn/',
       'Accept-Language': 'en-US,en;q=0.8',
       'Connection': 'keep-alive'}
    proxies = {}
    if proxy != None and proxy != '':
        proxies['http'] = 'http://' + proxy
    else:
        proxies = None
    try:
        for i in range (2):
            req = requests.get(url, headers = hdr, proxies = proxies).url
            url_res_pat = re.compile(r'search/(.*?)\?arrival_code')
            url_res = url_res_pat.findall(req)
            if url_res == [] or url_res == [''] or url_res == None:
                continue
            else :
                return url_res[0]
        return ""
    except Exception,e:
        logger.info("Get_search_id Error: %s" %str(e))
        return ""
Пример #7
0
 def test_trade_manager(self):
     #登录
     self.login_page.login()
     #获取实际结果
     re=self.trade_manager_page.main()
     #期望结果
     log.info("re")
Пример #8
0
 def test_reward_convert(self):
     convertnum="123456789000"
     #登录
     self.loginpage.login()
     #获取实际结果
     self.reward_convert_page.main(convertnum)
     #期望结果
     log.info("re")
Пример #9
0
 def test_buyEnquiry_export(self):
     #登录
     self.login_page.login()
     time.sleep(5)
     #获取实际结果
     re=self.buyEnquiry_export_page.main()
     #期望结果
     log.info("re")
Пример #10
0
 def login(self, username="******", psw="16888cst"):
     '''登录流程:'''
     log.info("begin login page")
     self.open_login_page()
     self.sendKeys(LoginPage.user_loc,username)#输入账号
     self.sendKeys(LoginPage.psw_loc,psw)#输入密码
     self.click(LoginPage.sub_loc)#点击登录按钮
     log.info("end login page")
Пример #11
0
 def main(self,convertnum):
     log.info("begin reward convert page")
     self.click(RewardConvertPage.qfzs_tab_loc)#点击群发助手
     time.sleep(2)
     self.click(RewardConvertPage.reward_convert_loc)#点击奖励兑换
     self.sendKeys(RewardConvertPage.input_convert_num,convertnum)#输入兑换码
     self.click(RewardConvertPage.convert_loc)#点击兑换
     log.info("end reward convert page")
Пример #12
0
 def login(self, username="******", psw="123456"):
     '''登录流程:'''
     log.info("begin login page")
     self.open_login_page()
     self.sendKeys(LoginPage.user_loc,username)#输入账号
     self.sendKeys(LoginPage.psw_loc,psw)#输入密码
     self.click(LoginPage.sub_loc)#点击登录按钮
     log.info("end login page")
Пример #13
0
 def test_auditing_coupon(self):
     #登录
     self.loginf_page.login()
     time.sleep(10)
     #获取实际结果
     re=self.auditing_coupon_page.main()
     #期望结果
     log.info("re")
Пример #14
0
 def test_consume_covert(self):
     code="573935501845"
     #登录
     self.login_page.login()
     #获取实际结果
     re=self.consume_covert_page.main(code)
     #期望结果
     log.info("re")
Пример #15
0
 def findElement(self,loctor):#loctor是元祖类型
     '''
     args:
     loctor 传元祖,如("id","xx")
     '''
     element = WebDriverWait(self.driver,self.timeout,self.poll).until(lambda x: x.find_element(*loctor))
     log.info('find location: %s,  element: %s', loctor, element.text)
     return element
Пример #16
0
 def main(self,scontent,sphone):
     log.info("begin sms send page")
     self.click(SmsMsendPage.qfzs_tab_loc)#点击“群发助手”
     time.sleep(2)
     self.click(SmsMsendPage.sms_msend_loc)#点击“短信群发”
     self.sendKeys(SmsMsendPage.input_sms_content,scontent)#输入短信内容
     self.sendKeys(SmsMsendPage.input_sms_sendee,sphone)#输入接收人手机号
     self.click(SmsMsendPage.send_loc)#点击发送
     log.info("end sms send page")
Пример #17
0
 def main(self,code):
     log.info("begin covert coupon page")
     self.click(CovertConsumePage.collector_tools_loc)#点击“集客工具”
     self.click(CovertConsumePage.coupon_loc)#点击优惠券
     self.click(CovertConsumePage.covert_tab)#点击兑换菜单
     self.sendKeys(CovertConsumePage.input_code,code)#输入兑换码
     self.click(CovertConsumePage.covert_loc)#点击兑换
     self.click(CovertConsumePage.sure_loc)#点击确定
     log.info("end covert coupon page")
Пример #18
0
 def test_buyEnquiry_allot(self):
     customer_key="胡萝卜土"
     #登录
     self.login_page.login()
     time.sleep(5)
     #获取实际结果
     re=self.buyEnquiry_allot_page.main(customer_key)
     #期望结果
     log.info("re")
Пример #19
0
 def test_sms_msend(self):
     scontent="双11活动开始了!"
     sphone="13424399553"
     #登录
     self.loginpage.login()
     time.sleep(10)
     #获取实际结果
     re=self.sms_msend_page.main(scontent,sphone)
     #期望结果
     log.info("re")
Пример #20
0
 def search(self,name="双12五折券"):
     log.info("begin grant coupon page")
     self.click(SearchCoupon.collector_tools_loc)#点击“集客工具”
     self.click(SearchCoupon.coupon_loc)#点击优惠券
     self.click(SearchCoupon.grant_loc)#点击发放
     time.sleep(2)
     self.sendKeys(SearchCoupon.input_coupon_name,name)#输入关键字
     time.sleep(2)
     self.click(SearchCoupon.search_loc)#点击查询
     log.info("end grant coupon page")
Пример #21
0
 def main(self):
     log.info("begin covert coupon page")
     self.click(CovertCouponPage.collector_tools_loc)#点击“集客工具”
     self.click(CovertCouponPage.coupon_loc)#点击优惠券菜单
     self.click(CovertCouponPage.covert_loc)#点击兑换
     self.click(CovertCouponPage.covert_records_loc)#点击兑换记录
     time.sleep(20)
     self.click(CovertCouponPage.export_loc)#点击导出
     self.click(CovertCouponPage.download_loc)#点击下载文件
     log.info("end covert coupon page")
Пример #22
0
def parseRoom(content,hotel_name,city_name_zh,check_in,check_out,hotel_id):
    room_list = []
    if content == '' or len(content) < 100:
        return room_list

    try:
        content_json = json.loads(content)['value']['hotelRoomList']
    except Exception, e:
        logger.info('elongHotelParser: Cannot load json' + str(e))
        return room_list
Пример #23
0
def get_json_url(dept_city=None,dest_city=None,dept_time=None):
    html_url = 'http://www.expedia.com.hk/Flights-Search?trip=oneway&leg1=from:'+dept_city+',to:'+dest_city+',departure:'+dept_time+'TANYT&passengers=children:0,adults:1,seniors:0,infantinlap:Y&options=cabinclass:coach&mode=search&'
    html_res = crawl_single_page(html_url)
    regex = re.compile(r'<div id="originalContinuationId">(.*?)</div>',re.M|re.S|re.I)
    match_id = re.search(regex,html_res)
    if match_id:
        return match_id.group(1).strip('\s')
    else:
        logger.info('not catch the originalContinuationId of json data')
        return False
Пример #24
0
def data_writer(room_list, taskcontent):
    if room_list == None or room_list == []:
        logger.error('No hotel parsed')
        return 
    try:
        InsertHotel_room(room_list)
        logger.info('Insert hotel [success] ' + taskcontent)
    except Exception, e:
        logger.error('Insert hotel [failed] ' + taskcontent)
        return 
Пример #25
0
 def main(self):
     log.info("begin data analysis page")
     time.sleep(5)
     self.click(DataAnalysisPage.collector_tools_loc)#点击集客工具
     self.click(DataAnalysisPage.collector_enroll_loc)#点击集客报名
     self.click(DataAnalysisPage.data_analysis_loc)#点击数据分析
     time.sleep(2)
     self.click(DataAnalysisPage.export_loc)#点击导出
     time.sleep(10)
     self.click(DataAnalysisPage.download_loc)#点击下载导出文件
     log.info("end data analysis page")
Пример #26
0
 def test_grant_coupon(self):
     #登录
     self.login_page.login()
     time.sleep(10)
     #查询优惠券
     self.search_coupon.search()
     time.sleep(5)
     #获取实际结果
     re=self.grant_coupon_page.main()
     #期望结果
     log.info("re")
Пример #27
0
def ctripFlight_task_parser(content):

    try:
        contents = content.strip().split('&')
        dept_id = contents[0]
        dest_id = contents[1]
        dept_date = contents[2][:4] + '-' + contents[2][4:6] + '-' + contents[2][6:]
        print dept_date
    except Exception,e:
        logger.info('wrong content format with %s'%content)
        return None
Пример #28
0
 def main(self):
     log.info("begin trade manager page")
     time.sleep(5)
     self.click(TradeManagerPage.collector_tools_loc)#点击集客工具
     self.click(TradeManagerPage.collector_enroll_loc)#点击集客报名
     self.click(TradeManagerPage.trade_manager_loc)#点击交易管理
     time.sleep(2)
     self.click(TradeManagerPage.export_loc)#点击导出
     time.sleep(10)
     self.click(TradeManagerPage.download_loc)#点击下载导出文件
     log.info("end trade manager page")
Пример #29
0
 def main(self,customer_key):
     log.info("begin buyEnquiry allot page")
     self.click(BuyEnquiryAllotPage.businessConsult_loc)#点击业务咨询
     self.click(BuyEnquiryAllotPage.businessclue_loc)#点击业务线索
     self.click(BuyEnquiryAllotPage.buyEnquiry_loc)#点击购车询价
     self.sendKeys(BuyEnquiryAllotPage.input_key_loc,customer_key)#输入关键字
     self.click(BuyEnquiryAllotPage.query_loc)#点击查询按钮
     self.click(BuyEnquiryAllotPage.select_loc)
     self.click(BuyEnquiryAllotPage.allot_loc)#点击分配按钮
     self.click(BuyEnquiryAllotPage.select_sales)#选择销售顾问
     self.click(BuyEnquiryAllotPage.save_loc)#点击保存按钮
     log.info("end buyEnquiry allot page")
Пример #30
0
 def test_add_material(self):
     title=u"关于双11活动"
     abstract=u"活动细则说明"
     content=u"活动细则说明内容"
     author=u"shelly"
     #登录
     self.loginpage.login()
     time.sleep(10)
     #获取实际结果
     res = self.material_page.main(title, author, abstract, content)
     #期望结果
     log.info(res)
Пример #31
0
async def get_sotw_history(Server):
    """Get all basic SOTW history for the server"""
    logger.info('------------------------------')
    logger.info(
        f'Initialized GET SOTW HISTORY - Server: {Server.name} | ID: {Server.id}'
    )
    db = await h.db_open(h.DB_DISCORD_PATH)
    history_list = []
    # Loop through all weeks in server
    for week in db[f'server:{Server.id}#sotw_history']:
        ranks_list = await ranks_from_top_players(week['players'],
                                                  give_awards=True)
        history_list.append(await build_final_rank_str(ranks_list,
                                                       skill=week['skill'],
                                                       old_date=week['date']))
    logger.info(
        f"FINISHED GET SOTW HISTORY - Server: {Server.name} | ID: {Server.id}")
    return history_list
Пример #32
0
 def test_delete_user(self, login_fixture, username, except_result,
                      except_code, except_msg):
     logger.info("*************** 开始执行用例 ***************")
     user_info = login_fixture
     admin_user = user_info.get("login_info").get("username")
     token = user_info.get("login_info").get("token")
     step_login(admin_user, token)
     result = delete_user(username, admin_user, token)
     step_1(username)
     assert result.success == except_result, result.error
     assert result.response.status_code == 200
     assert result.success == except_result, result.error
     logger.info("code ==>> 期望结果:{}, 实际结果:【 {} 】".format(
         except_code,
         result.response.json().get("code")))
     assert result.response.json().get("code") == except_code
     assert except_msg in result.msg
     logger.info("*************** 结束执行用例 ***************")
Пример #33
0
    def test_01(self):
        """
        下限价多单,撤单,验证用户余额,委托保证金余额
        """
        logger.info("用例编号:7-1--下多单,撤单,验证用户余额,委托保证金余额,")
        ConnectMysql(_type=mysql_type).sda_clear_open_multi_close_open_order(user_id=self.user_id, contract_id=sda_id, status=2)
        ConnectMysql(_type=mysql_type).sda_clear_open_empty_close_multi_order(user_id=self.user_id, contract_id=sda_id, status=2)
        ConnectRedis(_type=redis_type).sda_clear_order(sda_id=sda_id)
        ConnectRedis(_type=redis_type, db=4).sda_clear_user_balance(user_id=self.user_id, keys=sda_id)
        ConnectMysql(_type=mysql_type).sda_update_user_balance(user_id=self.user_id, sda_id=sda_id,
                                                               sda_balance=990000000000000)
        deal_price = 100000000
        deal_num = 100000000

        # 下委托前查询可用余额
        info_dict = account_info(user=self.buyer, session=self.session, sda_id=sda_id, price=1000000000)
        before_balance = info_dict["balance"]

        # 下多单限价
        buy_resp = self.session.post(url=base+sda_order_create_url, data=get_sda_order_create_param(
            sda_id=sda_id,order_type=order_type.多单,order_price_type=order_type.限价,order_price=deal_price,order_num=deal_num
        ))
        buy_order_id = JMESPathExtractor().extract(query="OBJECT.orderId", body=buy_resp.text)
        logger.info("用户:{0}--接口:{1}--状态:{2}--类型:多单--返回信息:{3}".format(
            self.buyer, sda_order_create_url, buy_resp.status_code, buy_resp.json()
        ))

        # 撤单
        time.sleep(1)
        cancel_resp = self.session.post(url=base+sda_order_cancel_url, data=get_sda_order_cancel_param(sda_id=sda_id, order_id=buy_order_id, order_type=多单))
        logger.info("撤单接口状态:{0}---返回信息:{1}".format(cancel_resp.status_code, cancel_resp.json()))
        cancel_order_id = JMESPathExtractor().extract(query="OBJECT.orderId", body=cancel_resp.text)
        sync_id = JMESPathExtractor().extract(query="syncLockKey", body=cancel_resp.text)
        cancel_msg = JMESPathExtractor().extract(query="MSG", body=cancel_resp.text)

        # 下委托后查询可用余额
        time.sleep(1)
        after_info_dict = account_info_sync(sync_id=sync_id, user=self.buyer, session=self.session, sda_id=sda_id,
                                            price=1000000000)
        after_balance = after_info_dict["balance"]

        order_id_flag = assert_list([buy_order_id, 200, "SUCCESS"], [cancel_order_id, cancel_resp.status_code, cancel_msg])
        available_margin_flag = assert_one(int(before_balance), int(after_balance) )
        self.assertListEqual([True, True], [available_margin_flag, order_id_flag])
Пример #34
0
    def test_02(self):
        """
        空单持仓中,限价全平,多个对应委托,成交其中部分委托,验证委托状态、用户余额、手续费
        """
        logger.info("用例编号:57-2---空单持仓中,限价全平,多个对应委托,成交其中部分委托,验证委托状态、用户余额、手续费")

        range_num = 10
        price = 120*100000000
        buy_num = 100*100000000
        sell_num = 20*100000000

        # 平空单
        time.sleep(0.5)
        sell_resp = self.sell_session.post(url=base+sda_order_create_url, data=get_sda_order_create_param(
            sda_id=sda_id, order_type=平空, order_price_type=限价, order_price=price, order_num=buy_num
        ))
        sell_sync_id = JMESPathExtractor().extract(query="syncLockKey", body=sell_resp.text)
        logger.info("接口:{0}----返回信息:{1}".format(sda_order_create_url, sell_resp.json()))
        # time.sleep(2)

        sync_53_id = None
        for i in range(range_num):
            # 53用户下多单。
            # time.sleep(1)
            buy_53_resp = self.session_53.post(url=base+sda_order_create_url,data=get_sda_order_create_param(
                sda_id=sda_id, order_type=空单, order_price_type=限价, order_price=price, order_num=sell_num
            ))
            sync_53_id = JMESPathExtractor().extract(query="syncLockKey", body=buy_53_resp.text)
            logger.info("接口:{0}---返回信息:{1}".format(sda_order_create_url, buy_53_resp.json()))

        # time.sleep(2)

        after_53_info_dict = account_info_sync(sync_id=sync_53_id, user=self.user_53, session=self.session_53,
                                               sda_id=sda_id)
        after_53_account_balance = after_53_info_dict["balance"]

        after_info_dict = account_info_sync(sync_id=sell_sync_id, user=self.seller, session=self.sell_session,
                                            sda_id=sda_id)
        after_account_balance = after_info_dict["balance"]

        flag_51 = assert_one(int(after_account_balance), 9999773204030925)
        flag_53 = assert_one(self.sda_balance - int(price * sell_num * range_num/100000000),
                             int(after_53_account_balance))
        self.assertListEqual([True, True], [flag_51, flag_53])
Пример #35
0
async def get_server_players(Server):
    """Gets member IDs with all players in a server"""
    logger.info('------------------------------')
    logger.info(
        f'Initialized GET SERVER PLAYERS - Name: {Server.name} | ID: {Server.id}'
    )
    db = await h.db_open(h.DB_DISCORD_PATH)
    # Loop through db to get member IDs for each player name
    members_players = {}
    for player in db[f'server:{Server.id}#all_players']:
        try:
            members_players[str(
                db[f'player:{player}#server:{Server.id}#member'])].append(
                    player)
        except:
            members_players[str(
                db[f'player:{player}#server:{Server.id}#member'])] = [player]
    logger.info(f"GET SERVER PLAYERS - Name: {Server.name} | ID: {Server.id}")
    return members_players
Пример #36
0
        def func(self):
            logger.info(
                '**************************************************START**************************************************'
            )
            location_id = ''
            opvalues = ''
            for key_dict in keyword_list:
                try:
                    logger.info(
                        '正在执行用例 %s 的 %s %s %s %s %s' %
                        (key_dict["XF_CASEID"], key_dict["XF_TSID"],
                         key_dict["XF_TSDESC"], key_dict["XF_ACTION"],
                         key_dict["XF_LOCATIONID"], key_dict["XF_OPVALUES"]))
                    location_id = key_dict["XF_LOCATIONID"]
                    if location_id is None:
                        opvalues = key_dict['XF_OPVALUES']
                        if opvalues is None:
                            self._use_keyword(key_dict["XF_ACTION"])
                        else:
                            self._use_keyword(key_dict["XF_ACTION"], opvalues)
                    else:
                        opvalues = key_dict['XF_OPVALUES']
                        location = self.get_location(
                            location_id)  # get loaction value
                        if opvalues is None:
                            self._use_keyword(key_dict["XF_ACTION"], location)
                        else:
                            if '##' in location:
                                location_element = location.split('##')
                                opvalues = location_element[
                                    0] + '##' + opvalues + location_element[1]
                            else:
                                opvalues = location + '##' + opvalues
                            self._use_keyword(key_dict["XF_ACTION"], opvalues)

                except Exception as e:
                    logger.info(
                        '执行用例 %s 的 %s %s %s %s %s 出错' %
                        (key_dict["XF_CASEID"], key_dict["XF_TSID"],
                         key_dict["XF_TSDESC"], key_dict["XF_ACTION"],
                         key_dict["XF_LOCATIONID"], key_dict["XF_OPVALUES"]))
                    logger.exception(e)
                    raise e
Пример #37
0
 def test_04(self):
     """
     查询当前委托接口,错误token,验证接口返回状态、MSG、STATUS
     """
     wrong_query_Present_Orde_data = {
         "languageType": 3,
         "currentPage": 1,
         "pageSize": 15,
         "timeStamp": "1538118050702",
         "token": "as65d465as4"
     }
     logger.info("用例编号:3-4----查询当前委托接口,错误token,验证接口返回状态、MSG、STATUS")
     resp = self.session.post(url=base+query_present_order_url, data=wrong_query_Present_Orde_data)
     status = JMESPathExtractor().extract(query="STATUS", body=resp.text)
     OBJECT = JMESPathExtractor().extract(query="OBJECT", body=resp.text)
     msg = JMESPathExtractor().extract(query="MSG", body=resp.text)
     logger.info("用户:{0}----url:{1}-----访问接口状态:{2}".format(BUYER, query_present_order_url, resp.status_code))
     logger.info("查询当前委托返回信息:{}".format(resp.json()))
     self.assertListEqual([200, "令牌错误", None, "1"], [resp.status_code, msg, OBJECT, status])
Пример #38
0
    def complete_workload(self, task, Error=0, proxy='NULL'):
        try:
            if self.__flag:
                if proxy == 'NULL':
                    proxy = []

                task.other_info['parser_error'] = int(Error)
                query = {"other_info": task.other_info}
                try:
                    try:
                        logger.info("[error_code 信息入库 redis error:%s, task:%s]".format(Error, task))
                    except Exception:
                        try:
                            logger.info("[error_code 信息入库 redis error:%s task:%s ]".format(Error,
                                                                                           str(task).decode(
                                                                                               'gbk').encode('utf8')))
                        except Exception:
                            pass
                    self.write_redis_ticket(task, proxy, Error)
                except Exception, e:
                    logger.exception('not redis con' + str(e))

                # 临时兼容,有mq配置使用mq推送
                if task.master_info.get('spider_mq_host', None):
                    call_back_toservice(task, query)
                else:
                    url = 'http://{0}/?type={1}&qid={2}&uid={3}&query={4}' \
                        .format(task.host, task.callback_type, task.req_qid, task.req_uid, urllib.quote(json.dumps(query)))
                    HttpClient(task.host).get(url)
                    logger.info("[error_code 信息入库 http code: {0} url: {1}]".format(Error, url))
                return True

            len_key = 1
            if task in self.TaskingDict:
                len_key = self.TaskingDict.pop(task)

            while len_key > 0:
                task_status = {"id": task.id, "content": task.content, "source": task.source,
                               "workload_key": task.workload_key, "error": int(Error), 'proxy': "NULL",
                               "timeslot": task.timeslot}
                self.__tasks_status.append(task_status)

                len_key -= 1
Пример #39
0
 def test_03(self):
     """
     账号错误,密码正确登陆,验证返回状态和状态代码
     """
     logger.info(
         "分割线----------------------------------------------------------------------------------------------------------------"
     )
     logger.info("用例编号:1-3---账号错误,密码正确登陆,验证返回状态、状态代码、OBJECT")
     resp = self.session.post(url=base + login_url,
                              headers=headers,
                              data=get_login_param(user=wrong_user_mail,
                                                   user_password=password))
     status = JMESPathExtractor().extract(query="MSG", body=resp.text)
     login_num = JMESPathExtractor().extract(query="STATUS", body=resp.text)
     OBJECT = JMESPathExtractor().extract(query="OBJECT", body=resp.text)
     logger.info(
         "错误账号:{0}-----登陆url:{1}-----接口返回状态:{2}------登陆状态:{3}".format(
             wrong_user_mail, login_url, resp.status_code, status))
     self.assertListEqual(["用户未注册", None, "1"], [status, OBJECT, login_num])
Пример #40
0
 def test_05(self):
     """
     提现后查询状态
     :return:
     """
     check_user_param = {
         "Email": "*****@*****.**",
         "Signature": "22e63226e0ae4111b6161a2bd1834721"
     }
     withdraw_param = {
         "Email": "*****@*****.**",
         "number": 900000000000,
         "Signature": "2bf28bcd080d619618430b32f77b64b4",
     }
     logger.info(
         "分割线----------------------------------------------------------------------------------------------------------------"
     )
     logger.info("用户编号:29-4-----测试提现")
     resp = self.session.post(url=base_url + login_url,
                              headers=headers,
                              data=get_login_param(user=BUYER,
                                                   user_password=password))
     status = JMESPathExtractor().extract(query="MSG", body=resp.text)
     logger.info(
         "用户:{0}------登陆url:{1}-------接口返回状态:{2}-------登陆状态{3}".format(
             BUYER, login_url, resp.status_code, status))
     check_user_resp = self.session.post(url=base_url + check_user_url,
                                         data=check_user_param)
     withdraw_resp = self.session.post(url=base_url + withdraw_url,
                                       data=withdraw_param)
     order_id = JMESPathExtractor().extract(query="OBJECT.withdrawId",
                                            body=withdraw_resp.text)
     key = _md5_user(word=order_id)
     get_withdraw_status_param = {
         "withdrawId": order_id,
         "Signature": key,
     }
     withdraw_status_resp = self.session.post(
         url=base_url + get_withdraw_status_url,
         data=get_withdraw_status_param)
     print(withdraw_status_resp.status_code)
     print(withdraw_status_resp.json())
Пример #41
0
 def test_02(self):
     """
     正常下市价买单,验证返回接口状态、MSG、STATUS
     """
     logger.info("用例编号:2-2-----正常下市价买单,验证返回接口状态、MSG、STATUS")
     resp = self.session.post(url=base + order_reservations_url,
                              data=get_order_reservations_param(
                                  transtion_id=transtion_id,
                                  order_type=市价,
                                  price=price,
                                  num=num))
     status = JMESPathExtractor().extract(query="STATUS", body=resp.text)
     msg = JMESPathExtractor().extract(query="MSG", body=resp.text)
     buyer_order_id = JMESPathExtractor().extract(
         query="OBJECT.buyerOrderId", body=resp.text)
     logger.info("用户:{0}----url:{1}-----接口状态:{2}".format(
         BUYER, order_reservations_url, resp.status_code))
     logger.info("下市价买单返回信息:{}".format(resp.json()))
     self.assertListEqual([200, "SUCCESS", "0"],
                          [resp.status_code, msg, status])
Пример #42
0
 def test_02(self):
     """
     账号正确,未加密密码登陆,验证返回状态的状态代码、OBJECT
     """
     logger.info(
         "分割线----------------------------------------------------------------------------------------------------------------"
     )
     logger.info("用例编号:1-2----账号正确,未加密密码登陆,验证返回状态、状态代码、OBJECT")
     resp = self.session.post(url=base + login_url,
                              headers=headers,
                              data=get_login_param(
                                  user=BUYER, user_password=wrong_password))
     status = JMESPathExtractor().extract(query="MSG", body=resp.text)
     login_num = JMESPathExtractor().extract(query="STATUS", body=resp.text)
     OBJECT = JMESPathExtractor().extract(query="OBJECT", body=resp.text)
     logger.info(
         "用户:{0}-----错误密码:{1}-------登陆url:{2}-----接口返回状态:{3}-----登陆状态:{4}".
         format(BUYER, wrong_password, login_url, resp.status_code, status))
     self.assertListEqual(["账户或密码错误!您还有4次登录机会", None, "1"],
                          [status, OBJECT, login_num])
Пример #43
0
async def toggle_player_entry(Server, Member, rs_name, entry):
    """Toggles a player entry's value between True and False"""
    logger.info('------------------------------')
    logger.info(
        f"Initialized TOGGLE PLAYER ENTRY - Player: {rs_name} | Member: {Member.name} | ID: {Member.id} | Server: {Server.name} | ID: {Server.id}"
    )
    db = await h.db_open(h.DB_DISCORD_PATH)
    try:
        if not await h.player_in_server_member(db, Server, Member, rs_name):
            raise ex.DataHandlerError(
                f'**{Member.name}** does not use OSRS account: *{rs_name}*')
    except Exception as e:
        raise e
    new_toggle = not db[f'player:{rs_name}#server:{Server.id}#{entry}']
    db[f'player:{rs_name}#server:{Server.id}#{entry}'] = new_toggle
    await h.db_write(h.DB_DISCORD_PATH, db)
    logger.info(
        f"FINISHED TOGGLE PLAYER ENTRY - Player: {rs_name} | Member: {Member.name} | ID: {Member.id} | Server: {Server.name} | ID: {Server.id}"
    )
    return new_toggle
Пример #44
0
def check_datas(r, case_info):
    expect_data = case_info['expectresult']['data']
    actual_data = json.loads(r.text)['data']
    with allure.step("校验返回结果data"):
        allure.attach(name='预期值data', body=str(expect_data))
        allure.attach(name='实际值data', body=str(actual_data))
    try:
        print('>>> actual_data:{}'.format(actual_data))
        print('>>> expect_data:{}'.format(expect_data))
        logger.info('>>> actual_data:{}'.format(actual_data))
        logger.info('>>> expect_data:{}'.format(expect_data))
        if isinstance(actual_data, list) and actual_data:
            actual_data = actual_data[0]
        if isinstance(expect_data, list) and expect_data:
            expect_data = expect_data[0]
        _check_dict(actual_data, expect_data)
    except Exception as e1:
        print(traceback.format_exc())
        logger.info(traceback.format_exc())
        raise e1  # 增加raise e1是为了assert失败仍能继续执行下面的用例
Пример #45
0
 def test_update_user(self, login_fixture, id, new_password, new_telephone,
                      new_sex, new_address, except_result, except_code,
                      except_msg):
     logger.info("*************** 开始执行用例 ***************")
     user_info = login_fixture
     admin_user = user_info.get("login_info").get("username")
     token = user_info.get("login_info").get("token")
     step_login(admin_user, token)
     result = update_user(id, admin_user, new_password, new_telephone,
                          token, new_sex, new_address)
     step_1(id)
     assert result.success == except_result, result.error
     assert result.response.status_code == 200
     assert result.success == except_result, result.error
     logger.info("code ==>> 期望结果:{}, 实际结果:【 {} 】".format(
         except_code,
         result.response.json().get("code")))
     assert result.response.json().get("code") == except_code
     assert except_msg in result.msg
     logger.info("*************** 结束执行用例 ***************")
Пример #46
0
    def test_02(self):
        """
        空单持仓,平空与空单成交
        """
        logger.info("用例编号:60-2---空单持仓,平空与空单成交")
        range_num = 10
        price = 20*100000000
        buy_num = 10*100000000
        before_sell_account_dict = account_info(user=self.seller, session=self.sell_session, sda_id=sda_id)
        before_sell_account_balance = before_sell_account_dict["balance"]
        print(before_sell_account_balance)
        # 平空单
        # time.sleep(2)
        sell_resp = self.sell_session.post(url=base+sda_order_create_url, data=get_sda_order_create_param(
            sda_id=sda_id, order_type=平空, order_price_type=限价, order_price=price, order_num=buy_num
        ))
        sell_sync_id = JMESPathExtractor().extract(query="syncLockKey", body=sell_resp.text)
        logger.info("接口:{0}----返回信息:{1}".format(sda_order_create_url, sell_resp.json()))

        # 53用户下空单。
        # time.sleep(2)
        buy_53_resp = self.session_53.post(url=base+sda_order_create_url,data=get_sda_order_create_param(
            sda_id=sda_id, order_type=空单, order_price_type=限价, order_price=price, order_num=buy_num
        ))
        sync_53_id = JMESPathExtractor().extract(query="syncLockKey", body=buy_53_resp.text)
        logger.info("接口:{0}---返回信息:{1}".format(sda_order_create_url, buy_53_resp.json()))

        # time.sleep(3)

        after_53_info_dict = account_info_sync(sync_id=sync_53_id, user=self.user_53, session=self.session_53,
                                               sda_id=sda_id)
        after_53_account_balance = after_53_info_dict["balance"]

        after_info_dict = account_info_sync(sync_id=sell_sync_id, user=self.seller, session=self.sell_session,
                                            sda_id=sda_id)
        after_account_balance = after_info_dict["balance"]

        flag_balance = 9999997802034236
        flag_51 = assert_one(int(after_account_balance), int(flag_balance))
        flag_53 = assert_one(self.sda_balance - int(price * buy_num / 100000000), int(after_53_account_balance))
        self.assertListEqual([True, True], [flag_51, flag_53])
Пример #47
0
async def get_sotw_stats(Server):
    """Get all basic SOTW player stats for the server"""
    logger.info('------------------------------')
    logger.info(
        f'Initialized GET SOTW STATS - Server: {Server.name} | ID: {Server.id}'
    )
    db = await h.db_open(h.DB_DISCORD_PATH)
    all_server_stats = {}
    # Loop through all weeks in server
    for week in db[f'server:{Server.id}#sotw_history']:
        await week_stats_from_players(week['players'], all_server_stats)
    sort_players = []
    for k, v in all_server_stats.items():
        sort_players.append(v)
    sort_players = sorted(sort_players,
                          key=itemgetter('rank_weight'),
                          reverse=True)
    final_players = await build_final_stats_str(sort_players)
    logger.info(
        f"FINISHED GET SOTW STATS - Server: {Server.name} | ID: {Server.id}")
    return final_players
Пример #48
0
    def _start(self):
        cycle = get_realtime_setting('LOAD_EVERY_X_CYCLE', int)
        while self.is_active:
            wait_time_s = get_realtime_setting('WAIT_TIME_S', int)
            if cycle >= get_realtime_setting('LOAD_EVERY_X_CYCLE', int):
                logger.info("Updating")
                self.load()
                cycle = 0

            logger.info("Retreiving medias...")
            for user in self.users:
                posts = self.get_posts(user.id, wait_time_s, post_count=-1)
                if posts is None:
                    # Something went wrong
                    continue

                logger.info("Downloading posts for user %s", user.name)
                self.download_images(user.name, posts)
            cycle += 1

            self._wait_with_log("WAIT_TIME_S")
Пример #49
0
def bc_run(code, asset, freq, start_date_str, end_date_str
           ):  # Overwrite run() method, put what you want the thread do here
    future_result_list = []

    g.ENV = Global()
    if isinstance(end_date_str, str):
        end_date = datetime.datetime.strptime(
            end_date_str + " " + end_date_suffix_map[freq],
            "%Y-%m-%d %H:%M:%S")
    g.ENV.code = code
    g.ENV.asset = asset
    g.ENV.freq = freq
    g.ENV.start_date = datetime.datetime.strptime(start_date_str, "%Y-%m-%d")
    g.ENV.end_date = end_date

    g.ENV.date = g.ENV.start_date
    index.__get_kdata__()
    future_list = []
    while True:
        logger.info("step into :%s", g.ENV.date)

        f1 = executor.submit(buy_cond, g.ENV)
        f1.add_done_callback(done)
        future_list.append(f1)
        f2 = executor.submit(sell_cond, g.ENV)
        f2.add_done_callback(done)
        future_list.append(f2)

        try:
            g.ENV.date_increase()
        except StockError:
            logger.info("StockError: [%s]  !", str(g.ENV))
        except EOFError:
            logger.info("step to end: [%s] , it's over !", g.ENV.date)
            break
    for future in concurrent.futures.as_completed(future_list):
        res = future.result()
        if res[-1]:
            future_result_list.append([res[0], res[1], res[2], res[3]])
    return DataFrame(future_result_list)
Пример #50
0
 def test_06(self):
     """
     限价买单,买入数量传参:"",验证接口返回状态、MSG、STATUS、OBJECT
     """
     logger.info("用例编号:2-6---限价买单,买入数量传参:" ",验证接口返回状态、MSG、STATUS、OBJECT")
     time.sleep(3)
     resp = self.session.post(url=base + order_reservations_url,
                              data=get_order_reservations_param(
                                  transtion_id=transtion_id,
                                  order_type=限价,
                                  price=price,
                                  num=""))
     status = JMESPathExtractor().extract(query="STATUS", body=resp.text)
     msg = JMESPathExtractor().extract(query="MSG", body=resp.text)
     OBJECT = JMESPathExtractor().extract(query="OBJECT", body=resp.text)
     buyer_order_id = JMESPathExtractor().extract(
         query="OBJECT.buyerOrderId", body=resp.text)
     logger.info("用户:{0}------url:{1}-----接口状态{2}".format(
         BUYER, order_reservations_url, resp.status_code))
     logger.info("限价买单接口返回信息:{}".format(resp.json()))
     self.assertListEqual([200, "订单数量不能为空", "1"],
                          [resp.status_code, msg, status])
Пример #51
0
async def change_new_botw(now_time):
    """Change to new BOTW & build a message string with new BOTW"""
    global BOTW_CONFIG
    logger.info('------------------------------')
    logger.info(
        f"Initialized CHANGE NEW BOTW - Old BOTW: {BOTW_CONFIG['current_boss']}"
    )
    # Update recent bosses
    current_boss = BOTW_CONFIG['current_boss']
    boss_pool = await h.db_open(BOTW_POOL)
    new_boss_override = None
    # Check for a boss pick override
    BOTW_CONFIG_TEMP = await h.db_open(BOTW_CONFIG_PATH)
    if BOTW_CONFIG_TEMP['pick_override'] and BOTW_CONFIG_TEMP[
            'pick_override'] in boss_pool['all_bosses']:
        new_boss_override = BOTW_CONFIG_TEMP['pick_override']
        BOTW_CONFIG = BOTW_CONFIG_TEMP
    BOTW_CONFIG['pick_override'] = None
    del BOTW_CONFIG['recent_bosses'][0]
    BOTW_CONFIG['recent_bosses'].append(current_boss)
    # Set new boss to override if available
    if new_boss_override:
        BOTW_CONFIG['current_boss'] = new_boss_override
    # No override, pick random
    else:
        # Make sure new boss is not in recent bosses
        while current_boss in BOTW_CONFIG['recent_bosses']:
            current_boss = random.choice(boss_pool['all_bosses'])
        # Got new boss
        BOTW_CONFIG['current_boss'] = current_boss
    # Make new deadline a week later from now
    new_deadline = (now_time + datetime.timedelta(days=DAYS_BETWEEN_BOTW))
    BOTW_CONFIG['pick_next'] = new_deadline.strftime(BOTW_BASIC_FMT)
    await update_botw_config(BOTW_CONFIG)
    new_botw_message = f"The new Boss of the Week is **{BOTW_CONFIG['current_boss']}**! The deadline is on *{new_deadline.strftime('%A, %B %d')}*. Get bossing!"
    logger.info(
        f"FINISHED CHANGE NEW BOTW - New BOTW: {BOTW_CONFIG['current_boss']} | New deadline: {new_deadline.strftime(BOTW_BASIC_FMT)}"
    )
    return new_botw_message
Пример #52
0
async def change_new_sotw(now_time):
    """Change to new SOTW & build a message string with new SOTW"""
    global SOTW_CONFIG
    logger.info('------------------------------')
    logger.info(
        f"Initialized CHANGE NEW SOTW - Old SOTW: {SOTW_CONFIG['current_skill']}"
    )
    # Update recent skills
    current_skill = SOTW_CONFIG['current_skill']
    skill_pool = await h.db_open(SOTW_POOL)
    new_skill_override = None
    # Check for a skill pick override
    SOTW_CONFIG_TEMP = await h.db_open(SOTW_CONFIG_PATH)
    if SOTW_CONFIG_TEMP['pick_override'] and SOTW_CONFIG_TEMP[
            'pick_override'] in skill_pool['all_skills']:
        new_skill_override = SOTW_CONFIG_TEMP['pick_override']
        SOTW_CONFIG = SOTW_CONFIG_TEMP
    SOTW_CONFIG['pick_override'] = None
    del SOTW_CONFIG['recent_skills'][0]
    SOTW_CONFIG['recent_skills'].append(current_skill)
    # Set new skill to override if available
    if new_skill_override:
        SOTW_CONFIG['current_skill'] = new_skill_override
    # No override, pick random
    else:
        # Make sure new skill is not in recent skills
        while current_skill in SOTW_CONFIG['recent_skills']:
            current_skill = random.choice(skill_pool['all_skills'])
        # Got new skill
        SOTW_CONFIG['current_skill'] = current_skill
    # Make new deadline a week later from now
    new_deadline = (now_time + datetime.timedelta(days=DAYS_BETWEEN_SOTW))
    SOTW_CONFIG['pick_next'] = new_deadline.strftime(SOTW_BASIC_FMT)
    await update_sotw_config(SOTW_CONFIG)
    new_sotw_message = f"The new Skill of the Week is **{SOTW_CONFIG['current_skill']}**! The deadline is on *{new_deadline.strftime('%A, %B %d')}*. Get skilling!"
    logger.info(
        f"FINISHED CHANGE NEW SOTW - New SOTW: {SOTW_CONFIG['current_skill']} | New deadline: {new_deadline.strftime(SOTW_BASIC_FMT)}"
    )
    return new_sotw_message
Пример #53
0
 def test_user_repeat_register(self, testcase_data):
     username = testcase_data["username"]
     password = testcase_data["password"]
     telephone = testcase_data["telephone"]
     sex = testcase_data["sex"]
     address = testcase_data["address"]
     except_result = testcase_data["except_result"]
     except_code = testcase_data["except_code"]
     except_msg = testcase_data["except_msg"]
     logger.info("*************** 开始执行用例 ***************")
     result = register_user(username, password, telephone, sex, address)
     step_1(username, password, telephone, sex, address)
     assert result.success is True, result.error
     result = register_user(username, password, telephone, sex, address)
     step_2(username, password, telephone, sex, address)
     assert result.success == except_result, result.error
     logger.info("code ==>> 期望结果:{}, 实际结果:【 {} 】".format(
         except_code,
         result.response.json().get("code")))
     assert result.response.json().get("code") == except_code
     assert except_msg in result.msg
     logger.info("*************** 结束执行用例 ***************")
Пример #54
0
    def test_01(self):
        """
        多单持仓,限价部分平仓,部分成交,验证委托状态、用户余额、手续费。
        """
        logger.info("用例编号:54-1----多单持仓,限价部分平仓,部分成交,验证委托状态、用户余额、手续费。")
        range_num = 10
        price = 120*100000000
        buy_num = 50*100000000
        sell_num = 20*100000000

        # 53用户下多单。
        time.sleep(0.5)
        buy_53_resp = self.session_53.post(url=base+sda_order_create_url,data=get_sda_order_create_param(
            sda_id=sda_id, order_type=多单, order_price_type=限价, order_price=price, order_num=sell_num
        ))
        sync_53_id = JMESPathExtractor().extract(query="syncLockKey", body=buy_53_resp.text)
        logger.info("接口:{0}---返回信息:{1}".format(sda_order_create_url, buy_53_resp.json()))

        # 平多单
        time.sleep(0.5)
        buy_resp = self.session.post(url=base+sda_order_create_url, data=get_sda_order_create_param(
            sda_id=sda_id, order_type=平多, order_price_type=限价, order_price=price, order_num=buy_num
        ))
        buy_sync_id = JMESPathExtractor().extract(query="syncLockKey", body=buy_resp.text)
        logger.info("接口:{0}----返回信息:{1}".format(sda_order_create_url, buy_resp.json()))

        # time.sleep(3)

        after_53_info_dict = account_info_sync(sync_id=sync_53_id, user=self.user_53, session=self.session_53,
                                               sda_id=sda_id)
        after_53_account_balance = after_53_info_dict["balance"]

        after_info_dict = account_info_sync(sync_id=buy_sync_id, user=self.buyer, session=self.session, sda_id=sda_id)
        after_account_balance = after_info_dict["balance"]

        flag_51 = assert_one(int(after_account_balance), 9999243479193815)
        flag_53 = assert_one(self.sda_balance - int(price * sell_num / 100000000), int(after_53_account_balance))
        self.assertListEqual([True, True], [flag_51, flag_53])
Пример #55
0
def create_app():
    template_path = "../resources/templates"
    static_path = "../resources/static"

    flask_app = Flask(__name__,
                      template_folder=template_path,
                      static_folder=static_path)

    # Crate Views
    logger.info("Create Server Health Check")
    create_view(flask_app)
    Bootstrap(flask_app)
    flask_app.config['BOOTSTRAP_SERVE_LOCAL'] = True

    # Create Api
    rest_api = Api(flask_app, doc=False)
    rest_parser = rest_api.parser()
    logger.info("Create Api For Check")
    create_api(rest_api)

    logger.info("All Application Create Done")

    return flask_app
Пример #56
0
async def add_server(Server):
    """Add a server to the bot"""
    logger.info('------------------------------')
    logger.info(f'Initialized ADD SERVER: {Server.id}')
    db = await h.db_open(h.DB_DISCORD_PATH)
    # Check if bot has been removed before
    try:
        db['removed_servers'].remove(Server.id)
    except ValueError:
        db[f'server:{Server.id}#all_players'] = []
        db[f'server:{Server.id}#channel'] = None
        db[f'server:{Server.id}#role'] = None
        db[f'server:{Server.id}#sotw_opt'] = True
        db[f'server:{Server.id}#sotw_progress'] = True
        db[f'server:{Server.id}#sotw_history'] = []
        db[f'server:{Server.id}#botw_opt'] = True
        db[f'server:{Server.id}#botw_progress'] = True
        db[f'server:{Server.id}#botw_history'] = []
        logger.debug('New server...')
    db['active_servers'].append(Server.id)
    await h.db_write(h.DB_DISCORD_PATH, db)
    logger.info(f"ADDED NEW SERVER - Name: {Server.name} | ID: {Server.id}")
    return True
Пример #57
0
 def close(self):
     """Method to close mysql database connection"""
     if self._conn:
         try:
             self._conn.close()
             logger.info("Database connection closed")
         except ProgrammingError as err:
             logger.error(
                 "Error while closing the connection: {}".format(err))
         except AttributeError as err:
             logger.info(
                 "Trying to close the connection to mysql: {}".format(err))
         except Exception as err:
             logger.error(
                 "Can't close the connection to the database: {}".format(
                     err))
         finally:
             self._conn = None
             self._connected = False
     else:
         logger.info(
             "Trying to execute close method on connection which doesn't exist"
         )
Пример #58
0
 def test_01(self):
     """
     正常登陆,验证返回的状态和状态代码、userId
     """
     logger.info(
         "分割线----------------------------------------------------------------------------------------------------------------"
     )
     logger.info("用户编号:1-1-----正常登陆,验证返回的状态、状态代码、OBJECT")
     resp = self.session.post(url=base + login_url,
                              headers=headers,
                              data=get_login_param(user=BUYER,
                                                   user_password=password))
     status = JMESPathExtractor().extract(query="MSG", body=resp.text)
     login_number = JMESPathExtractor().extract(query="STATUS",
                                                body=resp.text)
     user_id = JMESPathExtractor().extract(query="OBJECT.userId",
                                           body=resp.text)
     logger.info(
         "用户:{0}------登陆url:{1}-------接口返回状态:{2}-------登陆状态{3}".format(
             BUYER, login_url, resp.status_code, status))
     self.assertListEqual(
         ["SUCCESS", "3a4b44f789844704a52ae30852195cc7", "0"],
         [status, user_id, login_number])
Пример #59
0
    def test_01(self):
        """
        多单持仓,平仓,53用户下多单与之成交。
        """
        logger.info("用例编号:60-1---多单持仓,限价平仓,53用户下限价多单与之成交,验证持仓数据")
        range_num = 10
        price = 20*100000000
        buy_num = 10*100000000

        # 平多单
        time.sleep(0.5)
        buy_resp = self.session.post(url=base+sda_order_create_url, data=get_sda_order_create_param(
            sda_id=sda_id, order_type=平多, order_price_type=限价, order_price=price, order_num=buy_num
        ))
        buy_sync_id = JMESPathExtractor().extract(query="syncLockKey", body=buy_resp.text)
        logger.info("接口:{0}----返回信息:{1}".format(sda_order_create_url, buy_resp.json()))

        # 53用户下多单。
        # time.sleep(1)
        buy_53_resp = self.session_53.post(url=base+sda_order_create_url,data=get_sda_order_create_param(
            sda_id=sda_id, order_type=多单, order_price_type=限价, order_price=price, order_num=buy_num
        ))
        sync_53_id = JMESPathExtractor().extract(query="syncLockKey", body=buy_53_resp.text)
        logger.info("接口:{0}---返回信息:{1}".format(sda_order_create_url, buy_53_resp.json()))

        # time.sleep(2)

        after_53_info_dict = account_info_sync(sync_id=sync_53_id, user=self.user_53, session=self.session_53,
                                               sda_id=sda_id)
        after_53_account_balance = after_53_info_dict["balance"]

        after_info_dict = account_info_sync(sync_id=buy_sync_id, user=self.buyer, session=self.session, sda_id=sda_id)
        after_account_balance = after_info_dict["balance"]

        flag_51 = assert_one(int(after_account_balance), 10000001845965764)
        flag_53 = assert_one(self.sda_balance - int(price * buy_num / 100000000), int(after_53_account_balance))
        self.assertListEqual([True, True], [flag_51, flag_53])
Пример #60
0
 def test_03(self):
     """
     错误token下买单测试,验证接口状态、OBJECT、STATUS
     """
     wrong_param = {
         "transtionId": transtion_id,
         "orderType": 0,
         "buyerOrderPrice": price,
         "buyerOrderNum": num,
         "timeStamp": "1538118050702",
         "languageType": 3,
         "token": "ebf9a4df698f3c4da49d5b8",
     }
     logger.info("用例编号:2-3------错误token下买单测试,验证接口状态、OBJECT、STATUS")
     time.sleep(3)
     resp = self.session.post(url=base + order_reservations_url,
                              data=wrong_param)
     status = JMESPathExtractor().extract(query="STATUS", body=resp.text)
     msg = JMESPathExtractor().extract(query="MSG", body=resp.text)
     logger.info("用户:{0}------url:{1}-----错误token{2}".format(
         BUYER, order_reservations_url, wrong_param))
     logger.info("限价买单返回信息:{}".format(resp.json()))
     self.assertListEqual([200, "令牌错误", "1"],
                          [resp.status_code, msg, status])