예제 #1
0
 def api_create_order(self):
     data = {"products":
                 [{"product_id": 8, "count": 1}, {"product_id": 10, "count": 2}]
             }
     result = self.session.post(url=self.__url_create_order, json=data, headers=HEADERS)
     log.info("创建订单接口,请求url为:{} 响应结果为:{}".format(self.__url_create_order, result.json()))
     return result
예제 #2
0
 def get(self):
     log.info("Lista los Eventos. En estado Publico o Privado.")        
     page = int(request.args.get('page', 1))
     if isLogged() :
         return self.paginationResult(Event.query.getEventsPaginationForUser(page, currentUser()))
     else:
         return self.paginationResult(Event.query.getPublicEventsPagination(page))
예제 #3
0
 def hasAccess(self, user):
     log.info(
         "Verificar acceso del Usuario: {'%s'} al Evento con: {'tag':'%s'}"
         % (user, self.tag))
     return self.visibility.isPublic() or (
         user is not None
         and self.owner == user) or user.username in self.gests
예제 #4
0
    def test04_login(self, keywords, password, expect_code):
        r = self.api.api_login(keywords, password)
        log.info("请求数据:{} 响应数据:{}".format((keywords, password, expect_code),
                                          r.json()))

        print("登陆结果:", r.json())
        if "error" in password:
            log.info("锁定60验证...")
            r = self.api.api_login(keywords, password)
            log.info("请求数据:{} 响应数据:{}".format(
                (keywords, password, expect_code), r.json()))
            print("登陆结果:", r.json())

            r = self.api.api_login(keywords, password)
            log.info("请求数据:{} 响应数据:{}".format(
                (keywords, password, expect_code), r.json()))
            print("登陆结果:", r.json())

            sleep(60)
            r = self.api.api_login("13600001111", "q123456")
            log.info("请求数据:{} 响应数据:{}".format(
                (keywords, password, expect_code), r.json()))
            print("登陆结果:", r.json())

        try:
            common_assert(self, r, response_code=expect_code)
        except Exception as e:
            log.error(e)
            raise
예제 #5
0
 def test03_trust_recharge(self, amount, img_code, expect_msg):
     # 调用 充值验证码
     self.trust.api_trust_verify_code()
     # 调用 充值接口
     result = self.trust.api_trust_recharge(amount, img_code)
     if expect_msg == "OK":
         # html提取
         r = html_parser(result)
         # 3、三方充值
         result = self.session.post(url=r[0], data=r[1])
         try:
             # 断言
             assert expect_msg in result.text
             log.info("断言充值成功,断言信息:{} 实际结果为:{}".format(
                 expect_msg, result.text))
         except Exception as e:
             log.error(e)
             raise
     else:
         try:
             # 断言
             common_assert(result, expect_msg=expect_msg)
             log.info("断言充值成功,断言信息:{} 实际结果为:{}".format(
                 expect_msg, result.text))
         except Exception as e:
             log.error(e)
             raise
예제 #6
0
 def setUp(self) -> None:
     # 获取session对象 a01
     self.session = requests.session()
     log.info("正在获取session对象:{}".format(self.session))
     # 获取ApiRegLogin对象
     self.api = ApiRegLogin(self.session)
     log.info("正在获取ApiRegLogin对象: {}".format(self.api))
예제 #7
0
 def api_sms_code(self, phone, imgVerifyCode, type="reg"):
     # 1. 定义请求数据
     data = {'phone': phone, 'imgVerifyCode': imgVerifyCode, 'type': type}
     log.info("正在调用注册获取「手机」验证码接口 请求url: {} 请求数据:{}".format(
         self.__url_sms_code, data))
     # 2. 调用post方法
     return self.session.post(self.__url_sms_code, data=data)
