Python falcon.testing.create_environ() Examples

The following are 30 code examples of falcon.testing.create_environ(). You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may also want to check out all available functions/classes of the module falcon.testing , or try the search function .
Example #1
Source File: common.py    From shipyard with Apache License 2.0 6 votes vote down vote up
def create_req(ctx, body):
    '''creates a falcon request'''
    env = testing.create_environ(
        path='/',
        query_string='',
        protocol='HTTP/1.1',
        scheme='http',
        host='falconframework.org',
        port=None,
        headers={'Content-Type': 'application/json'},
        app='',
        body=body,
        method='POST',
        wsgierrors=None,
        file_wrapper=None)
    req = falcon.Request(env)
    req.context = ctx
    return req 
Example #2
Source File: test_resources.py    From graceful with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
def test_require_representation_application_json():
    resource = TestResource()

    # simple application/json content type
    env = create_environ(
        body=json.dumps({'one': 'foo', 'two': 'foo'}),
        headers={'Content-Type': 'application/json'},
    )

    representation = resource.require_representation(Request(env))
    assert isinstance(representation, dict)

    # application/json content type with charset param
    env = create_environ(
        body=json.dumps({'one': 'foo', 'two': 'foo'}),
        headers={'Content-Type': 'application/json; charset=UTF-8'},
    )

    representation = resource.require_representation(Request(env))
    assert isinstance(representation, dict) 
Example #3
Source File: test_resources.py    From graceful with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
def test_whole_serializer_validation_as_hhtp_bad_request(req):

    class TestSerializer(BaseSerializer):
        one = StringField("one different than two")
        two = StringField("two different than one")

        def validate(self, object_dict, partial=False):
            super().validate(object_dict, partial)
            # possible use case: kind of uniqueness relationship
            if object_dict['one'] == object_dict['two']:
                raise ValidationError("one must be different than two")

    class TestResource(Resource):
        serializer = TestSerializer()

    resource = TestResource()

    env = create_environ(
        body=json.dumps({'one': 'foo', 'two': 'foo'}),
        headers={'Content-Type': 'application/json'},
    )

    with pytest.raises(errors.HTTPBadRequest):
        resource.require_validated(Request(env)) 
Example #4
Source File: test_policy.py    From monasca-log-api with Apache License 2.0 6 votes vote down vote up
def test_ignore_case_role_check(self):
        lowercase_action = "example:lowercase_monasca_user"
        uppercase_action = "example:uppercase_monasca_user"

        monasca_user_context = request.Request(
            testing.create_environ(
                path="/",
                headers={
                    "X_USER_ID": "monasca_user",
                    "X_PROJECT_ID": "fake",
                    "X_ROLES": "MONASCA_user"
                }
            )
        )
        self.assertTrue(policy.authorize(monasca_user_context.context,
                                         lowercase_action,
                                         {}))
        self.assertTrue(policy.authorize(monasca_user_context.context,
                                         uppercase_action,
                                         {})) 
Example #5
Source File: test_request.py    From monasca-log-api with Apache License 2.0 6 votes vote down vote up
def test_use_context_from_request(self):
        req = request.Request(
            testing.create_environ(
                path='/',
                headers={
                    'X_AUTH_TOKEN': '111',
                    'X_USER_ID': '222',
                    'X_PROJECT_ID': '333',
                    'X_ROLES': 'terminator,predator'
                }
            )
        )

        self.assertEqual('111', req.context.auth_token)
        self.assertEqual('222', req.user_id)
        self.assertEqual('333', req.project_id)
        self.assertEqual(['terminator', 'predator'], req.roles) 
