def test_500_error(self): httpretty.register_uri(httpretty.GET, self.base_uri + "country/" + "1.2.3.10", status=500) with self.assertRaisesRegex(HTTPError, r"Received a server error \(500\) for"): self.run_client(self.client.country("1.2.3.10"))
def test_request(self): httpretty.register_uri( httpretty.GET, self.base_uri + "country/" + "1.2.3.4", body=json.dumps(self.country), status=200, content_type=self._content_type("country"), ) self.run_client(self.client.country("1.2.3.4")) request = httpretty.last_request self.assertEqual(request.path, "/geoip/v2.1/country/1.2.3.4", "correct URI is used") self.assertEqual(request.headers["Accept"], "application/json", "correct Accept header") self.assertRegex( request.headers["User-Agent"], "^GeoIP2-Python-Client/", "Correct User-Agent", ) self.assertEqual( request.headers["Authorization"], "Basic NDI6YWJjZGVmMTIzNDU2", "correct auth", )
def test_rotating_responses_with_requests(): """HTTPretty should support rotating responses with requests""" HTTPretty.register_uri(HTTPretty.GET, "https://api.yahoo.com/test", responses=[ HTTPretty.Response(body=b"first response", status=201), HTTPretty.Response( body=b'second and last response', status=202), ]) response1 = requests.get('https://api.yahoo.com/test') expect(response1.status_code).to.equal(201) expect(response1.text).to.equal('first response') response2 = requests.get('https://api.yahoo.com/test') expect(response2.status_code).to.equal(202) expect(response2.text).to.equal('second and last response') response3 = requests.get('https://api.yahoo.com/test') expect(response3.status_code).to.equal(202) expect(response3.text).to.equal('second and last response')
def test_unicode_querystrings(): """Querystrings should accept unicode characters""" HTTPretty.register_uri(HTTPretty.GET, "http://yipit.com/login", body="Find the best daily deals") requests.get('http://yipit.com/login?user=Gabriel+Falcão') expect(HTTPretty.last_request.querystring['user'][0]).should.be.equal( 'Gabriel Falcão')
def test_httpretty_should_allow_multiple_methods_for_the_same_uri(): """HTTPretty should allow registering multiple methods for the same uri""" url = "http://test.com/test" methods = ["GET", "POST", "PUT", "OPTIONS"] for method in methods: HTTPretty.register_uri(getattr(HTTPretty, method), url, method) for method in methods: request_action = getattr(requests, method.lower()) expect(request_action(url).text).to.equal(method)
def test_httpretty_ignores_querystrings_from_registered_uri(): """HTTPretty should ignore querystrings from the registered uri (requests library)""" HTTPretty.register_uri(HTTPretty.GET, "http://yipit.com/?id=123", body=b"Find the best daily deals") response = requests.get("http://yipit.com/", params={"id": 123}) expect(response.text).to.equal("Find the best daily deals") expect(HTTPretty.last_request.method).to.equal("GET") expect(HTTPretty.last_request.path).to.equal("/?id=123")
def test_no_body_error(self): httpretty.register_uri( httpretty.GET, self.base_uri + "country/" + "1.2.3.7", body="", status=400, content_type=self._content_type("country"), ) with self.assertRaisesRegex( HTTPError, "Received a 400 error for .* with no body"): self.run_client(self.client.country("1.2.3.7"))
def test_200_error(self): httpretty.register_uri( httpretty.GET, self.base_uri + "country/1.1.1.1", body="", status=200, content_type=self._content_type("country"), ) with self.assertRaisesRegex(GeoIP2Error, "could not decode the response as JSON"): self.run_client(self.client.country("1.1.1.1"))
def test_httpretty_provides_easy_access_to_querystrings(): """HTTPretty should provide an easy access to the querystring""" HTTPretty.register_uri(HTTPretty.GET, "http://yipit.com/", body="Find the best daily deals") requests.get("http://yipit.com/?foo=bar&foo=baz&chuck=norris") expect(HTTPretty.last_request.querystring).to.equal({ "foo": ["bar", "baz"], "chuck": ["norris"], })
def test_httpretty_should_mock_a_simple_get_with_requests_read(): """HTTPretty should mock a simple GET with requests.get""" HTTPretty.register_uri(HTTPretty.GET, "http://yipit.com/", body="Find the best daily deals") response = requests.get('http://yipit.com') expect(response.text).to.equal('Find the best daily deals') expect(HTTPretty.last_request.method).to.equal('GET') expect(HTTPretty.last_request.path).to.equal('/')
def test_bad_body_error(self): httpretty.register_uri( httpretty.GET, self.base_uri + "country/" + "1.2.3.9", body="bad body", status=400, content_type=self._content_type("country"), ) with self.assertRaisesRegex( HTTPError, "it did not include the expected JSON body"): self.run_client(self.client.country("1.2.3.9"))
async def test_invalid_data(generic_client, api_url): with Mocketizer(): HTTPretty.register_uri( HTTPretty.GET, api_url + '/users', body='[not json]', content_type='application/json', ) with pytest.raises(ValueError) as excinfo: await generic_client.users.all() assert '[not json]' in str(excinfo.value)
def test_httpretty_provides_easy_access_to_querystrings(): """HTTPretty should provide an easy access to the querystring""" HTTPretty.register_uri(HTTPretty.GET, "http://yipit.com/", body="Find the best daily deals") requests.get('http://yipit.com/?foo=bar&foo=baz&chuck=norris') expect(HTTPretty.last_request.querystring).to.equal({ 'foo': ['bar', 'baz'], 'chuck': ['norris'], })
def test_300_error(self): httpretty.register_uri( httpretty.GET, self.base_uri + "country/" + "1.2.3.11", status=300, content_type=self._content_type("country"), ) with self.assertRaisesRegex( HTTPError, r"Received a very surprising HTTP status \(300\) for"): self.run_client(self.client.country("1.2.3.11"))
def _test_error(self, status, error_code, error_class): msg = "Some error message" body = {"error": msg, "code": error_code} httpretty.register_uri( httpretty.GET, self.base_uri + "country/1.2.3.18", body=json.dumps(body), status=status, content_type=self._content_type("country"), ) with self.assertRaisesRegex(error_class, msg): self.run_client(self.client.country("1.2.3.18"))
def test_city_ok(self): httpretty.register_uri( httpretty.GET, self.base_uri + "city/" + "1.2.3.4", body=json.dumps(self.country), status=200, content_type=self._content_type("city"), ) city = self.run_client(self.client.city("1.2.3.4")) self.assertEqual(type(city), geoip2.models.City, "return value of client.city") self.assertEqual(city.traits.network, ipaddress.ip_network("1.2.3.0/24"), "network")
def test_unknown_error(self): msg = "Unknown error type" ip = "1.2.3.19" body = {"error": msg, "code": "UNKNOWN_TYPE"} httpretty.register_uri( httpretty.GET, self.base_uri + "country/" + ip, body=json.dumps(body), status=400, content_type=self._content_type("country"), ) with self.assertRaisesRegex(InvalidRequestError, msg): self.run_client(self.client.country(ip))
async def test_httprettish_session(self): url = "https://httpbin.org/ip" HTTPretty.register_uri( HTTPretty.GET, url, body=json.dumps(dict(origin="127.0.0.1")), ) async with aiohttp.ClientSession() as session: with async_timeout.timeout(3): async with session.get(url) as get_response: assert get_response.status == 200 assert await get_response.text( ) == '{"origin": "127.0.0.1"}'
def test_httpretty_should_allow_multiple_responses_with_multiple_methods(): """HTTPretty should allow multiple responses when binding multiple methods to the same uri""" url = "http://test.com/list" # add get responses HTTPretty.register_uri( HTTPretty.GET, url, responses=[HTTPretty.Response(body="a"), HTTPretty.Response(body="b")], ) # add post responses HTTPretty.register_uri( HTTPretty.POST, url, responses=[HTTPretty.Response(body="c"), HTTPretty.Response(body="d")], ) expect(requests.get(url).text).to.equal("a") expect(requests.post(url).text).to.equal("c") expect(requests.get(url).text).to.equal("b") expect(requests.get(url).text).to.equal("b") expect(requests.get(url).text).to.equal("b") expect(requests.post(url).text).to.equal("d") expect(requests.post(url).text).to.equal("d") expect(requests.post(url).text).to.equal("d")
def test_weird_body_error(self): httpretty.register_uri( httpretty.GET, self.base_uri + "country/" + "1.2.3.8", body='{"wierd": 42}', status=400, content_type=self._content_type("country"), ) with self.assertRaisesRegex( HTTPError, "Response contains JSON but it does not " "specify code or error keys", ): self.run_client(self.client.country("1.2.3.8"))
def test_httpretty_should_allow_multiple_responses_with_multiple_methods(): """HTTPretty should allow multiple responses when binding multiple methods to the same uri""" url = 'http://test.com/list' #add get responses HTTPretty.register_uri( HTTPretty.GET, url, responses=[HTTPretty.Response(body='a'), HTTPretty.Response(body='b')]) #add post responses HTTPretty.register_uri( HTTPretty.POST, url, responses=[HTTPretty.Response(body='c'), HTTPretty.Response(body='d')]) expect(requests.get(url).text).to.equal('a') expect(requests.post(url).text).to.equal('c') expect(requests.get(url).text).to.equal('b') expect(requests.get(url).text).to.equal('b') expect(requests.get(url).text).to.equal('b') expect(requests.post(url).text).to.equal('d') expect(requests.post(url).text).to.equal('d') expect(requests.post(url).text).to.equal('d')
def test_insights_ok(self): httpretty.register_uri( httpretty.GET, self.base_uri + "insights/1.2.3.4", body=json.dumps(self.insights), status=200, content_type=self._content_type("country"), ) insights = self.run_client(self.client.insights("1.2.3.4")) self.assertEqual(type(insights), geoip2.models.Insights, "return value of client.insights") self.assertEqual(insights.traits.network, ipaddress.ip_network("1.2.3.0/24"), "network") self.assertEqual(insights.traits.static_ip_score, 1.3, "static_ip_score is 1.3") self.assertEqual(insights.traits.user_count, 2, "user_count is 2")
def test_httpretty_should_allow_forcing_headers_requests(): """HTTPretty should allow forcing headers with requests""" HTTPretty.register_uri(HTTPretty.GET, "http://github.com/foo", body="<root><baz /</root>", forcing_headers={ 'Content-Type': 'application/xml', 'Content-Length': '19', }) response = requests.get('http://github.com/foo') expect(dict(response.headers)).to.equal({ 'content-type': 'application/xml', 'content-length': '19', })
def test_me(self): httpretty.register_uri( httpretty.GET, self.base_uri + "country/me", body=json.dumps(self.country), status=200, content_type=self._content_type("country"), ) implicit_me = self.run_client(self.client.country()) self.assertEqual(type(implicit_me), geoip2.models.Country, "country() returns Country object") explicit_me = self.run_client(self.client.country()) self.assertEqual( type(explicit_me), geoip2.models.Country, "country('me') returns Country object", )
def test_httprettish_session(self): url = 'https://httpbin.org/ip' HTTPretty.register_uri( HTTPretty.GET, url, body=json.dumps(dict(origin='127.0.0.1')), ) async def main(l): async with aiohttp.ClientSession(loop=l) as session: with async_timeout.timeout(3): async with session.get(url) as get_response: assert get_response.status == 200 assert await get_response.text() == '{"origin": "127.0.0.1"}' loop = asyncio.get_event_loop() loop.set_debug(True) loop.run_until_complete(main(loop))
def create_error(self, status_code=400, text="", content_type=None): uri = "/".join([self.base_uri, "transactions", "report"] if self. type == "report" else [self.base_uri, self.type]) if content_type is None: content_type = ( "application/json" if self.type == "report" else "application/vnd.maxmind.com-error+json; charset=UTF-8; version=2.0" ) httpretty.register_uri( httpretty.POST, uri=uri, status=status_code, body=text, content_type=content_type, ) return self.run_client( getattr(self.client, self.type)(self.full_request))
def fn(method, url, json=None, **kwargs): if json is not None: body = jsonlib.dumps(json) else: body = '' kwargs.setdefault('content-type', 'application/json') kwargs.setdefault('match_querystring', True) return HTTPretty.register_uri(method, simpl_url + url, body, **kwargs)
def test_httpretty_should_allow_forcing_headers_requests(): """HTTPretty should allow forcing headers with requests""" HTTPretty.register_uri( HTTPretty.GET, "http://github.com/foo", body="<root><baz /</root>", forcing_headers={ "Content-Type": "application/xml", "Content-Length": "19", }, ) response = requests.get("http://github.com/foo") expect(dict(response.headers)).to.equal({ "content-type": "application/xml", "content-length": "19", })
def create_success(self, text=None, client=None, request=None): uri = "/".join([self.base_uri, "transactions", "report"] if self. type == "report" else [self.base_uri, self.type]) httpretty.register_uri( httpretty.POST, uri=uri, status=204 if self.type == "report" else 200, body=self.response if text is None else text, content_type= "application/vnd.maxmind.com-minfraud-{0}+json; charset=UTF-8; version=2.0" .format(self.type), ) if client is None: client = self.client if request is None: request = self.full_request print(client) return self.run_client(getattr(client, self.type)(request))
def test_httpretty_should_mock_headers_requests(): """HTTPretty should mock basic headers with requests""" HTTPretty.register_uri(HTTPretty.GET, "http://github.com/", body="this is supposed to be the response", status=201) response = requests.get('http://github.com') expect(response.status_code).to.equal(201) expect(dict(response.headers)).to.equal({ 'content-type': 'text/plain; charset=utf-8', 'connection': 'close', 'content-length': '35', 'status': '201', 'server': 'Python/HTTPretty', 'date': response.headers['date'], })