예제 #8
0
 def test04_login(self, keywords, pwd, expect_msg):
     # 1. 判断当前执行是否为错误次数验证
     # if pwd == "error":
     #     i = 0
     #     result = None
     #     while i <3:
     #         # 调用3次错误密码 让其锁定
     #         result = self.api_reg.api_post_login(keywords=keywords,
     #                                              password=pwd)
     #         i+=1
     #     # 断言锁定状态
     #     common_assert(result, expect_msg=expect_msg)
     #     # 锁定60秒
     #     sleep(60)
     #     # 锁定结束,正常登录
     #     result = self.api_reg.api_post_login(keywords="13600001111",
     #                                          password="******")
     #     common_assert(result, expect_msg="登录成功")
     # 2. 非错误次数验证,执行登录
     result = self.api_reg.api_post_login(keywords=keywords, password=pwd)
     try:
         common_assert(result, expect_msg=expect_msg)
         log.info("断言通过,断言信息:{}".format(expect_msg))
     except Exception as e:
         # 日志
         log.error(e)
         # 抛异常
         raise
예제 #9
0
 def test02_get_approve(self, status, expect_msg):
     if status == "已登录":
         # 调用登录
         ApiGet.get_apireglogin(self.session).api_post_login(
             "13600001111", "test123")
         # 调用查询方法
         result = self.approve.api_get_approve()
         print("查询结果为 :", result.json())
         try:
             # 断言
             assert expect_msg in result.json().get("phone")
             # 记录日志
             log.info("认证查询接口断言成功!,断言内容:{}".format(expect_msg))
         except Exception as e:
             # 日志
             log.error(e)
             # 抛异常
             raise
     elif status == "未登录":
         # 调用查询方法
         result = self.approve.api_get_approve()
         try:
             # 断言
             assert "立即登录" in result.text
             # 记录日志
             log.info("认证查询接口断言成功!,断言内容:{}".format(expect_msg))
         except Exception as e:
             # 日志
             log.error(e)
             # 抛异常
             raise
예제 #10
0
 def test01_reg_img(self, random, response_code):
     r = self.reg_login.api_register_img_code(random)
     log.info("正在调用 注册图片验证码接口测试方法,响应状态码结果:{}".format(r.status_code))
     print("状态码:", r.status_code)
     print("结果为:", r.text)
     # 调用 公共断言
     common_assert(self, r, response_code=response_code, status_code=None)
예제 #11
0
 def test03_register(self, phone4, password, imgVerifyCode, phone_code,
                     dy_server, invite_phone, expect_code, status,
                     description):
     # 1. 获取图片验证码
     self.api.api_img_code(random.random())
     # 2. 获取短信验证码
     self.api.api_sms_code(phone4, imgVerifyCode)
     # 3. 调用注册接口
     r = self.api.api_register(phone4,
                               password,
                               imgVerifyCode,
                               phone_code,
                               dy_server,
                               invite_phone=invite_phone)
     print(r.json())
     log.info("请求数据:{} 响应结果:{}".format(
         (phone4, password, imgVerifyCode, phone_code, dy_server,
          invite_phone, expect_code, status, description), r.json()))
     try:
         # 4. 断言注册信息
         common_assert(self,
                       r,
                       response_code=expect_code,
                       status=status,
                       description=description)
     except Exception as e:
         log.error(e)
         raise
예제 #12
0
    def on_post(self, req, resp):
        """process the utterance using POST method"""
        req_data = req.context['data']
        classifier = req.context['classifier']
        if not req_data:
            raise RaiseError.error_invalid_parameter(
                description=req.context['data'])
        try:
            if classifier:
                #model,confidence_score = classifier.predict(req_data.get('question'))
                filename = req_data.get('filename')
                filetype = req_data.get('filetype')
                etl_obj = DataSource(filename, filetype)
                sheet_names = etl_obj.getMetaData()['sheet_names']
                l_msg = "output returned by the Model: {}".format(sheet_names)
                log.info(l_msg)

                bdata = OrderedDict()
                bdata['sheet_names'] = sheet_names
            else:
                log.error("classifier is not configured...")
        except:
            ExUtil.print_stack_trace()
            RaiseError.error_not_found(
                description='No Utterance Mapping found')
        self.on_success(resp, bdata)
