Пример #1
0
def test_bad_key_raises():
    """validate failed key logic"""
    if not DO_API_TESTS:
        pytest.xfail('Unable to test without test keys')

    bad_key = shortuuid.uuid()

    with pytest.raises(exceptions.APIKeyInvalid):
        authorized = api_utils.check_key(bad_key, throw_on_fail=True)

    try:
        authorized = api_utils.check_key(bad_key, throw_on_fail=True)
    except Exception as err_msg:
        assert err_msg.status == 401
        assert isinstance(err_msg.message, str)
Пример #2
0
def test_good_key():
    """validating check_key logic"""
    tdb = TinyDB(CACHE_PATH)
    vals = tdb.all()

    if not vals:
        global DO_API_TESTS
        DO_API_TESTS = False
        pytest.xfail('Unable to test without test keys')

    test_key = vals[0]['api_key']
    tdb.close()
    assert api_utils.check_key(test_key)

    tdb = TinyDB(CACHE_PATH)
    new_vals = tdb.search(Query().api_key == test_key)

    #TODO: fails on virgin key
    old_time = datetime.strptime(vals[0]['last_accessed'],
                                 '%Y-%m-%dT%H:%M:%S.%f').timestamp()

    new_time = datetime.strptime(new_vals[0]['last_accessed'],
                                 '%Y-%m-%dT%H:%M:%S.%f').timestamp()

    assert new_time > old_time
Пример #3
0
def test_good_key():
    """validating check_key logic"""
    connection = TinyMongoClient(CACHE_PATH)
    api_db = connection.prosperAPI.users
    vals = api_db.find()

    if not vals:
        global DO_API_TESTS
        DO_API_TESTS = False
        pytest.xfail('Unable to test without test keys')

    test_key = vals['api_key']
    assert api_utils.check_key(test_key)

    new_vals = api_db.find_one({'api_key': test_key})

    # TODO: fails on virgin key
    old_time = datetime.strptime(vals['last_accessed'],
                                 '%Y-%m-%dT%H:%M:%S.%f').timestamp()

    new_time = datetime.strptime(new_vals['last_accessed'],
                                 '%Y-%m-%dT%H:%M:%S.%f').timestamp()

    assert new_time > old_time
    connection.close()
Пример #4
0
def test_good_key():
    """validating check_key logic"""
    connection = TinyMongoClient(CACHE_PATH)
    api_db = connection.prosperAPI.users
    vals = api_db.find()

    if not vals:
        global DO_API_TESTS
        DO_API_TESTS = False
        pytest.xfail('Unable to test without test keys')

    test_key = vals['api_key']
    assert api_utils.check_key(test_key)

    new_vals = api_db.find_one({'api_key': test_key})

    # TODO: fails on virgin key
    old_time = datetime.strptime(
        vals['last_accessed'],
        '%Y-%m-%dT%H:%M:%S.%f').timestamp()

    new_time = datetime.strptime(
        new_vals['last_accessed'],
        '%Y-%m-%dT%H:%M:%S.%f').timestamp()

    assert new_time > old_time
    connection.close()
Пример #5
0
def test_bad_key():
    """validate failed key logic"""
    if not DO_API_TESTS:
        pytest.xfail('Unable to test without test keys')

    bad_key = shortuuid.uuid()

    assert api_utils.check_key(bad_key) is False
Пример #6
0
def test_bad_key():
    """validate failed key logic"""
    if not DO_API_TESTS:
        pytest.xfail('Unable to test without test keys')

    bad_key = shortuuid.uuid()

    assert api_utils.check_key(bad_key) is False
Пример #7
0
def test_bad_key_raises():
    """validate failed key logic"""
    if not DO_API_TESTS:
        pytest.xfail('Unable to test without test keys')

    bad_key = shortuuid.uuid()

    with pytest.raises(exceptions.APIKeyInvalid):
        authorized = api_utils.check_key(
            bad_key,
            throw_on_fail=True
        )

    try:
        authorized = api_utils.check_key(
            bad_key,
            throw_on_fail=True
        )
    except Exception as err_msg:
        assert err_msg.status == 401
        assert isinstance(err_msg.message, str)
