Ejemplo n.º 1
0
    def test_get_interests(self):
        cid = 1
        interests = ['interest']
        key = 'i:%s' % cid

        # start redis server
        redis_server = subprocess.Popen(shlex.split('redis-server --port %s' %
                                                    REDIS_PORT),
                                        shell=False,
                                        stdout=subprocess.PIPE,
                                        stderr=sys.stderr)
        redis_client = redis.Redis(host='localhost',
                                   port=REDIS_PORT,
                                   socket_connect_timeout=0.5,
                                   socket_timeout=0.5)

        st = store.Store(port=REDIS_PORT)

        redis_client.set(key, json.dumps(interests))
        self.assertEqual(get_interests(st, cid), interests)

        redis_client.delete(key)

        redis_server.terminate()
        redis_server.wait()

        self.assertEqual(get_interests(st, cid), [])
Ejemplo n.º 2
0
    def test_get_interests(self):
        cid = 1
        interests = ['interest']
        key = 'i:%s' % cid

        self.redis.set(key, json.dumps(interests))
        self.assertEqual(get_interests(self.store, cid), interests)

        self.redis.delete(key)
        self.assertEqual(get_interests(self.store, cid), [])
Ejemplo n.º 3
0
    def test_get_interests(self):
        cid = 1
        interests = ['interest']

        interest_dict = {
            'i:%s' % cid: json.dumps(interests),
        }
        store = Store(interests=interest_dict)

        self.assertEqual(get_interests(store, cid), interests)
        self.assertEqual(get_interests(store, cid + 1), [])
Ejemplo n.º 4
0
    def test_exception_get_interest(self, error, cid):
        """scoring.get_interests падает при недоступности хранилища"""

        st = self.get_store()
        st.redis.execute_command = mock.PropertyMock(
            side_effect=error)  # mock execute_command to raise exception

        try:
            scoring.get_interests(st, cid)
            pytest.fail("Exception expected")
        except error as e:
            assert True
Ejemplo n.º 5
0
def get_interest_answer(store, context, is_adminm, handler):
    context["nclients"] = len(handler.client_ids)
    result = {}
    for cid in handler.client_ids:
        result[str(cid)] = scoring.get_interests(store=store, cid=cid)

    return result
Ejemplo n.º 6
0
 def get_scoring(self, ctx, store):
     response = {
         str(cid): scoring.get_interests(store, cid)
         for cid in self.scoring_request.client_ids
     }
     ctx['nclients'] = len(self.scoring_request.client_ids)
     return response, OK
Ejemplo n.º 7
0
def clients_interests_handler(request, context, storage):
    # type: (MethodRequest, dict, InMemoryStorage) -> (str, int)
    """Handle request for clients interests."""
    response, code = {}, OK
    try:
        nested_request = ClientsInterestsRequest(**request.arguments)
    except TypeError:
        msg = 'Extra arguments in request: '
        logging.exception('%s :' % msg)
        response, code = msg, INVALID_REQUEST
        return response, code
    except ValueError as e:
        logging.exception('Validation error: ')
        response, code = str(e), BAD_REQUEST
        return response, code
    try:
        for client_id in nested_request.client_ids:
            response[client_id] = get_interests(storage, client_id)
    except (RuntimeError, KeyError):
        msg = 'Can not read from storage'
        logging.exception('%s: ' % msg)
        response, code = msg, INTERNAL_ERROR
        return response, code
    context['nclients'] = len(nested_request.client_ids)
    return response, code
Ejemplo n.º 8
0
def clients_interests(req, ctx, store):
    method_inst = ClientsInterestsRequest()
    is_valid = is_args_validated(req, method_inst)
    if is_valid is not True:
        return is_valid
    ctx['nclients'] = method_inst.get_context(req.arguments)
    return {str(item): scoring.get_interests(store, item) for item in method_inst.client_ids}, OK
Ejemplo n.º 9
0
def method_handler(request, ctx, store):
    response, code = {}, None
    request_body = request['body']
    logging.info('request body is: {}'.format(request_body))
    try:
        main_request = MethodRequest(request_body)
        if not check_auth(main_request):
            code = 403
            return response, code
        if main_request.method == 'online_score':
            method_request = OnlineScoreRequest(main_request.arguments)
            ctx['has'] = [i for i in method_request.get_fields().keys()]
            if main_request.is_admin:
                response = {"score": 42}
            else:
                response = {
                    "score": get_score(None, **method_request.get_fields())
                }
        elif main_request.method == 'clients_interests':
            method_request = ClientsInterestsRequest(main_request.arguments)
            ctx['nclients'] = len(method_request.client_ids)
            for id in method_request.client_ids:
                response[id] = get_interests(None, id)
        code = 200
        return response, code
    except AttributeError as e:
        response = e.args[0]
        code = 422

    return response, code
