Beispiel #1
0
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]
Beispiel #2
0
    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 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), '')
Beispiel #8
0
    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 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_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))
Beispiel #11
0
    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
Beispiel #12
0
 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
Beispiel #13
0
    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_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)
Beispiel #15
0
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
Beispiel #16
0
    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())
Beispiel #17
0
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
Beispiel #18
0
 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_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")
Beispiel #20
0
    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)
Beispiel #21
0
    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)
Beispiel #22
0
    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 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 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/"))
Beispiel #25
0
    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
Beispiel #26
0
 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
Beispiel #27
0
    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_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")
Beispiel #29
0
    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')
Beispiel #30
0
 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