Beispiel #1
0
class TestAPIConnection(unittest.TestCase):

    def setUp(self):
        self.api = EVE()

    def test_user_agent(self):
        @httmock.all_requests
        def default_user_agent(url, request):
            user_agent = request.headers.get('User-Agent', None)
            self.assertEqual(
                user_agent, 'PyCrest/{0} +https://github.com/pycrest/PyCrest'
                .format(pycrest.version))

        with httmock.HTTMock(default_user_agent):
            EVE()

        @httmock.all_requests
        def customer_user_agent(url, request):
            user_agent = request.headers.get('User-Agent', None)
            self.assertEqual(
                user_agent,
                'PyCrest-Testing/{0} +https://github.com/pycrest/PyCrest'
                .format(pycrest.version))

        with httmock.HTTMock(customer_user_agent):
            EVE(user_agent='PyCrest-Testing/{0} +https://github.com/pycrest/P'
                'yCrest'.format(pycrest.version))

    def test_headers(self):

        # Check default header
        @httmock.all_requests
        def check_default_headers(url, request):
            self.assertNotIn('PyCrest-Testing', request.headers)

        with httmock.HTTMock(check_default_headers):
            EVE()

        # Check custom header
        def check_custom_headers(url, request):
            self.assertIn('PyCrest-Testing', request.headers)

        with httmock.HTTMock(check_custom_headers):
            EVE(additional_headers={'PyCrest-Testing': True})

    def test_default_cache(self):
        self.assertTrue(isinstance(self.api.cache, DictCache))

    def test_callable_cache(self):
        class CustomCache(object):
            pass
        eve = EVE(cache=CustomCache)
        self.assertTrue(isinstance(eve.cache, CustomCache))

    def test_apicache(self):
        eve = EVE(cache=DictCache())
        self.assertTrue(isinstance(eve.cache, DictCache))

    @mock.patch('os.path.isdir', return_value=False)
    @mock.patch('os.mkdir')
    def test_cache_dir(self, mkdir_function, isdir_function):
        eve = EVE(cache_dir=TestFileCache.DIR)
        self.assertEqual(eve.cache_dir, TestFileCache.DIR)
        self.assertTrue(isinstance(eve.cache, FileCache))

    def test_default_url(self):

        @httmock.all_requests
        def root_mock(url, request):
            self.assertEqual(url.path, '/')
            self.assertEqual(url.query, '')
            return {'status_code': 200,
                    'content': '{}'.encode('utf-8')}

        with httmock.HTTMock(root_mock):
            self.api()

    def test_parse_parameters_url(self):

        @httmock.all_requests
        def key_mock(url, request):
            self.assertEqual(url.path, '/')
            self.assertEqual(url.query, 'key=value1')
            return {'status_code': 200,
                    'content': '{}'.encode('utf-8')}

        with httmock.HTTMock(key_mock):
            self.api.get('https://crest-tq.eveonline.com/?key=value1')

    def test_parse_parameters_override(self):

        @httmock.all_requests
        def key_mock(url, request):
            self.assertEqual(url.path, '/')
            self.assertEqual(url.query, 'key=value2')
            return {'status_code': 200,
                    'content': '{}'.encode('utf-8')}

        with httmock.HTTMock(key_mock):
            self.api.get(
                'https://crest-tq.eveonline.com/?key=value1',
                dict(key='value2'))

    def test_cache_hit(self):

        @httmock.all_requests
        def prime_cache(url, request):
            headers = {'content-type': 'application/json',
                       'Cache-Control': 'max-age=300;'}
            return httmock.response(200, '{}'.encode('utf-8'), headers)

        with httmock.HTTMock(prime_cache):
            self.assertEqual(self.api()._dict, {})

        @httmock.all_requests
        def cached_request(url, request):
            raise RuntimeError(
                'A cached request should never yield a HTTP request')

        with httmock.HTTMock(cached_request):
            self.api._data = None
            self.assertEqual(self.api()._dict, {})

    def test_cache_invalidate(self):
        @httmock.all_requests
        def prime_cache(url, request):
            headers = {'content-type': 'application/json',
                       'Cache-Control': 'max-age=300;'}
            return httmock.response(
                200, '{"cached": true}'.encode('utf-8'), headers)

        # Prime cache and force the expiration
        with httmock.HTTMock(prime_cache):
            self.api()
            # Nuke _data so the .get() is actually being called the next call
            self.api._data = None
            for key in self.api.cache._dict:
                # Make sure the cache is concidered 'expired'
                self.api.cache._dict[key]['expires'] = 0

        @httmock.all_requests
        def expired_request(url, request):
            self.assertTrue(isinstance(request, PreparedRequest))
            return httmock.response(200, '{}'.encode('utf-8'))

        with httmock.HTTMock(expired_request):
            self.api()

    def test_non_http_200(self):

        @httmock.all_requests
        def non_http_200(url, request):
            return {'status_code': 404}

        with httmock.HTTMock(non_http_200):
            self.assertRaises(APIException, self.api)

    def test_get_expires(self):
        # No header at all
        r = httmock.response(200, '{}'.encode('utf-8'))
        self.assertEqual(self.api._get_expires(r), 0)

        # Cache-Control header with no-cache
        r = httmock.response(status_code=200,
                             content='{}'.encode('utf-8'),
                             headers={'Cache-Control': 'no-cache'})
        self.assertEqual(self.api._get_expires(r), 0)

        # Cache-Control header with no-store
        r = httmock.response(status_code=200,
                             content='{}'.encode('utf-8'),
                             headers={'Cache-Control': 'no-store'})
        self.assertEqual(self.api._get_expires(r), 0)

        # Cache-Control header with wrong content
        r = httmock.response(status_code=200,
                             content='{}'.encode('utf-8'),
                             headers={'Cache-Control': 'no-way'})
        self.assertEqual(self.api._get_expires(r), 0)

        # Cache-Control header with max-age=300
        r = httmock.response(status_code=200,
                             content='{}'.encode('utf-8'),
                             headers={'Cache-Control': 'max-age=300'})
        self.assertEqual(self.api._get_expires(r), 300)

    def test_session_mock(self):
        # Check default header
        @httmock.all_requests
        def expired_request(url, request):
            print(url)
            print(request)
            self.assertTrue(isinstance(request, PreparedRequest))
            return httmock.response(200, '{}'.encode('utf-8'))

        with httmock.HTTMock(expired_request):
            self.api()
