Пример #1
0
    def test_app_expired_header_etag(self, urlopen_mock):
        @httmock.all_requests
        def check_etag(url, request):
            self.assertEqual(
                request.headers.get('If-None-Match'),
                '"esipyetag"')
            return httmock.response(
                headers={
                    'Expires': make_expire_time_str(),
                    'Etag': '"esipyetag"'
                },
                status_code=304)

        cache = DictCache()
        with httmock.HTTMock(*_swagger_spec_mock_):
            urlopen_mock.return_value = open(TestEsiApp.ESI_META_SWAGGER)
            self.assertEqual(len(cache._dict), 0)
            app = EsiApp(
                cache_time=None, cache=cache, cache_prefix='esipy_test')
            self.assertEqual(len(cache._dict), 1)

        cache.get(
            app.esi_meta_cache_key
        )[1]['expires'] = make_expired_time_str()
        cached_app = cache.get(app.esi_meta_cache_key)[0]

        with httmock.HTTMock(check_etag):
            urlopen_mock.return_value = open(TestEsiApp.ESI_META_SWAGGER)
            esiapp = EsiApp(
                cache_time=None, cache=cache, cache_prefix='esipy_test')
            self.assertEqual(cached_app, esiapp.app)
            urlopen_mock.return_value.close()
Пример #2
0
class TestDictCache(BaseTest):
    """ DictCache test class """
    def setUp(self):
        self.c = DictCache()
        self.c.set(*self.ex_str)
        self.c.set(*self.ex_int)
        self.c.set(*self.ex_cpx)

    def test_dict_cache_set(self):
        self.assertEqual(self.c._dict[self.ex_str[0]][0], self.ex_str[1])
        self.assertEqual(self.c._dict[self.ex_int[0]][0], self.ex_int[1])
        self.assertEqual(self.c._dict[self.ex_cpx[0]][0], self.ex_cpx[1])

    def test_dict_cache_get(self):
        self.check_complex(self.c.get(self.ex_cpx[0]))

    def test_dict_cache_invalidate(self):
        self.c.invalidate(self.ex_cpx[0])
        self.assertIsNone(self.c.get(self.ex_cpx[0]))

    def test_dict_cache_expiry(self):
        self.check_complex(self.c.get(self.ex_cpx[0]))
        self.c._dict[self.ex_cpx[0]] = (self.ex_cpx[1], time.time() - 1)
        self.assertIsNone(self.c.get(self.ex_cpx[0]))
        self.assertNotIn(self.ex_cpx[0], self.c._dict)
Пример #3
0
    def test_app_invalid_cache_value(self, urlopen_mock):
        cache = DictCache()
        cache.set(self.app.esi_meta_cache_key, 'somerandomvalue')
        urlopen_mock.return_value = open(TestEsiApp.ESI_META_SWAGGER)
        with httmock.HTTMock(*_swagger_spec_mock_):
            EsiApp(cache_prefix='esipy_test', cache=cache)

        self.assertNotEqual(cache.get(self.app.esi_meta_cache_key),
                            'somerandomvalue')
Пример #4
0
    def test_app_expired_header_no_etag(self, urlopen_mock):
        cache = DictCache()
        with httmock.HTTMock(*_swagger_spec_mock_):
            urlopen_mock.return_value = open(TestEsiApp.ESI_META_SWAGGER)
            app = EsiApp(
                cache_time=None, cache=cache, cache_prefix='esipy_test')

            urlopen_mock.return_value = open(TestEsiApp.ESI_V1_SWAGGER)
            appv1 = app.get_v1_swagger
            cache.get(self.ESI_V1_CACHE_KEY)[1]['Expires'] = None

            urlopen_mock.return_value = open(TestEsiApp.ESI_V1_SWAGGER)
            appv1_uncached = app.get_v1_swagger
            self.assertNotEqual(appv1, appv1_uncached)
Пример #5
0
def initialize_esi_client(refresh_token=None):
    """
    Retrieves a public or authorized ESI client.

    Args:
        auth_id (optional): refresh_token of the user whose client we want to
            retrieve. By default, a public ESI client is returned.

    Returns:
        esi_client (EsiClient): Client object from esipy.
    """
    auth = EsiSecurity(
        headers={'User-Agent': client_name},
        redirect_uri='https://localhost/callback',
        client_id=client_id,
        secret_key=secret_key,
    )
    if refresh_token is not None:
        auth.refresh_token = refresh_token
    esi_client = EsiClient(
        auth,
        retry_requests=True,
        cache=DictCache(),
        headers={'User-Agent': client_name},
    )
    return esi_client