Example #6
Source File: test_request.py    From monasca-log-api with Apache License 2.0 6 votes vote down vote up
def test_validate_context_type(self):
        with mock.patch.object(validation,
                               'validate_content_type') as vc_type, \
                mock.patch.object(validation,
                                  'validate_payload_size') as vp_size, \
                mock.patch.object(validation,
                                  'validate_cross_tenant') as vc_tenant:
            req = request.Request(testing.create_environ())
            vc_type.side_effect = Exception()

            try:
                req.validate(['test'])
            except Exception as ex:
                self.assertEqual(1, vc_type.call_count)
                self.assertEqual(0, vp_size.call_count)
                self.assertEqual(0, vc_tenant.call_count)

                self.assertIsInstance(ex, Exception) 
Example #7
Source File: test_request.py    From monasca-log-api with Apache License 2.0 6 votes vote down vote up
def test_validate_payload_size(self):
        with mock.patch.object(validation,
                               'validate_content_type') as vc_type, \
                mock.patch.object(validation,
                                  'validate_payload_size') as vp_size, \
                mock.patch.object(validation,
                                  'validate_cross_tenant') as vc_tenant:

            req = request.Request(testing.create_environ())
            vp_size.side_effect = Exception()

            try:
                req.validate(['test'])
            except Exception as ex:
                self.assertEqual(1, vc_type.call_count)
                self.assertEqual(1, vp_size.call_count)
                self.assertEqual(0, vc_tenant.call_count)

                self.assertIsInstance(ex, Exception) 
Example #8
Source File: test_request.py    From monasca-log-api with Apache License 2.0 6 votes vote down vote up
def test_validate_cross_tenant(self):
        with mock.patch.object(validation,
                               'validate_content_type') as vc_type, \
                mock.patch.object(validation,
                                  'validate_payload_size') as vp_size, \
                mock.patch.object(validation,
                                  'validate_cross_tenant') as vc_tenant:

            req = request.Request(testing.create_environ())
            vc_tenant.side_effect = Exception()

            try:
                req.validate(['test'])
            except Exception as ex:
                self.assertEqual(1, vc_type.call_count)
                self.assertEqual(1, vp_size.call_count)
                self.assertEqual(1, vc_tenant.call_count)

                self.assertIsInstance(ex, Exception) 
Example #9
Source File: test_actions_api.py    From shipyard with Apache License 2.0 6 votes vote down vote up
def create_req(ctx, body):
    '''creates a falcon request'''
    env = testing.create_environ(
        path='/',
        query_string='',
        protocol='HTTP/1.1',
        scheme='http',
        host='falconframework.org',
        port=None,
        headers={'Content-Type': 'application/json'},
        app='',
        body=body,
        method='POST',
        wsgierrors=None,
        file_wrapper=None)
    req = falcon.Request(env)
    req.context = ctx
    return req 
Example #10
Source File: test_policy.py    From monasca-log-api with Apache License 2.0 5 votes vote down vote up
def test_authorize_good_action(self):
        action = "example:allowed"
        ctx = request.Request(
            testing.create_environ(
                path="/",
                headers={
                    "X_USER_ID": "fake",
                    "X_PROJECT_ID": "fake",
                    "X_ROLES": "member"
                }
            )
        )
        result = policy.authorize(ctx.context, action, {}, False)
        self.assertTrue(result) 
Example #11
Source File: test_policy.py    From monasca-api with Apache License 2.0 5 votes vote down vote up
def _get_request_context(role):
        return request.Request(
            testing.create_environ(
                path='/',
                headers={'X_ROLES': role}
            )
        ) 
Example #12
Source File: test_policy.py    From monasca-log-api with Apache License 2.0 5 votes vote down vote up
def test_authorize_bad_action_no_exception(self):
        action = "example:denied"
        ctx = request.Request(
            testing.create_environ(
                path="/",
                headers={
                    "X_USER_ID": "fake",
                    "X_PROJECT_ID": "fake",
                    "X_ROLES": "member"
                }
            )
        )
        result = policy.authorize(ctx.context, action, {}, False)
        self.assertFalse(result) 