예제 #13
0
    def get_ex_message():
        # Get current system exception
        ex_type, ex_value, ex_traceback = sys.exc_info()

        log.info("Exception type : %s " % ex_type.__name__)
        log.info("Exception message : %s" % ex_value)
        return ex_type.__name__ + '::' + str(ex_value)
예제 #14
0
 def post(self):
     try:
         args = parser.parse_args()
         if (args['device'] is None) or (args['login'] is None) or (
                 args['password'] is None):
             return {'success': False, 'errno': ERRNO_FIELDS_ABSENT}, 400
         pass_md5 = hashlib.md5(
             args['password'].encode('utf-8')).hexdigest()
         user = User.query.filter(User.login == args['login'],
                                  User.password == pass_md5).one_or_none()
         if user is None:
             log.info("Invalid login/password")
             return {'success': False, 'errno': ERRNO_INVALID_PASSWORD}, 403
         new_token = Token(token=str(uuid.uuid4()),
                           user_id=user.id,
                           device=args['device'])
         if args['expires'] is not None:
             new_token.expires_at = datetime.fromtimestamp(args['expires'] /
                                                           1000.0)
         db.session.add(new_token)
         db.session.commit()
         log.info("Created new token: %s" % new_token.token)
         return {'token': new_token.token}
     except Exception as e:
         db.session.rollback()
         log.exception(e)
         return {'success': False, 'errno': ERRNO_INTERNAL_UNKNOWN}, 500
예제 #15
0
 def api_img_code(self, random):
     """
     :param random: 随机数
     :return: 响应对象
     """
     log.info("正在调用注册获取图片验证码接口 请求url: {}".format(
         self.__url_img_code.format(random)))
     return self.session.get(self.__url_img_code.format(random))
예제 #16
0
 def test02_tender_list(self, expect_id):
     # 调用 我的投资列表接口
     r = self.tender.api_tender_list()
     print("投资列表结果为:{}".format(r.json()))
     log.info("投资列表结果为:{}".format(r.json()))
     print("我的投资列表产品ID为:", r.json().get("items")[0].get("loan_id"))
     # 断言
     self.assertEqual(expect_id, r.json().get("items")[0].get("loan_id"))
예제 #17
0
 def test07_img_code_random_null(self):
     num = ""
     r = self.api.api_img_code(num)
     log.info("随机数为空获取验证码的响应状态码为:{}".format(r.status_code))
     try:
         common_assert(self, r, response_code=404, status=None)
     except Exception as e:
         log.error(e)
예제 #18
0
    def api_phone_code(self, phone, imgVerifyCode):
        # 1. 定义参数
        data = {"phone": phone, "imgVerifyCode": imgVerifyCode, "type": "reg"}
        log.info("正在调用注册手机验证码接口 url:{} 请求参数数据:{}".format(
            self.__url_phone, data))

        # 2. 调用post方法 参数为data时,默认请求头为 form-data
        return self.session.post(url=self.__url_phone, data=data)
예제 #19
0
 def test08_img_code_random_str(self):
     num = random.sample("qwerttyuiopasdfghjklzxcvbnm", 8)
     r = self.api.api_img_code("".join(num))
     log.info("随机数为空获取验证码的响应状态码为:{}".format(r.status_code))
     try:
         common_assert(self, r, response_code=400, status=None)
     except Exception as e:
         log.error(e)
예제 #20
0
 def __init__(self, *args, **kwargs):
     super(Application, self).__init__(*args, **kwargs)
     log.info("API Server Coming Up...")
     """ resource mapping """
     self.add_route("/", base.BaseResource())
     self.add_route("/v1/utterance", utterance.UtteranceResource())
     self.add_route("/x-tree/F5Monitor.html",
                    healthcheck.HealthCheckResource())
예제 #21
0
 def api_verify_token(self):
     # 定义data
     data = {"token": HEADERS.get("token")}
     # 调用post请求
     result = self.session.post(self.__url_token_verify, json=data)
     log.info("验证token接口,请求url为:{} 响应结果为:{}".format(self.__url_token_verify,
                                                    result.json()))
     return result
