def __init__(self): """ Constructor """ self.api_endpoint = current_app.config['FEEDBACK_SLACK_END_POINT'] def request_callback(request, uri, headers): """ Callback :param request: HTTP request :param uri: URI/URL to send the request :param headers: header of the HTTP request :return: httpretty response """ if 'text' in request.body: resp = json.dumps(dict( msg='success' )) return 200, headers, resp else: resp = json.dumps(dict( msg='fail' )) return 400, headers, resp HTTPretty.register_uri( method=HTTPretty.POST, uri=self.api_endpoint, body=request_callback, content_type="application/json" )
def test_httpretty_should_work_with_non_standard_ports(): "HTTPretty should work with a non-standard port number" HTTPretty.register_uri( HTTPretty.GET, re.compile("https://api.yipit.com:1234/v1/deal;brand=(?P<brand_name>\w+)"), body=lambda method, uri, headers: [200, headers, uri] ) HTTPretty.register_uri( HTTPretty.POST, "https://asdf.com:666/meow", body=lambda method, uri, headers: [200, headers, uri] ) response = requests.get('https://api.yipit.com:1234/v1/deal;brand=gap?first_name=chuck&last_name=norris') expect(response.text).to.equal('https://api.yipit.com:1234/v1/deal;brand=gap?first_name=chuck&last_name=norris') expect(HTTPretty.last_request.method).to.equal('GET') expect(HTTPretty.last_request.path).to.equal('/v1/deal;brand=gap?first_name=chuck&last_name=norris') response = requests.post('https://asdf.com:666/meow') expect(response.text).to.equal('https://asdf.com:666/meow') expect(HTTPretty.last_request.method).to.equal('POST') expect(HTTPretty.last_request.path).to.equal('/meow')
def test_new_from_url(self): HTTPretty.register_uri(HTTPretty.GET, 'http://example.com/', body='snerble') webpage = WebPage.new_from_url('http://example.com/') self.assertEquals(webpage.html, 'snerble')
def test_second_authentication_step_takes_code_and_makes_a_request(context): "github.API's second authentication step is a redirect" class MyStore(github.TokenStore): data = {} def set(self, k, v): self.data[k] = v def get(self, k): return self.data.get(k) simple = MyStore() api = github.API("app-id-here", "app-secret-here", store=simple) HTTPretty.register_uri( HTTPretty.POST, "https://github.com/login/oauth/access_token", body='{"access_token": "this-is-the-access-token"}', status=200, ) result = api.authenticate(code="visitor-code") assert that(result).is_a(github.API) last_request = HTTPretty.last_request assert that(last_request.headers).has("Authentication")
def test_fake_socket_passes_through_gettimeout(): import socket HTTPretty.enable() s = socket.socket(socket.AF_INET, socket.SOCK_STREAM) s.truesock = MagicMock() expect(s.gettimeout).called_with().should_not.throw(AttributeError) s.truesock.gettimeout.assert_called_with()
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_posts_with_type_and_arg(self): HTTPretty.register_uri(HTTPretty.GET, 'https://api.tumblr.com/v2/blog/seejohnrun.tumblr.com/posts/photo?limit=1', body='{"meta": {"status": 200, "msg": "OK"}, "response": {"posts": [] } }') args = { 'limit': 1 } response = self.client.posts('seejohnrun', 'photo', **args) assert response['posts'] == []
def test_callback_response(now): ("HTTPretty should call a callback function and set its return value as the body of the response" " requests") def request_callback(request, uri, headers): return [200, headers, "The {} response from {}".format(decode_utf8(request.method), uri)] HTTPretty.register_uri( HTTPretty.GET, "https://api.yahoo.com/test", body=request_callback) response = requests.get('https://api.yahoo.com/test') expect(response.text).to.equal("The GET response from https://api.yahoo.com/test") HTTPretty.register_uri( HTTPretty.POST, "https://api.yahoo.com/test_post", body=request_callback) response = requests.post( "https://api.yahoo.com/test_post", {"username": "******"} ) expect(response.text).to.equal("The POST response from https://api.yahoo.com/test_post")
def test_httpretty_should_allow_adding_and_overwritting_by_kwargs_u2(now): u"HTTPretty should allow adding and overwritting headers by keyword args " \ "with httplib2" HTTPretty.register_uri(HTTPretty.GET, "http://github.com/foo", body="this is supposed to be the response", server='Apache', content_length='27', content_type='application/json') headers, _ = httplib2.Http().request('http://github.com/foo', 'GET') expect(dict(headers)).to.equal({ 'content-type': 'application/json', 'content-location': 'http://github.com/foo', # httplib2 FORCES # content-location # even if the # server does not # provide it 'connection': 'close', 'content-length': '27', 'status': '200', 'server': 'Apache', 'date': now.strftime('%a, %d %b %Y %H:%M:%S GMT'), })
def test_can_inspect_last_request(now): "HTTPretty.last_request is a mimetools.Message request from last match" HTTPretty.register_uri(HTTPretty.POST, "http://api.github.com/", body='{"repositories": ["HTTPretty", "lettuce"]}') request = urllib2.Request( 'http://api.github.com', b'{"username": "******"}', { 'content-type': 'text/json', }, ) fd = urlopen(request) got = fd.read() fd.close() expect(HTTPretty.last_request.method).to.equal('POST') expect(HTTPretty.last_request.body).to.equal( b'{"username": "******"}', ) expect(HTTPretty.last_request.headers['content-type']).to.equal( 'text/json', ) expect(got).to.equal(b'{"repositories": ["HTTPretty", "lettuce"]}')
def test_methods(self): client = Hammock(self.BASE_URL) for method in ['GET', 'POST', 'PUT', 'DELETE', 'PATCH']: HTTPretty.register_uri(getattr(HTTPretty, method), self.URL) request = getattr(client, method) resp = request('sample', 'path', 'to', 'resource') self.assertEqual(HTTPretty.last_request.method, method)
def test_rotating_responses_with_requests(now): "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_httpretty_should_allow_registering_regexes_with_streaming_responses(): "HTTPretty should allow registering regexes with streaming responses" import os os.environ['DEBUG'] = 'true' def my_callback(request, url, headers): request.body.should.equal(b'hithere') return 200, headers, "Received" HTTPretty.register_uri( HTTPretty.POST, re.compile("https://api.yipit.com/v1/deal;brand=(?P<brand_name>\w+)"), body=my_callback, ) def gen(): yield b'hi' yield b'there' response = requests.post( 'https://api.yipit.com/v1/deal;brand=gap?first_name=chuck&last_name=norris', data=gen(), ) expect(response.content).to.equal(b"Received") expect(HTTPretty.last_request.method).to.equal('POST') expect(HTTPretty.last_request.path).to.equal('/v1/deal;brand=gap?first_name=chuck&last_name=norris')
def _mock_fetch_uris(endpoint, resource_uri): raw_values = _get_raw_values() values = iter(raw_values) rest = islice(values, 20) rest_data = list(rest) offset = 0 while rest_data: if offset == 0: # Match every request without "offset" in it. regexp_txt = "(?!.*offset)" else: regexp_txt = ".*&offset=%d.*" % offset regexp = re.compile(endpoint + regexp_txt) offset += 20 if offset == 80: next_uri = None else: query = '/?limit=20&key=install&offset=%d' next_uri = resource_uri + query % offset HTTPretty.register_uri( HTTPretty.GET, regexp, body=json_dumps({'meta': {"limit": 20, "next": next_uri, "offset": 0, "previous": None, "total_count": len(raw_values)}, 'objects': rest_data})) rest = islice(values, 20) rest_data = list(rest)
def test_recording_calls(port): ("HTTPretty should be able to record calls") # Given a destination path: destination = FIXTURE_FILE("recording-1.json") # When I record some calls with HTTPretty.record(destination): requests.get(server_url("/foobar?name=Gabriel&age=25", port)) requests.post(server_url("/foobar", port), data=json.dumps({'test': '123'}), headers={"Test": "foobar"}) # Then the destination path should exist os.path.exists(destination).should.be.true # And the contents should be json raw = open(destination).read() json.loads.when.called_with(raw).should_not.throw(ValueError) # And the contents should be expected data = json.loads(raw) data.should.be.a(list) data.should.have.length_of(2) # And the responses should have the expected keys response = data[0] response.should.have.key("request").being.length_of(5) response.should.have.key("response").being.length_of(3) response['request'].should.have.key("method").being.equal("GET") response['request'].should.have.key("headers").being.a(dict) response['request'].should.have.key("querystring").being.equal({ "age": [ "25" ], "name": [ "Gabriel" ] }) response['response'].should.have.key("status").being.equal(200) response['response'].should.have.key("body").being.an(text_type) response['response'].should.have.key("headers").being.a(dict) response['response']["headers"].should.have.key("Server").being.equal("TornadoServer/" + tornado_version) # And When I playback the previously recorded calls with HTTPretty.playback(destination): # And make the expected requests response1 = requests.get(server_url("/foobar?name=Gabriel&age=25", port)) response2 = requests.post( server_url("/foobar", port), data=json.dumps({'test': '123'}), headers={"Test": "foobar"}, ) # Then the responses should be the expected response1.json().should.equal({"foobar": {"age": "25", "name": "Gabriel"}}) response2.json()["foobar"].should.equal({}) response2.json()["req_body"].should.equal(json.dumps({"test": "123"})) response2.json()["req_headers"].should.have.key("Test") response2.json()["req_headers"]["Test"].should.equal("foobar")
def test_rotating_responses_with_httplib2(now): u"HTTPretty should support rotating responses with httplib2" HTTPretty.register_uri( HTTPretty.GET, "https://api.yahoo.com/test", responses=[ HTTPretty.Response(body="first response", status=201), HTTPretty.Response(body='second and last response', status=202), ]) headers1, body1 = httplib2.Http().request( 'https://api.yahoo.com/test', 'GET') expect(headers1['status']).to.equal('201') expect(body1).to.equal(b'first response') headers2, body2 = httplib2.Http().request( 'https://api.yahoo.com/test', 'GET') expect(headers2['status']).to.equal('202') expect(body2).to.equal(b'second and last response') headers3, body3 = httplib2.Http().request( 'https://api.yahoo.com/test', 'GET') expect(headers3['status']).to.equal('202') expect(body3).to.equal(b'second and last response')
def tearDown(self): HTTPretty.disable() HTTPretty.reset() self.backend = None self.strategy = None self.name = None self.complete_url = None
def __init__(self, api_endpoint): """ Constructor :param api_endpoint: name of the API end point """ self.api_endpoint = api_endpoint def request_callback(request, uri, headers): """ :param request: HTTP request :param uri: URI/URL to send the request :param headers: header of the HTTP request :return: httpretty response """ resp = json.dumps( { 'api-response': 'success', 'token': request.headers.get( 'Authorization', 'No Authorization header passed!' ) } ) return 200, headers, resp HTTPretty.register_uri( HTTPretty.GET, self.api_endpoint, body=request_callback, content_type="application/json" )
def test_multi_commands(self): """Check connection re-use""" HTTPretty.register_uri(HTTPretty.POST, 'https://%s/' % self.region.endpoint, json.dumps({'test': 'secure'}), content_type='application/json') conn = self.region.connect(aws_access_key_id='access_key', aws_secret_access_key='secret') resp1 = conn.make_request('myCmd1', {'par1': 'foo', 'par2': 'baz'}, "/", "POST") body1 = urlparse.parse_qs(HTTPretty.last_request.body) resp2 = conn.make_request('myCmd2', {'par3': 'bar', 'par4': 'narf'}, "/", "POST") body2 = urlparse.parse_qs(HTTPretty.last_request.body) self.assertEqual(body1['par1'], ['foo']) self.assertEqual(body1['par2'], ['baz']) with self.assertRaises(KeyError): body1['par3'] self.assertEqual(body2['par3'], ['bar']) self.assertEqual(body2['par4'], ['narf']) with self.assertRaises(KeyError): body2['par1'] self.assertEqual(resp1.read(), '{"test": "secure"}') self.assertEqual(resp2.read(), '{"test": "secure"}')
def test_connection_close(self): """Check connection re-use after close header is received""" HTTPretty.register_uri(HTTPretty.POST, 'https://%s/' % self.region.endpoint, json.dumps({'test': 'secure'}), content_type='application/json', connection='close') conn = self.region.connect(aws_access_key_id='access_key', aws_secret_access_key='secret') def mock_put_conn(*args, **kwargs): raise Exception('put_http_connection should not be called!') conn.put_http_connection = mock_put_conn resp1 = conn.make_request('myCmd1', {'par1': 'foo', 'par2': 'baz'}, "/", "POST") # If we've gotten this far then no exception was raised # by attempting to put the connection back into the pool # Now let's just confirm the close header was actually # set or we have another problem. self.assertEqual(resp1.getheader('connection'), 'close')
def test_disconnect_with_partial_pipeline(self): self.strategy.set_settings({ 'SOCIAL_AUTH_DISCONNECT_PIPELINE': ( 'social.pipeline.partial.save_status_to_session', 'social.tests.pipeline.ask_for_password', 'social.tests.pipeline.set_password', 'social.pipeline.disconnect.allowed_to_disconnect', 'social.pipeline.disconnect.get_entries', 'social.pipeline.disconnect.revoke_tokens', 'social.pipeline.disconnect.disconnect' ) }) self.do_login() user = User.get(self.expected_username) redirect = do_disconnect(self.backend, user) url = self.strategy.build_absolute_uri('/password') expect(redirect.url).to.equal(url) HTTPretty.register_uri(HTTPretty.GET, redirect.url, status=200, body='foobar') HTTPretty.register_uri(HTTPretty.POST, redirect.url, status=200) password = '******' requests.get(url) requests.post(url, data={'password': password}) data = parse_qs(HTTPretty.last_request.body) expect(data['password']).to.equal(password) self.strategy.session_set('password', data['password']) redirect = do_disconnect(self.backend, user) expect(len(user.social)).to.equal(0)
def render(self, template, json_mocks): if type(json_mocks) is not list: json_mocks = [json_mocks] responses = [HTTPretty.Response(get_json(_)) for _ in json_mocks] HTTPretty.register_uri(HTTPretty.GET, self.api_url, responses=responses, content_type='application/json') return render_template(template=template)
def test_callback_setting_headers_and_status_response(now): ("HTTPretty should call a callback function and uses it retur tuple as status code, headers and body" " requests") def request_callback(request, uri, headers): headers.update({'a': 'b'}) return [418, headers, "The {} response from {}".format(decode_utf8(request.method), uri)] HTTPretty.register_uri( HTTPretty.GET, "https://api.yahoo.com/test", body=request_callback) response = requests.get('https://api.yahoo.com/test') expect(response.text).to.equal("The GET response from https://api.yahoo.com/test") expect(response.headers).to.have.key('a').being.equal("b") expect(response.status_code).to.equal(418) HTTPretty.register_uri( HTTPretty.POST, "https://api.yahoo.com/test_post", body=request_callback) response = requests.post( "https://api.yahoo.com/test_post", {"username": "******"} ) expect(response.text).to.equal("The POST response from https://api.yahoo.com/test_post") expect(response.headers).to.have.key('a').being.equal("b") expect(response.status_code).to.equal(418)
def test_can_inspect_last_request_with_ssl(now): "HTTPretty.last_request is recorded even when mocking 'https' (SSL)" HTTPretty.register_uri(HTTPretty.POST, "https://secure.github.com/", body='{"repositories": ["HTTPretty", "lettuce"]}') request = urllib2.Request( 'https://secure.github.com', b'{"username": "******"}', { 'content-type': 'text/json', }, ) fd = urlopen(request) got = fd.read() fd.close() expect(HTTPretty.last_request.method).to.equal('POST') expect(HTTPretty.last_request.body).to.equal( b'{"username": "******"}', ) expect(HTTPretty.last_request.headers['content-type']).to.equal( 'text/json', ) expect(got).to.equal(b'{"repositories": ["HTTPretty", "lettuce"]}')
def test_fake_socket_passes_through_shutdown(): import socket HTTPretty.enable() s = socket.socket(socket.AF_INET, socket.SOCK_STREAM) s.truesock = MagicMock() expect(s.shutdown).called_with(socket.SHUT_RD).should_not.throw(AttributeError) s.truesock.shutdown.assert_called_with(socket.SHUT_RD)
def test_callback_response(now): ("HTTPretty should all a callback function to be set as the body with" " urllib2") def request_callback(request, uri, headers): return [200, headers, "The {0} response from {1}".format(decode_utf8(request.method), uri)] HTTPretty.register_uri( HTTPretty.GET, "https://api.yahoo.com/test", body=request_callback) fd = urllib2.urlopen('https://api.yahoo.com/test') got = fd.read() fd.close() expect(got).to.equal(b"The GET response from https://api.yahoo.com/test") HTTPretty.register_uri( HTTPretty.POST, "https://api.yahoo.com/test_post", body=request_callback) request = urllib2.Request( "https://api.yahoo.com/test_post", b'{"username": "******"}', { 'content-type': 'text/json', }, ) fd = urllib2.urlopen(request) got = fd.read() fd.close() expect(got).to.equal(b"The POST response from https://api.yahoo.com/test_post")
def __init__(self): """ Constructor """ self.api_endpoint = current_app.config['GOOGLE_RECAPTCHA_ENDPOINT'] def request_callback(request, uri, headers): """ Callback :param request: HTTP request :param uri: URI/URL to send the request :param headers: header of the HTTP request :return: httpretty response """ data = request.parsed_body if data['response'][0] == 'correct_response': res = {'success': True} elif data['response'][0] == 'incorrect_response': res = {'success': False} elif data['response'][0] == 'dont_return_200': return 503, headers, "Service Unavailable" else: raise Exception( "This case is not expected by the tests: {0}".format(data) ) return 200, headers, json.dumps(res) HTTPretty.register_uri( method=HTTPretty.POST, uri=self.api_endpoint, body=request_callback, content_type="application/json" )
def test_file_exists_no_duplicate(self): HTTPretty.register_uri(HTTPretty.GET, "http://foo.net/foo.pdf", body="foo") rg = ResourceGrabber("http://foo.net/foo.pdf") with open(os.path.join(self.directory, 'foo.pdf'), 'wb') as f: f.write('foo') self.assertEqual(rg.download(self.directory, duplicate_check=True), None)
def test_no_tags(self): HTTPretty.register_uri(HTTPretty.POST, 'https://api.tumblr.com/v2/blog/seejohnrun.tumblr.com/post', body='{"meta": {"status": 201, "msg": "OK"}, "response": []}') response = self.client.create_link('seejohnrun.tumblr.com', tags=[]) experimental_body = parse_qs(HTTPretty.last_request.body) assert 'tags' not in experimental_body
def test_httpretty_should_support_a_list_of_successive_responses_urllib2(now): "HTTPretty should support adding a list of successive " \ "responses with urllib2" HTTPretty.register_uri( HTTPretty.GET, "https://api.yahoo.com/test", responses=[ HTTPretty.Response(body="first response", status=201), HTTPretty.Response(body='second and last response', status=202), ]) request1 = urlopen('https://api.yahoo.com/test') body1 = request1.read() request1.close() expect(request1.code).to.equal(201) expect(body1).to.equal(b'first response') request2 = urlopen('https://api.yahoo.com/test') body2 = request2.read() request2.close() expect(request2.code).to.equal(202) expect(body2).to.equal(b'second and last response') request3 = urlopen('https://api.yahoo.com/test') body3 = request3.read() request3.close() expect(request3.code).to.equal(202) expect(body3).to.equal(b'second and last response')
def test_httpretty_should_not_raise_on_socket_send_when_uri_not_registered(): """HTTPretty should not raise a RuntimeError when the fakesocket is used in an invalid usage. """ import socket HTTPretty.enable() sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM, 0) sock.setblocking(0) expect(sock.sendto).when.called_with( b'whatever', ('127.0.0.1', 53)).should_not.throw(RuntimeError) sock.close() HTTPretty.reset() HTTPretty.disable()
def _login_setup(self, user_url=None): self.strategy.set_settings({'SOCIAL_AUTH_STEAM_API_KEY': '123abc'}) HTTPretty.register_uri(HTTPretty.POST, 'https://steamcommunity.com/openid/login', status=200, body=self.server_response) HTTPretty.register_uri(HTTPretty.GET, user_url or 'https://steamcommunity.com/openid/id/123', status=200, body=self.user_discovery_body) HTTPretty.register_uri(HTTPretty.GET, INFO_URL, status=200, body=self.player_details)
def auth_handlers(self, start_url): target_url = self.handle_state( start_url, self.strategy.build_absolute_uri(self.complete_url)) HTTPretty.register_uri(HTTPretty.GET, start_url, status=301, location=target_url) HTTPretty.register_uri(HTTPretty.GET, target_url, status=200, body='foobar') HTTPretty.register_uri(self._method(self.backend.ACCESS_TOKEN_METHOD), uri=self.backend.access_token_url(), status=self.access_token_status, body=self.access_token_body or '', content_type='text/json') if self.user_data_url: HTTPretty.register_uri( HTTPretty.POST if self.user_data_url_post else HTTPretty.GET, self.user_data_url, body=self.user_data_body or '', content_type=self.user_data_content_type) return target_url
def start(self): self.backend.reset() HTTPretty.enable() for method in HTTPretty.METHODS: for key, value in self.backend.urls.iteritems(): HTTPretty.register_uri( method=method, uri=re.compile(key), body=value, ) # Mock out localhost instance metadata HTTPretty.register_uri( method=method, uri=re.compile('http://169.254.169.254/latest/meta-data/.*'), body=metadata_response)
def setUp(self): """Setup the test""" super().setUp() # Mock out the NGP VAN endpoints HTTPretty.register_uri(HTTPretty.GET, 'https://accounts.ngpvan.com/Home/Xrds', status=200, body=self.discovery_body) HTTPretty.register_uri(HTTPretty.GET, 'https://accounts.ngpvan.com/user/abcd123', status=200, body=self.discovery_body) HTTPretty.register_uri(HTTPretty.GET, 'https://accounts.ngpvan.com/OpenId/Provider', status=200, body=self.discovery_body)
def test_recording_calls(): ("HTTPretty should be able to record calls") # Given a destination path: destination = FIXTURE_FILE("recording-.json") # When I record some calls with HTTPretty.record(destination): requests.get(server_url("/foobar?name=Gabriel&age=25")) requests.post(server_url("/foobar"), data=json.dumps({'test': '123'})) # Then the destination path should exist os.path.exists(destination).should.be.true # And the contents should be json raw = open(destination).read() json.loads.when.called_with(raw).should_not.throw(ValueError) # And the contents should be expected data = json.loads(raw) data.should.be.a(list) data.should.have.length_of(2) # And the responses should have the expected keys response = data[0] response.should.have.key("request").being.length_of(5) response.should.have.key("response").being.length_of(3) response['request'].should.have.key("method").being.equal("GET") response['request'].should.have.key("headers").being.a(dict) response['request'].should.have.key("querystring").being.equal({ "age": ["25"], "name": ["Gabriel"] }) response['response'].should.have.key("status").being.equal(200) response['response'].should.have.key("body").being.an(text_type) response['response'].should.have.key("headers").being.a(dict) response['response']["headers"].should.have.key("server").being.equal( "TornadoServer/" + tornado_version)
def auth_handlers(self, start_url): target_url = self.handle_state( start_url, self.strategy.build_absolute_uri(self.complete_url)) HTTPretty.register_uri(HTTPretty.GET, start_url, status=301, location=target_url) HTTPretty.register_uri(HTTPretty.GET, target_url, status=200, body='foobar') if self.user_data_url: HTTPretty.register_uri( HTTPretty.POST if self.user_data_url_post else HTTPretty.GET, self.user_data_url, body=self.user_data_body or '', content_type=self.user_data_content_type) return target_url
def start(self): self.__class__.nested_count += 1 for backend in self.backends.values(): backend.reset() if not HTTPretty.is_enabled(): HTTPretty.enable() for method in HTTPretty.METHODS: backend = list(self.backends.values())[0] for key, value in backend.urls.items(): HTTPretty.register_uri( method=method, uri=re.compile(key), body=value, ) # Mock out localhost instance metadata HTTPretty.register_uri( method=method, uri=re.compile('http://169.254.169.254/latest/meta-data/.*'), body=metadata_response)
def test_http_passthrough(): url = 'http://ip4.me/' response1 = requests.get(url) HTTPretty.enable() HTTPretty.register_uri(HTTPretty.GET, 'http://google.com/', body="Not Google") response2 = requests.get('http://google.com/') expect(response2.content).to.equal(b'Not Google') response3 = requests.get(url) expect(response3.content).to.equal(response1.content) HTTPretty.disable() response4 = requests.get(url) expect(response4.content).to.equal(response1.content)
def do_start(self): HTTPretty.register_uri(HTTPretty.GET, self.openid_url(), status=200, body=self.discovery_body, content_type='application/xrds+xml') start = self.strategy.start() self.post_start() form, inputs = self.get_form_data(start) HTTPretty.register_uri(HTTPretty.POST, form.get('action'), status=200, body=self.server_response) response = requests.post(form.get('action'), data=inputs) self.strategy.set_request_data(parse_qs(response.content)) HTTPretty.register_uri(HTTPretty.POST, form.get('action'), status=200, body='is_valid:true\n') return self.strategy.complete()
def test_https_passthrough(): url = 'https://raw.githubusercontent.com/gabrielfalcao/HTTPretty/master/COPYING' response1 = requests.get(url, stream=True) HTTPretty.enable() HTTPretty.register_uri(HTTPretty.GET, 'https://google.com/', body="Not Google") response2 = requests.get('https://google.com/') expect(response2.content).to.equal(b'Not Google') response3 = requests.get(url, stream=True) (response3.content).should.equal(response1.content) HTTPretty.disable() response4 = requests.get(url, stream=True) (response4.content).should.equal(response1.content)
def test_http_passthrough(): url = 'http://httpbin.org/status/200' response1 = requests.get(url) response1 = requests.get(url, stream=True) HTTPretty.enable() HTTPretty.register_uri(HTTPretty.GET, 'http://google.com/', body="Not Google") response2 = requests.get('http://google.com/') expect(response2.content).to.equal(b'Not Google') response3 = requests.get(url, stream=True) (response3.content).should.equal(response1.content) HTTPretty.disable() response4 = requests.get(url, stream=True) (response4.content).should.equal(response1.content)
def __init__(self, response, regex='.*'): """ Constructor :param response: user response """ self.response = response def request_callback(request, uri, headers): """ :param request: HTTP request :param uri: URI/URL to send the request :param headers: header of the HTTP request :return: """ return self.response['status_code'], \ headers, \ json.dumps(self.response['response']) HTTPretty.register_uri( HTTPretty.GET, re.compile(regex), body=request_callback, content_type='application/json' ) HTTPretty.register_uri( HTTPretty.POST, re.compile(regex), body=request_callback, content_type='application/json' ) HTTPretty.register_uri( HTTPretty.PUT, re.compile(regex), body=request_callback, content_type='application/json' )
def test_httpretty_allows_to_chose_if_querystring_should_be_matched(): "HTTPretty should provide a way to not match regexes that have a different querystring" HTTPretty.register_uri( HTTPretty.GET, "http://localhost:9090", ) HTTPretty.register_uri(HTTPretty.GET, re.compile(r"http://localhost:9090/what/?$"), body="Nudge, nudge, wink, wink. Know what I mean?", match_querystring=True) HTTPretty.register_uri(HTTPretty.GET, re.compile(r"http://localhost:9090/what.*[?]?.*"), body="Different", match_querystring=False) response = requests.get('http://localhost:9090/what/') expect( response.text).to.equal('Nudge, nudge, wink, wink. Know what I mean?') response = requests.get('http://localhost:9090/what/', params={'flying': 'coconuts'}) expect(response.text).to.not_be.equal( 'Nudge, nudge, wink, wink. Know what I mean?')
def test_https_passthrough(): from sure import expect from httpretty import HTTPretty import requests url = 'https://www.cloudflare.com/ips-v4' response1 = requests.get(url) HTTPretty.enable() HTTPretty.register_uri(HTTPretty.GET, 'http://google.com/', body="Not Google") response2 = requests.get('http://google.com/') expect(response2.content).to.equal('Not Google') response3 = requests.get(url) expect(response3.content).to.equal(response1.content) HTTPretty.disable() response4 = requests.get(url) expect(response4.content).to.equal(response1.content)
def teardown_class(cls): HTTPretty.disable()
def test_create_service(self): HTTPretty.register_uri(HTTPretty.POST, self.services_url) actual_response = self.tenant_api_client.create_service( name="Test-Service", description="Test Keystone Identity Service") self._build_assertions(actual_response, self.services_url)
def test_update_user(self): HTTPretty.register_uri(HTTPretty.PUT, self.user_url) actual_response = self.tenant_api_client.update_user( user_id=self.user_id) self._build_assertions(actual_response, self.user_url)
def test_queue(self): HTTPretty.register_uri(HTTPretty.GET, 'https://api.tumblr.com/v2/blog/codingjester.tumblr.com/posts/queue', body='{"meta": {"status": 200, "msg": "OK"}, "response": {"posts": [] } }') response = self.client.queue('codingjester.tumblr.com') assert response['posts'] == []
def test_create_chat(self): HTTPretty.register_uri(HTTPretty.POST, 'https://api.tumblr.com/v2/blog/codingjester.tumblr.com/post', body='{"meta": {"status": 201, "msg": "OK"}, "response": []}') response = self.client.create_chat('codingjester.tumblr.com', conversation="JB: Testing is rad.\nJC: Hell yeah.") assert response == []
def test_followers(self): HTTPretty.register_uri(HTTPretty.GET, 'https://api.tumblr.com/v2/blog/codingjester.tumblr.com/followers', body='{"meta": {"status": 200, "msg": "OK"}, "response": {"users": [] } }') response = self.client.followers('codingjester.tumblr.com') assert response['users'] == []
def test_blogInfo(self): HTTPretty.register_uri(HTTPretty.GET, 'https://api.tumblr.com/v2/blog/codingjester.tumblr.com/info', body='{"meta": {"status": 200, "msg": "OK"}, "response": {"blog": {} } }') response = self.client.blog_info('codingjester.tumblr.com') assert response['blog'] == {}
def test_posts_with_type(self): HTTPretty.register_uri(HTTPretty.GET, 'https://api.tumblr.com/v2/blog/seejohnrun.tumblr.com/posts/photo', body='{"meta": {"status": 200, "msg": "OK"}, "response": {"posts": [] } }') response = self.client.posts('seejohnrun', 'photo') assert response['posts'] == []
def test_create_video(self): HTTPretty.register_uri(HTTPretty.POST, 'https://api.tumblr.com/v2/blog/codingjester.tumblr.com/post', body='{"meta": {"status": 201, "msg": "OK"}, "response": []}') response = self.client.create_video('codingjester.tumblr.com', embed="blahblahembed") assert response == []
def test_create_audio(self): HTTPretty.register_uri(HTTPretty.POST, 'https://api.tumblr.com/v2/blog/codingjester.tumblr.com/post', body='{"meta": {"status": 201, "msg": "OK"}, "response": []}') response = self.client.create_audio('codingjester.tumblr.com', external_url="https://media.tumblr.com/audio.mp3") assert response == []
def test_create_photo(self): HTTPretty.register_uri(HTTPretty.POST, 'https://api.tumblr.com/v2/blog/codingjester.tumblr.com/post', body='{"meta": {"status": 201, "msg": "OK"}, "response": []}') response = self.client.create_photo('codingjester.tumblr.com', source="https://media.tumblr.com/image.jpg") assert response == []
def test_create_tenant(self): HTTPretty.register_uri(HTTPretty.POST, self.tenants_url) actual_response = self.tenant_api_client.create_tenant(name="Admin") self._build_assertions(actual_response, self.tenants_url)
def test_blogLikes_with_before(self): HTTPretty.register_uri(HTTPretty.GET, 'https://api.tumblr.com/v2/blog/codingjester.tumblr.com/likes', body='{"meta": {"status": 200, "msg": "OK"}, "response": {"liked_posts": [] } }') response = self.client.blog_likes('codingjester.tumblr.com', before=1418684291) assert response['liked_posts'] == []
def test_delete_tenant(self): HTTPretty.register_uri(HTTPretty.DELETE, self.tenant_url) actual_response = self.tenant_api_client.delete_tenant( tenant_id=self.tenant_id) self._build_assertions(actual_response, self.tenant_url)
def test_create_quote(self): HTTPretty.register_uri(HTTPretty.POST, 'https://api.tumblr.com/v2/blog/codingjester.tumblr.com/post', body='{"meta": {"status": 201, "msg": "OK"}, "response": []}') response = self.client.create_quote('codingjester.tumblr.com', quote="It's better to love and lost, than never have loved at all.") assert response == []