Example #13
Source File: test_policy.py    From monasca-log-api with Apache License 2.0 5 votes vote down vote up
def test_authorize_bad_action_throws(self):
        action = "example:denied"
        ctx = request.Request(
            testing.create_environ(
                path="/",
                headers={
                    "X_USER_ID": "fake",
                    "X_PROJECT_ID": "fake",
                    "X_ROLES": "member"
                }
            )
        )
        self.assertRaises(os_policy.PolicyNotAuthorized, policy.authorize,
                          ctx.context, action, {}) 
Example #14
Source File: test_policy.py    From monasca-log-api with Apache License 2.0 5 votes vote down vote up
def test_authorize_nonexist_action_throws(self):
        action = "example:noexist"
        ctx = request.Request(
            testing.create_environ(
                path="/",
                headers={
                    "X_USER_ID": "fake",
                    "X_PROJECT_ID": "fake",
                    "X_ROLES": "member"
                }
            )
        )
        self.assertRaises(os_policy.PolicyNotRegistered, policy.authorize,
                          ctx.context, action, {}) 
Example #15
Source File: test_helpers.py    From monasca-api with Apache License 2.0 5 votes vote down vote up
def _get_request_context(role='fake_role'):
        return request.Request(
            testing.create_environ(
                path="/",
                query_string="tenant_id=fake_tenant_id",
                headers={
                    "X_PROJECT_ID": "fake_project_id",
                    "X_ROLES": role
                }
            )
        ) 
Example #16
Source File: test_helpers.py    From monasca-api with Apache License 2.0 5 votes vote down vote up
def test_validate_json_content_type_incorrect_content_type(self):
        req = request.Request(
            testing.create_environ(
                headers={'Content-Type': 'multipart/form-data'}
            )
        )
        self.assertRaises(errors.HTTPBadRequest, helpers.validate_json_content_type, req) 
Example #17
Source File: test_helpers.py    From monasca-api with Apache License 2.0 5 votes vote down vote up
def test_validate_json_content_type(self):
        req = request.Request(
            testing.create_environ(
                headers={'Content-Type': 'application/json'}
            )
        )
        helpers.validate_json_content_type(req) 
Example #18
Source File: test_helpers.py    From monasca-api with Apache License 2.0 5 votes vote down vote up
def test_from_json_incorrect_message(self):
        req = request.Request(
            testing.create_environ(
                body='incorrect message',
            )
        )
        self.assertRaises(errors.HTTPBadRequest, helpers.from_json, req) 
Example #19
Source File: test_helpers.py    From monasca-api with Apache License 2.0 5 votes vote down vote up
def test_from_json(self):
        body_json = {'test_body': 'test'}
        req = request.Request(
            testing.create_environ(
                body=rest_utils.as_json(body_json),
            )
        )
        response = helpers.from_json(req)
        self.assertEqual(body_json, response) 
Example #20
Source File: conftest.py    From openapi-core with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def environ_factory():
    def create_env(method, path, server_name):
        return create_environ(
            host=server_name,
            path=path,
        )
    return create_env 
Example #21
Source File: test_policy.py    From monasca-api with Apache License 2.0 5 votes vote down vote up
def test_authorize_good_action(self):
        action = "example:allowed"
        ctx = request.Request(
            testing.create_environ(
                path="/",
                headers={
                    "X_USER_ID": "fake",
                    "X_PROJECT_ID": "fake",
                    "X_ROLES": "member"
                }
            )
        )
        result = policy.authorize(ctx.context, action, {}, False)
        self.assertTrue(result) 
Example #22
Source File: test_policy.py    From monasca-api with Apache License 2.0 5 votes vote down vote up
def test_authorize_bad_action_no_exception(self):
        action = "example:denied"
        ctx = request.Request(
            testing.create_environ(
                path="/",
                headers={
                    "X_USER_ID": "fake",
                    "X_PROJECT_ID": "fake",
                    "X_ROLES": "member"
                }
            )
        )
        result = policy.authorize(ctx.context, action, {}, False)
        self.assertFalse(result) 