Ejemplo n.º 10
0
def process_clients_interests_request(request, ctx, store):
    res = {}
    for id in request.client_ids:
        res[id] = get_interests(store, id)

    ctx["nclients"] = len(request.client_ids)
    return res, OK
Ejemplo n.º 11
0
 def response(self, ctx, store, is_admin=False):
     interests = {}
     for cid in self.client_ids:
         interests.update(
             {cid: get_interests(store=store, cid=self.client_ids)})
     ctx.update({'nclients': len(self.client_ids)})
     return interests
Ejemplo n.º 12
0
Archivo: api.py Proyecto: isz/homeworks
def get_interests_response(request, ctx, store, is_admin=False):
    resp = {}
    for cid in request.client_ids:
        resp[cid] = get_interests(store, cid)

    ctx['nclients'] = len(request.client_ids)
    return resp
Ejemplo n.º 13
0
    def process(self, ctx=None, store=None):
        result = {}
        for cid in self.client_ids:
            result[cid] = scoring.get_interests(store, cid)

        ctx.update({'nclients': len(self.client_ids)})
        return result
Ejemplo n.º 14
0
def client_ids_request_handler(request, ctx, store):
    ctx['nclients'] = 0 if request.client_ids is None else len(
        request.client_ids)
    return {
        str(cid): scoring.get_interests(store, cid)
        for cid in request.client_ids
    }, OK
Ejemplo n.º 15
0
 def result(self):
     interests = {
         client_id: get_interests(self.store, client_id)
         for client_id in self.client_ids
     }
     self.ctx.update(nclients=len(self.client_ids))
     return interests, self.code
Ejemplo n.º 16
0
def method_handler(request, ctx, store):
    response, code = None, None
    request = request['body']
    request_user = MethodRequest(**vars(request))
    if request.method == 'online_score' and not request_user.is_admin:
        data = request.arguments
        try:
            obj = OnlineScoreRequest(**data)
            response = get_score(store, obj.phone, obj.email, obj.birthday,
                                 obj.gender, obj.first_name, obj.last_name)
            code = OK
        except Exception as ex:
            response = str(ex)
            code = BAD_REQUEST
    elif request.method == 'online_score' and request_user.is_admin:
        response = {"score": 42}
        code = OK
    elif request.method == 'clients_interests':
        try:
            clients = ClientsInterestsRequest(**request.arguments)
        except ValidationError as ex:
            response = str(ex)
            code = BAD_REQUEST
        else:
            response = {}
            for client in clients.client_ids:
                client_response = get_interests(store, client)
                response.update([(str(client), client_response)])
            code = OK
    return response, code
Ejemplo n.º 17
0
    def test_ok_get(self, key, values):
        st = self.get_store()

        st.redis.delete(key)
        st.redis.rpush("i:{0}".format(key), *values)

        assert scoring.get_interests(st, key) == values
Ejemplo n.º 18
0
    def test_ok_reconnect(self, error, cid):
        """Проверяем, что при соответствующей настройке таймаутов попытки реконнекта продолжаются какое-то время"""

        attempts = 2
        delay = 0.6

        st = self.get_store(reconnect_attempts=attempts, reconnect_delay=delay)
        st.redis.execute_command = mock.PropertyMock(
            side_effect=error)  # mock execute_command to raise exception

        start = datetime.datetime.now()
        try:
            scoring.get_interests(st, cid)
            pytest.fail("Exception expected")
        except error:
            end = datetime.datetime.now()
            assert (end - start).total_seconds() >= attempts * delay
Ejemplo n.º 19
0
 def get_request_result(self, user_is_admin: bool, ctx: dict, store):
     self.client_ids: list
     ctx["nclients"] = len(self.client_ids)
     result = {}
     for id_ in self.client_ids:
         # В задании указано, что ключ должен в str
         result[str(id_)] = get_interests(store, id_)
     return result, OK
Ejemplo n.º 20
0
    def test_get_interests_success_return(self, return_mock, return_value):
        store = self.get_store(return_mock)
        key = 'test'

        r = scoring.get_interests(store, key)

        assert r == return_value
        store.get.assert_called_with(f"i:{key}")
