Python httmock.all_requests() Examples

The following are 30 code examples of httmock.all_requests(). You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may also want to check out all available functions/classes of the module httmock , or try the search function .
Example #1
Source File: test_list_parser.py    From refstack-client with Apache License 2.0 6 votes vote down vote up
def test_get_base_test_ids_from_list_file_url(self):
        """Test that we can parse the test cases from a test list URL."""
        list_file = self.test_path + "/test-list.txt"

        with open(list_file, 'rb') as f:
            content = f.read()

        @httmock.all_requests
        def request_mock(url, request):
            return {'status_code': 200,
                    'content': content}

        with httmock.HTTMock(request_mock):
            online_list = self.parser._get_base_test_ids_from_list_file(
                "http://127.0.0.1/test-list.txt")

        expected_list = ['tempest.api.test1',
                         'tempest.api.test2',
                         'tempest.api.test3(scenario)']
        self.assertEqual(expected_list, sorted(online_list)) 
Example #2
Source File: api_tests.py    From consulate with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
def test_get_list_200_returns_response_body(self):
        @httmock.all_requests
        def response_content(_url_unused, request):
            headers = {
                'X-Consul-Index': 4,
                'X-Consul-Knownleader': 'true',
                'X-Consul-Lastcontact': 0,
                'Date': 'Fri, 19 Dec 2014 20:44:28 GMT',
                'Content-Length': 13,
                'Content-Type': 'application/json'
            }
            content = b'{"consul": []}'
            return httmock.response(200, content, headers, None, 0, request)

        with httmock.HTTMock(response_content):
            values = self.endpoint._get_list([str(uuid.uuid4())])
            self.assertEqual(values, [{'consul': []}]) 
Example #3
Source File: api_tests.py    From consulate with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
def test_get_200_returns_response_body(self):
        @httmock.all_requests
        def response_content(_url_unused, request):
            headers = {
                'X-Consul-Index': 4,
                'X-Consul-Knownleader': 'true',
                'X-Consul-Lastcontact': 0,
                'Date': 'Fri, 19 Dec 2014 20:44:28 GMT',
                'Content-Length': 13,
                'Content-Type': 'application/json'
            }
            content = b'{"consul": []}'
            return httmock.response(200, content, headers, None, 0, request)

        with httmock.HTTMock(response_content):
            values = self.endpoint._get([str(uuid.uuid4())])
            self.assertEqual(values, {'consul': []}) 
Example #4
Source File: test_client.py    From EsiPy with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
def test_client_cache_request(self):
        @httmock.all_requests
        def fail_if_request(url, request):
            self.fail('Cached data is not supposed to do requests')

        incursion_operation = self.app.op['get_incursions']

        with httmock.HTTMock(public_incursion_no_expires):
            incursions = self.client_no_auth.request(incursion_operation())
            self.assertEqual(incursions.data[0].state, 'mobilizing')

        with httmock.HTTMock(public_incursion_no_expires_second):
            incursions = self.client_no_auth.request(incursion_operation())
            self.assertEqual(incursions.data[0].state, 'established')

        with httmock.HTTMock(public_incursion):
            incursions = self.client_no_auth.request(incursion_operation())
            self.assertEqual(incursions.data[0].state, 'mobilizing')

        with httmock.HTTMock(fail_if_request):
            incursions = self.client_no_auth.request(incursion_operation())
            self.assertEqual(incursions.data[0].state, 'mobilizing') 
Example #5
Source File: test_pycrest.py    From PyCrest with MIT License 6 votes vote down vote up
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() 
Example #6
Source File: test_pycrest.py    From PyCrest with MIT License 6 votes vote down vote up
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, {}) 
Example #7
Source File: test_pycrest.py    From PyCrest with MIT License 6 votes vote down vote up
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}) 
Example #8
Source File: test_pycrest.py    From PyCrest with MIT License 6 votes vote down vote up
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)) 
Example #9
Source File: mocked_network.py    From prometheus-api-client-python with MIT License 6 votes vote down vote up
def mock_response(
        content, url=None, path='', headers=None, response_url=None, status_code=200, cookies=None, func=None
):
    """Universal handler for specify mocks inplace"""
    if func is None:

        def mocked(url, request):
            mock = response(
                status_code=status_code, content=content, request=request, headers=headers
            )
            if cookies:
                mock.cookies = cookies
            mock.url = response_url if response_url else url
            return mock

    else:
        mocked = func

    if url:
        parsed = urlparse(url)
        return urlmatch(netloc=parsed.netloc, path=parsed.path)(func=mocked)
    elif path:
        return urlmatch(path=path)(func=mocked)
    else:
        return all_requests(func=mocked) 
