Exemple #1
0
def pop_ctx():
    """Removes the test context(s) from the current stack(s)
    """
    if getattr(_request_ctx_stack.top, 'fixtures_request_context', False):
        _request_ctx_stack.pop()
    if _app_ctx_stack is not None and getattr(_app_ctx_stack.top, 'fixtures_app_context', False):
        _app_ctx_stack.pop()
Exemple #2
0
    def test_validate_form(self):
        from flask import _request_ctx_stack
        _request_ctx_stack.pop()

        # form
        class ValidateForm(Form):
            string = StringField(
                'String',
                [validators.DataRequired(),
                 validators.Length(min=3, max=10)])
            boolean = BooleanField('Boolean', [
                validators.DataRequired(),
            ])

        @validate(ValidateForm)
        def test(string, boolean):
            pass

        # raises error
        with pytest.raises(ValueError):
            test(string='a', boolean='test')

        # no error
        assert test(string='test', boolean=True) is None
        return
Exemple #3
0
    def test_validate_validators(self):
        from flask import _request_ctx_stack
        _request_ctx_stack.pop()

        # function
        @validate(email=validators.Email(),
                  check=optional(
                      StringField('check', [
                          validators.Length(min=3, max=10),
                          validators.EqualTo('confirm')
                      ])),
                  confirm=optional(validators.Length(min=3, max=10)))
        def test(email, check, confirm):
            pass

        # raises error
        with pytest.raises(ValueError):
            test(email='test', check='test', confirm='test')

        # raises error
        with pytest.raises(ValueError):
            test(email='*****@*****.**', check='t', confirm='t')

        # raises error
        with pytest.raises(ValueError):
            test(email='*****@*****.**', check='test', confirm='aaaa')

        # no error
        assert test(email='*****@*****.**', check='test', confirm='test') is None
        return
Exemple #4
0
    def open(self, *args, **kwargs):
        if self.context_preserved:
            _request_ctx_stack.pop()
            self.context_preserved = False
        kwargs.setdefault('environ_overrides', {}) \
            ['flask._preserve_context'] = self.preserve_context

        as_tuple = kwargs.pop('as_tuple', False)
        buffered = kwargs.pop('buffered', False)
        follow_redirects = kwargs.pop('follow_redirects', False)

        builder = EnvironBuilder(*args, **kwargs)

        if self.application.config.get('SERVER_NAME'):
            server_name = self.application.config.get('SERVER_NAME')
            if ':' not in server_name:
                http_host, http_port = server_name, None
            else:
                http_host, http_port = server_name.split(':', 1)
            if builder.base_url == 'http://localhost/':
                # Default Generated Base URL
                if http_port != None:
                    builder.host = http_host + ':' + http_port
                else:
                    builder.host = http_host
        old = _request_ctx_stack.top
        try:
            return Client.open(self,
                               builder,
                               as_tuple=as_tuple,
                               buffered=buffered,
                               follow_redirects=follow_redirects)
        finally:
            self.context_preserved = _request_ctx_stack.top is not old
Exemple #5
0
    def open(self, *args, **kwargs):
        if self.context_preserved:
            _request_ctx_stack.pop()
            self.context_preserved = False
        kwargs.setdefault('environ_overrides', {}) \
            ['flask._preserve_context'] = self.preserve_context

        as_tuple = kwargs.pop('as_tuple', False)
        buffered = kwargs.pop('buffered', False)
        follow_redirects = kwargs.pop('follow_redirects', False)

        builder = EnvironBuilder(*args, **kwargs)

        if self.application.config.get('SERVER_NAME'):
            server_name = self.application.config.get('SERVER_NAME')
            if ':' not in server_name:
                http_host, http_port = server_name, None
            else:
                http_host, http_port = server_name.split(':', 1)
            if builder.base_url == 'http://localhost/':
                # Default Generated Base URL
                if http_port != None:
                    builder.host = http_host + ':' + http_port
                else:
                    builder.host = http_host
        old = _request_ctx_stack.top
        try:
            return Client.open(self, builder,
                               as_tuple=as_tuple,
                               buffered=buffered,
                               follow_redirects=follow_redirects)
        finally:
            self.context_preserved = _request_ctx_stack.top is not old