Пример #8
0
    def get(self, return_type):
        args = self.reqparse.parse_args()
        LOGGER.info('Prophet {0} Request: {1}'.format(return_type, args))

        if return_type not in return_supported_types():
            return 'INVALID RETURN FORMAT', 405

        mode = api_config.SwitchCCPSource(
            api_config.CONFIG.get('GLOBAL', 'crest_or_esi'))
        forecast_range = api_config.DEFAULT_RANGE
        if 'range' in args:
            forecast_range = args.get('range')
        ## Validate inputs ##
        try:
            api_utils.check_key(args.get('api'),
                                throw_on_fail=True,
                                logger=LOGGER)
            crest_utils.validate_id('map_regions',
                                    args.get('regionID'),
                                    config=api_config.CONFIG,
                                    mode=mode,
                                    logger=LOGGER)
            crest_utils.validate_id('inventory_types',
                                    args.get('typeID'),
                                    config=api_config.CONFIG,
                                    mode=mode,
                                    logger=LOGGER)
            forecast_range = forecast_utils.check_requested_range(
                forecast_range,
                max_range=api_config.MAX_RANGE,
                raise_for_status=True)
        except exceptions.ValidatorException as err:
            LOGGER.warning('ERROR: unable to validate type/region ids' +
                           '\n\targs={0}'.format(args),
                           exc_info=True)
            return err.message, err.status
        except Exception:  #pragma: no cover
            LOGGER.error('ERROR: unable to validate type/region ids' +
                         'args={0}'.format(args),
                         exc_info=True)
            return 'UNHANDLED EXCEPTION', 500

        ## check cache ##
        cache_data = forecast_utils.check_prediction_cache(
            args.get('regionID'), args.get('typeID'))
        LOGGER.debug(cache_data)
        if cache_data is not None:
            LOGGER.info('returning cached forecast')
            message = forecast_reporter(cache_data, forecast_range,
                                        return_type, LOGGER)

            return message

        ## No cache, get data ##
        try:
            if args.get('typeID') in api_config.SPLIT_INFO:
                LOGGER.info('FORK: using split utility')
                data = split_utils.fetch_split_history(
                    args.get('regionID'),
                    args.get('typeID'),
                    mode,
                    data_range=api_config.MAX_RANGE,
                    config=api_config.CONFIG,
                    logger=LOGGER)
                data.sort_values(by='date', ascending=True, inplace=True)
            else:
                data = forecast_utils.fetch_extended_history(
                    args.get('regionID'),
                    args.get('typeID'),
                    mode=mode,
                    data_range=api_config.MAX_RANGE,
                    config=api_config.CONFIG,
                    logger=LOGGER)
            data = forecast_utils.build_forecast(data, api_config.MAX_RANGE)
        except exceptions.ValidatorException as err:
            #FIX ME: testing?
            LOGGER.warning('ERROR: unable to generate forecast' +
                           '\n\targs={0}'.format(args),
                           exc_info=True)
            return err.message, err.status
        except Exception:  #pragma: no cover
            LOGGER.error('ERROR: unable to generate forecast' +
                         '\n\targs={0}'.format(args),
                         exc_info=True)
            return 'UNHANDLED EXCEPTION', 500

        ## Update cache ##
        forecast_utils.write_prediction_cache(args.get('regionID'),
                                              args.get('typeID'),
                                              data,
                                              logger=LOGGER)
        try:
            message = forecast_reporter(data, forecast_range, return_type,
                                        LOGGER)
        except Exception as err_msg:  #pragma: no cover
            LOGGER.error('invalid format requested' +
                         '\n\targs={0}'.format(args) +
                         '\n\treturn_type={0}'.format(return_type),
                         exc_info=True)
            return 'UNABLE TO GENERATE REPORT', 500
        return message
Пример #9
0
    def get(self, return_type):
        args = self.reqparse.parse_args()
        self.logger.info('Prophet %s Request: %s', return_type, args)

        if return_type not in return_supported_types():
            return 'INVALID RETURN FORMAT', 405

        forecast_range = api_config.DEFAULT_RANGE
        if 'range' in args:
            forecast_range = args.get('range')
        ## Validate inputs ##
        try:
            api_utils.check_key(
                args.get('api'),
                throw_on_fail=True,
                logger=self.logger,
            )
            crest_utils.validate_id(
                'map_regions',
                args.get('regionID'),
                config=api_config.CONFIG,
                logger=self.logger,
            )
            crest_utils.validate_id(
                'inventory_types',
                args.get('typeID'),
                config=api_config.CONFIG,
                logger=self.logger,
            )
            forecast_range = forecast_utils.check_requested_range(
                forecast_range,
                max_range=api_config.MAX_RANGE,
                raise_for_status=True
            )
        except exceptions.ValidatorException as err:
            self.logger.warning(
                'ERROR: unable to validate type/region ids\n\targs=%s',
                args,
                exc_info=True
            )
            return err.message, err.status
        except Exception: #pragma: no cover
            self.logger.error(
                'ERROR: unable to validate type/region ids\n\targs=%s',
                args,
                exc_info=True
            )
            return 'UNHANDLED EXCEPTION', 500

        ## check cache ##
        cache_data = forecast_utils.check_prediction_cache(
            args.get('regionID'),
            args.get('typeID')
        )
        self.logger.debug(cache_data)
        if cache_data is not None:
            self.logger.info('returning cached forecast')
            message = forecast_reporter(
                cache_data,
                forecast_range,
                return_type,
                self.logger,
            )

            return message

        ## No cache, get data ##
        try:
            if args.get('typeID') in api_config.SPLIT_INFO:
                LOGGER.info('FORK: using split utility')
                data = split_utils.fetch_split_history(
                    args.get('regionID'),
                    args.get('typeID'),
                    data_range=api_config.MAX_RANGE,
                    config=api_config.CONFIG,
                    logger=self.logger,
                )
                data.sort_values(
                    by='date',
                    ascending=True,
                    inplace=True
                )
            else:
                data = forecast_utils.fetch_extended_history(
                    args.get('regionID'),
                    args.get('typeID'),
                    data_range=api_config.MAX_RANGE,
                    config=api_config.CONFIG,
                    logger=self.logger,
                )
            data = forecast_utils.build_forecast(
                data,
                api_config.MAX_RANGE
            )
        except exceptions.ValidatorException as err:
            #FIX ME: testing?
            self.logger.warning(
                'ERROR: unable to generate forecast\n\targs=%s',
                args,
                exc_info=True
            )
            return err.message, err.status
        except Exception: #pragma: no cover
            LOGGER.error(
                'ERROR: unable to generate forecast\n\targs=%s',
                args,
                exc_info=True
            )
            return 'UNHANDLED EXCEPTION', 500

        ## Update cache ##
        forecast_utils.write_prediction_cache(
            args.get('regionID'),
            args.get('typeID'),
            data,
            logger=self.logger,
        )
        try:
            message = forecast_reporter(
                data,
                forecast_range,
                return_type,
                self.logger,
            )
        except Exception as err_msg:    #pragma: no cover
            LOGGER.error(
                'invalid format requested'
                '\n\targs=%s'
                '\n\treturn_type=%s',
                args, return_type,
                exc_info=True
            )
            return 'UNABLE TO GENERATE REPORT', 500
        return message