Пример #6
0
def config_esi_cache(cache_url):
    """Configure ESI cache backend

    Args:
        cache_url (string): diskcache or redis url

    Returns:
        cache: esipy.cache

    >>> config_esi_cache('diskcache:/tmp/esipy-diskcache') # doctest: +ELLIPSIS
    <esipy.cache.FileCache object at 0x...>
    >>> config_esi_cache('redis://*****:*****@127.0.0.1:6379/') # doctest: +ELLIPSIS
    <esipy.cache.RedisCache object at 0x...>
    """
    cache = DictCache()
    if cache_url:
        cache_url = urlparse(cache_url)
        if cache_url.scheme == 'diskcache':
            from esipy.cache import FileCache
            filename = cache_url.path
            cache = FileCache(path=filename)
        elif cache_url.scheme == 'redis':
            from esipy.cache import RedisCache
            import redis
            redis_server = cache_url.hostname
            redis_port = cache_url.port
            redis_client = redis.Redis(host=redis_server, port=redis_port)
            cache = RedisCache(redis_client)
    return cache
Пример #7
0
    def test_app_valid_header_etag(self, urlopen_mock):
        @httmock.all_requests
        def fail_if_request(url, request):
            self.fail('Cached data is not supposed to do requests')

        cache = DictCache()

        with httmock.HTTMock(*_swagger_spec_mock_):
            urlopen_mock.return_value = open(TestEsiApp.ESI_META_SWAGGER)
            EsiApp(cache_time=None, cache=cache, cache_prefix='esipy_test')

        with httmock.HTTMock(fail_if_request):
            urlopen_mock.return_value = open(TestEsiApp.ESI_META_SWAGGER)
            EsiApp(cache_time=None, cache=cache, cache_prefix='esipy_test')
            urlopen_mock.return_value.close()
Пример #8
0
    def setUp(self, urlopen_mock):
        # I hate those mock... thx urlopen instead of requests...
        urlopen_mock.return_value = open('test/resources/swagger.json')

        self.app = App.create('https://esi.tech.ccp.is/latest/swagger.json')

        self.security = EsiSecurity(
            app=self.app,
            redirect_uri=TestEsiPy.CALLBACK_URI,
            client_id=TestEsiPy.CLIENT_ID,
            secret_key=TestEsiPy.SECRET_KEY,
        )

        self.cache = DictCache()
        self.client = EsiClient(self.security, cache=self.cache)
        self.client_no_auth = EsiClient(cache=self.cache, retry_requests=True)
Пример #9
0
    def __init__(self, security=None, **kwargs):
        """ Init the ESI client object
        :param security: (optional) the security object [default: None]
        :param headers: (optional) additional headers we want to add
        :param transport_adapter: (optional) an HTTPAdapter object / implement
        :param cache: (optional) esipy.cache.BaseCache cache implementation.
        :param raw_body_only: (optional) default value [False] for all requests
        """
        super(EsiClient, self).__init__(security)

        # lets get rid of all our kwargs
        headers = kwargs.pop('headers', {})
        transport_adapter = kwargs.pop('transport_adapter', None)
        # initiate the cache object
        if 'cache' not in kwargs:
            self.cache = DictCache()
        else:
            cache = kwargs.pop('cache')
            if isinstance(cache, BaseCache):
                self.cache = cache
            elif cache is None:
                self.cache = DummyCache()
            else:
                raise ValueError('Provided cache must implement BaseCache')

        # store default raw_body_only in case user never want parsing
        self.raw_body_only = kwargs.pop('raw_body_only', False)

        self.timeout = kwargs.pop('timeout', 10)

        self.security = security
        self._session = Session()

        # check for specified headers and update session.headers

        if 'User-Agent' not in headers:
            headers['User-Agent'] = ('EsiPy/Client - '
                                     'https://github.com/Kyria/EsiPy')
        self._session.headers.update({"Accept": "application/json"})
        self._session.headers.update(headers)

        # transport adapter
        if isinstance(transport_adapter, HTTPAdapter):
            self._session.mount('http://', transport_adapter)
            self._session.mount('https://', transport_adapter)
