def setup_method(self, method): httpretty.enable() httpretty.reset() httpretty.register_uri( httpretty.POST, 'http://%s:8181/api/osd/configure/' % INSTALL_HOST, body=self.post_request_callback, content_type='application/json') self.requests = []
def test_message_with_domain(self): """ Given a message with a domain specified And that domain exists in the list of known domains When the message is processed Then the message is posted And the push message is queued """ from maxbunny.consumers.conversations import __consumer__ from maxbunny.tests.mockers.conversations import CONVERSATION_MESSAGE as message message_id = '00000000001' self.set_server(message, message_id) httpretty.enable() http_mock_info() http_mock_post_user_message(uri='tests.local', message_id=message_id) runner = MockRunner('conversations', 'maxbunny.ini', 'instances2.ini') consumer = __consumer__(runner) consumer.process(message) httpretty.disable() httpretty.reset() sleep(0.1) # Leave a minimum time to message to reach rabbitmq messages = self.server.get_all('push') self.assertEqual(len(messages), 1) self.assertEqual(messages[0][0]['a'], 'k') self.assertEqual(messages[0][0]['o'], 'm') self.assertEqual(messages[0][0]['s'], 'b') self.assertEqual(messages[0][0]['d']['id'], '00000000001')
def test_get_alphanames_list(self): expected_results = ( ('TEST_ALPHANAME', 'ACTIVE'), ('GRAMMAR_NAZI', 'ACTIVE'), ('LALALA', 'MODERATE'), ) httpretty.register_uri(httpretty.POST, SMSFlyAPI.API_URL, body="""<?xml version="1.0" encoding="utf-8"?> <message> <state alfaname="TEST_ALPHANAME" status="ACTIVE" /> <state alfaname="GRAMMAR_NAZI" status="ACTIVE" /> <state alfaname="LALALA" status="MODERATE" /> </message> """) alphaname_res = self.api.get_alphanames_list() for n, state in enumerate(alphaname_res.findAll('state')): self.assertEqual(state.attrs['alfaname'], expected_results[n][0]) # it's `alfaname` due to docs :( self.assertEqual(state.attrs['status'], expected_results[n][1]) httpretty.reset() httpretty.register_uri(httpretty.POST, SMSFlyAPI.API_URL, body=request_body_callback) api_req_body = self.api.get_alphanames_list() expected_body = ('<?xml version="1.0" encoding="utf-8"?>\n' '<request>' '<operation>MANAGEALFANAME</operation>' '<command id="GETALFANAMESLIST"/>' '</request>') self.assertEqual(str(api_req_body), expected_body)
def test_set_headers(version): httpretty.reset() httpretty.enable() uri = get_fix(version).DISCOVERY_URI_HTTP response = get_fix(version).DISCOVERY_RESPONSE register_uri(uri, response, version) client = make_client( version, headers={CUSTOM_HEADER_NAME: CUSTOM_HEADER_VALUE}) services = client.discover_services(uri=uri) assert len(services) == 4 message = get_sent_message(version) assert type(message) == (tm11 if version == 11 else tm10).DiscoveryRequest last_request = httpretty.last_request() assert CUSTOM_HEADER_NAME in last_request.headers assert last_request.headers[CUSTOM_HEADER_NAME] == CUSTOM_HEADER_VALUE httpretty.disable() httpretty.reset()
def tearDown(self): self.w3afcore.quit() self.kb.cleanup() if self.MOCK_RESPONSES: httpretty.disable() httpretty.reset()
def test_invalid_message_missing_username(self): """ Given a message with missing username When the message is processed Then an exception is raised And the push message is not queued """ from maxbunny.consumers.conversations import __consumer__ from maxbunny.tests.mockers.conversations import MISSING_USERNAME_MESSAGE as message self.set_server({}, None) httpretty.enable() http_mock_info() runner = MockRunner('conversations', 'maxbunny.ini', 'instances2.ini') consumer = __consumer__(runner) self.assertRaisesWithMessage( BunnyMessageCancel, 'Missing username in message', consumer.process, message ) httpretty.disable() httpretty.reset() sleep(0.1) # Leave a minimum time to message to reach rabbitmq messages = self.server.get_all('push') self.assertEqual(len(messages), 0)
def test_with_path(self, baseapi): httpretty.enable() stub_request('http://localhost:8080/v3/nodes/node1') baseapi._query('nodes', path='node1') assert httpretty.last_request().path == '/v3/nodes/node1' httpretty.disable() httpretty.reset()
def tearDown(self): os.remove("line_file.json") os.remove("array_file.json") os.remove("object_file.json") os.remove("block_file.json") httpretty.disable() httpretty.reset()
def test_for_name_translation_required_parameters(api, json_response): httpretty.enable() httpretty.register_uri(httpretty.POST, "https://api.rosette.com/rest/v1/info", body=json_response, status=200, content_type="application/json") httpretty.register_uri(httpretty.POST, "https://api.rosette.com/rest/v1/name-translation", body=json_response, status=200, content_type="application/json") params = NameTranslationParameters() params["entityType"] = "PERSON" params["targetScript"] = "Latn" with pytest.raises(RosetteException) as e_rosette: result = api.name_translation(params) assert e_rosette.value.status == 'missingParameter' assert e_rosette.value.message == 'Required Name Translation parameter not supplied' params["name"] = "some data to translate" with pytest.raises(RosetteException) as e_rosette: result = api.name_translation(params) assert e_rosette.value.status == 'missingParameter' assert e_rosette.value.message == 'Required Name Translation parameter not supplied' params["targetLanguage"] = "eng" result = api.name_translation(params) assert result["name"] == "Rosette API" httpretty.disable() httpretty.reset()
def httprettified(request): """ pytest style fixture to activate/deactive httpretty so that you get the benefit of the @httpretty.activate decoratator without having to use it. Basically, this won't work: @httpretty.activate def test_foo(some_pytest_fixture): pass Use this instead: def test_foo(httprettified, some_pytest_fixture): # interactions with httpretty occur as if you'd decorated # this function with @httpretty.activate httpretty.register_uri(...) If you're passing multiple fixtures to the test that rely on httpretty being activated, make sure that `httprettified` is before all the other fixtures that depend on it. :param request: This is a pytest (confusingly named) param. Don't worry about it. """ # TODO: move to test util package httpretty.reset() httpretty.enable() def fin(): httpretty.disable() request.addfinalizer(fin)
def test_metric(self, baseapi): httpretty.enable() stub_request('http://localhost:8080/v3/metrics/mbean/test') baseapi.metric('test') assert httpretty.last_request().path == '/v3/metrics/mbean/test' httpretty.disable() httpretty.reset()
def setUp(self): super(ThreadSerializerDeserializationTest, self).setUp() httpretty.reset() httpretty.enable() self.addCleanup(httpretty.reset) self.addCleanup(httpretty.disable) self.user = UserFactory.create() self.register_get_user_response(self.user) self.request = RequestFactory().get("/dummy") self.request.user = self.user self.minimal_data = { "course_id": unicode(self.course.id), "topic_id": "test_topic", "type": "discussion", "title": "Test Title", "raw_body": "Test body", } self.existing_thread = Thread(**make_minimal_cs_thread({ "id": "existing_thread", "course_id": unicode(self.course.id), "commentable_id": "original_topic", "thread_type": "discussion", "title": "Original Title", "body": "Original body", "user_id": str(self.user.id), "username": self.user.username, "read": "False", "endorsed": "False" }))
def test_missing_domain_missing_default(self): """ Given a message with no domain specified And there is no default domain specified When the message is processed Then an exception is raised And the push message is not queued """ from maxbunny.consumers.conversations import __consumer__ from maxbunny.tests.mockers.conversations import MISSING_DOMAIN_MESSAGE as message self.set_server({}, None) httpretty.enable() http_mock_info() runner = MockRunner('conversations', 'maxbunny.ini', 'instances.ini') consumer = __consumer__(runner) self.assertRaisesWithMessage( BunnyMessageCancel, 'Missing domain, and default could not be loaded', consumer.process, message ) httpretty.disable() httpretty.reset() sleep(0.1) # Leave a minimum time to message to reach rabbitmq messages = self.server.get_all('push') self.assertEqual(len(messages), 0)
def test_request_redirect_delete(self): url = self.client.format_url("/get_endpoint") request = self.client.delete(url, {'check':True}) httpretty.register_uri(httpretty.DELETE, 'https://my_service.com/http/success/200', status=200) httpretty.register_uri(httpretty.DELETE, "https://my_service.com/get_endpoint", responses=[ httpretty.Response(body="", status=307, method='DELETE', location='/http/success/200'), ]) response = self.client.send(request) self.assertEqual(response.status_code, 200, msg="Should redirect on 307 with location header") self.assertEqual(response.request.method, 'DELETE') self.assertEqual(response.history[0].status_code, 307) self.assertTrue(response.history[0].is_redirect) httpretty.reset() httpretty.register_uri(httpretty.DELETE, "https://my_service.com/get_endpoint", responses=[ httpretty.Response(body="", status=307, method='DELETE'), ]) response = self.client.send(request) self.assertEqual(response.status_code, 307, msg="Should not redirect on 307 without location header") self.assertEqual(response.history, []) self.assertFalse(response.is_redirect)
def test_invalid_message_unknown_domain(self): """ Given a message with a domain specified And that domain doesn't match any of the known domains When the message is processed Then an exception is raised And the push message is not queued """ from maxbunny.consumers.conversations import __consumer__ from maxbunny.tests.mockers.conversations import UNKNOWN_DOMAIN_MESSAGE as message self.set_server({}, None) httpretty.enable() http_mock_info() runner = MockRunner('conversations', 'maxbunny.ini', 'instances2.ini') consumer = __consumer__(runner) self.assertRaisesWithMessage( BunnyMessageCancel, 'Unknown domain "unknown"', consumer.process, message ) httpretty.disable() httpretty.reset() sleep(0.1) # Leave a minimum time to message to reach rabbitmq messages = self.server.get_all('push') self.assertEqual(len(messages), 0)
def test_known_pull_request_task(app, owner, repository, session): """Task pull_request /pulls/1 that already exists.""" httpretty.reset() cs1 = CommitStatus(repository, "1", "https://github.com/pulls/1", {"message": [], "files": {}}) cs2 = CommitStatus(repository, "2", "https://github.com/pulls/2", {"message": [], "files": {}}) session.add(cs1) session.add(cs2) session.commit() bs = BranchStatus(cs2, "test:my-branch", "https://github.com/pulls/1", {"commits": [cs1, cs2], "files": {}}) session.add(bs) session.commit() assert_that(bs.is_pending(), equal_to(False)) httpretty.enable() pull_request(bs.id, "https://api.github.com/pulls/1", "http://kwalitee.invenio-software.org/status/2", {"ACCESS_TOKEN": "deadbeef"}) httpretty.disable() latest_requests = httpretty.HTTPretty.latest_requests assert_that(len(latest_requests), equal_to(0), "No requests are expected")
def test_request_redirect_post(self): request = self.client.post("/get_endpoint", {'check':True}) httpretty.register_uri(httpretty.GET, 'https://my_service.com/http/success/get/200', status=200) httpretty.register_uri(httpretty.POST, "https://my_service.com/get_endpoint", responses=[ httpretty.Response(body="", status=303, method='POST', location='/http/success/get/200'), ]) response = self.client.send(request) self.assertEqual(response.status_code, 200, msg="Should redirect with GET on 303 with location header") self.assertEqual(response.request.method, 'GET') self.assertEqual(response.history[0].status_code, 303) self.assertTrue(response.history[0].is_redirect) httpretty.reset() httpretty.register_uri(httpretty.POST, "https://my_service.com/get_endpoint", responses=[ httpretty.Response(body="", status=303, method='POST'), ]) response = self.client.send(request) self.assertEqual(response.status_code, 303, msg="Should not redirect on 303 without location header") self.assertEqual(response.history, []) self.assertFalse(response.is_redirect)
def test_add_alphaname(self): httpretty.register_uri(httpretty.POST, SMSFlyAPI.API_URL, body="""<?xml version="1.0" encoding="utf-8"?> <message> <state alfaname="TEST_ALPHANAME" status="MODERATE" /> </message> """) alphaname_res = self.api.add_alphaname('TEST_ALPHANAME') self.assertEqual(alphaname_res.state.attrs['alfaname'], 'TEST_ALPHANAME') # it's `alfaname` due to docs :( self.assertEqual(alphaname_res.state.attrs['status'], 'MODERATE') httpretty.reset() httpretty.register_uri(httpretty.POST, SMSFlyAPI.API_URL, body=request_body_callback) api_req_body = self.api.add_alphaname('TEST_ALPHANAME') expected_body = ('<?xml version="1.0" encoding="utf-8"?>\n' '<request>' '<operation>MANAGEALFANAME</operation>' '<command alfaname="TEST_ALPHANAME" id="ADDALFANAME"/>' '</request>') self.assertEqual(str(api_req_body), expected_body)
def test_bad_verification_code(app, db): with app.test_request_context(): # Test redirect client = app.test_client() resp = client.get( url_for('invenio_oauthclient.login', remote_app='github') ) assert resp.status_code == 302 assert resp.location.startswith( 'https://github.com/login/oauth/authorize' ) state = get_state(resp.location) httpretty.enable() fixtures.register_github_api() # Test restart of auth flow when getting a bad_verification_code resp = client.get( url_for( 'invenio_oauthclient.authorized', remote_app='github', code='bad_verification_code', state=state, ) ) assert resp.status_code == 302 # assert resp.location.endswith( # url_for('invenio_oauthclient.login', remote_app='github') # ) httpretty.disable() httpretty.reset()
def tearDown(self): httpretty.disable() httpretty.reset() tinify.app_identifier = None tinify.key = None tinify.compression_count
def test_session(self): """ Ensures that the session has the expected connectivity """ httpretty.enable() httpretty.register_uri( httpretty.GET, 'http://consul.internal:8501/v1/status/leader', body="localhost:8300", ) app = self.create_app() consul = Consul( app, consul_host='consul.internal', consul_port='8501', test_connection=True ) self.assertIsNotNone(consul) httpretty.disable() httpretty.reset() app = self.create_app() self.assertRaises( ConsulConnectionError, lambda: Consul( app, consul_host='consul.internal', consul_port='8501', test_connection=True ), )
def test_bad_verification_code(self): # Test redirect resp = self.client.get( url_for("oauthclient.login", remote_app='github') ) self.assertStatus(resp, 302) assert resp.location.startswith( "https://github.com/login/oauth/authorize" ) httpretty.enable() fixtures.register_github_api() # Test restart of auth flow when getting a bad_verification_code resp = self.client.get( url_for( "oauthclient.authorized", remote_app='github', code='bad_verification_code' ) ) assert resp.status_code == 302 assert resp.location.endswith( url_for('oauthclient.login', remote_app='github') ) httpretty.disable() httpretty.reset()
def test_fact_names(self, baseapi): httpretty.enable() stub_request('http://localhost:8080/pdb/query/v4/fact-names') baseapi.fact_names() assert httpretty.last_request().path == '/pdb/query/v4/fact-names' httpretty.disable() httpretty.reset()
def test_environments(self, baseapi): httpretty.enable() stub_request('http://localhost:8080/pdb/query/v4/environments') baseapi.environments() assert httpretty.last_request().path == '/pdb/query/v4/environments' httpretty.disable() httpretty.reset()
def test_has_request(): ("httpretty.has_request() correctly detects " "whether or not a request has been made") httpretty.reset() httpretty.has_request().should.be.false with patch('httpretty.httpretty.last_request', return_value=HTTPrettyRequest('')): httpretty.has_request().should.be.true
def test_fail_with_invalid_reply_to(self): httpretty.register_uri(httpretty.POST, 'https://api.sendgrid.com/api/mail.send.json') # manually confirm r = self.client.post('/[email protected]', headers = {'Referer': 'http://carlitos.net/'}, data={'name': 'carlitos'} ) f = Form.query.first() f.confirm_sent = True f.confirmed = True DB.session.add(f) DB.session.commit() # fail with an invalid '_replyto' httpretty.reset() r = self.client.post('/[email protected]', headers = {'Referer': 'http://carlitos.net/'}, data={'name': 'Real Stock', '_replyto': 'The best offers.'} ) self.assertEqual(False, httpretty.has_request()) self.assertEqual(400, r.status_code) self.assertEqual(0, Form.query.first().counter) # fail with an invalid 'email' httpretty.reset() r = self.client.post('/[email protected]', headers = {'Referer': 'http://carlitos.net/'}, data={'name': 'Real Stock', 'email': 'The best offers.'} ) self.assertEqual(False, httpretty.has_request()) self.assertEqual(400, r.status_code) self.assertEqual(0, Form.query.first().counter)
def moves_auth(): httpretty.enable() def _method(method): return {"GET": httpretty.GET, "POST": httpretty.POST}[method] strategy = DjangoStrategy(MovesOAuth2, DjangoStorage) start_url = strategy.start().url target_url = handle_state(MovesOAuth2, start_url, strategy.build_absolute_uri("/complete/{0}/?code=foobar")) 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( _method(MovesOAuth2.ACCESS_TOKEN_METHOD), uri=MovesOAuth2.ACCESS_TOKEN_URL, status=200, body=json.dumps({"access_token": "foobar", "token_type": "bearer"}), content_type="text/json", ) user_data_url = "https://api.moves-app.com.com/oauth2/v1/user/profile" if user_data_url: httpretty.register_uri( httpretty.GET, user_data_url, body=json.dumps({"userId": "1010101010011"}), content_type="application/json" ) yield httpretty.disable() httpretty.reset()
def tearDown(self): """ Tear down test. """ httpretty.disable() httpretty.reset() if os.path.exists('output_test'): shutil.rmtree('output_test')
def mock_credentials_api(self, user, data=None, status_code=200, reset_url=True, is_next_page=False): """Utility for mocking out Credentials API URLs.""" self.assertTrue(httpretty.is_enabled(), msg='httpretty must be enabled to mock Credentials API calls.') internal_api_url = CredentialsApiConfig.current().internal_api_url.strip('/') url = internal_api_url + '/user_credentials/?username='******'/user_credentials/?page=2&username='******'next'] = next_page_url next_page_body = json.dumps(self.CREDENTIALS_NEXT_API_RESPONSE) httpretty.register_uri( httpretty.GET, next_page_url, body=body, content_type='application/json', status=status_code ) httpretty.register_uri( httpretty.GET, url, body=next_page_body, content_type='application/json', status=status_code ) else: httpretty.register_uri( httpretty.GET, url, body=body, content_type='application/json', status=status_code )
def test_timeout(version): httpretty.reset() httpretty.enable() timeout_in_sec = 1 client = make_client(version) # # configure to raise the error before the timeout # client.timeout = timeout_in_sec / 2.0 def timeout_request_callback(request, uri, headers): sleep(timeout_in_sec) return (200, headers, "All good!") uri = get_fix(version).DISCOVERY_URI_HTTP httpretty.register_uri( httpretty.POST, uri, body=timeout_request_callback, content_type='application/json' ) with pytest.raises(requests.exceptions.Timeout): client.discover_services(uri=uri) httpretty.disable() httpretty.reset()
def setUp(self): super().setUp() httpretty.reset() httpretty.enable() self.addCleanup(httpretty.reset) self.addCleanup(httpretty.disable) self.user = UserFactory.create() self.register_get_user_response(self.user) self.request = RequestFactory().get("/dummy") self.request.user = self.user self.minimal_data = { "thread_id": "test_thread", "raw_body": "Test body", } self.existing_comment = Comment( **make_minimal_cs_comment({ "id": "existing_comment", "thread_id": "existing_thread", "body": "Original body", "user_id": str(self.user.id), "username": self.user.username, "course_id": str(self.course.id), }))
def test_the_name_translation_endpoint(api, json_response): """Test the name translation endpoint""" httpretty.enable() httpretty.register_uri(httpretty.POST, "https://api.rosette.com/rest/v1/info", body=json_response, status=200, content_type="application/json") httpretty.register_uri(httpretty.POST, "https://api.rosette.com/rest/v1/name-translation", body=json_response, status=200, content_type="application/json") params = NameTranslationParameters() params["name"] = "some data to translate" params["entityType"] = "PERSON" params["targetLanguage"] = "eng" params["targetScript"] = "Latn" result = api.name_translation(params) assert result["name"] == "Rosette API" httpretty.disable() httpretty.reset()
def test_post_cut(self): client = Client('https://httpbin.org/post', 'https://httpbin.org/post', directory) content = { "to_cut": { "start_time": "16/12/2018 00:51:54;16", "end_time": "16/12/2018 01:38:24;0", "title": "SUP - (DES)ENCONTRO PERFEITO - S", "duration": "00:46:29;15", "reconcile_key": "20181215234" } } path = {"video_path": client.video_path} content.update(path) httpretty.enable() httpretty.register_uri(httpretty.POST, "https://httpbin.org/post", body=json.dumps(content)) response = client.post_cut(json.dumps(content)) self.assertEqual(response.status_code, 200) self.assertEqual(response.json(), content) httpretty.disable() httpretty.reset()
def _set_mock_metadata(gce_meta=None): if gce_meta is None: gce_meta = GCE_META def _request_callback(method, uri, headers): url_path = urlparse(uri).path if url_path.startswith('/computeMetadata/v1/'): path = url_path.split('/computeMetadata/v1/')[1:][0] recursive = path.endswith('/') path = path.rstrip('/') else: path = None if path in gce_meta: response = gce_meta.get(path) if recursive: response = json.dumps(response) return (200, headers, response) else: return (404, headers, '') # reset is needed. https://github.com/gabrielfalcao/HTTPretty/issues/316 httpretty.reset() httpretty.register_uri(httpretty.GET, MD_URL_RE, body=_request_callback)
def test_bad_verification_code(self): # Test redirect resp = self.client.get( url_for("oauthclient.login", remote_app='github')) self.assertStatus(resp, 302) assert resp.location.startswith( "https://github.com/login/oauth/authorize") httpretty.enable() fixtures.register_github_api() # Test restart of auth flow when getting a bad_verification_code resp = self.client.get( url_for("oauthclient.authorized", remote_app='github', code='bad_verification_code')) assert resp.status_code == 302 assert resp.location.endswith( url_for('oauthclient.login', remote_app='github')) httpretty.disable() httpretty.reset()
def test_rollback_templating_definition_inside(): """Test spintest with templating inside rollback.""" httpretty.enable() httpretty.register_uri(httpretty.POST, "http://test.com/test", status=500) httpretty.register_uri( httpretty.GET, "http://test.com/test", body=json.dumps({"foo": "bar"}), status=200, ) httpretty.register_uri(httpretty.DELETE, "http://test.com/bar", status=204) spintest( ["http://test.com"], [{ "method": "POST", "route": "/test", "rollback": [ { "method": "GET", "route": "/test", "output": "test" }, { "method": "DELETE", "route": "/{{ test['foo'] }}" }, ], }], ) assert httpretty.last_request().method == httpretty.DELETE httpretty.disable() httpretty.reset()
def test_task_with_fix_token_set_configuration(): """Test spintest with a strict match on custom body.""" httpretty.enable() httpretty.register_uri( httpretty.GET, "http://test.com/test", body=json.dumps({ "a": "a", "b": "b", "c": "c" }), status=200, ) result = spintest( ["http://test.com"], [{ "method": "GET", "route": "/test", "expected": { "code": 200, "body": { "a": "a", "b": "b", "c": "c" }, "expected_match": "strict", }, }], token="ABC", ) assert True is result httpretty.disable() httpretty.reset()
def test_fail_with_invalid_reply_to(self): httpretty.register_uri(httpretty.POST, 'https://api.sendgrid.com/api/mail.send.json') # manually confirm r = self.client.post('/[email protected]', headers={'Referer': 'http://carlitos.net/'}, data={'name': 'carlitos'}) f = Form.query.first() f.confirm_sent = True f.confirmed = True DB.session.add(f) DB.session.commit() # fail with an invalid '_replyto' httpretty.reset() r = self.client.post('/[email protected]', headers={'Referer': 'http://carlitos.net/'}, data={ 'name': 'Real Stock', '_replyto': 'The best offers.' }) self.assertEqual(False, httpretty.has_request()) self.assertEqual(400, r.status_code) self.assertEqual(0, Form.query.first().counter) # fail with an invalid 'email' httpretty.reset() r = self.client.post('/[email protected]', headers={'Referer': 'http://carlitos.net/'}, data={ 'name': 'Real Stock', 'email': 'The best offers.' }) self.assertEqual(False, httpretty.has_request()) self.assertEqual(400, r.status_code) self.assertEqual(0, Form.query.first().counter)
def test_invalid_response(version): httpretty.reset() httpretty.enable() uri = get_fix(version).DISCOVERY_URI_HTTP # FIXME: httpretty returns body as byte string (utf-8 encoded) # and when libtaxii tries to join headers (unicode) with the body (binary) # error happens. Line in Libtaxii codebase # https://github.com/EclecticIQ/libtaxii/blob/master/libtaxii/__init__.py#L126 return httpretty.register_uri(httpretty.POST, uri, body='INVALID-BODY', content_type='text/html') client = make_client(version) with pytest.raises(exc.InvalidResponseError): client.discover_services(uri=uri) httpretty.disable() httpretty.reset()
def setUp(self): """ Initialize the configuration """ Cache.last_updated[APIURL] = {'__oldest': '2016-12-18T11:49:37Z'} httpretty.reset() httpretty.enable(allow_net_connect=False) oscrc = os.path.join(FIXTURES, 'oscrc') osc.core.conf.get_config(override_conffile=oscrc, override_no_keyring=True, override_no_gnome_keyring=True) #osc.conf.config['debug'] = 1 #osc.conf.config['http_debug'] = 1 logging.basicConfig() self.logger = logging.getLogger(__file__) self.logger.setLevel(logging.DEBUG) self.checker = FactorySourceChecker(apiurl = APIURL, user = '******', logger = self.logger) self.checker.override_allow = False # Test setup cannot handle.
def setUp(self): super(CommentViewSetPartialUpdateTest, self).setUp() httpretty.reset() httpretty.enable() self.addCleanup(httpretty.disable) self.register_get_user_response(self.user) self.url = reverse("comment-detail", kwargs={"comment_id": "test_comment"}) cs_thread = make_minimal_cs_thread({ "id": "test_thread", "course_id": unicode(self.course.id), }) self.register_get_thread_response(cs_thread) cs_comment = make_minimal_cs_comment({ "id": "test_comment", "course_id": cs_thread["course_id"], "thread_id": cs_thread["id"], "username": self.user.username, "user_id": str(self.user.id), "created_at": "2015-06-03T00:00:00Z", "updated_at": "2015-06-03T00:00:00Z", "body": "Original body", }) self.register_get_comment_response(cs_comment) self.register_put_comment_response(cs_comment)
def setUp(self): super(SamlIntegrationTestUtilities, self).setUp() self.enable_saml( private_key=self._get_private_key(), public_key=self._get_public_key(), entity_id="https://saml.example.none", ) # Mock out HTTP requests that may be made to TestShib: httpretty.enable() httpretty.reset() self.addCleanup(httpretty.reset) self.addCleanup(httpretty.disable) def metadata_callback(_request, _uri, headers): """ Return a cached copy of TestShib's metadata by reading it from disk """ return (200, headers, self.read_data_file('testshib_metadata.xml')) httpretty.register_uri(httpretty.GET, TESTSHIB_METADATA_URL, content_type='text/xml', body=metadata_callback) def cache_duration_metadata_callback(_request, _uri, headers): """Return a cached copy of TestShib's metadata with a cacheDuration attribute""" return (200, headers, self.read_data_file('testshib_metadata_with_cache_duration.xml')) httpretty.register_uri( httpretty.GET, TESTSHIB_METADATA_URL_WITH_CACHE_DURATION, content_type='text/xml', body=cache_duration_metadata_callback ) # Configure the SAML library to use the same request ID for every request. # Doing this and freezing the time allows us to play back recorded request/response pairs uid_patch = patch('onelogin.saml2.utils.OneLogin_Saml2_Utils.generate_unique_id', return_value='TESTID') uid_patch.start() self.addCleanup(uid_patch.stop) self._freeze_time(timestamp=1434326820) # This is the time when the saved request/response was recorded.
def test__request(self): url = 'http://example.com' auth = self.client._make_auth(self.api_id, self.api_password).decode('utf-8') httpretty.register_uri(httpretty.GET, url, '{"response": {"result_code": 0}}') response = self.client._request(url) request = httpretty.HTTPretty.last_request self.assertEqual(response, {'result_code': 0}) self.assertEqual(request.headers.get('Accept'), 'application/json') self.assertEqual(request.headers.get('Authorization'), auth) httpretty.register_uri(httpretty.PUT, url, '{"response": {"result_code": 0}}') response = self.client._request(url, {'user': '******'}) request = httpretty.HTTPretty.last_request self.assertEqual(response, {'result_code': 0}) self.assertEqual(request.headers.get('Accept'), 'application/json') self.assertEqual(request.headers.get('Authorization'), auth) self.assertEqual(request.headers.get('Content-Type'), 'application/x-www-form-urlencoded') self.assertEqual(request.body, b'user=tel%3A%2B79998887766') httpretty.reset() httpretty.register_uri(httpretty.GET, url, '{"response": {"result_code": 33}}', status=400) try: self.client._request(url) except QiwiError as e: self.assertEqual(e.code, 33) else: self.fail('QiwiError not raised')
def testItemCreation(self): """ Tests creation of a new item using a template """ zot = z.Zotero("myuserID", "user", "myuserkey") HTTPretty.register_uri( HTTPretty.GET, "https://api.zotero.org/items/new?itemType=book", body=self.item_templt, content_type="application/json", ) template = zot.item_template("book") httpretty.reset() HTTPretty.register_uri( HTTPretty.POST, "https://api.zotero.org/users/myuserID/items", body=self.creation_doc, content_type="application/json", status=200, ) # now let's test something resp = zot.create_items([template]) self.assertEqual("ABC123", resp["success"]["0"]) request = httpretty.last_request() self.assertFalse("If-Unmodified-Since-Version" in request.headers)
def test_two_tokens_are_generated_with_one_task_with_two_retry(): httpretty.enable() httpretty.register_uri( httpretty.GET, "http://test.com/test", status=200, body=json.dumps({"status": "CREATED"}), ) httpretty.register_uri( httpretty.GET, "http://test.com/test", status=200, body=json.dumps({"status": "CREATING"}), ) loop = asyncio.new_event_loop() token_func = FakeCreatedToken() manager = TaskManager( ["http://test.com"], [{ "method": "GET", "route": "/test", "expected": { "body": { "status": "CREATED" } }, "retry": 1, }], token=token_func, ) result = loop.run_until_complete(manager.next()) assert "SUCCESS" == result["status"] assert token_func.call_count == 2 httpretty.disable() httpretty.reset()
def test_metric_v2_list(self, baseapi): # test metric() (no arguments) metrics_body = { 'request': { 'type': 'list' }, 'value': { 'java.util.logging': { 'type=Logging': {} }, }, 'timestamp': 0, 'status': 200 } httpretty.enable() httpretty.register_uri(httpretty.GET, 'http://localhost:8080/metrics/v2/list', body=json.dumps(metrics_body)) metric = baseapi.metric() assert httpretty.last_request().path == '/metrics/v2/list' assert metric == {'java.util.logging': {'type=Logging': {}}} httpretty.disable() httpretty.reset()
def test_to_low_flush_interval(self): self._write_client.__del__() self._write_client = WriteApi(influxdb_client=self.influxdb_client, write_options=WriteOptions( batch_size=8, flush_interval=1, jitter_interval=1000)) httpretty.register_uri(httpretty.POST, uri="http://localhost/api/v2/write", status=204) for i in range(50): val_one = float(i) val_two = float(i) + 0.5 point_one = Point("OneMillis").tag("sensor", "sensor1").field( "PSI", val_one).time(time=i) point_two = Point("OneMillis").tag("sensor", "sensor2").field( "PSI", val_two).time(time=i) self._write_client.write("my-bucket", "my-org", [point_one, point_two]) time.sleep(0.1) self._write_client.__del__() _requests = httpretty.httpretty.latest_requests for _request in _requests: body = _request.parsed_body self.assertTrue(body, msg="Parsed body should be not empty " + str(_request)) httpretty.reset()
def test_task_with_ignore_option_followed_by_error(): """Test spintest with ignore option.""" httpretty.enable() httpretty.register_uri(httpretty.GET, "http://test.com/test", status=500) result = spintest( ["http://test.com"], [ { "method": "GET", "route": "/test", "ignore": True }, { "method": "GET", "route": "/test" }, ], ) assert False is result httpretty.disable() httpretty.reset()
def setUp(self) -> None: # https://github.com/gabrielfalcao/HTTPretty/issues/368 import warnings warnings.filterwarnings("ignore", category=ResourceWarning, message="unclosed.*") warnings.filterwarnings("ignore", category=PendingDeprecationWarning, message="isAlive*") httpretty.enable() httpretty.reset() conf = influxdb_client.configuration.Configuration() conf.host = "http://localhost" conf.debug = False self.influxdb_client = InfluxDBClient(url=conf.host, token="my-token") self.write_options = WriteOptions(batch_size=2, flush_interval=5_000, retry_interval=3_000) self._write_client = WriteApi(influxdb_client=self.influxdb_client, write_options=self.write_options)
def setUp(self): self.kb.cleanup() self.w3afcore = w3afCore() self.request_callback_call_count = 0 self.request_callback_match = 0 if self.MOCK_RESPONSES: httpretty.reset() httpretty.enable() try: url = URL(self.target_url) except ValueError, ve: msg = ('When using MOCK_RESPONSES you need to set the' ' target_url attribute to a valid URL, exception was:' ' "%s".') raise Exception(msg % ve) domain = url.get_domain() proto = url.get_protocol() port = url.get_port() self._register_httpretty_uri(proto, domain, port)
def test_fail_but_appears_to_have_succeeded_with_gotcha(self): httpretty.register_uri(httpretty.POST, 'https://api.sendgrid.com/api/mail.send.json') # manually confirm r = self.client.post('/[email protected]', headers={'Referer': 'http://carlitos.net/'}, data={'name': 'carlitos'}) f = Form.query.first() f.confirm_sent = True f.confirmed = True DB.session.add(f) DB.session.commit() httpretty.reset() r = self.client.post('/[email protected]', headers={'Referer': 'http://carlitos.net/'}, data={ 'name': 'Real Stock', '_gotcha': 'The best offers.' }) self.assertEqual(False, httpretty.has_request()) self.assertEqual(302, r.status_code) self.assertEqual(0, Form.query.first().counter)
def test_metric_v2_version_string(self, baseapi): metrics_body = { 'request': { 'mbean': 'test:name=Num', 'type': 'read' }, 'value': { 'Value': 0 }, 'timestamp': 0, 'status': 200 } httpretty.enable() httpretty.register_uri( httpretty.GET, 'http://localhost:8080/metrics/v2/read/test:name=Num', body=json.dumps(metrics_body)) metric = baseapi.metric('test:name=Num', version='v2') assert httpretty.last_request( ).path == '/metrics/v2/read/test%3Aname%3DNum' assert metric['Value'] == 0 httpretty.disable() httpretty.reset()
def test_response_handling(self): client = Client(api_key, api_secret) # Check that 2XX responses always return the response error_response = { 'errors': [{ 'id': 'fakeid', 'message': 'some error message', }], 'data': mock_item, } error_str = json.dumps(error_response) for code in [200, 201, 204]: hp.register_uri(hp.GET, re.compile('.*' + str(code) + '$'), lambda r, u, h: (code, h, error_str)) response = client._get(str(code)) self.assertEqual(response.status_code, code) # Check that when the error data is in the response, that's what is used. import pycoinbase.wallet.error for eid, eclass in six.iteritems( pycoinbase.wallet.error._error_id_to_class): error_response = { 'errors': [{ 'id': eid, 'message': 'some message', }], 'data': mock_item, } error_str = json.dumps(error_response) hp.reset() hp.register_uri(hp.GET, re.compile('.*test$'), lambda r, u, h: (400, h, error_str)) with self.assertRaises(eclass): client._get('test') # Check that when the error data is missing, the status code is used # instead. error_response = {'data': mock_item} for code, eclass in six.iteritems( pycoinbase.wallet.error._status_code_to_class): hp.reset() hp.register_uri( hp.GET, re.compile('.*test$'), lambda r, u, h: (code, h, json.dumps(error_response))) with self.assertRaises(eclass): client._get('test') # Check that when the response code / error id is unrecognized, a generic # APIError is returned hp.reset() hp.register_uri(hp.GET, re.compile('.*test$'), lambda r, u, h: (418, h, '{}')) with self.assertRaises(APIError): client._get('test')
def assertCorrectActivityUrl(self, course, activity_type=None): """ Verifies that the activity URL is correct. """ uri = self.get_api_url('courses/{0}/activity/'.format(course.course_id)) if activity_type: uri += '?activity_type=%s' % activity_type httpretty.register_uri(httpretty.GET, uri, body='{}') course.activity(activity_type) date = '2014-01-01' httpretty.reset() httpretty.register_uri(httpretty.GET, '{0}&start_date={1}'.format(uri, date), body='{}') course.activity(activity_type, start_date=date) httpretty.reset() httpretty.register_uri(httpretty.GET, '{0}&end_date={1}'.format(uri, date), body='{}') course.activity(activity_type, end_date=date) httpretty.reset() httpretty.register_uri(httpretty.GET, '{0}&start_date={1}&end_date={1}'.format(uri, date), body='{}') course.activity(activity_type, start_date=date, end_date=date)
def assertCorrectEnrollmentUrl(self, course, demographic=None): """ Verifies that the enrollment URL is correct. """ uri = self.get_api_url('courses/{0}/enrollment/'.format(course.course_id)) if demographic: uri += '%s/' % demographic httpretty.register_uri(httpretty.GET, uri, body='{}') course.enrollment(demographic) date = '2014-01-01' httpretty.reset() httpretty.register_uri(httpretty.GET, '{0}?start_date={1}'.format(uri, date), body='{}') course.enrollment(demographic, start_date=date) httpretty.reset() httpretty.register_uri(httpretty.GET, '{0}?end_date={1}'.format(uri, date), body='{}') course.enrollment(demographic, end_date=date) httpretty.reset() httpretty.register_uri(httpretty.GET, '{0}?start_date={1}&end_date={1}'.format(uri, date), body='{}') course.enrollment(demographic, start_date=date, end_date=date)
def tearDown(self): # Reset HTTPretty state (clean up registered urls and request history) httpretty.reset()
def tearDown(self): httpretty.reset() httpretty.disable()
def tearDown(self): super(MockRequestTestCase, self).tearDown() httpretty.reset() httpretty.disable()
def tearDownClass(cls): httpretty.disable() httpretty.reset()
def test_roles(self): role_1782974_dict = { "id": 1782974, "name": "Founder", "user_ids": [8083365], "created_at": "2017-06-26T22:34:41Z", "updated_at": "2017-06-26T22:34:52Z" } role_1782959_dict = { "id": 1782959, "name": "Developer", "user_ids": [8083366], "created_at": "2017-06-26T22:15:45Z", "updated_at": "2017-06-26T22:32:52Z" } role_1782884_dict = { "id": 1782884, "name": "Designer", "user_ids": [8083367], "created_at": "2017-06-26T20:41:00Z", "updated_at": "2017-06-26T20:42:25Z" } role_2_dict = { "id": 2, "name": "Project Manager", "user_ids": [8083365, 8083366], "created_at": "2017-06-26T22:34:41Z", "updated_at": "2017-06-26T22:34:52Z" } roles_dict = { "roles": [role_1782974_dict, role_1782959_dict, role_1782884_dict], "per_page": 100, "total_pages": 1, "total_entries": 3, "next_page": None, "previous_page": None, "page": 1, "links": { "first": "https://api.harvestapp.com/v2/roles?page=1&per_page=100", "next": None, "previous": None, "last": "https://api.harvestapp.com/v2/roles?page=1&per_page=100" } } # roles httpretty.register_uri(httpretty.GET, "https://api.harvestapp.com/api/v2/roles?page=1&per_page=100", body=json.dumps(roles_dict), status=200 ) roles = from_dict(data_class=Roles, data=roles_dict) requested_roles = self.harvest.roles() self.assertEqual(requested_roles, roles) # get_role httpretty.register_uri(httpretty.GET, "https://api.harvestapp.com/api/v2/roles/1782974", body=json.dumps(role_1782974_dict), status=200 ) role = from_dict(data_class=Role, data=role_1782974_dict) requested_role = self.harvest.get_role(role_id= 1782974) self.assertEqual(requested_role, role) # create_role httpretty.register_uri(httpretty.POST, "https://api.harvestapp.com/api/v2/roles", body=json.dumps(role_2_dict), status=201 ) role = from_dict(data_class=Role, data=role_2_dict) requested_role = self.harvest.create_role(name= "Project Manager", user_ids= [8083365,8083366]) self.assertEqual(requested_role, role) # update_role role_2_dict["name"] = "PM" role_2_dict["user_ids"] = [8083365,8083366,8083367] httpretty.register_uri(httpretty.PATCH, "https://api.harvestapp.com/api/v2/roles/2", body=json.dumps(role_2_dict), status=200 ) new_role = from_dict(data_class=Role, data=role_2_dict) requested_new_role = self.harvest.update_role(role_id= 2, name= "PM", user_ids= [8083365,8083366,8083367]) self.assertEqual(requested_new_role, new_role) # delete_project httpretty.register_uri(httpretty.DELETE, "https://api.harvestapp.com/api/v2/roles/2", status=200 ) requested_deleted_role = self.harvest.delete_role(role_id= 2) self.assertEqual(requested_deleted_role, None) httpretty.reset()