Exemple #6
0
def pop_ctx():
    """Removes the test context(s) from the current stack(s)
    """
    if getattr(_request_ctx_stack.top, 'fixtures_request_context', False):
        _request_ctx_stack.pop()
    if _app_ctx_stack is not None and getattr(_app_ctx_stack.top, 'fixtures_app_context', False):
        _app_ctx_stack.pop()
Exemple #7
0
 def my_url_for(self, endpoint, **values):
     try:
         # RequestContext.push() causes wrong context to be popped when app
         # preserves context on exception, the default for app.debug=True.
         # Instead, push/pop directly on the LocalStack.
         _request_ctx_stack.push(self.invitation_context)
         return url_for(endpoint, **values)
     finally:
         _request_ctx_stack.pop()
Exemple #8
0
 def open(self, *args, **kwargs):
     if self.context_preserved:
         _request_ctx_stack.pop()
         self.context_preserved = False
     kwargs.setdefault('environ_overrides', {}) \
         ['flask._preserve_context'] = self.preserve_context
     old = _request_ctx_stack.top
     try:
         return Client.open(self, *args, **kwargs)
     finally:
         self.context_preserved = _request_ctx_stack.top is not old
Exemple #9
0
    def session_transaction(self, *args, **kwargs):
        """When used in combination with a ``with`` statement this opens a
        session transaction.  This can be used to modify the session that
        the test client uses.  Once the ``with`` block is left the session is
        stored back.

        ::

            with client.session_transaction() as session:
                session['value'] = 42

        Internally this is implemented by going through a temporary test
        request context and since session handling could depend on
        request variables this function accepts the same arguments as
        :meth:`~flask.Flask.test_request_context` which are directly
        passed through.
        """
        if self.cookie_jar is None:
            raise RuntimeError(
                "Session transactions only make sense " "with cookies enabled."
            )
        app = self.application
        environ_overrides = kwargs.setdefault("environ_overrides", {})
        self.cookie_jar.inject_wsgi(environ_overrides)
        outer_reqctx = _request_ctx_stack.top
        with app.test_request_context(*args, **kwargs) as c:
            session_interface = app.session_interface
            sess = session_interface.open_session(app, c.request)
            if sess is None:
                raise RuntimeError(
                    "Session backend did not open a session. " "Check the configuration"
                )

            # Since we have to open a new request context for the session
            # handling we want to make sure that we hide out own context
            # from the caller.  By pushing the original request context
            # (or None) on top of this and popping it we get exactly that
            # behavior.  It's important to not use the push and pop
            # methods of the actual request context object since that would
            # mean that cleanup handlers are called
            _request_ctx_stack.push(outer_reqctx)
            try:
                yield sess
            finally:
                _request_ctx_stack.pop()

            resp = app.response_class()
            if not session_interface.is_null_session(sess):
                session_interface.save_session(app, sess, resp)
            headers = resp.get_wsgi_headers(c.request.environ)
            self.cookie_jar.extract_wsgi(c.request.environ, headers)
    def session_transaction(self, *args, **kwargs):
        """When used in combination with a ``with`` statement this opens a
        session transaction.  This can be used to modify the session that
        the test client uses.  Once the ``with`` block is left the session is
        stored back.

        ::

            with client.session_transaction() as session:
                session['value'] = 42

        Internally this is implemented by going through a temporary test
        request context and since session handling could depend on
        request variables this function accepts the same arguments as
        :meth:`~flask.Flask.test_request_context` which are directly
        passed through.
        """
        if self.cookie_jar is None:
            raise RuntimeError('Session transactions only make sense '
                               'with cookies enabled.')
        app = self.application
        environ_overrides = kwargs.setdefault('environ_overrides', {})
        self.cookie_jar.inject_wsgi(environ_overrides)
        outer_reqctx = _request_ctx_stack.top
        with app.test_request_context(*args, **kwargs) as c:
            session_interface = app.session_interface
            sess = session_interface.open_session(app, c.request)
            if sess is None:
                raise RuntimeError('Session backend did not open a session. '
                                   'Check the configuration')

            # Since we have to open a new request context for the session
            # handling we want to make sure that we hide out own context
            # from the caller.  By pushing the original request context
            # (or None) on top of this and popping it we get exactly that
            # behavior.  It's important to not use the push and pop
            # methods of the actual request context object since that would
            # mean that cleanup handlers are called
            _request_ctx_stack.push(outer_reqctx)
            try:
                yield sess
            finally:
                _request_ctx_stack.pop()

            resp = app.response_class()
            if not session_interface.is_null_session(sess):
                session_interface.save_session(app, sess, resp)
            headers = resp.get_wsgi_headers(c.request.environ)
            self.cookie_jar.extract_wsgi(c.request.environ, headers)
