def test_resource_in_discovery_container_after_get_patch_delete(self): with mock.patch('requests.get') as requests_get_mock: resource = {"@odata.id": "odata.id", "something": "irrelevant"} get_response = Mock() get_response.status_code = ReturnCodes.OK get_response.headers = {} get_response.text = json.dumps(resource) requests_get_mock.return_value = get_response discovery_container = DiscoveryContainer() self.api_caller.get_resource("/resource", discovery_container) self.assertEqual(discovery_container["http://{API_ENDPOINT}/resource".format( API_ENDPOINT=API_ENDPOINT)].body, resource) patched_resource = {"@odata.id": "odata.id", "something": "relevant"} get_response.text = json.dumps(patched_resource) with mock.patch('requests.patch') as requests_patch_mock: patch_response = Mock() patch_response.status_code = ReturnCodes.OK patch_response.headers = {} patch_response.text = "{}" requests_patch_mock.return_value = patch_response _, _, _, _ = self.api_caller.patch_resource("/resource", discovery_container) self.assertEqual(discovery_container["http://{API_ENDPOINT}/resource".format( API_ENDPOINT=API_ENDPOINT)].body, patched_resource) with mock.patch('requests.delete') as requests_delete_mock: delete_response = Mock() delete_response.status_code = ReturnCodes.NO_CONTENT delete_response.headers = {} delete_response.text = "" requests_delete_mock.return_value = delete_response _, _, _, _ = self.api_caller.delete_resource("/resource", discovery_container) self.assertNotIn("/resource", discovery_container)
def get_mock(): ysc = youtube_status_code yu = youtube_url yc = youtube_cookies yt = youtube_text yh = youtube_headers yosc = youtube_oembed_status_code you = youtube_oembed_url yoh = youtube_oembed_headers yot = youtube_oembed_text mock_obj_1 = Mock() mock_obj_1.status_code = ysc mock_obj_1.url = yu mock_obj_1.headers = yh mock_obj_1.cookies = yc mock_obj_1.text = yt mock_obj_1.json = lambda: json.loads(mock_obj_1.text) mock_obj_2 = Mock() mock_obj_2.status_code = 200 mock_obj_2.url = you mock_obj_2.headers = yoh mock_obj_2.text = yot mock_obj_2.json = lambda: json.loads(mock_obj_2.text) return [mock_obj_1, mock_obj_1, mock_obj_2]
def test_gluster_check_object_creation_err(self): with patch('gluster.swift.common.constraints.__check_object_creation', mock_check_object_creation): req = Mock() req.headers = [] self.assertTrue(cnt.gluster_check_object_creation(req, 'dir/.')) req.headers = ['x-delete-at'] self.assertTrue(cnt.gluster_check_object_creation(req, 'dir/z'))
def test_service_policies(self): gc = Mock() service_key = 'service_key' pdpm = PolicyDecisionPointManager(gc) # see that the PDP for service is the default self.assertEqual(pdpm.get_service_pdp(service_key), pdpm.load_common_service_pdp) pdpm.load_service_policy_rules(service_key, self.permit_ION_MANAGER_rule) # see that the PDP for service is not the default anymore self.assertNotEqual(pdpm.get_service_pdp(service_key), pdpm.load_common_service_pdp) # check request without a service_key raises NotFound error invocation = Mock() invocation.message_annotations = {} invocation.get_message_receiver.return_value = None with self.assertRaises(NotFound) as chk_res: pdpm.check_service_request_policies(invocation) self.assertIn(chk_res.exception.message, 'No receiver for this message') # check that, because actor does not have ION_MANAGER role, policy evaluates to a denial # (really Not Applicable, because of the inelegant hack of a policy we are setting up our pdp with) mock_header = Mock() invocation.message_annotations = {} invocation.message = {'argument1': 0} invocation.headers = {'op': 'op', 'process': 'process', 'request': 'request', 'ion-actor-id': 'ion-actor-id', 'receiver': 'resource-registry', 'sender-type': 'sender-type', 'sender-service': 'Unknown', 'ion-actor-roles': {'org_name': ['ion-actor-roles']}} invocation.get_message_receiver.return_value = 'service_key' invocation.get_service_name.return_value = 'Unknown' invocation.get_message_sender.return_value = ['Unknown','Unknown'] def get_header_value(key, default): return invocation.headers.get(key, default) mock_header.side_effect = get_header_value invocation.get_header_value = mock_header mock_args = Mock() process = Mock() process.org_governance_name = 'org_name' invocation.args = {'process': process} def get_arg_value(key, default): return invocation.args.get(key, default) mock_args.side_effect = get_arg_value invocation.get_arg_value = mock_args gc.system_root_org_name = 'sys_org_name' response = pdpm.check_service_request_policies(invocation) self.assertEqual(response.value, "NotApplicable") # check that policy evaluates to Permit because actor has ION_MANAGER role invocation.message_annotations = {} invocation.headers = {'op': 'op', 'process': 'process', 'request': 'request', 'ion-actor-id': 'ion-actor-id', 'receiver': 'resource-registry', 'sender-type': 'sender-type', 'sender-service': 'sender-service', 'ion-actor-roles': {'sys_org_name': ['ION_MANAGER']}} response = pdpm.check_service_request_policies(invocation) self.assertEqual(response.value, "Permit")
def test_validate_headers(self): req = Mock() req.headers = [] self.assertEqual(cnt.validate_headers(req), '') req.headers = ['x-some-header'] self.assertEqual(cnt.validate_headers(req), '') req.headers = ['x-delete-at', 'x-some-header'] self.assertNotEqual(cnt.validate_headers(req), '') req.headers = ['x-delete-after', 'x-some-header'] self.assertNotEqual(cnt.validate_headers(req), '') req.headers = ['x-delete-at', 'x-delete-after', 'x-some-header'] self.assertNotEqual(cnt.validate_headers(req), '')
def test_gluster_check_object_creation_err(self): with patch('gluster.swift.common.constraints.__check_object_creation', mock_check_object_creation): req = Mock() req.headers = [] self.assertTrue(cnt.gluster_check_object_creation(req, 'dir/.')) #TODO: Although we now support x-delete-at and x-delete-after, #retained this test case as we may add some other header to #unsupported list in future raise SkipTest req.headers = ['x-delete-at'] self.assertTrue(cnt.gluster_check_object_creation(req, 'dir/z'))
def test_validate_headers_ignoring_config_set(self): with patch('gluster.swift.common.constraints.' 'Glusterfs._ignore_unsupported_headers', True): req = Mock() req.headers = [] self.assertEqual(cnt.validate_headers(req), '') req.headers = ['x-some-header'] self.assertEqual(cnt.validate_headers(req), '') req.headers = ['x-delete-at', 'x-some-header'] self.assertEqual(cnt.validate_headers(req), '') req.headers = ['x-delete-after', 'x-some-header'] self.assertEqual(cnt.validate_headers(req), '') req.headers = ['x-delete-at', 'x-delete-after', 'x-some-header'] self.assertEqual(cnt.validate_headers(req), '')
def test_fail_max_retry(self): # this tests the read function when HTTP requests keep returning 503s # read call fails when it reaches the maximum number of retries, in # this case set to 2 # mock the 503 responses mock_resp = Mock(name="503 resp") mock_resp.status_code = 503 mock_resp.content = "Testing" headers = {'Content-Length': 10, 'X-CADC-Content-Length': 5, 'Retry-After': 4} def getheader(name, default): return headers[name] mock_resp.headers = MagicMock() mock_resp.headers.get.side_effect = getheader conn = Connection() conn.session.send = Mock(return_value=mock_resp) vofile = vos.VOFile(["Some URL"], conn, "GET") req = requests.Request("GET", "http://some/url") vofile.request = req.prepare() # set number of retries to 1 and check the OSError was thrown vofile.maxRetries = 1 with self.assertRaises(OSError) as cm: vofile.read() mock_resp.headers.get.assert_called_with('Retry-After', 5)
def test_username_from_request_succeds(self, validate_mock, fetch_mock): mock_http_request = Mock() mock_http_request.headers = {'Authorization': 'Bearer any_access_token'} fetch_mock.return_value = {'sub': 'any_user'} validate_mock.return_value = True self.assertEqual('any_user', username_from_request(mock_http_request))
def setUp(self): response = Mock() response.content = json.dumps({'status': 'ok'}) response.headers = {'Content-Type': 'application/json'} response.ok = True response.status_code = requests.codes.ok self.response = response
def get_signed_grade_mock_request_with_correct_signature(self): """ Generate a proper LTI request object """ mock_request = Mock() mock_request.headers = { 'X-Requested-With': 'XMLHttpRequest', 'Content-Type': 'application/x-www-form-urlencoded', 'Authorization': ( u'OAuth realm="https://testurl/", oauth_body_hash="wwzA3s8gScKD1VpJ7jMt9b%2BMj9Q%3D",' 'oauth_nonce="18821463", oauth_timestamp="1409321145", ' 'oauth_consumer_key="__consumer_key__", oauth_signature_method="HMAC-SHA1", ' 'oauth_version="1.0", oauth_signature="fHsE1hhIz76/msUoMR3Lyb7Aou4%3D"' ) } mock_request.url = u'https://testurl' mock_request.http_method = u'POST' mock_request.method = mock_request.http_method mock_request.body = ( '<?xml version=\'1.0\' encoding=\'utf-8\'?>\n' '<imsx_POXEnvelopeRequest xmlns="http://www.imsglobal.org/services/ltiv1p1/xsd/imsoms_v1p0">' '<imsx_POXHeader><imsx_POXRequestHeaderInfo><imsx_version>V1.0</imsx_version>' '<imsx_messageIdentifier>edX_fix</imsx_messageIdentifier></imsx_POXRequestHeaderInfo>' '</imsx_POXHeader><imsx_POXBody><replaceResultRequest><resultRecord><sourcedGUID>' '<sourcedId>MITxLTI/MITxLTI/201x:localhost%3A8000-i4x-MITxLTI-MITxLTI-lti-3751833a214a4f66a0d18f63234207f2:363979ef768ca171b50f9d1bfb322131</sourcedId>' # pylint: disable=line-too-long '</sourcedGUID><result><resultScore><language>en</language><textString>0.32</textString></resultScore>' '</result></resultRecord></replaceResultRequest></imsx_POXBody></imsx_POXEnvelopeRequest>' ) return mock_request
def build_response_mock(status_code, json_body=None, headers=None, add_content_length=True, **kwargs): real_response = requests.Response() real_response.status_code = status_code text = None if json_body is not None: text = json.dumps(json_body) if add_content_length and headers is not {}: real_response.headers['content-length'] = len(text) if headers is not None: for k, v in headers.items(): real_response.headers[k] = v for k, v in kwargs.items(): setattr(real_response, k, v) response = Mock(wraps=real_response, autospec=True) if text: response.text = text # for some reason, wraps cannot handle attributes which are dicts # and accessed by key response.headers = real_response.headers response.content = text return response
def test_check_object_creation(self): req = Mock() req.headers = dict() valid_object_names = ["a/b/c/d", '/'.join(("1@3%&*0-", "};+=]|")), '/'.join(('a' * 255, 'b' * 255, 'c' * 221))] for o in valid_object_names: self.assertFalse(cnt.check_object_creation(req, o)) invalid_object_names = ["a/./b", "a/b/../d", "a//b", "a/c//", '/'.join(('a' * 256, 'b' * 255, 'c' * 221)), '/'.join(('a' * 255, 'b' * 255, 'c' * 222))] for o in invalid_object_names: self.assertTrue(cnt.check_object_creation(req, o)) # Check for creation of directory marker objects that ends with slash with patch.dict(req.headers, {'content-type': 'application/directory'}): self.assertFalse(cnt.check_object_creation(req, "a/b/c/d/")) # Check creation of objects ending with slash having any other content # type than application/directory is not allowed for content_type in ('text/plain', 'text/html', 'image/jpg', 'application/octet-stream', 'blah/blah'): with patch.dict(req.headers, {'content-type': content_type}): self.assertTrue(cnt.check_object_creation(req, "a/b/c/d/"))
def get_signed_grade_mock_request(self, namespace_lti_v1p1=True): """ Example of signed request from LTI Provider. When `namespace_v1p0` is set to True then the default namespase from LTI 1.1 will be used. Otherwise fake namespace will be added to XML. """ mock_request = Mock() mock_request.headers = { 'X-Requested-With': 'XMLHttpRequest', 'Content-Type': 'application/x-www-form-urlencoded', 'Authorization': u'OAuth oauth_nonce="135685044251684026041377608307", \ oauth_timestamp="1234567890", oauth_version="1.0", \ oauth_signature_method="HMAC-SHA1", \ oauth_consumer_key="test_client_key", \ oauth_signature="my_signature%3D", \ oauth_body_hash="JEpIArlNCeV4ceXxric8gJQCnBw="' } mock_request.url = u'http://testurl' mock_request.http_method = u'POST' params = {} if not namespace_lti_v1p1: params = { 'namespace': "http://www.fakenamespace.com/fake" } mock_request.body = self.get_request_body(params) return mock_request
def setUp(self): # mock request object request = Request() request.method = "GET" request.url = "http://example.com/" request.params = {} request.data = {} request.params_and_data = {} self.request = request # mock response object response = Mock() response.content = "access_token=321" response.headers = {"content-type": "text/html; charset=UTF-8"} response.ok = True response.status_code = 200 self.response = response # mock raise_for_status with an error def raise_for_status(): raise Exception("Response not OK!") self.raise_for_status = raise_for_status # mock hook object hook = Mock() hook.consumer_key = "123" hook.consumer_secret = "456" hook.access_token = "321" hook.access_token_secret = "654" self.hook = hook
def test_http_error_401_simple(self, clean_mock, init_mock, step_mock, response_mock): headers_from_server = {'www-authenticate': 'Negotiate xxx'} init_mock.side_effect = lambda x: (x, "context") response_mock.return_value = "foo" parent_mock = Mock() parent_return_mock = Mock() parent_return_mock.headers = {'www-authenticate': "Negotiate bar"} parent_mock.open.return_value = parent_return_mock request_mock = Mock(spec=self._get_dummy_request()) h = urllib_kerb.HTTPNegotiateHandler() h.add_parent(parent_mock) rv = h.http_error_401(request_mock, "", "", "", headers_from_server) init_mock.assert_called() step_mock.assert_any_call("context", "xxx") # verify authGSSClientStep was called for response as well step_mock.assert_any_call("context", "bar") response_mock.assert_called_with("context") request_mock.add_unredirected_header.assert_called_with( 'Authorization', 'Negotiate %s' % "foo") self.assertEqual(rv, parent_return_mock) clean_mock.assert_called_with("context")
def test_agent_policies(self): # set up data gc = Mock() service_key = "service_key" resource_id = "resource_id" pdpm = PolicyDecisionPointManager(gc) invocation = Mock() mock_header = Mock() invocation.message_annotations = {} invocation.message = {"argument1": 0} invocation.headers = { "op": "op", "process": "process", "request": "request", "ion-actor-id": "ion-actor-id", "receiver": "resource-registry", "sender-type": "sender-type", "sender-service": "Unknown", "ion-actor-roles": {"org_name": ["SUPERUSER"]}, } invocation.get_message_receiver.return_value = "service_key" invocation.get_service_name.return_value = "Unknown" invocation.get_message_sender.return_value = ["Unknown", "Unknown"] def get_header_value(key, default): return invocation.headers.get(key, default) mock_header.side_effect = get_header_value invocation.get_header_value = mock_header mock_args = Mock() process = Mock() process.org_governance_name = "org_name" process.resource_id = "resource_id" invocation.args = {"process": process} def get_arg_value(key, default="Unknown"): return invocation.args.get(key, default) mock_args.side_effect = get_arg_value invocation.get_arg_value = mock_args gc.system_root_org_name = "sys_org_name" # check that service policies result in denying the request pdpm.set_service_policy_rules(service_key, self.deny_SUPERUSER_rule) pdpm.set_resource_policy_rules(resource_id, self.permit_SUPERUSER_rule) response = pdpm.check_agent_request_policies(invocation) self.assertEqual(response.value, "Deny") # check that resource policies result in denying the request pdpm.set_service_policy_rules(service_key, self.permit_SUPERUSER_rule) pdpm.set_resource_policy_rules(resource_id, self.deny_SUPERUSER_rule) response = pdpm.check_agent_request_policies(invocation) self.assertEqual(response.value, "Deny") # check that both service and resource policies need to allow a request pdpm.set_service_policy_rules(service_key, self.permit_SUPERUSER_rule) pdpm.set_resource_policy_rules(resource_id, self.permit_SUPERUSER_rule) response = pdpm.check_agent_request_policies(invocation) self.assertEqual(response.value, "Permit")
def test_auth_header_preserved_from_s3_redirects(self): request = AWSRequest() request.url = 'https://bucket.s3.amazonaws.com/' request.method = 'GET' request.headers['Authorization'] = 'original auth header' prepared_request = request.prepare() fake_response = Mock() fake_response.headers = { 'location': 'https://bucket.s3-us-west-2.amazonaws.com'} fake_response.url = request.url fake_response.status_code = 307 fake_response.is_permanent_redirect = False # This line is needed to disable the cookie handling # code in requests. fake_response.raw._original_response = None success_response = Mock() success_response.raw._original_response = None success_response.is_redirect = False success_response.status_code = 200 session = PreserveAuthSession() session.send = Mock(return_value=success_response) list(session.resolve_redirects( fake_response, prepared_request, stream=False)) redirected_request = session.send.call_args[0][0] # The Authorization header for the newly sent request should # still have our original Authorization header. self.assertEqual( redirected_request.headers['Authorization'], 'original auth header')
def test__on_deliver(self): # mock up the method frame (delivery_tag is really only one we care about) m = Mock() m.consumer_tag = sentinel.consumer_tag m.delivery_tag = sentinel.delivery_tag m.redelivered = sentinel.redelivered m.exchange = sentinel.exchange m.routing_key = sentinel.routing_key # mock up the header-frame h = Mock() h.headers = { 'this_exists': sentinel.exists } # use a mock for the recv queue rqmock = Mock(spec=RecvChannel.SizeNotifyQueue) self.ch._recv_queue = rqmock # now we can call! self.ch._on_deliver(sentinel.chan, m, h, sentinel.body) # assert the call rqmock.put.assert_called_once_with((sentinel.body, h.headers, sentinel.delivery_tag)) # assert the headers look ok self.assertIn(sentinel.exists, rqmock.put.call_args[0][0][1].itervalues())
def test_no_expected_value(self): # Given config = Config.from_dict({'host': 'host'}, __file__) response = Mock() response.headers = { 'Content-Type': 'application/json' } spec = { 'name': 'header', 'header': 'Content-Type', } # When assertion = HeaderAssertion.from_dict(spec) # Then self.assertEqual(assertion.header, spec['header']) self.assertEqual(assertion.expected_value, None) self.assertEqual(assertion.regexp, False) # When case = MockTestCase() assertion.run(config, 'http://host/uri', case, response) # Then self.assertEqual(case.assertIn.call_count, 1) call = case.assertIn.call_args args, kwargs = call self.assertEqual(args, (spec['header'], response.headers)) self.assertIn('msg', kwargs) self.assertFalse(case.assertRegexpMatches.called) self.assertFalse(case.assertEqual.called)
def test_head_object_with_json(self): http_response = Mock() http_response.encoding = 'utf-8' http_response.headers = CaseInsensitiveDict( {'Date': 'Thu, 22 Aug 2013 02:11:57 GMT', 'Content-Length': '0', 'x-amz-request-id': '2B74ECB010FF029E', 'ETag': '"40d06eb6194712ac1c915783004ef730"', 'Server': 'AmazonS3', 'content-type': 'application/json', 'Content-Type': 'application/json', 'accept-ranges': 'bytes', 'Last-Modified': 'Tue, 20 Aug 2013 18:33:25 GMT', 'x-amz-server-side-encryption': 'AES256'}) http_response.content = '' put_object = self.s3.get_operation('HeadObject') expected = {"AcceptRanges": "bytes", "ContentType": "application/json", "LastModified": "Tue, 20 Aug 2013 18:33:25 GMT", "ContentLength": "0", "ETag": '"40d06eb6194712ac1c915783004ef730"', "ServerSideEncryption": "AES256" } response_data = get_response(self.session, put_object, http_response)[1] self.assertEqual(response_data, expected)
def __one_bad_two_ok(*args): response = Mock() response.ok = args[0] == 'http://example.com/oembed2' response.text = 'hello, world' response.headers = {'content-type': 'application/json'} return response
def test_call(self): body = "body" headers = {"header": "value"} path = "/authorize" status_code = 200 http_code = "200 OK" environment = {"PATH_INFO": path, "myvar": "value"} request_mock = Mock(spec=Request) request_class_mock = Mock(return_value=request_mock) responseMock = Mock(spec=Response) responseMock.body = body responseMock.headers = headers responseMock.status_code = status_code server_mock = Mock(spec=Provider) server_mock.dispatch.return_value = responseMock start_response_mock = Mock() wsgi = Wsgi(server=server_mock, authorize_uri=path, request_class=request_class_mock, env_vars=["myvar"]) result = wsgi(environment, start_response_mock) request_class_mock.assert_called_with(environment) server_mock.dispatch.assert_called_with(request_mock, {"myvar": "value"}) start_response_mock.assert_called_with(http_code, headers.items()) self.assertEqual(result, [body])
def test_get_response_size_from_content(self): parser = HTMLParser('', False) mock_response = Mock() mock_response.headers = {} mock_response.content = '1234567890' parser.response = mock_response assert parser.get_response_size() == 10
def test_list_objects_with_invalid_content_length(self): http_response = Mock() http_response.encoding = 'utf-8' http_response.headers = CaseInsensitiveDict( {'Date': 'Thu, 22 Aug 2013 02:11:57 GMT', # We say we have 265 bytes but we're returning 0, # this should raise an exception because this is not # a HEAD request. 'Content-Length': '265', 'x-amz-request-id': '2B74ECB010FF029E', 'ETag': '"40d06eb6194712ac1c915783004ef730"', 'Server': 'AmazonS3', 'content-type': 'binary/octet-stream', 'Content-Type': 'binary/octet-stream', 'accept-ranges': 'bytes', 'Last-Modified': 'Tue, 20 Aug 2013 18:33:25 GMT', 'x-amz-server-side-encryption': 'AES256' }) http_response.content = '' http_response.request.method = 'GET' list_objects = self.s3.get_operation('ListObjects') expected = {"AcceptRanges": "bytes", "ContentType": "binary/octet-stream", "LastModified": "Tue, 20 Aug 2013 18:33:25 GMT", "ContentLength": "265", "ETag": '"40d06eb6194712ac1c915783004ef730"', "ServerSideEncryption": "AES256" } with self.assertRaises(IncompleteReadError): response_data = get_response(self.session, list_objects, http_response)[1]
def _create_fake_m2message(self, async_upload_path): message = Mock() message.headers = {"x-mongrel2-upload-start": async_upload_path, "x-mongrel2-upload-done": async_upload_path} message.async_upload_path = async_upload_path message.server_id = "uuid" message.client_id = "42" return message
def setUp(self): # mock request object request = Request() request.method = 'GET' request.url = 'http://example.com/' request.params = {} request.data = {} request.params_and_data = {} self.request = request # mock response object response = Mock() response.content = 'access_token=321' response.headers = {'content-type': 'text/html; charset=UTF-8'} response.ok = True response.status_code = 200 self.response = response # mock raise_for_status with an error def raise_for_status(): raise Exception('Response not OK!') self.raise_for_status = raise_for_status # mock hook object hook = Mock() hook.consumer_key = '123' hook.consumer_secret = '456' hook.access_token = '321' hook.access_token_secret = '654' self.hook = hook
def test_username_from_request_fails_for_missing_user_info(self, validate_mock, fetch_mock): mock_http_request = Mock() mock_http_request.headers = {'Authorization': 'Bearer any_access_token'} validate_mock.return_value = False self.assertIsNone(username_from_request(mock_http_request))
def test_successfully_unzip_from_uri(self, open_patch, requests_patch, progressbar_patch, path_patch, unzip_patch): get_request_mock = Mock() get_request_mock.headers = {"Content-length": "200"} get_request_mock.iter_content.return_value = [b'data1'] requests_patch.get.return_value = get_request_mock file_mock = Mock() open_patch.return_value.__enter__.return_value = file_mock progressbar_mock = Mock() progressbar_patch.return_value.__enter__.return_value = progressbar_mock path_mock = Mock() path_mock.exists.return_value = True path_patch.return_value = path_mock unzip_from_uri('uri', 'layer_zip_path', 'output_zip_dir', 'layer_arn') requests_patch.get.assert_called_with('uri', stream=True) get_request_mock.iter_content.assert_called_with(chunk_size=None) open_patch.assert_called_with('layer_zip_path', 'wb') file_mock.write.assert_called_with(b'data1') progressbar_mock.update.assert_called_with(5) path_patch.assert_called_with('layer_zip_path') path_mock.unlink.assert_called() unzip_patch.assert_called_with('layer_zip_path', 'output_zip_dir', permission=0o700)
def mock_response(self, status_code, headers, data): mock_response = Mock() mock_response.status_code = status_code mock_response.headers = headers mock_response.text = json.dumps(data) self.request_mock.return_value = mock_response
def _set_auth_headers(kwargs): if kwargs.get("auth"): mock_request = Mock() mock_request.headers = {} kwargs["auth"](mock_request) if "headers" not in kwargs: kwargs["headers"] = {} kwargs["headers"].update(mock_request.headers)
def test_file_call(): handler = Mock() response = Mock() response.content = 'bytes here' response.headers = {} handler.process_request.return_value = BaseResponse(response) uber_file = uber.documentation.handler(handler)() assert uber_file.data == 'bytes here'
def test_unauthorized_no_challenge_by_default(self): app = Flask(__name__) api = flask_restful.Api(app) response = Mock() response.headers = {} with app.test_request_context('/foo'): response = api.unauthorized(response) assert_false('WWW-Authenticate' in response.headers)
def test_should_add_authorization_header(self): auth = BearerTokenAuth('access_token') request = Mock() request.headers = {} auth(request) self.assertEqual(request.headers, {'Authorization': 'Bearer access_token'})
def test_get_http_auth_credentials_good_reponse(auth_mock): m = Mock() m.url = 'http://domain.com' m.headers = {'www-authenticate': 'Basic realm="Restricted"'} auth = HTTPBasicAuth("username", "password") auth_mock.return_value = auth returned_auth = http._get_http_auth_credentials(m) assert returned_auth == auth
def test_request_retries(caplog): caplog.set_level(logging.DEBUG) link = Link('http://localhost') session = Mock(PipSession) session.headers = {} session.get.side_effect = requests.exceptions.RetryError('Retry error') assert _get_html_page(link, session=session) is None assert ('Could not fetch URL http://localhost: Retry error - skipping' in caplog.text)
def test_cube_desc(): response = Mock() response.body = [] response.headers = {} Client.fetch = Mock(return_value=response) v1 = kylinpy.Kylinpy(host='host', username='******', password='******', version='v1').cube_desc('cube_name') response = Mock() response.body = {'data': {'cube': []}, 'code': 000, 'msg': ''} response.headers = {} v2 = kylinpy.Kylinpy(host='host', username='******', password='******', version='v2').cube_desc('cube_name') assert v1 == v2
def test_jwt_required_raises_error_if_jwt_invalid(config): mock_request = Mock() mock_request.headers = {"Authorization": "random token!"} service = FakeService() with pytest.raises(UserNotAuthorised): service.fake_function(mock_request)
def test_jwt_required_raises_error_if_missing_header(): mock_request = Mock() mock_request.headers = {} service = FakeService() with pytest.raises(UserNotAuthorised): service.fake_function(mock_request)
def _network_response_mock_from_request_response(request_response): mock_network_response = Mock(DefaultNetworkResponse) mock_network_response.request_response = request_response mock_network_response.json.side_effect = request_response.json mock_network_response.content = request_response.content mock_network_response.headers = request_response.headers mock_network_response.status_code = request_response.status_code mock_network_response.ok = request_response.ok return mock_network_response
def test_validate_internal_request__no_token(self): mock_request = Mock() mock_request.headers = {} with self.assertRaises(services.InvalidInternalToken) as cm: services.validate_internal_request(mock_request) self.assertEqual('no token', str(cm.exception))
def test_get_http_auth_credentials_acl(req_mock, auth_mock): m = Mock() m.url = 'http://domain.com' m.headers = {'www-authenticate': 'acsjwt"'} auth_mock.return_value = ("username", "password") req_mock.status_code = 404 returned_auth = http._get_http_auth(m, urlparse(m.url), "acsjwt") assert type(returned_auth) == http.DCOSAcsAuth
def test_unauthorized(self): app = Flask(__name__) api = flask_restful.Api(app) response = Mock() response.headers = {} with app.test_request_context('/foo'): response = api.unauthorized(response) self.assertEquals(response.headers['WWW-Authenticate'], 'Basic realm="flask-restful"')
def test_create_index(caps_get_mock, base_get_mock, base_post_mock): caps_get_mock.return_value = BASE_URL client = CadcTapClient(net.Subject()) response1 = Mock() response1.status_code = 303 job_location = 'http://go.here' response1.headers = {'Location': job_location} base_post_mock.return_value = response1 response2 = Mock() response2.status_code = 200 response2.text = "EXECUTING" base_get_mock.side_effect = [response2] response3 = Mock() response3.status_code = 200 response3.text = "COMPLETED" base_get_mock.side_effect = [response2, response3] client.create_index('schema.sometable', 'col1', unique=True) # expected post calls post_calls = [ call((TABLE_UPDATE_CAPABILITY_ID, None), allow_redirects=False, data={ 'table': 'schema.sometable', 'unique': 'true', 'index': 'col1' }), call('{}/phase'.format(job_location), data={'PHASE': 'RUN'}) ] base_post_mock.assert_has_calls(post_calls) # expected get calls get_calls = [ call('{}/phase'.format(job_location), data={'WAIT': 1}), call('{}/phase'.format(job_location), data={'WAIT': 1}) ] base_get_mock.assert_has_calls(get_calls) # error cases with pytest.raises(AttributeError): client.create_index(None, 'col1') with pytest.raises(AttributeError): client.create_index('sometable', None) response4 = Mock() response4.status_code = 200 response4.text = 'ABORTED' base_get_mock.side_effect = [response4, response4] client = CadcTapClient(net.Subject()) with pytest.raises(RuntimeError): client.create_index('sometable', 'col1') response5 = Mock() response5.status_code = 500 base_get_mock.side_effect = [response1, response4, response4] client = CadcTapClient(net.Subject()) with pytest.raises(RuntimeError): client.create_index('sometable', 'col1')
def test_source(self): req = Mock(['args', 'headers', 'values']) req.args = {'foo': 'bar'} req.headers = {'baz': 'bat'} arg = Argument('foo', location=['args']) self.assertEquals(arg.source(req), MultiDict(req.args)) arg = Argument('foo', location=['headers']) self.assertEquals(arg.source(req), MultiDict(req.headers))
def _dummy_send(*args, **kwargs): dummy_response = Mock() dummy_response.headers = {} dummy_response.status_code = status_code dummy_response.text = response_body dummy_response.request = args[0] dummy_response.cookies = {} _dummy_send.call_args = (args, kwargs) return dummy_response
def test_unauthorized_custom_realm(self): app = Flask(__name__) app.config['HTTP_BASIC_AUTH_REALM'] = 'Foo' api = flask_restful.Api(app, serve_challenge_on_401=True) response = Mock() response.headers = {} with app.test_request_context('/foo'): response = api.unauthorized(response) self.assertEquals(response.headers['WWW-Authenticate'], 'Basic realm="Foo"')
def token_response_with_charset(self): response = Mock() response.headers = { 'status': '200', 'content-type': 'text/html; charset=UTF-8', } response.content = '\n<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">\n<html>\n<head>\n\t<title>Updating Token...</title>\n\t<link rel="shortcut icon" type="image/x-icon" href="/ubericon.ico">\n\t<meta http-equiv="Refresh" content="4">\n\t<link href="/locale/en_US/css/stylesheet.css" rel="stylesheet" type="text/css">\n\t<style type="text/css">\n\t<!--\n.config-box-4 {height:auto !important;height:400px;min-height:400px;}\n\t-->\n\t</style>\n\t<script type="text/javascript" src="/js/jquery.js"></script>\n\t<script language="javascript">\n\t\tif (top.location != location) {\n\t\t\ttop.location.href = document.location.href;\n\t\t}\n\t\t$(function() {\t\n\t\t\t$("body").delegate("div.notification a.close","click",function(e) {\n\t\t\t\te.preventDefault();\n\t\t\t\t$(this).closest(\'div.notification-wrapper\').hide();\n\t\t\t});\n\t\t});\n\t\t\n\t</script>\n</head>\n<body>\n\t<div style="background: #ccccff url(\'/images/background_pagebar.png\') repeat-x top left;padding:0 10px;border-bottom:1px solid #999999;">\n\t\t<div style="padding:6px 0;">\n\t\t\t<img src="/images/logo_ubersmith.png" width="126" height="24" border="0" />\n\t\t</div>\n\t</div>\n\t\n\t<div class="config-box-1" style="margin:15px;"><div class="config-box-2"><div class="config-box-3"><div class="config-box-4">\n<table border="0" cellpadding="10" cellspacing="0">\n\t\t\t\t\t<tr valign="top">\n\t\t\t\t\t\t<td rowspan="2"><img src="/images/uber-anim.gif" /></td>\n\t\t\t\t\t\t<td class="CellText"><span style="font-size:150%;font-weight:bold;">Ubersmith Token Update</span></td>\n\t\t\t\t\t</tr>\n\t\t\t\t\t<tr>\n\t\t\t\t\t\t<td class="CellText">Please wait while your token is updated.</td>\n\t\t\t\t\t</tr>\n\t\t\t\t</table>\n\t</div></div></div></div>\n</body>\n</html>\n' response.text = text_type(response.content) return response
def test_previously_deadlettered_first_backoff(self, backoff): message = Mock() message.headers = { 'x-death': [{ # previously deadlettered elsewhere 'exchange': 'not-backoff', 'count': 99 }] } assert backoff.get_next_expiration(message, "backoff") == 1000
def test_get_xml(self): with mock.patch('requests.get') as get: response = Mock() response.status_code = ReturnCodes.OK response.headers = {} response.text = "<xml></xml>" get.return_value = response link, status, status_code, response_body, headers = self.api_caller.get_xml("uri") self.assertEqual("<xml></xml>", response_body)
def _dummy_send(*args, **kwargs): dummy_response = Mock() dummy_response.headers = {} dummy_response.getheaders = Mock(return_value={}) dummy_response.status = status_code dummy_response.read = Mock(return_value=response_body) dummy_response.request = args[0] dummy_response.cookies = {} _dummy_send.call_args = (args, kwargs) return dummy_response
def test_unexpected_async_post_response(self): with mock.patch('requests.post') as requests_get_mock: response = Mock() response.status_code = ReturnCodes.ACCEPTED response.headers = {} response.text = "{}" requests_get_mock.return_value = response with self.assertRaises(AsyncOperation): self.api_caller.post_resource('odata_id', DiscoveryContainer(), payload={}, wait_if_async=False)
def test_async_create_without_location(self): with mock.patch('requests.post') as requests_post_mock: response = Mock() response.status_code = ReturnCodes.ACCEPTED response.headers = {} response.text = None requests_post_mock.return_value = response with mock.patch('requests.get') as requests_get_mock: response = Mock() response.status_code = 204 response.headers = {} response.text = None requests_get_mock.return_value = response with StdoutCapture() as output: status, status_code, response_body, headers = self.api_caller.post_resource('odata_id', DiscoveryContainer(), payload={}) self.assertIn('Location header not found', '\n'.join(output))
def test_incorrect_status_code(self): with mock.patch('requests.get') as requests_get_mock: response = Mock() response.status_code = 500 response.headers = {} response.text = "{}" requests_get_mock.return_value = response link, status, status_code, response_body, headers = \ self.api_caller.get_resource("/resource", DiscoveryContainer()) self.assertFalse(status)
def test_get_node_url(): client = Client() with pytest.raises(TypeError): client.get_node_url('vos://cadc.nrc.ca!vospace/auser', sort='Blah') with pytest.raises(ValueError): client.get_node_url('vos://cadc.nrc.ca!vospace/auser', order='Blah') response = Mock(spec=requests.Response) response.status_code = 303 resource_id = 'ivo://cadc.nrc.ca/vospace' session_mock = Mock(spec=requests.Session, get=Mock(return_value=response)) session_mock.headers = Mock() client._endpoints[resource_id] = vos.EndPoints(resource_id_uri=resource_id) client._endpoints[resource_id].conn.ws_client._session = session_mock equery = urlparse(client.get_node_url('vos://cadc.nrc.ca!vospace/auser', sort=vos.SortNodeProperty.DATE)).query assert(urllib.parse.unquote(equery) == 'sort={}'.format(vos.SortNodeProperty.DATE.value)) equery = urlparse(client.get_node_url('vos://cadc.nrc.ca!vospace/auser', sort=vos.SortNodeProperty.LENGTH, order='asc')).query args = urllib.parse.unquote(equery).split('&') assert(2 == len(args)) assert('order=asc' in args) assert('sort={}'.format(vos.SortNodeProperty.LENGTH.value) in args) equery = urlparse(client.get_node_url('vos://cadc.nrc.ca!vospace/auser', order='desc')).query assert('order=desc' == urllib.parse.unquote(equery)) # test header view transfer_url = 'https://some.location/some/headers' response.headers = {'Location': transfer_url} client._endpoints[resource_id].conn.ws_client._session.get = \ Mock(return_value=response) assert transfer_url == \ client.get_node_url('vos://cadc.nrc.ca!vospace/auser', view='header')[0] # get the argument lists for client.conn.session.get args, kwargs = client._endpoints[ resource_id].conn.ws_client._session.get.call_args_list[0] # check head is amongst the other parameters assert kwargs['params']['view'] == 'header'
def test_secret_not_required(self): from lti.contrib.flask import FlaskToolProvider mock_req = Mock() mock_req.form = {'oauth_consumer_key': 'foo'} mock_req.headers = {'Content-type': 'bar'} mock_req.url = 'http://example.edu/foo/bar' tp = FlaskToolProvider.from_flask_request(request=mock_req) self.assertEqual(tp.consumer_key, 'foo') self.assertEqual(tp.launch_headers['Content-type'], 'bar') self.assertEqual(tp.launch_url, 'http://example.edu/foo/bar')
def test_last_backoff_single_queue(self, backoff): message = Mock() message.headers = { 'x-death': [{ 'exchange': 'backoff', 'queue': 'backoff--1', 'count': 3 }] } assert backoff.get_next_expiration(message, "backoff") == 3000
def test_count_greater_than_schedule_length(self, backoff): message = Mock() message.headers = { 'x-death': [{ 'exchange': 'backoff', 'queue': 'backoff--1', 'count': 5 }] } assert backoff.get_next_expiration(message, "backoff") == 3000
def test_parses_known_exception(event_parser): mock_event = Mock(spec=EventStreamMessage) mock_event.headers = { ":exception-type": "BadRequestException", ":content-type": "application/json", ":message-type": "exception", } mock_event.payload = b'{"Message": "The request was bad."}' with pytest.raises(BadRequestException): event_parser.parse(mock_event)
def test_parses_unknown_exception(event_parser): mock_event = Mock(spec=EventStreamMessage) mock_event.headers = { ":exception-type": "ServerOnFire", ":content-type": "application/json", ":message-type": "exception", } mock_event.payload = b"" with pytest.raises(ServiceException): event_parser.parse(mock_event)