Python responses.RequestsMock() Examples
The following are 30
code examples of responses.RequestsMock().
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
responses
, or try the search function
.
Example #1
Source File: test_app.py From shhh with MIT License | 6 votes |
def test_api_post_haveibeenpwned_not_reachable(self): payload = { "secret": "secret message", "passphrase": "Hello123", "haveibeenpwned": True } with self.client as c: with responses.RequestsMock() as rsps: rsps.add( responses.GET, re.compile(r"^(https:\/\/api\.pwnedpasswords\.com\/).*"), body=Exception) response = json.loads( c.post("/api/c", json=payload).get_data()) # haveibeenpwned wasn't reachable, but secret still created if it has # all mandatory requirements. r = Parse(response) self.assertEqual(r.response.status, "created")
Example #2
Source File: test_session.py From rets with MIT License | 6 votes |
def test_table_metadata(self): with open("tests/rets_responses/STANDARD-XML/GetMetadata_table.xml") as f: contents = "".join(f.readlines()) with responses.RequestsMock() as resps: resps.add( resps.POST, "http://server.rets.com/rets/GetMetadata.ashx", body=contents, status=200, ) table = self.session.get_table_metadata( resource="Property", resource_class="1" ) self.assertEqual(len(table), 162)
Example #3
Source File: test_session.py From rets with MIT License | 6 votes |
def test_lookup_type_metadata(self): with open("tests/rets_responses/STANDARD-XML/GetMetadata_lookup.xml") as f: contents = "".join(f.readlines()) with responses.RequestsMock() as resps: resps.add( resps.POST, "http://server.rets.com/rets/GetMetadata.ashx", body=contents, status=200, ) lookup_values = self.session.get_lookup_values( resource="Property", lookup_name="1_2" ) self.assertEqual(len(lookup_values), 9)
Example #4
Source File: test_rate_limiter.py From idunn with Apache License 2.0 | 6 votes |
def test_rate_limiter_without_redis(): """ Test that Idunn doesn't stop external requests when no redis has been set: 10 requests to Idunn should generate 10 requests to Wikipedia API """ client = TestClient(app) with responses.RequestsMock() as rsps: rsps.add( "GET", re.compile(r"^https://.*\.wikipedia.org/"), status=200, json={"test": "test"} ) for i in range(10): response = client.get(url=f"http://localhost/v1/pois/osm:relation:7515426?lang=es",) assert len(rsps.calls) == 10
Example #5
Source File: test_session.py From rets with MIT License | 6 votes |
def test_alternative_lookup_type_metadata(self): with open("tests/rets_responses/STANDARD-XML/GetMetadata_lookup2.xml") as f: contents = "".join(f.readlines()) with responses.RequestsMock() as resps: resps.add( resps.POST, "http://server.rets.com/rets/GetMetadata.ashx", body=contents, status=200, ) lookup_values = self.session.get_lookup_values( resource="Property", lookup_name="mls_cooling" ) self.assertEqual(len(lookup_values), 4)
Example #6
Source File: test_kuzzle.py From idunn with Apache License 2.0 | 6 votes |
def test_kuzzle_event_nok(): """ Check that an error 501 is raised when kuzzle port and address not set """ # with pytest.raises(Exception): filepath = os.path.join(os.path.dirname(__file__), "fixtures", "kuzzle_event_response.json") with open(filepath, "r") as f: json_event = json.load(f) client = TestClient(app) with responses.RequestsMock(assert_all_requests_are_fired=False) as rsps: rsps.add( "POST", re.compile(r"^http://localhost:7512/opendatasoft/events/"), status=200, json=json_event, ) response = client.get( url=f"http://localhost/v1/events?bbox=2.0667651,48.432533,2.9384989,49.0349191& ,*&size=5", ) assert response.status_code == 501
Example #7
Source File: test_directions.py From idunn with Apache License 2.0 | 6 votes |
def mock_directions_car(): with override_settings( { "QWANT_DIRECTIONS_API_BASE_URL": "http://api.qwant/directions", "MAPBOX_DIRECTIONS_ACCESS_TOKEN": None, } ): fixture_path = os.path.join( os.path.dirname(__file__), "fixtures/directions", "qwant_directions_car.json", ) with responses.RequestsMock() as rsps: rsps.add( "GET", re.compile(r"^http://api.qwant/directions/"), status=200, json=json.load(open(fixture_path)), ) yield rsps
Example #8
Source File: test_session.py From rets with MIT License | 6 votes |
def test_port_added_to_actions(self): with open("tests/rets_responses/Login_relative_url.xml") as f: contents = "".join(f.readlines()) with responses.RequestsMock() as resps: resps.add( resps.POST, "http://server.rets.com:9999/rets/Login.ashx", body=contents, status=200, ) s = Session( login_url="http://server.rets.com:9999/rets/Login.ashx", username="retsuser", version="1.5", ) s.login() for cap in s.capabilities.values(): parts = urlparse(cap) self.assertEqual(parts.port, 9999)
Example #9
Source File: test_environment_weather.py From idunn with Apache License 2.0 | 6 votes |
def test_weather_city(): """ Check result when place is a city """ filepath = os.path.join(os.path.dirname(__file__), "fixtures", "api_weather_response.json") with open(filepath, "r") as f: json_aq = json.load(f) with responses.RequestsMock() as rsps: rsps.add( "GET", re.compile(r"^http://api.openweathermap.org/data/2.5/"), status=200, json=json_aq ) res = Weather.from_es(Admin(testee), lang="en") assert res == Weather(**{"temperature": 291.89, "icon": "01d",})
Example #10
Source File: test_session.py From rets with MIT License | 6 votes |
def test_table_metadata(self): with open("tests/rets_responses/COMPACT-DECODED/GetMetadata_table.xml") as f: contents = "".join(f.readlines()) with responses.RequestsMock() as resps: resps.add( resps.POST, "http://server.rets.com/rets/GetMetadata.ashx", body=contents, status=200, ) table = self.session.get_table_metadata( resource="Property", resource_class="RES" ) self.assertEqual(len(list(table)), 208)
Example #11
Source File: test_live.py From instagram_private_api_extensions with MIT License | 6 votes |
def test_downloader_conn_error(self): exception = ConnectionError() with responses.RequestsMock(assert_all_requests_are_fired=True) as rsps: max_retry = 3 for _ in range(max_retry + 1): rsps.add(responses.GET, self.TEST_MPD_URL, body=exception) dl = live.Downloader( mpd=self.TEST_MPD_URL, output_dir='output_connerror', duplicate_etag_retry=2, singlethreaded=True, max_connection_error_retry=max_retry) dl.run() dl.stream_id = '17875351285037717' output_file = 'output_connerror.mp4' dl.stitch(output_file, cleartempfiles=True) self.assertFalse(os.path.isfile(output_file), '{0!s} not generated'.format(output_file))
Example #12
Source File: test_session.py From rets with MIT License | 6 votes |
def test_cache_metadata(self): with open("tests/rets_responses/COMPACT-DECODED/GetMetadata_table.xml") as f: contents = "".join(f.readlines()) with responses.RequestsMock() as resps: resps.add( resps.POST, "http://server.rets.com/rets/GetMetadata.ashx", body=contents, status=200, ) self.session.get_table_metadata(resource="Property", resource_class="RES") self.assertIn( "METADATA-TABLE:Property:RES", list(self.session.metadata_responses.keys()) ) # Subsequent call without RequestMock should fail unless we get the saved response from metadata_responses table = self.session.get_table_metadata( resource="Property", resource_class="RES" ) self.assertEqual(len(list(table)), 208)
Example #13
Source File: test_session.py From rets with MIT License | 6 votes |
def test_change_parser_automatically(self): self.assertEqual(self.session.metadata_format, "COMPACT-DECODED") with open("tests/rets_responses/Errors/20514.xml") as f: dtd_error = "".join(f.readlines()) with open("tests/rets_responses/STANDARD-XML/GetMetadata_system.xml") as f: content = "".join(f.readlines()) with responses.RequestsMock() as resps: resps.add( resps.POST, "http://server.rets.com/rets/GetMetadata.ashx", body=dtd_error, status=200, ) resps.add( resps.POST, "http://server.rets.com/rets/GetMetadata.ashx", body=content, status=200, ) self.session.get_system_metadata() self.assertEqual(self.session.metadata_format, "STANDARD-XML")
Example #14
Source File: test_stripe.py From zulip with Apache License 2.0 | 6 votes |
def generate_and_save_stripe_fixture(decorated_function_name: str, mocked_function_name: str, mocked_function: CallableT) -> Callable[[Any, Any], Any]: # nocoverage def _generate_and_save_stripe_fixture(*args: Any, **kwargs: Any) -> Any: # Note that mock is not the same as mocked_function, even though their # definitions look the same mock = operator.attrgetter(mocked_function_name)(sys.modules[__name__]) fixture_path = stripe_fixture_path(decorated_function_name, mocked_function_name, mock.call_count) try: with responses.RequestsMock() as request_mock: request_mock.add_passthru("https://api.stripe.com") # Talk to Stripe stripe_object = mocked_function(*args, **kwargs) except stripe.error.StripeError as e: with open(fixture_path, 'w') as f: error_dict = e.__dict__ error_dict["headers"] = dict(error_dict["headers"]) f.write(json.dumps(error_dict, indent=2, separators=(',', ': '), sort_keys=True) + "\n") raise e with open(fixture_path, 'w') as f: if stripe_object is not None: f.write(str(stripe_object) + "\n") else: f.write("{}\n") return stripe_object return _generate_and_save_stripe_fixture
Example #15
Source File: test_session.py From rets with MIT License | 6 votes |
def test_wildcard_lookups(self): with open("tests/rets_responses/STANDARD-XML/GetMetadata_wildcard.xml") as f: contents = "".join(f.readlines()) with responses.RequestsMock() as resps: resps.add( resps.POST, "http://server.rets.com/rets/GetMetadata.ashx", body=contents, status=200, ) format_hold = self.session.metadata_format try: self.session.metadata_format = "STANDARD-XML" lookup_values = self.session.get_lookup_values( resource="Property", lookup_name="*" ) finally: self.session.metadata_format = format_hold self.assertEqual(len(lookup_values), 40)
Example #16
Source File: test_session.py From rets with MIT License | 6 votes |
def setUp(self): super(Session15Tester, self).setUp() with open("tests/rets_responses/Login.xml") as f: contents = "".join(f.readlines()) with responses.RequestsMock() as resps: resps.add( resps.POST, "http://server.rets.com/rets/Login.ashx", body=contents, status=200, ) self.session = Session( login_url="http://server.rets.com/rets/Login.ashx", username="retsuser", version="1.5", ) self.session.metadata_format = "STANDARD-XML" self.session.login()
Example #17
Source File: test_wiki_ES.py From idunn with Apache License 2.0 | 6 votes |
def test_no_lang_WIKI_ES(): """ Test that when we don't have the lang available in the index we call Wikipedia API """ client = TestClient(app) with responses.RequestsMock(assert_all_requests_are_fired=False) as rsps: rsps.add( "GET", re.compile(r"^https://.*\.wikipedia.org/"), status=200, json={"test": "test"} ) """ We make a request in russian language ("ru") """ response = client.get(url=f"http://localhost/v1/pois/osm:way:7777777?lang=ru",) assert len(rsps.calls) == 1
Example #18
Source File: test_session.py From rets with MIT License | 6 votes |
def test_system_metadata(self): with open("tests/rets_responses/COMPACT-DECODED/GetMetadata_system.xml") as f: contents = "".join(f.readlines()) with responses.RequestsMock() as resps: resps.add( resps.POST, "http://server.rets.com/rets/GetMetadata.ashx", body=contents, status=200, ) sys_metadata = self.session.get_system_metadata() self.assertEqual(sys_metadata["version"], "1.11.76001") self.assertEqual(sys_metadata["system_id"], "MLS-RETS")
Example #19
Source File: test_session.py From rets with MIT License | 6 votes |
def setUp(self): super(SessionTester, self).setUp() with open("tests/rets_responses/Login.xml") as f: contents = "".join(f.readlines()) with responses.RequestsMock() as resps: resps.add( resps.POST, "http://server.rets.com/rets/Login.ashx", body=contents, status=200, headers={"Set-Cookie": "ASP.NET_SessionId=zacqcc1gjhkmazjznjmyrinq;"}, ) self.session = Session( login_url="http://server.rets.com/rets/Login.ashx", username="retsuser", version="RETS/1.7.2", session_id_cookie_name="ASP.NET_SessionId", ) self.session.login()
Example #20
Source File: conftest.py From renku-python with Apache License 2.0 | 6 votes |
def dataset_responses(): """Authentication responses.""" with responses.RequestsMock(assert_all_requests_are_fired=False) as rsps: def request_callback(request): return (200, {'Content-Type': 'application/text'}, '1234') rsps.add_callback( responses.GET, 'http://example.com/file', callback=request_callback ) rsps.add_callback( responses.GET, 'https://example.com/file', callback=request_callback ) rsps.add_callback( responses.GET, 'http://example.com/file.ext?foo=bar', callback=request_callback ) yield rsps
Example #21
Source File: test_page.py From fbmq with MIT License | 5 votes |
def __init__(self, subpath, expected=None, method=None, utest=None, api_ver=None): self.subpath = subpath self.expected = None self.method = method if method else self.POST self.utest = utest self.set_expected(expected=expected) self.req_mock = responses.RequestsMock() self.api_ver = api_ver if api_ver else 'v2.6'
Example #22
Source File: test_web.py From CloudBot with GNU General Public License v3.0 | 5 votes |
def mock_requests(): with RequestsMock() as reqs: yield reqs
Example #23
Source File: test_newrelic.py From opencraft with GNU Affero General Public License v3.0 | 5 votes |
def test_delete_email_notification_channel(self): """ Check that the delete_email_notification_channel function behaves correctly if DELETE request unsuccessful. We expect the function *not* to raise an exception if the notification channel to delete can not be found (i.e., if the DELETE request comes back with a 404). In all other cases the function should raise an exception. """ channel_id = 1 client_errors = [status_code for status_code in requests.status_codes._codes if 400 <= status_code < 500] server_errors = [status_code for status_code in requests.status_codes._codes if 500 <= status_code < 600] for error in client_errors + server_errors: with responses.RequestsMock() as mock_responses: mock_responses.add( responses.DELETE, '{}/{}.json'.format(newrelic.ALERTS_CHANNELS_API_URL, channel_id), status=error ) try: newrelic.delete_email_notification_channel(channel_id) except requests.exceptions.HTTPError: if error == requests.codes.not_found: self.fail('Should not raise an exception for {} response.'.format(error)) else: if not error == requests.codes.not_found: self.fail('Should raise an exception for {} response.'.format(error))
Example #24
Source File: test_session.py From rets with MIT License | 5 votes |
def test_object_metadata(self): with open("tests/rets_responses/COMPACT-DECODED/GetMetadata_objects.xml") as f: contents = "".join(f.readlines()) with responses.RequestsMock() as resps: resps.add( resps.POST, "http://server.rets.com/rets/GetMetadata.ashx", body=contents, status=200, ) object_metadata = self.session.get_object_metadata(resource="Agent") self.assertEqual(len(list(object_metadata)), 3)
Example #25
Source File: test_session.py From rets with MIT License | 5 votes |
def test_auto_offset(self): with open("tests/rets_responses/COMPACT-DECODED/Search_1of2.xml") as f: search1_contents = "".join(f.readlines()) with open("tests/rets_responses/COMPACT-DECODED/Search_2of2.xml") as f: search2_contents = "".join(f.readlines()) with responses.RequestsMock() as resps: resps.add( resps.POST, "http://server.rets.com/rets/Search.ashx", body=search1_contents, status=200, stream=True, ) resps.add( resps.POST, "http://server.rets.com/rets/Search.ashx", body=search2_contents, status=200, stream=True, ) results_gen = self.session.search( resource="Property", resource_class="RES", search_filter={"ListingPrice": 200000}, ) results = list(results_gen) self.assertEqual(len(results), 6)
Example #26
Source File: test_session.py From rets with MIT License | 5 votes |
def test_class_metadata(self): with open("tests/rets_responses/COMPACT-DECODED/GetMetadata_classes.xml") as f: contents = "".join(f.readlines()) with open( "tests/rets_responses/COMPACT-DECODED/GetMetadata_classes_single.xml" ) as f: single_contents = "".join(f.readlines()) with responses.RequestsMock() as resps: resps.add( resps.POST, "http://server.rets.com/rets/GetMetadata.ashx", body=contents, status=200, ) resource_classes = self.session.get_class_metadata(resource="Agent") self.assertEqual(len(list(resource_classes)), 6) resps.add( resps.POST, "http://server.rets.com/rets/GetMetadata.ashx", body=single_contents, status=200, ) resource_classes_single = self.session.get_class_metadata( resource="Property" ) self.assertEqual(len(list(resource_classes_single)), 1)
Example #27
Source File: test_session.py From rets with MIT License | 5 votes |
def test_preferred_object(self): with open("tests/rets_responses/GetObject_multipart.byte", "rb") as f: multiple = f.read() multi_headers = { "Content-Type": 'multipart/parallel; boundary="24cbd0e0afd2589bb9dcb1f34cf19862"; charset=utf-8', "Connection": "keep-alive", "RETS-Version": "RETS/1.7.2", "MIME-Version": "1.0, 1.0", } with responses.RequestsMock() as resps: resps.add( resps.POST, "http://server.rets.com/rets/GetObject.ashx", body=multiple, status=200, headers=multi_headers, ) obj = self.session.get_preferred_object( resource="Property", object_type="Photo", content_id=1 ) self.assertTrue(obj) resps.add( resps.POST, "http://server.rets.com/rets/GetObject.ashx", body=multiple, status=200, ) resource = dict() resource["ResourceID"] = "Agent" obj1 = self.session.get_preferred_object( resource=resource, object_type="Photo", content_id=1 ) self.assertTrue(obj1)
Example #28
Source File: test_session.py From rets with MIT License | 5 votes |
def test_resource_metadata(self): with open( "tests/rets_responses/COMPACT-DECODED/GetMetadata_resources.xml" ) as f: contents = "".join(f.readlines()) with responses.RequestsMock() as resps: resps.add( resps.POST, "http://server.rets.com/rets/GetMetadata.ashx", body=contents, status=200, ) resource = self.session.get_resource_metadata() self.assertEqual(len(list(resource)), 6)
Example #29
Source File: test_session.py From rets with MIT License | 5 votes |
def test_logout(self): with open("tests/rets_responses/Logout.html") as f: contents = "".join(f.readlines()) with responses.RequestsMock() as resps: resps.add( resps.POST, "http://server.rets.com/rets/Logout.ashx", body=contents, status=200, ) self.assertTrue(self.session.logout())
Example #30
Source File: test_openedx_database_mixins.py From opencraft with GNU Affero General Public License v3.0 | 5 votes |
def test_rabbitmq_api_error(self, mock_consul): """ Test that RabbitMQAPIError is thrown during auth issues """ with responses.RequestsMock() as rsps: # Emulate 401 Unauthorized rsps.add( responses.GET, '{}/api/overview'.format(self.instance.rabbitmq_server.api_url), content_type='application/json', body='{}', status=401 ) with self.assertRaises(RabbitMQAPIError): self.instance._rabbitmq_request('get', 'overview')