Exemple #11
0
    def test_validate_types(self):
        from flask import _request_ctx_stack
        _request_ctx_stack.pop()

        # function
        @validate(one=str,
                  two=float,
                  three=list,
                  four=optional(dict(
                      foo=str,
                      bar=str,
                  )),
                  five=optional([str]))
        def test(one, two, three, four=None, five=None):
            pass

        # no exception
        test(one='test', two=1.5, three=[1])
        test(one='test',
             two=1.5,
             three=[1],
             four=dict(foo='foo', bar='bar'),
             five=['one', 'two'])

        # non-optional
        try:
            test(one=1, two='test', three=1)
            self.fail('ValueError not thrown')
        except ValueError as exc:
            message = str(exc)
            assert 'one:' in message
            assert 'two:' in message
            assert 'three:' in message

        # optional
        try:
            test(one='test',
                 two=1.5,
                 three=[1],
                 four=dict(foo=1, bar='bar'),
                 five=[1, 2])
            self.fail('ValueError not thrown')
        except ValueError as exc:
            message = str(exc)
            assert 'four:' in message
            assert 'five:' in message
        return
Exemple #12
0
    def test_validate_mixed(self):
        from flask import _request_ctx_stack
        _request_ctx_stack.pop()

        # function
        @validate(email=validators.Email(),
                  one=dict(length=validators.Length(min=3)),
                  two=float)
        def test(email, one, two):
            pass

        # no error
        test(email='*****@*****.**', one=dict(length='test'), two=1.5)

        # nested error
        with pytest.raises(ValueError):
            test(email='*****@*****.**', one=dict(length='te'), two=1.5)
        return
Exemple #13
0
 def wrapper(*args, **kwargs):
     if current_app and current_app.name == 'jupiter.app':
         return wrapped(*args, **kwargs)
     current_request_context = _request_ctx_stack.pop()
     try:
         with create_app().app_context():
             value = wrapped(*args, **kwargs)
     finally:
         if current_request_context is not None:
             current_request_context.push()
     return value
Exemple #14
0
    def test_validate_optional(self):
        from flask import _request_ctx_stack
        _request_ctx_stack.pop()

        # function
        @validate.optional(
            one=str,
            two=float,
        )
        def test(one='test', two=1.1):
            pass

        # no error
        test(one='str')
        test(two=5.5)

        # error
        with pytest.raises(ValueError):
            test(one=1)
        return
Exemple #15
0
def test_recordsearchv2_with_preference_param_no_request_no_param(app):
    # WARNING: the app fixture *somehow* pushes a request context
    #          even though it should not. We pop it and push it back later.
    if _request_ctx_stack.top:
        prior_request_ctx = _request_ctx_stack.pop()

    assert has_request_context() is False

    search = SpySearchV2().with_preference_param()

    assert {} == search.exposed_params

    _request_ctx_stack.push(prior_request_ctx)
Exemple #16
0
 def __exit__(self, exc_type, exc_value, tb):
     self.preserve_context = False
     if self.context_preserved:
         _request_ctx_stack.pop()
Exemple #17
0
 def logout(self, follow_redirects=True):
     """Perform log-out."""
     resp = self.get("/logout", follow_redirects=follow_redirects)
     _request_ctx_stack.pop()
     self.cookie_jar.clear()
     return resp
Exemple #18
0
 def __exit__(self, exc_type, exc_value, tb):
     self.preserve_context = False
     if self.context_preserved:
         _request_ctx_stack.pop()