Beispiel #2
0
class TestAPIConnection(unittest.TestCase):

    def setUp(self):
        self.api = EVE()

    def test_user_agent(self):
        @httmock.all_requests
        def default_user_agent(url, request):
            user_agent = request.headers.get('User-Agent', None)
            self.assertEqual(
                user_agent, 'PyCrest/{0} +https://github.com/pycrest/PyCrest'
                .format(pycrest.version))

        with httmock.HTTMock(default_user_agent):
            EVE()

        @httmock.all_requests
        def customer_user_agent(url, request):
            user_agent = request.headers.get('User-Agent', None)
            self.assertEqual(
                user_agent,
                'PyCrest-Testing/{0} +https://github.com/pycrest/PyCrest'
                .format(pycrest.version))

        with httmock.HTTMock(customer_user_agent):
            EVE(user_agent='PyCrest-Testing/{0} +https://github.com/pycrest/P'
                'yCrest'.format(pycrest.version))

    def test_headers(self):

        # Check default header
        @httmock.all_requests
        def check_default_headers(url, request):
            self.assertNotIn('PyCrest-Testing', request.headers)

        with httmock.HTTMock(check_default_headers):
            EVE()

        # Check custom header
        def check_custom_headers(url, request):
            self.assertIn('PyCrest-Testing', request.headers)

        with httmock.HTTMock(check_custom_headers):
            EVE(additional_headers={'PyCrest-Testing': True})

    def test_custom_transport_adapter(self):
        """ Check if the transport adapter is the one expected (especially if we set it) """
        class TestHttpAdapter(HTTPAdapter):
            def __init__(self, *args, **kwargs):
                super(TestHttpAdapter, self).__init__(*args, **kwargs)
                
        class FakeHttpAdapter(object):
            def __init__(self, *args, **kwargs):
                pass
                
        eve = EVE()
        self.assertTrue(isinstance(eve._session.get_adapter('http://'), HTTPAdapter))
        self.assertTrue(isinstance(eve._session.get_adapter('https://'), HTTPAdapter))
        self.assertFalse(isinstance(eve._session.get_adapter('http://'), TestHttpAdapter))
        self.assertFalse(isinstance(eve._session.get_adapter('https://'), TestHttpAdapter))
        
        eve = EVE(transport_adapter=TestHttpAdapter())
        self.assertTrue(isinstance(eve._session.get_adapter('http://'), TestHttpAdapter))
        self.assertTrue(isinstance(eve._session.get_adapter('https://'), TestHttpAdapter))
        
        # check that the wrong httpadapter is not used
        eve = EVE(transport_adapter=FakeHttpAdapter())
        self.assertTrue(isinstance(eve._session.get_adapter('http://'), HTTPAdapter))
        self.assertFalse(isinstance(eve._session.get_adapter('http://'), FakeHttpAdapter))
        
        eve = EVE(transport_adapter='')
        self.assertTrue(isinstance(eve._session.get_adapter('http://'), HTTPAdapter))
        
            
    def test_default_cache(self):
        self.assertTrue(isinstance(self.api.cache, DictCache))

    def test_no_cache(self):
        eve = EVE(cache=None)
        self.assertTrue(isinstance(eve.cache, DummyCache))
        
    def test_implements_apiobject(self):
        class CustomCache(object):
            pass
        with self.assertRaises(ValueError):
            eve = EVE(cache=CustomCache)

    def test_apicache(self):
        eve = EVE(cache=DictCache())
        self.assertTrue(isinstance(eve.cache, DictCache))


    @mock.patch('os.path.isdir', return_value=False)		
    @mock.patch('os.mkdir')		
    def test_file_cache(self, mkdir_function, isdir_function):
        file_cache = FileCache(path=TestFileCache.DIR)
        eve = EVE(cache=file_cache)		
        self.assertEqual(file_cache.path, TestFileCache.DIR)		
        self.assertTrue(isinstance(eve.cache, FileCache))		


    def test_default_url(self):

        @httmock.all_requests
        def root_mock(url, request):
            self.assertEqual(url.path, '/')
            self.assertEqual(url.query, '')
            return {'status_code': 200,
                    'content': '{}'.encode('utf-8')}

        with httmock.HTTMock(root_mock):
            self.api()

    def test_parse_parameters_url(self):

        @httmock.all_requests
        def key_mock(url, request):
            self.assertEqual(url.path, '/')
            self.assertEqual(url.query, 'key=value1')
            return {'status_code': 200,
                    'content': '{}'.encode('utf-8')}

        with httmock.HTTMock(key_mock):
            self.api.get('https://crest-tq.eveonline.com/?key=value1')

    def test_parse_parameters_override(self):

        @httmock.all_requests
        def key_mock(url, request):
            self.assertEqual(url.path, '/')
            self.assertEqual(url.query, 'key=value2')
            return {'status_code': 200,
                    'content': '{}'.encode('utf-8')}

        with httmock.HTTMock(key_mock):
            self.api.get(
                'https://crest-tq.eveonline.com/?key=value1',
                dict(key='value2'))

    def test_cache_hit(self):
        @httmock.all_requests
        def prime_cache(url, request):
            headers = {'content-type': 'application/json',
                       'Cache-Control': 'max-age=300;'}
            return httmock.response(200, '{}'.encode('utf-8'), headers)

        with httmock.HTTMock(prime_cache):
            self.assertEqual(self.api()._dict, {})

        @httmock.all_requests
        def cached_request(url, request):
            raise RuntimeError(
                'A cached request should never yield a HTTP request')

        with httmock.HTTMock(cached_request):
            self.api._data = None
            self.assertEqual(self.api()._dict, {})
          
    def test_caching_arg_hit(self):
        """ Test the caching argument for ApiConnection and ApiObject __call__() """
        
        @httmock.urlmatch(
            scheme="https",
            netloc=r"(api-sisi\.test)?(crest-tq\.)?eveonline\.com$",
            path=r"^/market/prices/?$")
        def market_prices_cached_mock(url, request):
            headers = {'content-type': 'application/json',
               'Cache-Control': 'max-age=300;'}
            return httmock.response(
                status_code=200,
                headers=headers,
                content='{}'.encode('utf-8'))
                        
        with httmock.HTTMock(root_mock, market_prices_cached_mock):
            self.assertEqual(self.api.cache._dict, {})
            
            self.api(caching=False)
            self.assertEqual(self.api.cache._dict, {})
            
            self.api._data = None
            self.api()
            self.assertEqual(len(self.api.cache._dict), 1)
            
            self.assertEqual(self.api().marketData(caching=False)._dict, {})
            self.assertEqual(len(self.api.cache._dict), 1)
            
            self.assertEqual(self.api().marketData()._dict, {})
            self.assertEqual(len(self.api.cache._dict), 2)


    def test_cache_invalidate(self):
        @httmock.all_requests
        def prime_cache(url, request):
            headers = {'content-type': 'application/json',
                       'Cache-Control': 'max-age=300;'}
            return httmock.response(
                200, '{"cached": true}'.encode('utf-8'), headers)

        # Prime cache and force the expiration
        with httmock.HTTMock(prime_cache):
            self.api()
            # Nuke _data so the .get() is actually being called the next call
            self.api._data = None
            for key in self.api.cache._dict:
                # Make sure the cache is concidered 'expired'
                self.api.cache._dict[key]['expires'] = 0

        @httmock.all_requests
        def expired_request(url, request):
            self.assertTrue(isinstance(request, PreparedRequest))
            return httmock.response(200, '{}'.encode('utf-8'))

        with httmock.HTTMock(expired_request):
            self.api()

    def test_non_http_200(self):

        @httmock.all_requests
        def non_http_200(url, request):
            return {'status_code': 404, 'content' : {'message' : 'not found'}}

        with httmock.HTTMock(non_http_200):
            self.assertRaises(APIException, self.api)

    def test_get_expires(self):
        # No header at all
        r = httmock.response(200, '{}'.encode('utf-8'))
        self.assertEqual(self.api._get_expires(r), 0)

        # Cache-Control header with no-cache
        r = httmock.response(status_code=200,
                             content='{}'.encode('utf-8'),
                             headers={'Cache-Control': 'no-cache'})
        self.assertEqual(self.api._get_expires(r), 0)

        # Cache-Control header with no-store
        r = httmock.response(status_code=200,
                             content='{}'.encode('utf-8'),
                             headers={'Cache-Control': 'no-store'})
        self.assertEqual(self.api._get_expires(r), 0)

        # Cache-Control header with wrong content
        r = httmock.response(status_code=200,
                             content='{}'.encode('utf-8'),
                             headers={'Cache-Control': 'no-way'})
        self.assertEqual(self.api._get_expires(r), 0)

        # Cache-Control header with max-age=300
        r = httmock.response(status_code=200,
                             content='{}'.encode('utf-8'),
                             headers={'Cache-Control': 'max-age=300'})
        self.assertEqual(self.api._get_expires(r), 300)

    def test_session_mock(self):
        # Check default header
        @httmock.all_requests
        def expired_request(url, request):
            print(url)
            print(request)
            self.assertTrue(isinstance(request, PreparedRequest))
            return httmock.response(200, '{}'.encode('utf-8'))

        with httmock.HTTMock(expired_request):
            self.api()