Example #10
Source File: test_guidelines.py    From refstack with Apache License 2.0 5 votes vote down vote up
def test_get_guideline_file(self):
        @httmock.all_requests
        def github_mock(url, request):
            content = {'foo': 'bar'}
            return httmock.response(200, content, None, None, 5, request)
        url = self.URL + "2015.03.json"
        with httmock.HTTMock(github_mock):
            actual_response = self.get_json(url)

        expected_response = {'foo': 'bar'}
        self.assertEqual(expected_response, actual_response) 
Example #11
Source File: test_guidelines.py    From refstack with Apache License 2.0 5 votes vote down vote up
def test_get_guidelines_list_error_code(self):
        """Test when the HTTP status code isn't a 200 OK."""
        @httmock.all_requests
        def github_api_mock(url, request):
            content = {'title': 'Not Found'}
            return httmock.response(404, content, None, None, 5, request)

        with httmock.HTTMock(github_api_mock):
            result = self.guidelines.get_guideline_list()
        self.assertEqual(result, {'powered': []}) 
Example #12
Source File: test_guidelines.py    From refstack with Apache License 2.0 5 votes vote down vote up
def test_get_capability_file_error_code(self):
        """Test when the HTTP status code isn't a 200 OK."""
        @httmock.all_requests
        def github_api_mock(url, request):
            content = {'title': 'Not Found'}
            return httmock.response(404, content, None, None, 5, request)

        with httmock.HTTMock(github_api_mock):
            result = self.guidelines.get_guideline_contents('2010.03.json')
        self.assertIsNone(result) 
Example #13
Source File: test_client.py    From EsiPy with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def test_esipy_expired_header_etag(self):
        @httmock.all_requests
        def check_etag(url, request):
            self.assertEqual(
                request.headers.get('If-None-Match'),
                '"esipy_test_etag_status"'
            )
            return httmock.response(
                headers={'Etag': '"esipy_test_etag_status"',
                         'expires': make_expire_time_str(),
                         'date': make_expire_time_str()},
                status_code=304)

        operation = self.app.op['get_status']()

        with httmock.HTTMock(eve_status):
            self.assertEqual(self.cache._dict, {})
            res = self.client.request(operation)
            self.assertNotEqual(self.cache._dict, {})
            self.assertEqual(res.data.server_version, "1313143")

        time.sleep(2)

        with httmock.HTTMock(check_etag):
            res = self.client.request(operation)
            self.assertEqual(res.data.server_version, "1313143") 
Example #14
Source File: test_app.py    From EsiPy with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
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() 
Example #15
Source File: test_app.py    From EsiPy with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
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() 
Example #16
Source File: acl_tests.py    From consulate with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def test_bootstrap_success(self):
        expectation = self.uuidv4()

        @httmock.all_requests
        def response_content(_url_unused, request):
            return httmock.response(
                200, json.dumps({'ID': expectation}), {}, None, 0, request)

        with httmock.HTTMock(response_content):
            result = self.consul.acl.bootstrap()

        self.assertEqual(result, expectation) 
Example #17
Source File: acl_tests.py    From consulate with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def test_bootstrap_request_exception(self):

        @httmock.all_requests
        def response_content(_url_unused, _request):
            raise OSError

        with httmock.HTTMock(response_content):
            with self.assertRaises(exceptions.RequestError):
                self.consul.acl.bootstrap() 
Example #18
Source File: api_tests.py    From consulate with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def test_get_404_returns_empty_list(self):
        @httmock.all_requests
        def response_content(_url_unused, request):
            headers = {
                'content-length': 0,
                'content-type': 'text/plain; charset=utf-8'
            }
            return httmock.response(404, None, headers, None, 0, request)

        with httmock.HTTMock(response_content):
            values = self.endpoint._get([str(uuid.uuid4())])
            self.assertEqual(values, []) 
Example #19
Source File: kv_tests.py    From consulate with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def test_contains_evaluates_false(self):
        @httmock.all_requests
        def response_content(_url_unused, request):
            return httmock.response(404, None, {}, None, 0, request)

        with httmock.HTTMock(response_content):
            self.assertNotIn('foo', self.kv) 
Example #20
Source File: kv_tests.py    From consulate with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def test_contains_evaluates_true(self):
        @httmock.all_requests
        def response_content(_url_unused, request):
            return httmock.response(200, None, {}, None, 0, request)

        with httmock.HTTMock(response_content):
            self.assertIn('foo', self.kv) 
Example #21
Source File: test_pycrest.py    From PyCrest with MIT License 5 votes vote down vote up
def test_http_201_post(self):
        @httmock.all_requests
        def http_201(url, request):
            return {'status_code': 201, 'content' : {'message' : 'created new object'}}

        with httmock.HTTMock(http_201):
            res = self.api.writeableEndpoint(method='post')
        self.assertTrue(isinstance(res, APIObject)) 
