def test_rotating_responses_with_requests(now): u"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_support_a_list_of_successive_responses_httplib2( context, now): u"HTTPretty should support adding a list of successive responses with httplib2" HTTPretty.register_uri( HTTPretty.GET, "http://github.com/gabrielfalcao/httpretty", responses=[ HTTPretty.Response(body="first response", status=201), HTTPretty.Response(body='second and last response', status=202), ]) headers1, body1 = context.http.request( 'http://github.com/gabrielfalcao/httpretty', 'GET') assert that(headers1['status']).equals('201') assert that(body1).equals('first response') headers2, body2 = context.http.request( 'http://github.com/gabrielfalcao/httpretty', 'GET') assert that(headers2['status']).equals('202') assert that(body2).equals('second and last response') headers3, body3 = context.http.request( 'http://github.com/gabrielfalcao/httpretty', 'GET') assert that(headers3['status']).equals('202') assert that(body3).equals('second and last response')
def setUp(self): HTTPretty.register_uri(HTTPretty.GET, "http://localhost/", responses=[ HTTPretty.Response("glub glub"), HTTPretty.Response("buble buble"), ])
def test_httpretty_should_allow_multiple_responses_with_multiple_methods(): u"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_get_from_cache_when_twitter_api_fails(self, logging_mock): exception_message = 'Too many requests' HTTPretty.register_uri( HTTPretty.GET, self.api_url, responses=[ HTTPretty.Response(body=get_json('jeresig.json'), status=200, content_encoding='identity'), HTTPretty.Response(body=exception_message, status=429, content_encoding='identity'), ]) # it should be ok by now output, context = render_template( """{% get_tweets for "jresig" as tweets %}""") cache_key = get_user_cache_key(asvar='tweets', username='******') expect(cache.get(cache_key)).should.have.length_of(1) expect(context['tweets'][0]['text']).to.equal( "This is not John Resig - you should be following @jeresig instead!!!" ) # when twitter api fails, should use cache output2, context2 = render_template( """{% get_tweets for "jresig" as tweets %}""") expect(cache.get(cache_key)).should.have.length_of(1) expect(context2['tweets'][0]['text']).to.equal( "This is not John Resig - you should be following @jeresig instead!!!" ) logging_mock.assert_called_with(self.logger_name) expect(logging_mock.return_value.error.call_args[0][0]).should.contain( exception_message)
def test_fetch_repo_list_multiple_sites(self): responses = [ HTTPretty.Response( body=open(self.test_data_folder + 'test_response_01.json').read(), status=200, link='<https://api.github.com/organizations/1989101/repos?page=2>;' ' rel="next", ' '<https://api.github.com/organizations/1989101/repos?page=3>; ' 'rel="last"'), HTTPretty.Response( body=open(self.test_data_folder + 'test_response_02.json').read(), status=200, link='<https://api.github.com/organizations/1989101/repos?page=3>; ' 'rel="next", ' '<https://api.github.com/organizations/1989101/repos?page=3>;' ' rel="last"'), HTTPretty.Response( body=open(self.test_data_folder + 'test_response_03.json').read(), status=200, link='<https://api.github.com/organizations/1989101/repos?page=3>; ' 'rel="last"'), ] HTTPretty.register_uri(HTTPretty.GET, "https://api.github.com/orgs/some_org/repos", responses=responses) self.git_repo_updater_obj.refresh_repo_list() self.assertEqual(len(self.git_repo_updater_obj.repo_list_cache), 6)
def test_httpretty_should_support_a_list_of_successive_responses_urllib2(now): u"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 = urllib2.urlopen('https://api.yahoo.com/test') body1 = request1.read() request1.close() assert that(request1.code).equals(201) assert that(body1).equals('first response') request2 = urllib2.urlopen('https://api.yahoo.com/test') body2 = request2.read() request2.close() assert that(request2.code).equals(202) assert that(body2).equals('second and last response') request3 = urllib2.urlopen('https://api.yahoo.com/test') body3 = request3.read() request3.close() assert that(request3.code).equals(202) assert that(body3).equals('second and last response')
def test_retry_limit(): qps_headers = { 'X-Mashery-Error-Code': 'ERR_403_DEVELOPER_OVER_QPS', 'X-Mashery-Error-Detail': 'Account Over Queries Per Second Limit', 'Retry-After': 1 } qps_response = HTTPretty.Response( body='', status=403, adding_headers=qps_headers) httpretty.register_uri( httpretty.GET, re.compile(r'.*', re.M), responses=[ qps_response, qps_response, qps_response, HTTPretty.Response(body='{}', status=200), ] ) retry = WhispirRetry(total=1) whispir = whispyr.Whispir( TEST_USERNAME, TEST_PASSWORD, TEST_API_KEY, retry=retry) with pytest.raises(ClientError) as excinfo: whispir.request('get', 'workspaces') exc = excinfo.value assert exc.response.status_code == 403
def test_rotating_responses_with_httplib2(now): "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 mock_api(cls): """ Set up the URI mapping """ # this is not going to work because some URL endpoints = {} endpoints['/schemas/images/?$'] = [ MockEndpoint(HTTPretty.GET, response_body=cls.raw_images_schema_str) ] endpoints['/schemas/image/?$'] = [ MockEndpoint(HTTPretty.GET, response_body=cls.raw_image_schema_str) ] endpoints['/images/?$'] = [ MockEndpoint(HTTPretty.POST, response_headers={ 'Location': '/v2/images/21c697d1-2cc5-4a45-ba50-61fab15ab9b7' }, response_body=cls.raw_image_str, response_code=201), MockEndpoint(HTTPretty.GET, response_body=cls.raw_images_str, response_code=200) ] endpoints['/images/{image_id}'.format(image_id=cls.image_id_regex)] = [ MockEndpoint( HTTPretty.PATCH, # TODO: validate request maybe response_body=cls.raw_image_str, response_code=201), MockEndpoint(HTTPretty.GET, response_body=cls.raw_image_str), MockEndpoint(HTTPretty.DELETE, response_code=204) ] url = '/images/{image_id}/tags/{tag}'.format( image_id=cls.image_id_regex, tag=cls.tag_regex) endpoints[url] = [ MockEndpoint(HTTPretty.PUT, response_code=204), MockEndpoint(HTTPretty.DELETE, responses=[ HTTPretty.Response('successfully deleted', status=204), HTTPretty.Response('already deleted', status=404) ]) ] # register the endpoints for uri, responses in endpoints.items(): for response in responses: response.register('{0}{1}'.format(GLANCE_API_SERVER_ENDPOINT, uri))
def setUpClass(cls): cls.service = Exchange2010Service( connection=ExchangeNTLMAuthConnection( url=FAKE_EXCHANGE_URL, username=FAKE_EXCHANGE_USERNAME, password=FAKE_EXCHANGE_PASSWORD)) cls.get_change_key_response = HTTPretty.Response( body=GET_ITEM_RESPONSE_ID_ONLY.encode('utf-8'), status=200, content_type='text/xml; charset=utf-8') cls.update_event_response = HTTPretty.Response( body=UPDATE_ITEM_RESPONSE.encode('utf-8'), status=200, content_type='text/xml; charset=utf-8')
def test_no_retry_for_forbidden(whispir): httpretty.register_uri( httpretty.GET, re.compile(r'.*', re.M), responses=[ HTTPretty.Response(body='', status=403), HTTPretty.Response(body='{}', status=200), ] ) with pytest.raises(ClientError) as excinfo: whispir.request('get', 'workspaces') exc = excinfo.value assert exc.response.status_code == 403
def test_temp_failure(self): responses = [HTTPretty.Response(body="{'test': 'fail'}", status=500), HTTPretty.Response(body="{'test': 'success'}", status=200)] HTTPretty.register_uri(HTTPretty.POST, 'https://%s/temp_fail/' % self.region.endpoint, responses=responses) conn = self.region.connect(aws_access_key_id='access_key', aws_secret_access_key='secret') resp = conn.make_request('myCmd1', {'par1': 'foo', 'par2': 'baz'}, '/temp_fail/', 'POST') self.assertEqual(resp.read(), "{'test': 'success'}")
def test_waiting_for_job(self): """test Job.wait_for(<id>) works""" with open(self.json_file) as f: running_data = json.load(f) with open(self.json_file) as f: finished_data = json.load(f) running_data[self.cls.COLLECTION_NAME][:] = [d for d in running_data[self.cls.COLLECTION_NAME] if d[camelize(self.cls.PRIMARY_KEY)] == 4] finished_data[self.cls.COLLECTION_NAME][:] = [d for d in finished_data[self.cls.COLLECTION_NAME] if d[camelize(self.cls.PRIMARY_KEY)] == 4] finished_data[self.cls.COLLECTION_NAME][0]['status'] = 'COMPLETE' finished_data[self.cls.COLLECTION_NAME][0]['message'] = '12345' HTTPretty.register_uri(HTTPretty.GET, self.es_url+'/'+str(4), responses = [ #HTTPretty.Response(body=json.dumps(running_data), status=200, content_type='application/json') HTTPretty.Response(body=json.dumps(finished_data), status=200, content_type='application/json') ]) def validate(x): assert isinstance(x, self.cls) assert x.status == 'COMPLETE' assert x.message == '12345' y = self.cls.wait_for(4, callback=validate) z = self.cls.wait_for(4) assert z is True
def test_auth(self): HTTPretty.register_uri( HTTPretty.GET, 'http://rtkit.test/ticket/1', responses=[ HTTPretty.Response(body='', status=401, www_authenticate='Basic realm="rtkit.test"'), HTTPretty.Response(body='RT/3.8.10 200 Ok\n\n# Ticket 1 does not exist.\n\n\n', status=200), ] ) self.resource.get( path='ticket/1', headers={'User-Agent': 'rtkit-ua', } ) self.assertEqual( HTTPretty.last_request.headers['authorization'], 'Basic ' + base64.b64encode('USER:PASS'), )
def test_xmlrpciterator(self): """Tests bookingcom api client using xml rcp iterator""" mock_url = XmlRpcEndPointIterator.create_url('getCountries') HTTPretty.register_uri( HTTPretty.POST, mock_url, responses=[ HTTPretty.Response(body=self._FIXTURE_OFFSET_FIRST), HTTPretty.Response(body=self._FIXTURE_OFFSET_LATTER) ]) client = BookingcomClient( end_point_iterator_class=XmlRpcEndPointIterator) countries = list(client.getCountries(rows=3)) self.assertEqual(len(countries), 5) self.assertEqual(countries[0]['countrycode'], 'ad') self.assertEqual(countries[0]['name'], 'Andorra') self.assertEqual(countries[4]['countrycode'], 'al') self.assertEqual(countries[4]['name'], 'Albania')
def register_api_call(self, path, responses): response_objects = [] for response in responses: response_objects.append(HTTPretty.Response(**response)) HTTPretty.register_uri(HTTPretty.POST, self.wercker_url + '/api/1.0/' + path, responses=response_objects)
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_retry_succeeded(whispir): qps_headers = { 'X-Mashery-Error-Code': 'ERR_403_DEVELOPER_OVER_QPS', 'X-Mashery-Error-Detail': 'Account Over Queries Per Second Limit', 'Retry-After': 1 } qps_response = HTTPretty.Response( body='', status=403, adding_headers=qps_headers) httpretty.register_uri( httpretty.GET, re.compile(r'.*', re.M), responses=[ qps_response, qps_response, HTTPretty.Response(body='{}', status=200), ] ) assert whispir.request('get', 'workspaces') == {}
def test_do_not_retry_qpd(whispir): qps_headers = { 'X-Mashery-Error-Code': 'ERR_403_DEVELOPER_OVER_QPD', 'X-Mashery-Error-Detail': 'Account Over Queries Per Day Limit', 'Retry-After': 20 * 60 * 60 # 20 hours in seconds } httpretty.register_uri( httpretty.GET, re.compile(r'.*', re.M), responses=[ HTTPretty.Response( body='', status=403, adding_headers=qps_headers), HTTPretty.Response(body='{}', status=200), ] ) with pytest.raises(ClientError) as excinfo: whispir.request('get', 'workspaces') exc = excinfo.value assert exc.response.status_code == 403
def test_auth(self): HTTPretty.register_uri( HTTPretty.GET, 'http://rtkit.test/ticket/1', responses=[ HTTPretty.Response(body='RT/3.8.10 200 Ok\n\n# Ticket 1 does not exist.\n\n\n', status=200), ] ) self.resource.get( path='ticket/1', headers={'User-Agent': 'rtkit-ua', } ) self.assertEqual(HTTPretty.latest_requests[0].path, '/ticket/1?user=USER&pass=PASS')