Example #23
Source File: test_policy.py    From monasca-api with Apache License 2.0 5 votes vote down vote up
def test_authorize_bad_action_throws(self):
        action = "example:denied"
        ctx = request.Request(
            testing.create_environ(
                path="/",
                headers={
                    "X_USER_ID": "fake",
                    "X_PROJECT_ID": "fake",
                    "X_ROLES": "member"
                }
            )
        )
        self.assertRaises(os_policy.PolicyNotAuthorized, policy.authorize,
                          ctx.context, action, {}) 
Example #24
Source File: test_policy.py    From monasca-api with Apache License 2.0 5 votes vote down vote up
def test_authorize_nonexist_action_throws(self):
        action = "example:noexist"
        ctx = request.Request(
            testing.create_environ(
                path="/",
                headers={
                    "X_USER_ID": "fake",
                    "X_PROJECT_ID": "fake",
                    "X_ROLES": "member"
                }
            )
        )
        self.assertRaises(os_policy.PolicyNotRegistered, policy.authorize,
                          ctx.context, action, {}) 
Example #25
Source File: base.py    From monasca-api with Apache License 2.0 5 votes vote down vote up
def create_environ(*args, **kwargs):
        return testing.create_environ(
            *args,
            **kwargs
        ) 
Example #26
Source File: test_resources.py    From graceful with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def test_parameter_with_many_and_custom_container_method():
    class StringSetParam(StringParam):
        # container is custom method call ("bound" to param instance)
        def container(self, values):
            return set(values)

    class SomeResource(Resource):
        foo = StringSetParam(details="give me foo", many=True)

    env = create_environ(query_string="foo=bar&foo=baz")
    resource = SomeResource()
    params = resource.require_params(Request(env))

    assert isinstance(params['foo'], set)
    assert 'bar' in params['foo'] and 'baz' in params['foo'] 
Example #27
Source File: test_resources.py    From graceful with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def test_parameter_with_many_and_custom_container_type_object():
    class StringSetParam(StringParam):
        # container is simply a type object (it is not a descriptor)
        # so does not receive self as a parameter
        container = set

    class SomeResource(Resource):
        foo = StringSetParam(details="give me foo", many=True)

    env = create_environ(query_string="foo=bar&foo=baz")
    resource = SomeResource()
    params = resource.require_params(Request(env))

    assert isinstance(params['foo'], set)
    assert 'bar' in params['foo'] and 'baz' in params['foo'] 
Example #28
Source File: test_resources.py    From graceful with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def test_parameter_with_many_and_default(req):
    class SomeResource(Resource):
        foo = StringParam(details="give me foo", default='baz', many=True)

    resource = SomeResource()
    params = resource.require_params(req)

    assert isinstance(params['foo'], Iterable)
    assert params['foo'] == ['baz']

    env = create_environ(query_string="foo=bar")
    params = resource.require_params(Request(env))

    assert isinstance(params['foo'], Iterable)
    assert params['foo'] == ['bar'] 
Example #29
Source File: test_resources.py    From graceful with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def test_parameter_with_validation_enabled_passes(query_string):
    class SomeResource(Resource):
        number = IntParam(
            details="number with min/max bounds",
            validators=[min_validator(10), max_validator(20)]
        )

    env = create_environ(query_string=query_string)
    resource = SomeResource()
    params = resource.require_params(Request(env))

    assert isinstance(params['number'], int) 
Example #30
Source File: test_resources.py    From graceful with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def test_parameter_with_many_and_required():
    class SomeResource(Resource):
        foo = IntParam(details="give me foo", required=True, many=True)

    env = create_environ(query_string="foo=1&foo=2")
    resource = SomeResource()
    params = resource.require_params(Request(env))

    assert isinstance(params['foo'], Iterable)
    assert set(params['foo']) == {1, 2}