Пример #10
0
    def setUp(self, urlopen_mock):
        # I hate those mock... thx urlopen instead of requests...
        urlopen_mock.return_value = open('test/resources/swagger.json')
        warnings.simplefilter('ignore')

        self.app = App.create('https://esi.evetech.net/latest/swagger.json')

        with open(TestEsiPy.RSC_SSO_ENDPOINTS, 'r') as sso_endpoints:
            with open(TestEsiPy.RSC_JWKS, "r") as jwks:
                self.security = EsiSecurity(
                    app=self.app,
                    redirect_uri=TestEsiPy.CALLBACK_URI,
                    client_id=TestEsiPy.CLIENT_ID,
                    secret_key=TestEsiPy.SECRET_KEY,
                    sso_endpoints=json.load(sso_endpoints),
                    jwks_key=json.load(jwks))

        self.cache = DictCache()
        self.client = EsiClient(self.security, cache=self.cache)
        self.client_no_auth = EsiClient(cache=self.cache, retry_requests=True)
Пример #11
0
def setup_esi(app_id, app_secret, refresh_token, cache=DictCache()):
    """Set up the ESI client

    Args:
        app_id (string): SSO Application ID from CCP
        app_secret (string): SSO Application Secret from CCP
        refresh_token (string): SSO refresh token
        cache (False, optional): esipy.cache instance

    Returns:
        tuple: esi app definition, esi client

    >>> setup_esi(CONFIG['SSO_APP_ID'], CONFIG['SSO_APP_KEY'],
    ...           CONFIG['SSO_REFRESH_TOKEN'], cache) # doctest: +ELLIPSIS
    (<pyswagger.core.App object ...>, <esipy.client.EsiClient object ...>)
    """
    esi_meta = EsiApp(cache=cache)
    esi = esi_meta.get_latest_swagger

    esi_security = EsiSecurity(
        redirect_uri='http://localhost',
        client_id=app_id,
        secret_key=app_secret,
        headers={'User-Agent': 'https://github.com/eve-n0rman/structurebot'})

    esi_security.update_token({
        'access_token': '',
        'expires_in': -1,
        'refresh_token': refresh_token
    })

    esi_client = EsiClient(
        retry_requests=True,
        headers={'User-Agent': 'https://github.com/eve-n0rman/structurebot'},
        raw_body_only=False,
        security=esi_security,
        cache=cache)

    return (esi, esi_client, esi_security)
Пример #12
0
 def setUp(self):
     self.c = DictCache()
     self.c.set(*self.ex_str)
     self.c.set(*self.ex_int)
     self.c.set(*self.ex_cpx)
Пример #13
0
 def test_esipy_client_with_cache(self):
     cache = DictCache()
     client_with_cache = EsiClient(cache=cache)
     self.assertTrue(isinstance(client_with_cache.cache, BaseCache))
     self.assertEqual(client_with_cache.cache, cache)
Пример #14
0
class TestDictCache(BaseTest):
    """ DictCache test class """

    def setUp(self):
        self.c = DictCache()
        self.c.set(*self.ex_str)
        self.c.set(*self.ex_int)
        self.c.set(*self.ex_cpx)

    def tearDown(self):
        self.c.invalidate(self.ex_str[0])
        self.c.invalidate(self.ex_int[0])
        self.c.invalidate(self.ex_cpx[0])

    def test_dict_cache_set(self):
        self.assertEqual(self.c._dict[self.ex_str[0]], self.ex_str[1])
        self.assertEqual(self.c._dict[self.ex_int[0]], self.ex_int[1])
        self.assertEqual(self.c._dict[self.ex_cpx[0]], self.ex_cpx[1])

    def test_dict_cache_get(self):
        self.check_complex(self.c.get(self.ex_cpx[0]))

    def test_dict_cache_invalidate(self):
        self.c.invalidate(self.ex_cpx[0])
        self.assertIsNone(self.c.get(self.ex_cpx[0]))

    def test_dict_cache_clear(self):
        self.assertEqual(self.c._dict[self.ex_str[0]], self.ex_str[1])
        self.assertEqual(len(self.c._dict), 3)
        self.c.clear()
        self.assertEqual(len(self.c._dict), 0)