예제 #22
0
 def test06_img_code_random_int(self):
     num = random.randint(10000000, 999999999)
     r = self.api.api_img_code(num)
     print("响应状态吗为:", r.status_code)
     log.info("随机整数获取验证码的响应状态码为:".format(r.status_code))
     try:
         common_assert(self, r, status=None)
     except Exception as e:
         log.error(e)
예제 #23
0
 def test05_is_login(self, is_login, response_code, status_code, expect_msg):
     if is_login == "已登录":
         # 1.调用登录
         self.reg_login.api_login(keywords="13600001111", password="******")
         # 调用查询登录接口
     r = self.reg_login.api_is_login()
     print("登录状态为:", r.json())
     log.info("正在调用 是否登录接口 测试方法,响应状态码结果:{}".format(r.json()))
     common_assert(self, r, response_code, status_code, expect_msg)
예제 #24
0
    def delete(self):
        args = removeEventParser.parse_args()
        event = Event.query.get_by_tag(args.tag)

        Assistance.query.removeFromEventTag(event.tag)

        event.remove()
        log.info("Elimina un Evento con: {'tag':'%s'}" % event.tag)
        return {}, 201
예제 #25
0
 def api_post_login(self, keywords, password):
     # 1、定义请求参数
     data = {
         "keywords": keywords,
         "password": password
     }
     log.info("正在登录接口,请求url:{}, 请求数据:{}".format(self.__url_login, data))
     # 2、调用post
     return self.session.post(url=self.__url_login, data=data)
예제 #26
0
 def test03_my_loan_list(self):
     r = self.api.api_my_loan_list()
     print("我的投资列表结果为:", r.json())
     log.info("我的投资列表结果为:{}".format(r.json()))
     try:
         self.assertEqual("642", r.json().get("items")[0].get("loan_id"))
     except Exception as e:
         log.error(e)
         raise
예제 #27
0
 def test18_login_username_not_exists(self):
     r = self.api.api_login(phone7, password)
     print("登陆结果:", r.json())
     log.info("登录·用户不存在结果:{}".format(r.json()))
     try:
         common_assert(self, r, status=100, description="用户不存在")
     except Exception as e:
         log.error(e)
         raise
예제 #28
0
 def api_get_sms_code(self, phone, imgVerifyCode):
     # 1、定义参数
     data = {
         "phone": phone,
         "imgVerifyCode": imgVerifyCode,
         "type": "reg"
     }
     log.info("正在调用获取短信验证码接口,请求url:{}, 请求数据:{}".format(self.__url_sms, data))
     # 2、请求
     return self.session.post(self.__url_sms, data=data)
예제 #29
0
 def test01_approve(self, realname, card_id, response_code, status_code,
                    expect_msg):
     # 调用登录
     self.common.get_api_reg_login().api_login("13600001111", "test12345")
     # 调用 认证接口
     r = self.approve.api_approve(realname, card_id)
     log.info("认证结果为:{}".format(r.json()))
     print("认证结果为:", r.json())
     # 断言
     common_assert(self, r, response_code, status_code, expect_msg)
예제 #30
0
async def fetch(casevault, url, body, session, user):
    log.info(str(body))
    tmp = {
        'parameters': body,
        'user': user
    }

    with aiohttp.Timeout(10):
        async with session.post(url, data = json.dumps(tmp), headers = {'content-type': 'application/json'}, timeout=15) as response:
            return await get_response(casevault, response)
예제 #31
0
    def lackRequirements(self):
        log.info("Suma todos los requisitos que los usuarios se comprometieron a llevar al evento.")
        lack = [] 
        requirements = Assistance.query.get_requirements_by_event_tag(self.tag)
        keyfunc = lambda r: r.name

        for req in requirements : req.quantity = -req.quantity
        requirements += self.requirement
        requirements.sort(key=keyfunc)

        for name, reqs in groupby(requirements,key=keyfunc):
            lack.append(Requirement(name=name, quantity= sum(req.quantity for req in reqs)))
        return lack
