def test_get_items_rated_as_good_by_other_users(self): HTTPretty.register_uri(HTTPretty.GET, "http://some.com/api/1.0/json/itemtypes", body='{"itemTypes": {"itemType": ["ITEM", "LUBE"]}}', content_type="application/json") product = G(Product, parent=None) params = { "user_id": "auser", "item_id": 1234 } expected_get_params = { "tenantid": ["tenant"], "apikey": ["key"], "userid": ["auser"], "itemid": ["1234"] } expected_response = '{"recommendeditems": {"item": [{"id": %s}]}}' % product.upc HTTPretty.register_uri(HTTPretty.GET, "http://some.com/api/1.0/json/itemsratedgoodbyotherusers", body=expected_response, content_type="application/json") response = self.gateway.get_items_rated_as_good_by_other_users(**params) get_params = HTTPretty.last_request.querystring self.assertEqual(get_params, expected_get_params) self.assertEqual(len(response), 1) self.assertEqual(response[0]['product'].upc, product.upc)
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_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_get_worst_rated_items(self): HTTPretty.register_uri(HTTPretty.GET, "http://some.com/api/1.0/json/itemtypes", body='{"itemTypes": {"itemType": ["ITEM", "LUBE"]}}', content_type="application/json") product = G(Product, parent=None) params = { "max_results": 1, "requested_item_type": "ITEM", "time_range": 'week' } expected_get_params = { "tenantid": ["tenant"], "apikey": ["key"], "numberOfResults": ["1"], "requesteditemtype": ["ITEM"], "timeRange": ["WEEK"] } expected_response = '{"recommendeditems": {"item": [{"id": %s}]}}' % product.upc HTTPretty.register_uri(HTTPretty.GET, "http://some.com/api/1.0/json/worstrateditems", body=expected_response, content_type="application/json") response = self.gateway.get_worst_rated_items(**params) get_params = HTTPretty.last_request.querystring self.assertEqual(get_params, expected_get_params) self.assertEqual(len(response), 1) self.assertEqual(response[0]['product'].upc, product.upc)
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_httpretty_reset_by_switching_protocols_for_same_port(): "HTTPretty should reset protocol/port associations" HTTPretty.register_uri( HTTPretty.GET, "http://api.yipit.com:1234/v1/deal", body=lambda method, uri, headers: [200, headers, uri] ) response = requests.get('http://api.yipit.com:1234/v1/deal') expect(response.text).to.equal('http://api.yipit.com:1234/v1/deal') expect(HTTPretty.last_request.method).to.equal('GET') expect(HTTPretty.last_request.path).to.equal('/v1/deal') HTTPretty.reset() HTTPretty.register_uri( HTTPretty.GET, "https://api.yipit.com:1234/v1/deal", body=lambda method, uri, headers: [200, headers, uri] ) response = requests.get('https://api.yipit.com:1234/v1/deal') expect(response.text).to.equal('https://api.yipit.com:1234/v1/deal') expect(HTTPretty.last_request.method).to.equal('GET') expect(HTTPretty.last_request.path).to.equal('/v1/deal')
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_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_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_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_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 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_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_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 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 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_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_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_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_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 __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_bypasses_when_disabled(context): u"HTTPretty should bypass all requests by disabling it" HTTPretty.register_uri( HTTPretty.GET, "http://localhost:9999/go-for-bubbles/", body="glub glub") HTTPretty.disable() fd = urllib2.urlopen('http://localhost:9999/go-for-bubbles/') got1 = fd.read() fd.close() expect(got1).to.equal( '. o O 0 O o . o O 0 O o . o O 0 O o . o O 0 O o . o O 0 O o .') fd = urllib2.urlopen('http://localhost:9999/come-again/') got2 = fd.read() fd.close() expect(got2).to.equal('<- HELLO WORLD ->') HTTPretty.enable() fd = urllib2.urlopen('http://localhost:9999/go-for-bubbles/') got3 = fd.read() fd.close() expect(got3).to.equal('glub glub')
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 __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_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 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 __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 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_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")
# # enable HTTPretty mocking if PTL_TESTING set # import os if os.getenv('PTL_TESTING'): from httpretty import HTTPretty # monkey patch the socket module (and leave it that way! DANGEROUS) HTTPretty.enable() # siteurl = "http://pootle.example.com/" siteurl = "http://localhost/" HTTPretty.register_uri(HTTPretty.GET, siteurl, body='<html></html>', content_type="text/html") baseurl = siteurl + "api/v1/" HTTPretty.register_uri(HTTPretty.GET, baseurl, body='["API Root"]', content_type="application/json") language_list = """ { "meta": { "limit": 1000, "next": null, "offset": 0,
def test_lack_of_trailing_slash(): ("HTTPretty should automatically append a slash to given urls") url = 'http://www.youtube.com' HTTPretty.register_uri(HTTPretty.GET, url, body='') response = requests.get(url) response.status_code.should.equal(200)
def test_streaming_responses(now): """ Mock a streaming HTTP response, like those returned by the Twitter streaming API. """ @contextmanager def in_time(time, message): """ A context manager that uses signals to force a time limit in tests (unlike the `@within` decorator, which only complains afterward), or raise an AssertionError. """ def handler(signum, frame): raise AssertionError(message) signal.signal(signal.SIGALRM, handler) signal.setitimer(signal.ITIMER_REAL, time) yield signal.setitimer(signal.ITIMER_REAL, 0) # XXX this obviously isn't a fully functional twitter streaming client! twitter_response_lines = [ b'{"text":"If \\"for the boobs\\" requests to follow me one more time I\'m calling the police. http://t.co/a0mDEAD8"}\r\n', b'\r\n', b'{"text":"RT @onedirection: Thanks for all your # FollowMe1D requests Directioners! We\u2019ll be following 10 people throughout the day starting NOW. G ..."}\r\n' ] TWITTER_STREAMING_URL = "https://stream.twitter.com/1/statuses/filter.json" HTTPretty.register_uri(HTTPretty.POST, TWITTER_STREAMING_URL, body=(l for l in twitter_response_lines), streaming=True) # taken from the requests docs # test iterating by line # Http://docs.python-requests.org/en/latest/user/advanced/# streaming-requests response = requests.post(TWITTER_STREAMING_URL, data={'track': 'requests'}, auth=('username', 'password'), stream=True) line_iter = response.iter_lines() with in_time(0.01, 'Iterating by line is taking forever!'): for i in range(len(twitter_response_lines)): expect(next(line_iter).strip()).to.equal( twitter_response_lines[i].strip()) HTTPretty.register_uri(HTTPretty.POST, TWITTER_STREAMING_URL, body=(l for l in twitter_response_lines), streaming=True) # test iterating by line after a second request response = requests.post( TWITTER_STREAMING_URL, data={'track': 'requests'}, auth=('username', 'password'), stream=True, ) line_iter = response.iter_lines() with in_time( 0.01, 'Iterating by line is taking forever the second time ' 'around!'): for i in range(len(twitter_response_lines)): expect(next(line_iter).strip()).to.equal( twitter_response_lines[i].strip()) HTTPretty.register_uri(HTTPretty.POST, TWITTER_STREAMING_URL, body=(l for l in twitter_response_lines), streaming=True) # test iterating by char response = requests.post(TWITTER_STREAMING_URL, data={'track': 'requests'}, auth=('username', 'password'), stream=True) twitter_expected_response_body = b''.join(twitter_response_lines) with in_time(0.02, 'Iterating by char is taking forever!'): twitter_body = b''.join(c for c in response.iter_content(chunk_size=1)) expect(twitter_body).to.equal(twitter_expected_response_body) # test iterating by chunks larger than the stream HTTPretty.register_uri(HTTPretty.POST, TWITTER_STREAMING_URL, body=(l for l in twitter_response_lines), streaming=True) response = requests.post(TWITTER_STREAMING_URL, data={'track': 'requests'}, auth=('username', 'password'), stream=True) with in_time(0.02, 'Iterating by large chunks is taking forever!'): twitter_body = b''.join( c for c in response.iter_content(chunk_size=1024)) expect(twitter_body).to.equal(twitter_expected_response_body)
def auth_handlers(self, start_url): HTTPretty.register_uri(HTTPretty.GET, self.jwks_url, body=json.dumps({'keys': [JWK_PUBLIC_KEY]}), content_type='application/json') return super().auth_handlers(start_url)
def do_login_with_partial_pipeline(self, before_complete=None): self.strategy.set_settings({ 'SOCIAL_AUTH_GITHUB_KEY': 'a-key', 'SOCIAL_AUTH_GITHUB_SECRET': 'a-secret-key', 'SOCIAL_AUTH_LOGIN_REDIRECT_URL': self.login_redirect_url, 'SOCIAL_AUTH_AUTHENTICATION_BACKENDS': ('social.backends.github.GithubOAuth2', ), 'SOCIAL_AUTH_PIPELINE': ('social.pipeline.social_auth.social_details', 'social.pipeline.social_auth.social_uid', 'social.pipeline.social_auth.auth_allowed', 'social.pipeline.partial.save_status_to_session', 'social.tests.pipeline.ask_for_password', 'social.pipeline.social_auth.social_user', 'social.pipeline.user.get_username', 'social.pipeline.user.create_user', 'social.pipeline.social_auth.associate_user', 'social.pipeline.social_auth.load_extra_data', 'social.tests.pipeline.set_password', 'social.pipeline.user.user_details') }) start_url = do_auth(self.backend).url target_url = self.strategy.build_absolute_uri( '/complete/github/?code=foobar') start_query = parse_qs(urlparse(start_url).query) location_url = target_url + ('?' in target_url and '&' or '?') + \ 'state=' + start_query['state'] location_query = parse_qs(urlparse(location_url).query) HTTPretty.register_uri(HTTPretty.GET, start_url, status=301, location=location_url) HTTPretty.register_uri(HTTPretty.GET, location_url, status=200, body='foobar') response = requests.get(start_url) expect(response.url).to.equal(location_url) expect(response.text).to.equal('foobar') HTTPretty.register_uri(HTTPretty.GET, uri=self.backend.ACCESS_TOKEN_URL, status=200, body=self.access_token_body or '', content_type='text/json') if self.user_data_url: HTTPretty.register_uri(HTTPretty.GET, self.user_data_url, body=self.user_data_body or '', content_type='text/json') self.strategy.set_request_data(location_query, self.backend) def _login(backend, user, social_user): backend.strategy.session_set('username', user.username) redirect = do_complete(self.backend, user=self.user, login=_login) 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']) if before_complete: before_complete() redirect = do_complete(self.backend, user=self.user, login=_login) expect(self.strategy.session_get('username')).to.equal( self.expected_username) expect(redirect.url).to.equal(self.login_redirect_url)
def setUp(self): HTTPretty.enable() HTTPretty.register_uri(HTTPretty.GET, FULL_URL, body=json.dumps(self.response), content_type="text/xml")
def test_http_get(): HTTPretty.register_uri( HTTPretty.GET, "http://127.0.0.1/v1/current_conditions", body=RESPONSE, ) wlll.set_units( temperature=wlll.units.TemperatureUnit.FAHRENHEIT, pressure=wlll.units.PressureUnit.INCH_MERCURY, rain=wlll.units.RainUnit.INCH, wind_speed=wlll.units.WindSpeedUnit.MILES_PER_HOUR, ) conditions = wlll.get_conditions("127.0.0.1") assert conditions.timestamp == datetime.fromtimestamp(1531754005) inside = conditions.inside assert isinstance(inside, wlll.conditions.InsideConditions) assert inside.lsid == 48307 assert inside.temp == 78 assert inside.hum == 41.1 assert inside.dew_point == 7.8 assert inside.heat_index == 8.4 barometric = conditions.barometric assert isinstance(barometric, wlll.conditions.BarometricConditions) assert barometric.lsid == 48306 assert barometric.bar_absolute == 30.008 assert barometric.bar_sea_level == 30.008 assert barometric.bar_trend == None assert len(conditions.moisture_temperature_stations) == 1 mt0 = conditions.moisture_temperature_stations[0] assert isinstance(mt0, wlll.conditions.MoistureTemperatureConditions) assert mt0.txid == 3 assert mt0.rx_state == None assert mt0.trans_battery_flag == None assert mt0.temp_1 == None assert mt0.temp_2 == None assert mt0.temp_3 == None assert mt0.temp_4 == None assert mt0.moist_soil_1 == None assert mt0.moist_soil_2 == None assert mt0.moist_soil_3 == None assert mt0.moist_soil_4 == None assert mt0.wet_leaf_1 == None assert mt0.wet_leaf_2 == None assert len(conditions.integrated_sensor_suites) == 1 iss0 = conditions.integrated_sensor_suites[0] assert isinstance(iss0, wlll.conditions.SensorSuiteConditions) assert iss0.lsid == 48308 assert iss0.txid == 1 assert iss0.rx_state == wlll.conditions.RadioReceptionState.SCANNING assert iss0.trans_battery_flag == 0 assert iss0.temp == 62.7 assert iss0.hum == 1.1 assert iss0.dew_point == -0.3 assert iss0.wet_bulb == None assert iss0.heat_index == 5.5 assert iss0.wind_chill == 6.0 assert iss0.thw_index == 5.5 assert iss0.thsw_index == 5.5 assert iss0.wind_speed_last == 2 assert iss0.wind_speed_avg_last_1_min == 4 assert iss0.wind_speed_avg_last_2_min == 42606 assert iss0.wind_speed_avg_last_10_min == 42606 assert iss0.wind_speed_hi_last_2_min == 8 assert iss0.wind_speed_hi_last_10_min == 8 assert iss0.wind_dir_last == None assert iss0.wind_dir_scalar_avg_last_1_min == 15 assert iss0.wind_dir_scalar_avg_last_2_min == 170.7 assert iss0.wind_dir_scalar_avg_last_10_min == 4822.5 assert iss0.wind_dir_at_hi_speed_last_2_min == 0.0 assert iss0.wind_dir_at_hi_speed_last_10_min == 0.0 assert iss0.rainfall_last_60_min == None assert iss0.rainfall_last_24_hr == None assert iss0.rainfall_daily == _counts_to_inch(63) assert iss0.rainfall_monthly == _counts_to_inch(63) assert iss0.rainfall_year == _counts_to_inch(63) assert iss0.rain_rate_last == 0 assert iss0.rain_rate_hi_last_1_min == None assert iss0.rain_rate_hi_last_15_min == 0 assert iss0.rain_storm_last == None assert iss0.rain_storm_last_start_at == None assert iss0.rain_storm_last_end_at == None assert iss0.solar_rad == 747 assert iss0.uv_index == 5.5
def test_login(self): HTTPretty.register_uri(HTTPretty.GET, 'https://bitbucket.org/api/1.0/emails/', status=200, body=self.emails_body) self.do_login()
def pre_complete_callback(self, start_url): 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')
def pipeline_handlers(self, url): HTTPretty.register_uri(HTTPretty.GET, url, status=200, body='foobar') HTTPretty.register_uri(HTTPretty.POST, url, status=200)
def setUp(self): """ Set stuff up """ self.items_doc = """<?xml version="1.0"?> <feed xmlns="http://www.w3.org/2005/Atom" xmlns:zapi="http://zotero.org/ns/api"> <title>Zotero / urschrei / Items</title> <id>http://zotero.org/users/436/items?limit=3&content=json</id> <link rel="self" type="application/atom+xml" href="https://api.zotero.org/users/436/items?limit=1&content=json"/> <link rel="first" type="application/atom+xml" href="https://api.zotero.org/users/436/items?limit=1&content=json"/> <link rel="next" type="application/atom+xml" href="https://api.zotero.org/users/436/items?limit=1&content=json&start=3"/> <link rel="last" type="application/atom+xml" href="https://api.zotero.org/users/436/items?limit=1&content=json&start=1086"/> <link rel="alternate" type="text/html" href="http://zotero.org/users/436/items?limit=1"/> <zapi:totalResults>1087</zapi:totalResults> <zapi:apiVersion>1</zapi:apiVersion> <updated>2011-05-28T11:07:58Z</updated> <entry> <title>Copyright in custom code: Who owns commissioned software?</title> <author> <name>urschrei</name> <uri>http://zotero.org/urschrei</uri> </author> <id>http://zotero.org/urschrei/items/T4AH4RZA</id> <published>2011-02-14T00:27:03Z</published> <updated>2011-02-14T00:27:03Z</updated> <link rel="self" type="application/atom+xml" href="https://api.zotero.org/users/436/items/T4AH4RZA?content=json"/> <link rel="alternate" type="text/html" href="http://zotero.org/urschrei/items/T4AH4RZA"/> <zapi:key>T4AH4RZA</zapi:key> <zapi:itemType>journalArticle</zapi:itemType> <zapi:creatorSummary>McIntyre</zapi:creatorSummary> <zapi:numChildren>1</zapi:numChildren> <zapi:numTags>0</zapi:numTags> <content type="application/json" zapi:etag="7252daf2495feb8ec89c61f391bcba24">{"itemType":"journalArticle","title":"Copyright in custom code: Who owns commissioned software?","creators":[{"creatorType":"author","firstName":"T. J.","lastName":"McIntyre"}],"abstractNote":"","publicationTitle":"Journal of Intellectual Property Law \u0026 Practice","volume":"","issue":"","pages":"","date":"2007","series":"","seriesTitle":"","seriesText":"","journalAbbreviation":"","language":"","DOI":"","ISSN":"1747-1532","shortTitle":"Copyright in custom code","url":"","accessDate":"","archive":"","archiveLocation":"","libraryCatalog":"Google Scholar","callNumber":"","rights":"","extra":"","tags":[]}</content> </entry> </feed>""" self.attachments_doc = """<?xml version="1.0"?> <feed xmlns="http://www.w3.org/2005/Atom" xmlns:zapi="http://zotero.org/ns/api"> <title>Zotero / urschrei / Items</title> <id>http://zotero.org/users/436/items?limit=1&content=json</id> <link rel="self" type="application/atom+xml" href="https://api.zotero.org/users/436/items?limit=1&content=json"/> <link rel="first" type="application/atom+xml" href="https://api.zotero.org/users/436/items?limit=1&content=json"/> <link rel="next" type="application/atom+xml" href="https://api.zotero.org/users/436/items?limit=1&content=json&start=1"/> <link rel="last" type="application/atom+xml" href="https://api.zotero.org/users/436/items?limit=1&content=json&start=1128"/> <link rel="alternate" type="text/html" href="http://zotero.org/users/436/items?limit=1"/> <zapi:totalResults>1129</zapi:totalResults> <zapi:apiVersion>1</zapi:apiVersion> <updated>2012-01-11T19:54:47Z</updated> <entry> <title>1641 Depositions</title> <author> <name>urschrei</name> <uri>http://zotero.org/urschrei</uri> </author> <id>http://zotero.org/urschrei/items/TM8QRS36</id> <published>2012-01-11T19:54:47Z</published> <updated>2012-01-11T19:54:47Z</updated> <link rel="self" type="application/atom+xml" href="https://api.zotero.org/users/436/items/TM8QRS36?content=json"/> <link rel="up" type="application/atom+xml" href="https://api.zotero.org/users/436/items/47RUN6RI?content=json"/> <link rel="alternate" type="text/html" href="http://zotero.org/urschrei/items/TM8QRS36"/> <zapi:key>TM8QRS36</zapi:key> <zapi:itemType>attachment</zapi:itemType> <zapi:numTags>0</zapi:numTags> <content zapi:type="json" zapi:etag="1686f563f9b4cb1db3a745a920bf0afa">{"itemType":"attachment","title":"1641 Depositions","accessDate":"2012-01-11 19:54:47","url":"http://1641.tcd.ie/project-conservation.php","note":"","linkMode":1,"mimeType":"text/html","charset":"utf-8","tags":[]}</content> </entry> </feed>""" self.collections_doc = """<?xml version="1.0"?> <feed xmlns="http://www.w3.org/2005/Atom" xmlns:zapi="http://zotero.org/ns/api"> <title>Zotero / urschrei / Collections</title> <id>http://zotero.org/users/436/collections?limit=1&content=json</id> <link rel="self" type="application/atom+xml" href="https://api.zotero.org/users/436/collections?limit=1&content=json"/> <link rel="first" type="application/atom+xml" href="https://api.zotero.org/users/436/collections?limit=1&content=json"/> <link rel="next" type="application/atom+xml" href="https://api.zotero.org/users/436/collections?limit=1&content=json&start=1"/> <link rel="last" type="application/atom+xml" href="https://api.zotero.org/users/436/collections?limit=1&content=json&start=37"/> <link rel="alternate" type="text/html" href="http://zotero.org/users/436/collections?limit=1"/> <zapi:totalResults>38</zapi:totalResults> <zapi:apiVersion>1</zapi:apiVersion> <updated>2011-03-16T15:00:09Z</updated> <entry> <title>Badiou</title> <author> <name>urschrei</name> <uri>http://zotero.org/urschrei</uri> </author> <id>http://zotero.org/urschrei/collections/HTUHVPE5</id> <published>2011-03-16T14:48:18Z</published> <updated>2011-03-16T15:00:09Z</updated> <link rel="self" type="application/atom+xml" href="https://api.zotero.org/users/436/collections/HTUHVPE5"/> <link rel="alternate" type="text/html" href="http://zotero.org/urschrei/collections/HTUHVPE5"/> <zapi:key>HTUHVPE5</zapi:key> <zapi:numCollections>0</zapi:numCollections> <zapi:numItems>27</zapi:numItems> <content type="application/json" zapi:etag="7252daf2495feb8ec89c61f391bcba24">{"name":"A Midsummer Night's Dream","parent":false}</content> </entry> </feed>""" self.tags_doc = """<?xml version="1.0"?> <feed xmlns="http://www.w3.org/2005/Atom" xmlns:zapi="http://zotero.org/ns/api"> <title>Zotero / urschrei / Tags</title> <id>http://zotero.org/users/436/tags?limit=1&content=json</id> <link rel="self" type="application/atom+xml" href="https://api.zotero.org/users/436/tags?limit=1&content=json"/> <link rel="first" type="application/atom+xml" href="https://api.zotero.org/users/436/tags?limit=1&content=json"/> <link rel="next" type="application/atom+xml" href="https://api.zotero.org/users/436/tags?limit=1&content=json&start=1"/> <link rel="last" type="application/atom+xml" href="https://api.zotero.org/users/436/tags?limit=1&content=json&start=319"/> <link rel="alternate" type="text/html" href="http://zotero.org/users/436/tags?limit=1"/> <zapi:totalResults>320</zapi:totalResults> <zapi:apiVersion>1</zapi:apiVersion> <updated>2010-03-27T13:56:08Z</updated> <entry xmlns:zxfer="http://zotero.org/ns/transfer"> <title>Authority in literature</title> <author> <name>urschrei</name> <uri>http://zotero.org/urschrei</uri> </author> <id>http://zotero.org/urschrei/tags/Authority+in+literature</id> <published>2010-03-26T18:23:14Z</published> <updated>2010-03-27T13:56:08Z</updated> <link rel="self" type="application/atom+xml" href="https://api.zotero.org/users/436/tags/Authority+in+literature"/> <link rel="alternate" type="text/html" href="http://zotero.org/urschrei/tags/Authority+in+literature"/> <zapi:numItems>1</zapi:numItems> </entry> </feed>""" self.groups_doc = """<?xml version="1.0"?> <feed xmlns="http://www.w3.org/2005/Atom" xmlns:zapi="http://zotero.org/ns/api"> <title>urschrei’s Groups</title> <id>http://zotero.org/users/436/groups?limit=1&content=json</id> <link rel="self" type="application/atom+xml" href="https://api.zotero.org/users/436/groups?limit=1&content=json"/> <link rel="first" type="application/atom+xml" href="https://api.zotero.org/users/436/groups?limit=1&content=json"/> <link rel="next" type="application/atom+xml" href="https://api.zotero.org/users/436/groups?limit=1&content=json&start=1"/> <link rel="last" type="application/atom+xml" href="https://api.zotero.org/users/436/groups?limit=1&content=json&start=1"/> <link rel="alternate" type="text/html" href="http://zotero.org/users/436/groups?limit=1"/> <zapi:totalResults>2</zapi:totalResults> <zapi:apiVersion>1</zapi:apiVersion> <updated>2010-07-04T21:56:22Z</updated> <entry xmlns:zxfer="http://zotero.org/ns/transfer"> <title>DFW</title> <author> <name>urschrei</name> <uri>http://zotero.org/urschrei</uri> </author> <id>http://zotero.org/groups/dfw</id> <published>2010-01-20T12:31:26Z</published> <updated>2010-07-04T21:56:22Z</updated> <link rel="self" type="application/atom+xml" href="https://api.zotero.org/groups/10248?content=json"/> <link rel="alternate" type="text/html" href="http://zotero.org/groups/dfw"/> <zapi:numItems>468</zapi:numItems> <content type="application/json">{"name":"DFW","owner":436,"type":"PublicOpen","description":"%3Cp%3EA+grouped+collection+of+the+David+Foster+Wallace+bibliography%2C+adapted%2Fedited%2Fupdated+from+what%27s+available+elsewhere.%3C%2Fp%3E","url":"","hasImage":1,"libraryEnabled":1,"libraryEditing":"admins","libraryReading":"all","fileEditing":"none","members":{"2":539271}}</content> </entry> </feed>""" self.bib_doc = """<?xml version="1.0"?> <feed xmlns="http://www.w3.org/2005/Atom" xmlns:zapi="http://zotero.org/ns/api"> <title>Zotero / urschrei / Top-Level Items</title> <id>http://zotero.org/users/436/items/top?limit=1&content=bib</id> <link rel="self" type="application/atom+xml" href="https://api.zotero.org/users/436/items/top?limit=1&content=bib"/> <link rel="first" type="application/atom+xml" href="https://api.zotero.org/users/436/items/top?limit=1&content=bib"/> <link rel="next" type="application/atom+xml" href="https://api.zotero.org/users/436/items/top?limit=1&content=bib&start=1"/> <link rel="last" type="application/atom+xml" href="https://api.zotero.org/users/436/items/top?limit=1&content=bib&start=949"/> <link rel="alternate" type="text/html" href="http://zotero.org/users/436/items/top?limit=1"/> <zapi:totalResults>950</zapi:totalResults> <zapi:apiVersion>1</zapi:apiVersion> <updated>2011-02-14T00:27:03Z</updated> <entry> <title>Copyright in custom code: Who owns commissioned software?</title> <author> <name>urschrei</name> <uri>http://zotero.org/urschrei</uri> </author> <id>http://zotero.org/urschrei/items/T4AH4RZA</id> <published>2011-02-14T00:27:03Z</published> <updated>2011-02-14T00:27:03Z</updated> <link rel="self" type="application/atom+xml" href="https://api.zotero.org/users/436/items/T4AH4RZA?content=bib"/> <link rel="alternate" type="text/html" href="http://zotero.org/urschrei/items/T4AH4RZA"/> <zapi:key>T4AH4RZA</zapi:key> <zapi:itemType>journalArticle</zapi:itemType> <zapi:creatorSummary>McIntyre</zapi:creatorSummary> <zapi:numChildren>1</zapi:numChildren> <zapi:numTags>0</zapi:numTags> <content type="xhtml" zapi:etag="7252daf2495feb8ec89c61f391bcba24"> <div xmlns="http://www.w3.org/1999/xhtml" class="csl-bib-body" style="line-height: 1.35; padding-left: 2em; text-indent:-2em;"> <div class="csl-entry">McIntyre, T. J. “Copyright in custom code: Who owns commissioned software?” <i>Journal of Intellectual Property Law & Practice</i> (2007).</div> </div> </content> </entry> </feed>""" self.created_response = """<?xml version="1.0"?> <entry xmlns="http://www.w3.org/2005/Atom" xmlns:zapi="http://zotero.org/ns/api"> <title>Hell, I don't Know</title> <author> <name>urschrei</name> <uri>http://zotero.org/urschrei</uri> </author> <id>http://zotero.org/urschrei/items/NVGIBE59</id> <published>2011-12-14T19:24:20Z</published> <updated>2011-12-17T19:19:37Z</updated> <link rel="self" type="application/atom+xml" href="https://api.zotero.org/users/436/items/NVGIBE59?content=json"/> <link rel="alternate" type="text/html" href="http://zotero.org/urschrei/items/NVGIBE59"/> <zapi:key>NVGIBE59</zapi:key> <zapi:itemType>journalArticle</zapi:itemType> <zapi:creatorSummary>Salo</zapi:creatorSummary> <zapi:year/> <zapi:numChildren>1</zapi:numChildren> <zapi:numTags>0</zapi:numTags> <content type="application/json" zapi:etag="1ed002db69174ae2ae0e3b90499df15e">{"itemType":"journalArticle","title":"Hell, I don't Know","creators":[{"creatorType":"author","firstName":"Dorotea","lastName":"Salo"}],"abstractNote":"","publicationTitle":"","volume":"","issue":"","pages":"","date":"","series":"","seriesTitle":"","seriesText":"","journalAbbreviation":"","language":"","DOI":"","ISSN":"","shortTitle":"","url":"","accessDate":"","archive":"","archiveLocation":"","libraryCatalog":"","callNumber":"","rights":"","extra":"","tags":[]}</content> </entry>""" self.item_templt = """{ "itemType" : "book", "title" : "", "creators" : [ { "creatorType" : "author", "firstName" : "", "lastName" : "" } ], "url" : "", "tags" : [], "notes" : [], "etag" : "" }""" self.item_types = """[ { "itemType":"artwork", "localized":"Artwork" }, { "itemType":"audioRecording", "localized":"Audio Recording" }, { "itemType":"bill", "localized":"Bill" }, { "itemType":"blogPost", "localized":"Blog Post" }, { "itemType":"book", "localized":"Book" }, { "itemType":"bookSection", "localized":"Book Section" }, { "itemType":"case", "localized":"Case" }, { "itemType":"computerProgram", "localized":"Computer Program" }, { "itemType":"conferencePaper", "localized":"Conference Paper" }, { "itemType":"dictionaryEntry", "localized":"Dictionary Entry" }, { "itemType":"document", "localized":"Document" }, { "itemType":"email", "localized":"E-mail" }, { "itemType":"encyclopediaArticle", "localized":"Encyclopedia Article" }, { "itemType":"film", "localized":"Film" }, { "itemType":"forumPost", "localized":"Forum Post" }, { "itemType":"hearing", "localized":"Hearing" }, { "itemType":"instantMessage", "localized":"Instant Message" }, { "itemType":"interview", "localized":"Interview" }, { "itemType":"journalArticle", "localized":"Journal Article" }, { "itemType":"letter", "localized":"Letter" }, { "itemType":"magazineArticle", "localized":"Magazine Article" }, { "itemType":"manuscript", "localized":"Manuscript" }, { "itemType":"map", "localized":"Map" }, { "itemType":"newspaperArticle", "localized":"Newspaper Article" }, { "itemType":"note", "localized":"Note" }, { "itemType":"patent", "localized":"Patent" }, { "itemType":"podcast", "localized":"Podcast" }, { "itemType":"presentation", "localized":"Presentation" }, { "itemType":"radioBroadcast", "localized":"Radio Broadcast" }, { "itemType":"report", "localized":"Report" }, { "itemType":"statute", "localized":"Statute" }, { "itemType":"tvBroadcast", "localized":"TV Broadcast" }, { "itemType":"thesis", "localized":"Thesis" }, { "itemType":"videoRecording", "localized":"Video Recording" }, { "itemType":"webpage", "localized":"Web Page" } ]""" self.keys_response = """ABCDE\nFGHIJ\nKLMNO\n""" # Add the item file to the mock response by default HTTPretty.enable() HTTPretty.register_uri( HTTPretty.GET, 'https://api.zotero.org/users/myuserID/items?content=json&key=myuserkey', body=self.items_doc)
def request_token_handler(self): HTTPretty.register_uri(self._method(self.backend.REQUEST_TOKEN_METHOD), self.backend.REQUEST_TOKEN_URL, body=self.request_token_body, status=200)
def test_login_next_format(self): url = 'https://api.github.com/user/emails' HTTPretty.register_uri(HTTPretty.GET, url, status=200, body=json.dumps([{'email': '*****@*****.**'}]), content_type='application/json') self.do_login()
def stub_put(path, *args, **kwargs): HTTPretty.register_uri(HTTPretty.PUT, campfire_url(path), *args, **kwargs)
def auth_handlers(self, start_url): url = 'https://api.github.com/teams/123/members/foobar' HTTPretty.register_uri(HTTPretty.GET, url, status=204, body='') return super().auth_handlers(start_url)
def test_spam_is_spam(self): HTTPretty.register_uri(HTTPretty.POST, "http://cleanweb-api.yandex.ru/1.0/complain", body=self.valid_response) Cleanweb(key='zzz').complain(id='somekindofmsgid', is_spam=False) self.assertBodyQueryString(spamtype=['ham'], id=['somekindofmsgid'])
def test_heading(self): HTTPretty.register_uri(HTTPretty.GET, 'http://localhost:2222/heading', body='{"result": 2.43}') assert self.goat.heading == 2.43
def auth_handlers(self, start_url): url = 'https://api.github.com/teams/123/members/foobar' HTTPretty.register_uri(HTTPretty.GET, url, status=404, body='{"message": "Not Found"}', content_type='application/json') return super().auth_handlers(start_url)
def test_user_info(self): """ unit test of user_info """ HTTPretty.register_uri(HTTPretty.GET, '%s/me' % AnyDoAPIBinder.host) ret = self.api.user_info() self.assertEqual(ret.status_code, 200)
def test_wind(self): HTTPretty.register_uri(HTTPretty.GET, 'http://localhost:2222/wind', body='{"direction": 8.42}') assert self.goat.wind.direction == 8.42
def auth_handlers(self, start_url): url = 'https://www.example.com/api/v3/teams/123/members/foobar' HTTPretty.register_uri(HTTPretty.GET, url, status=204, body='') return super(GithubEnterpriseTeamOAuth2Test, self).auth_handlers( start_url )
def test_root(self): HTTPretty.register_uri(HTTPretty.GET, 'http://localhost:2222/', body='{"goatd": {"version": "0.1mock"}}') assert self.goat.version
def auth_handlers(self, start_url): url = 'https://api.github.com/orgs/foobar/members/foobar' HTTPretty.register_uri(HTTPretty.GET, url, status=204, body='') return super(GithubOrganizationOAuth2Test, self).auth_handlers(start_url)
b'{"george": 1, "paul": 2, "ringo": 3, "john": 4}\r\n', b"\n", b'"this is just a string"\n', b"[1,2,3]", ] rpc = RestClient(mock_url, "passkey", timeout=1) json_stream = [j for t in expected_stream if (j := _jsonify(t))] # no blanks # test multiple times for test_num in range(2): print(f"\niteration #{test_num}") HTTPretty.register_uri( HTTPretty.POST, mock_url + "/stream/it/", body=(ln for ln in expected_stream), streaming=True, ) response_stream = rpc.request_stream("POST", "/stream/it/", {}) with _in_time(10, "Iterating by line is taking forever!"): for i, resp in enumerate(response_stream): print(f"{resp=}") assert resp == json_stream[i] # now w/ chunk sizes for chunk_size in [None, -1, 0, 1, 2, 3, 4, 8, 9, 20, 100, 1024, 32768]: print(f"\nchunk_size: {chunk_size}") HTTPretty.register_uri( HTTPretty.POST, mock_url + "/stream/it/w/chunks",
def test_get_task_by_id_fail(self): """ unit test of get_task_by_id error case """ uuid = utils.create_uuid() HTTPretty.register_uri(HTTPretty.GET, '%s/me/tasks/%s' % (AnyDoAPIBinder.host, uuid)) self.assertRaises(AnyDoAPIError, self.conn.get_task_by_id, uuid)
def test_feedparser_not_expected_response(self): HTTPretty.register_uri(HTTPretty.GET, 'http://example.org/rss') with self.assertRaises(SystemExit) as e: parser = feed_parser.FeedParser('http://example.org/rss') self.assertEqual(1, e.exception.code)
def test_get_user_info_fail(self): """ unit test of get_user_info error case """ HTTPretty.register_uri(HTTPretty.GET, '%s/me' % AnyDoAPIBinder.host) self.assertRaises(AnyDoAPIError, self.conn.get_user_info)
def __init__(self, **kwargs): """ Constructor :param api_endpoint: name of the API end point :param user_uid: unique API user ID to be returned :return: no return """ self.kwargs = kwargs self.api_endpoint = current_app.config['BIBLIB_SOLR_BIG_QUERY_URL'] 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: """ if self.kwargs.get('solr_docs'): docs = self.kwargs['solr_docs'] elif self.kwargs.get('canonical_bibcode'): docs = [] canonical_bibcodes = self.kwargs.get('canonical_bibcode') for i in range(len(canonical_bibcodes)): docs.append({'bibcode': canonical_bibcodes[i]}) print docs else: docs = [{'bibcode': 'bibcode'} for i in range(self.kwargs.get('number_of_bibcodes', 1))] resp = { 'responseHeader': { 'status': 0, 'QTime': 152, 'params': { 'fl': 'bibcode', 'q': '*:*', 'wt': 'json' } }, 'response': { 'numFound': 1, 'start': 0, 'docs': docs } } if self.kwargs.get('fail', False): resp.pop('response') resp = json.dumps(resp) status = self.kwargs.get('status', 200) return status, headers, resp HTTPretty.register_uri( HTTPretty.POST, self.api_endpoint, body=request_callback, content_type='application/json' )
def setUp(self): HTTPretty.register_uri( HTTPretty.POST, '%s/j_spring_security_check' % AnyDoAPIBinder.host) self.conn = api.AnyDoAPI(username=settings.USERNAME, password=settings.PASSWORD)
def test_get_all_categories_fail(self): """ unit test of get_all_categories error case """ HTTPretty.register_uri(HTTPretty.GET, '%s/me/categories' % AnyDoAPIBinder.host) self.assertRaises(AnyDoAPIError, self.conn.get_all_categories)