Example #22
Source File: test_pycrest.py    From PyCrest with MIT License 5 votes vote down vote up
def test_non_http_200_delete(self):

        @httmock.all_requests
        def non_http_200(url, request):
            return {'status_code': 201, 'content' : {'message' : 'created new object'}}

        with httmock.HTTMock(non_http_200):
            self.assertRaises(APIException, self.api.writeableEndpoint, method='delete')

    #201 received from successful contact creation via POST 
Example #23
Source File: test_pycrest.py    From PyCrest with MIT License 5 votes vote down vote up
def test_non_http_200_201_post(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.writeableEndpoint, method='post') 
Example #24
Source File: test_pycrest.py    From PyCrest with MIT License 5 votes vote down vote up
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() 
Example #25
Source File: test_pycrest.py    From PyCrest with MIT License 5 votes vote down vote up
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) 
Example #26
Source File: test_pycrest.py    From PyCrest with MIT License 5 votes vote down vote up
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') 
Example #27
Source File: test_pycrest.py    From PyCrest with MIT License 5 votes vote down vote up
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() 
Example #28
Source File: test_pycrest.py    From PyCrest with MIT License 5 votes vote down vote up
def test_authorize_non_200(self):

        @httmock.all_requests
        def mock_login(url, request):
            return httmock.response(status_code=204,
                                    content='{}')

        with httmock.HTTMock(mock_login):
            self.assertRaises(APIException, self.api.authorize, code='code') 
Example #29
Source File: test_guidelines.py    From refstack with Apache License 2.0 4 votes vote down vote up
def test_get_guideline_list(self):
        @httmock.all_requests
        def github_api_mock(url, request):
            headers = {'content-type': 'application/json'}
            content = [{'name': '2015.03.json',
                        'path': '2015.03.json',
                        'type': 'file'},
                       {'name': '2015.next.json',
                        'path': '2015.next.json',
                        'type': 'file'},
                       {'name': '2015.03',
                        'path': '2015.03',
                        'file': '2015.03',
                        'type': 'dir'},
                       {'name': 'test.2018.02.json',
                        'path': 'add-ons/test.2018.02.json',
                        'type': 'file'},
                       {'name': 'test.next.json',
                        'path': 'add-ons/test.next.json',
                        'type': 'file'}]
            content = json.dumps(content)
            return httmock.response(200, content, headers, None, 5, request)

        with httmock.HTTMock(github_api_mock):
            actual_response = self.get_json(self.URL)

        expected_powered = [
            {'name': u'2015.03.json',
             'file': u'2015.03.json'},
            {'name': u'2015.next.json',
             'file': u'2015.next.json'}
        ]
        expected_test_addons = [
            {u'name': u'2018.02.json',
             u'file': u'test.2018.02.json'},
            {u'name': u'next.json',
             u'file': u'test.next.json'}
        ]
        self.assertIn(u'powered', actual_response.keys())
        self.assertIn(u'test', actual_response.keys())
        self.assertEqual(expected_test_addons, actual_response['test'])
        self.assertEqual(expected_powered, actual_response['powered']) 
Example #30
Source File: test_guidelines.py    From refstack with Apache License 2.0 4 votes vote down vote up
def test_get_guideline_test_list(self):
        @httmock.all_requests
        def github_mock(url, request):
            content = {
                'schema': '1.4',
                'platform': {'required': ['compute', 'object']},
                'components': {
                    'compute': {
                        'required': ['cap-1'],
                        'advisory': [],
                        'deprecated': [],
                        'removed': []
                    },
                    'object': {
                        'required': ['cap-2'],
                        'advisory': ['cap-3'],
                        'deprecated': [],
                        'removed': []
                    }
                },
                'capabilities': {
                    'cap-1': {
                        'tests': {
                            'test_1': {'idempotent_id': 'id-1234'},
                            'test_2': {'idempotent_id': 'id-5678',
                                       'aliases': ['test_2_1']},
                            'test_3': {'idempotent_id': 'id-1111',
                                       'flagged': {'reason': 'foo'}}
                        }
                    },
                    'cap-2': {
                        'tests': {
                            'test_4': {'idempotent_id': 'id-1233'}
                        }
                    }
                }
            }
            return httmock.response(200, content, None, None, 5, request)
        url = self.URL + "2016.03/tests"
        with httmock.HTTMock(github_mock):
            actual_response = self.get_json(url, expect_errors=True)

        expected_list = ['test_1[id-1234]', 'test_2[id-5678]',
                         'test_2_1[id-5678]', 'test_3[id-1111]',
                         'test_4[id-1233]']
        expected_response = '\n'.join(expected_list)
        self.assertEqual(expected_response, actual_response.text)