Beispiel #3
0
class TestAPIConnection(unittest.TestCase):
    def setUp(self):
        self.api = EVE()

    def test_user_agent(self):
        @httmock.all_requests
        def default_user_agent(url, request):
            user_agent = request.headers.get('User-Agent', None)
            self.assertEqual(
                user_agent,
                'PyCrest/{0} +https://github.com/pycrest/PyCrest'.format(
                    pycrest.version))

        with httmock.HTTMock(default_user_agent):
            EVE()

        @httmock.all_requests
        def customer_user_agent(url, request):
            user_agent = request.headers.get('User-Agent', None)
            self.assertEqual(
                user_agent,
                'PyCrest-Testing/{0} +https://github.com/pycrest/PyCrest'.
                format(pycrest.version))

        with httmock.HTTMock(customer_user_agent):
            EVE(user_agent='PyCrest-Testing/{0} +https://github.com/pycrest/P'
                'yCrest'.format(pycrest.version))

    def test_headers(self):

        # Check default header
        @httmock.all_requests
        def check_default_headers(url, request):
            self.assertNotIn('PyCrest-Testing', request.headers)

        with httmock.HTTMock(check_default_headers):
            EVE()

        # Check custom header
        def check_custom_headers(url, request):
            self.assertIn('PyCrest-Testing', request.headers)

        with httmock.HTTMock(check_custom_headers):
            EVE(additional_headers={'PyCrest-Testing': True})

    def test_default_cache(self):
        self.assertTrue(isinstance(self.api.cache, DictCache))

    def test_callable_cache(self):
        class CustomCache(object):
            pass

        eve = EVE(cache=CustomCache)
        self.assertTrue(isinstance(eve.cache, CustomCache))

    def test_apicache(self):
        eve = EVE(cache=DictCache())
        self.assertTrue(isinstance(eve.cache, DictCache))

    @mock.patch('os.path.isdir', return_value=False)
    @mock.patch('os.mkdir')
    def test_cache_dir(self, mkdir_function, isdir_function):
        eve = EVE(cache_dir=TestFileCache.DIR)
        self.assertEqual(eve.cache_dir, TestFileCache.DIR)
        self.assertTrue(isinstance(eve.cache, FileCache))

    def test_default_url(self):
        @httmock.all_requests
        def root_mock(url, request):
            self.assertEqual(url.path, '/')
            self.assertEqual(url.query, '')
            return {'status_code': 200, 'content': '{}'.encode('utf-8')}

        with httmock.HTTMock(root_mock):
            self.api()

    def test_parse_parameters_url(self):
        @httmock.all_requests
        def key_mock(url, request):
            self.assertEqual(url.path, '/')
            self.assertEqual(url.query, 'key=value1')
            return {'status_code': 200, 'content': '{}'.encode('utf-8')}

        with httmock.HTTMock(key_mock):
            self.api.get('https://crest-tq.eveonline.com/?key=value1')

    def test_parse_parameters_override(self):
        @httmock.all_requests
        def key_mock(url, request):
            self.assertEqual(url.path, '/')
            self.assertEqual(url.query, 'key=value2')
            return {'status_code': 200, 'content': '{}'.encode('utf-8')}

        with httmock.HTTMock(key_mock):
            self.api.get('https://crest-tq.eveonline.com/?key=value1',
                         dict(key='value2'))

    def test_cache_hit(self):
        @httmock.all_requests
        def prime_cache(url, request):
            headers = {
                'content-type': 'application/json',
                'Cache-Control': 'max-age=300;'
            }
            return httmock.response(200, '{}'.encode('utf-8'), headers)

        with httmock.HTTMock(prime_cache):
            self.assertEqual(self.api()._dict, {})

        @httmock.all_requests
        def cached_request(url, request):
            raise RuntimeError(
                'A cached request should never yield a HTTP request')

        with httmock.HTTMock(cached_request):
            self.api._data = None
            self.assertEqual(self.api()._dict, {})

    def test_cache_invalidate(self):
        @httmock.all_requests
        def prime_cache(url, request):
            headers = {
                'content-type': 'application/json',
                'Cache-Control': 'max-age=300;'
            }
            return httmock.response(200, '{"cached": true}'.encode('utf-8'),
                                    headers)

        # Prime cache and force the expiration
        with httmock.HTTMock(prime_cache):
            self.api()
            # Nuke _data so the .get() is actually being called the next call
            self.api._data = None
            for key in self.api.cache._dict:
                # Make sure the cache is concidered 'expired'
                self.api.cache._dict[key]['expires'] = 0

        @httmock.all_requests
        def expired_request(url, request):
            self.assertTrue(isinstance(request, PreparedRequest))
            return httmock.response(200, '{}'.encode('utf-8'))

        with httmock.HTTMock(expired_request):
            self.api()

    def test_non_http_200(self):
        @httmock.all_requests
        def non_http_200(url, request):
            return {'status_code': 404, 'content': {'message': 'not found'}}

        with httmock.HTTMock(non_http_200):
            self.assertRaises(APIException, self.api)

    def test_get_expires(self):
        # No header at all
        r = httmock.response(200, '{}'.encode('utf-8'))
        self.assertEqual(self.api._get_expires(r), 0)

        # Cache-Control header with no-cache
        r = httmock.response(status_code=200,
                             content='{}'.encode('utf-8'),
                             headers={'Cache-Control': 'no-cache'})
        self.assertEqual(self.api._get_expires(r), 0)

        # Cache-Control header with no-store
        r = httmock.response(status_code=200,
                             content='{}'.encode('utf-8'),
                             headers={'Cache-Control': 'no-store'})
        self.assertEqual(self.api._get_expires(r), 0)

        # Cache-Control header with wrong content
        r = httmock.response(status_code=200,
                             content='{}'.encode('utf-8'),
                             headers={'Cache-Control': 'no-way'})
        self.assertEqual(self.api._get_expires(r), 0)

        # Cache-Control header with max-age=300
        r = httmock.response(status_code=200,
                             content='{}'.encode('utf-8'),
                             headers={'Cache-Control': 'max-age=300'})
        self.assertEqual(self.api._get_expires(r), 300)

    def test_session_mock(self):
        # Check default header
        @httmock.all_requests
        def expired_request(url, request):
            print(url)
            print(request)
            self.assertTrue(isinstance(request, PreparedRequest))
            return httmock.response(200, '{}'.encode('utf-8'))

        with httmock.HTTMock(expired_request):
            self.api()