Ejemplo n.º 21
0
def clients_interests_handler(req, ctx, store):
    clients_interests = ClientsInterestsRequest()
    clients_interests.validate(req.arguments)
    ctx['nclients'] = len(clients_interests.client_ids)
    interests = {_id: get_interests(store, _id) for _id in
                 clients_interests.client_ids}
    logging.info(f'Client interest: {interests}')
    return interests, OK
Ejemplo n.º 22
0
 def test_invalid_get_interests(self, arguments):
     client_ids, date = arguments.get('client_ids'), arguments.get('date')
     result_store = {
         cid: scoring.get_interests(self.fake_store, cid)
         for cid in client_ids
     }
     result_fake_r = {cid: [] for cid in client_ids}
     self.assertEqual(result_fake_r, result_store)
Ejemplo n.º 23
0
 def process_request(self, request, context, store):
     r = ClientsInterestsRequest(request.data['arguments'])
     r.validate()
     if not r.is_valid:
         return r.errors, INVALID_REQUEST
     context["nclients"] = len(r.client_ids.value)
     response_body = {cid: get_interests(store, cid) for cid in r.client_ids.value}
     return response_body, OK
Ejemplo n.º 24
0
 def process(self):
     """Function returns clients interests and http code OK"""
     clients_interests = {}
     for id_value in self.storage["client_ids"]:
         clients_interests.update({
             id_value: get_interests(self.store, id_value)
         })
     return clients_interests, OK
Ejemplo n.º 25
0
def clients_interests_handler(request: MethodRequest, ctx, store):
    api_request = ClientsInterestsRequest(**request.arguments)
    logging.debug(f'HAS: {api_request.has}')
    ctx['has'] = api_request.has
    return OK, {
        cid: get_interests(store, cid)
        for cid in api_request.client_ids
    }
Ejemplo n.º 26
0
Archivo: test.py Proyecto: ildarkit/hw3
 def test_on_connected_store_set_get_interests(self, user_interest):
     key = 'i:{}'.format(user_interest['user_id'])
     self.store.redis.delete(key)
     self.store.redis.rpush(key, user_interest['interest1'])
     self.store.redis.rpush(key, user_interest['interest2'])
     self.assertEqual(
         scoring.get_interests(self.store, user_interest['user_id']),
         [user_interest['interest1'], user_interest['interest2']])
Ejemplo n.º 27
0
def clients_interests_handler(ctx, metreq, store):
    client_int_r = ClientsInterestsRequest(**metreq.arguments)
    if client_int_r.errors:
        return client_int_r.errors, INVALID_REQUEST
    ctx["nclients"] = len(client_int_r.client_ids)
    result_cid_interests = {}
    for cid in client_int_r.client_ids:
        result_cid_interests[cid] = scoring.get_interests(store, cid)
    return result_cid_interests, OK
Ejemplo n.º 28
0
def process_ClientsInterestsRequest(request, ctx, store):
    r = ClientsInterestsRequest(**request.arguments)
    if not r.check_request():
        return r.error_text, INVALID_REQUEST

    ctx["nclients"] = len(r.client_ids)
    response_body = {cid: get_interests(store, cid) for cid in r.client_ids}

    return response_body, OK
Ejemplo n.º 29
0
    def get_response(self, store, context, is_admin):

        result = {}
        for cid in self.client_ids:
            result[str(cid)] = get_interests(store, cid)

        context["nclients"] = len(self.client_ids)

        return result
Ejemplo n.º 30
0
def clients_interests(req, context, storage):
    response, code = {}, OK
    method = ClientsInterestsRequest(**req.arguments)
    if not method.is_valid():
        return method.error_message, INVALID_REQUEST
    context['nclients'] = len(method.client_ids)
    for i in method.client_ids:
        response[i] = scoring.get_interests(storage, None)
    return response, code
Ejemplo n.º 31
0
 def get_result(self, is_admin, store):
     results = {}
     if not self.client_ids == None:
         for client in self.client_ids.value:
             try:
                 store.set_mode('persistent')
                 results[client] = get_interests(store.storage, client)
             except Exception as error:
                 print ("clilent int except")
                 return {"message": self.err_msg(INTERNAL_ERROR, (), error.message)}, INTERNAL_ERROR
     return results, OK
Ejemplo n.º 32
0
 def get_result(self, is_admin, store):
     results = {}
     if not self.client_ids == None:
         for client in self.client_ids.value:
             results[client] = get_interests(store, client)
     return results, OK