예제 #32
0
 def put(self):
     args = event_parser.parse_args()
     event = Event.query.get_by_tag(args.tag)
     event.name = args.name
     event.description = args.description
     event.venue = Venue.query.get_by_name(args.venue["name"])
     event.time = args.time
     event.date = args.date
     event.image = args.image
     event.gests = map(lambda gest: gest["username"], args.gests)
     event.requirement = map(lambda req: Requirement(name=req["name"],quantity=req["quantity"]), args.requirement)
     event.capacity = args.capacity
     event.visibility = Visibility.query.get(args.visibility)
     event.save()
     log.info("Edita un Evento con: {'tag':'%s'}" % event.tag)
     return event, 201
    def post(self):
        args = assistance_parser.parse_args()
        event = Event.query.get_by_tag(args.event)
        if not event.hasAvailability():
            api.abort(400, "The event haven't availability")

        newAssistance = Assistance(
            eventTag = args.event,
            event = event.getAppearanceAssistance(),
            user = currentUser().username,
            requirements = map(lambda req: Requirement(name=req["name"],quantity=req["quantity"]), args.requirements)
        )
        newAssistance.save()
        mailService.assistance(newAssistance, currentUser())
        log.info("Crea una Asistencia con: {'evento':'%s'}" % newAssistance.event)
        return newAssistance, 201    
예제 #34
0
 def get(self, tag):
     log.info("Otorga el Evento con: {'tag':'%s'}" % tag)
     event = Event.query.get_by_tag(tag)
     event.hasAssistance = False
     event.isOwner= False
     user = currentUser()
     event.soldOut = not event.hasAvailability()
     if event.hasAccess(user) :
         if isLogged():
             assistance = Assistance.query.get_by_eventTag_and_user(event.tag, user)
             event.hasAssistance = assistance is not None
             event.requirementMissing = event.lackRequirements()
             event.isOwner = event.owner.username == user.username
         return event
     else:
         log.warning("Se requiere Autorizacion para este recurso.")
         api.abort(401, "Authorization Required")
예제 #35
0
 def post(self):
     args = event_parser.parse_args()
     newEvent = Event(
         tag = args.tag,
         name = args.name,
         description = args.description,
         venue = Venue.query.get_by_name(args.venue["name"]),
         time = args.time,
         date = args.date,
         image = args.image,
         gests = map(lambda gest: gest["username"], args.gests),
         requirement = map(lambda req: Requirement(name=req["name"],quantity=req["quantity"]), args.requirement),
         capacity = args.capacity,
         visibility = Visibility.query.get(args.visibility),
         owner = currentUser()
     )
     newEvent.save()
     log.info("Crea un Evento con: {'tag':'%s'}" % newEvent.tag)
     return newEvent, 201
예제 #36
0
 def get_by_name(self, username):
     log.info("Busca un Usuario por nombre")
     return self.filter(self.type.username == username).first_or_404()
예제 #37
0
 def delete(self, tag):
     log.info("Elimina un Evento con: {'tag':'%s'}" % tag)
     eventToDelete = Event.query.get_by_tag(tag)
     eventToDelete.remove()
     return '', 204
예제 #38
0
 def get(self, name):
     log.info("Busca la Visibilidad: %s de un Evento." % name)
     return self.filter(self.type.name == name).first_or_404()
예제 #39
0
 def get_by_tag(self, tag):
     log.info("Busca un Evento con: {'tag':%s}" % tag)
     return self.filter(self.type.tag == tag).first_or_404()
예제 #40
0
 def hasAccess(self, user):
     log.info("Verificar acceso del Usuario: {'%s'} al Evento con: {'tag':'%s'}" % (user, self.tag))
     return self.visibility.isPublic() or (user is not None and self.owner == user) or user.username in self.gests
예제 #41
0
 def availability(self):
     log.info("Calcular la disponibilidad del Evento con: {'tag':'%s'}" % self.tag)
     return self.capacity - Assistance.query.get_amount_by_event(self.tag)