Beispiel #1
0
def do_request(app, expect_status=500):
    app = lint.middleware(app)
    app = ErrorMiddleware(app, {}, debug=True)
    app = clear_middleware(app)
    testapp = TestApp(app)
    res = testapp.get('', status=expect_status, expect_errors=True)
    return res
def do_request(app, expect_status=500):
    app = lint.middleware(app)
    app = ErrorMiddleware(app, {}, debug=True)
    app = clear_middleware(app)
    testapp = TestApp(app)
    res = testapp.get('', status=expect_status,
                      expect_errors=True)
    return res
Beispiel #3
0
 def do_request(self, req, status, expect_errors):
     """
     Executes the given request (``req``), with the expected
     ``status``.  Generally ``.get()`` and ``.post()`` are used
     instead.
     """
     __tracebackhide__ = True
     errors = StringIO()
     req.environ["wsgi.errors"] = errors
     if self.cookies:
         c = BaseCookie()
         for name, value in self.cookies.items():
             c[name] = value
         req.environ["HTTP_COOKIE"] = str(c).split(": ", 1)[1]
     req.environ["paste.testing"] = True
     req.environ["paste.testing_variables"] = {}
     app = lint.middleware(self.app)
     old_stdout = sys.stdout
     out = CaptureStdout(old_stdout)
     try:
         sys.stdout = out
         start_time = time.time()
         ## FIXME: should it be an option to not catch exc_info?
         res = req.get_response(app, catch_exc_info=True)
         end_time = time.time()
     finally:
         sys.stdout = old_stdout
         sys.stderr.write(out.getvalue())
     res.app = app
     res.test_app = self
     # We do this to make sure the app_iter is exausted:
     res.body
     res.errors = errors.getvalue()
     total_time = end_time - start_time
     for name, value in req.environ["paste.testing_variables"].items():
         if hasattr(res, name):
             raise ValueError(
                 "paste.testing_variables contains the variable %r, but "
                 "the response object already has an attribute by that "
                 "name" % name
             )
         setattr(res, name, value)
     if not expect_errors:
         self._check_status(status, res)
         self._check_errors(res)
     res.cookies_set = {}
     for header in res.headers.getall("set-cookie"):
         try:
             c = BaseCookie(header)
         except CookieError, e:
             raise CookieError("Could not parse cookie header %r: %s" % (header, e))
         for key, morsel in c.items():
             self.cookies[key] = morsel.value
             res.cookies_set[key] = morsel.value
Beispiel #4
0
 def do_request(self, req, status, expect_errors):
     """
     Executes the given request (``req``), with the expected
     ``status``.  Generally ``.get()`` and ``.post()`` are used
     instead.
     """
     __tracebackhide__ = True
     errors = StringIO()
     req.environ['wsgi.errors'] = errors
     if self.cookies:
         c = BaseCookie()
         for name, value in self.cookies.items():
             c[name] = value
         req.environ['HTTP_COOKIE'] = str(c).split(': ', 1)[1]
     req.environ['paste.testing'] = True
     req.environ['paste.testing_variables'] = {}
     app = lint.middleware(self.app)
     old_stdout = sys.stdout
     out = CaptureStdout(old_stdout)
     try:
         sys.stdout = out
         start_time = time.time()
         ## FIXME: should it be an option to not catch exc_info?
         res = req.get_response(app, catch_exc_info=True)
         end_time = time.time()
     finally:
         sys.stdout = old_stdout
         sys.stderr.write(out.getvalue())
     res.app = app
     res.test_app = self
     # We do this to make sure the app_iter is exausted:
     res.body
     res.errors = errors.getvalue()
     total_time = end_time - start_time
     for name, value in req.environ['paste.testing_variables'].items():
         if hasattr(res, name):
             raise ValueError(
                 "paste.testing_variables contains the variable %r, but "
                 "the response object already has an attribute by that "
                 "name" % name)
         setattr(res, name, value)
     if not expect_errors:
         self._check_status(status, res)
         self._check_errors(res)
     res.cookies_set = {}
     for header in res.headers.getall('set-cookie'):
         try:
             c = BaseCookie(header)
         except CookieError, e:
             raise CookieError("Could not parse cookie header %r: %s" %
                               (header, e))
         for key, morsel in c.items():
             self.cookies[key] = morsel.value
             res.cookies_set[key] = morsel.value
Beispiel #5
0
 def _get_resp(self, url):
     req = TestRequest.blank(url)
     app = lint.middleware(self.app.app)
     res = req.get_response(app, True)
     return res
Beispiel #6
0
 def test_lint_iterator_returned(self):
     linter = middleware(lambda x, y: None)  # None is not an iterator
     msg = "The application must return an iterator, if only an empty list"
     with self.assertRaisesRegexp(AssertionError, msg):
         linter({'wsgi.input': 'foo', 'wsgi.errors': 'foo'}, 'foo')
Beispiel #7
0
 def test_lint_no_keyword_args(self):
     linter = middleware(application)
     with self.assertRaisesRegexp(AssertionError, "No keyword arguments "
                                                  "allowed"):
         linter({}, 'foo', baz='baz')
Beispiel #8
0
 def test_lint_too_few_args(self):
     linter = middleware(application)
     with self.assertRaisesRegexp(AssertionError, "Two arguments required"):
         linter()
     with self.assertRaisesRegexp(AssertionError, "Two arguments required"):
         linter({})
Beispiel #9
0
    def do_request(self, req, status, expect_errors):
        """
        Executes the given request (``req``), with the expected
        ``status``.  Generally ``.get()`` and ``.post()`` are used
        instead.

        To use this::

            resp = app.do_request(webtest.TestRequest.blank(
                'url', ...args...))

        Note you can pass any keyword arguments to
        ``TestRequest.blank()``, which will be set on the request.
        These can be arguments like ``content_type``, ``accept``, etc.
        """
        __tracebackhide__ = True # NOQA
        errors = StringIO()
        req.environ['wsgi.errors'] = errors
        script_name = req.environ.get('SCRIPT_NAME', '')
        if script_name and req.path_info.startswith(script_name):
            req.path_info = req.path_info[len(script_name):]
        cookies = self.cookies or {}
        cookies = list(cookies.items())
        if 'Cookie' in req.headers:
            req_cookies = req.headers['Cookie'].split(str(';'))
            req_cookies = [i.strip() for i in req_cookies]
            req_cookies = [i.split(str('='), 1) for i in req_cookies]
            cookies.extend(req_cookies)
        if cookies:
            cookie_header = str('').join([
                str('%s=%s; ') % (name, cookie_quote(value))
                for name, value in cookies])
            req.environ['HTTP_COOKIE'] = cookie_header
        req.environ['paste.testing'] = True
        req.environ['paste.testing_variables'] = {}
        app = lint.middleware(self.app)
        ## FIXME: should it be an option to not catch exc_info?
        res = req.get_response(app, catch_exc_info=True)
        res._use_unicode = self.use_unicode
        res.request = req
        res.app = app
        res.test_app = self
        # We do this to make sure the app_iter is exausted:
        try:
            res.body
        except TypeError:
            pass
        res.errors = errors.getvalue()
        for name, value in req.environ['paste.testing_variables'].items():
            if hasattr(res, name):
                raise ValueError(
                    "paste.testing_variables contains the variable %r, but "
                    "the response object already has an attribute by that "
                    "name" % name)
            setattr(res, name, value)
        if not expect_errors:
            self._check_status(status, res)
            self._check_errors(res)
        res.cookies_set = {}
        for header in res.headers.getall('set-cookie'):
            try:
                c = SimpleCookie(header)
            except CookieError:
                raise CookieError(
                    "Could not parse cookie header %r" % (header,))
            for key, morsel in c.items():
                self.cookies[key] = morsel.value
                res.cookies_set[key] = morsel.value
        return res
Beispiel #10
0
 def test_lint_no_keyword_args(self):
     linter = middleware(application)
     with self.assertRaisesRegexp(AssertionError, "No keyword arguments "
                                  "allowed"):
         linter({}, 'foo', baz='baz')
Beispiel #11
0
 def test_lint_too_few_args(self):
     linter = middleware(application)
     with self.assertRaisesRegexp(AssertionError, "Two arguments required"):
         linter()
     with self.assertRaisesRegexp(AssertionError, "Two arguments required"):
         linter({})
Beispiel #12
0
 def _get_resp(url):
     req = TestRequest.blank(url)
     res = req.get_response(lint.middleware(app.app), True)
     return res
Beispiel #13
0
    def do_request(self, req, status, expect_errors):
        """
        Executes the given request (``req``), with the expected
        ``status``.  Generally ``.get()`` and ``.post()`` are used
        instead.

        To use this::

            resp = app.do_request(webtest.TestRequest.blank(
                'url', ...args...))

        Note you can pass any keyword arguments to
        ``TestRequest.blank()``, which will be set on the request.
        These can be arguments like ``content_type``, ``accept``, etc.
        """
        __tracebackhide__ = True
        errors = StringIO()
        req.environ['wsgi.errors'] = errors
        if self.cookies:
            cookie_header = ''.join([
                '%s="%s"; ' % (name, cookie_quote(value))
                for name, value in self.cookies.items()])
            req.environ['HTTP_COOKIE'] = cookie_header
        req.environ['paste.testing'] = True
        req.environ['paste.testing_variables'] = {}
        app = lint.middleware(self.app)
        old_stdout = sys.stdout
        out = CaptureStdout(old_stdout)
        try:
            sys.stdout = out
            start_time = time.time()
            ## FIXME: should it be an option to not catch exc_info?
            res = req.get_response(app, catch_exc_info=True)
            end_time = time.time()
        finally:
            sys.stdout = old_stdout
        res.app = app
        res.test_app = self
        # We do this to make sure the app_iter is exausted:
        res.body
        res.errors = errors.getvalue()
        total_time = end_time - start_time
        for name, value in req.environ['paste.testing_variables'].items():
            if hasattr(res, name):
                raise ValueError(
                    "paste.testing_variables contains the variable %r, but "
                    "the response object already has an attribute by that "
                    "name" % name)
            setattr(res, name, value)
        if not expect_errors:
            self._check_status(status, res)
            self._check_errors(res)
        res.cookies_set = {}
        for header in res.headers.getall('set-cookie'):
            try:
                c = BaseCookie(header)
            except CookieError, e:
                raise CookieError(
                    "Could not parse cookie header %r: %s" % (header, e))
            for key, morsel in c.items():
                self.cookies[key] = morsel.value
                res.cookies_set[key] = morsel.value
def test_iter_app():
    res = do_request(lint.middleware(iter_app), 200)
    #print res
    assert 'None raises error' in res
    assert 'yielder' in res
Beispiel #15
0
    def do_request(self, req, status=None, expect_errors=None):
        """
        Executes the given webob Request (``req``), with the expected
        ``status``.  Generally :meth:`~webtest.TestApp.get` and
        :meth:`~webtest.TestApp.post` are used instead.

        To use this::

            req = webtest.TestRequest.blank('url', ...args...)
            resp = app.do_request(req)

        .. note::

            You can pass any keyword arguments to
            ``TestRequest.blank()``, which will be set on the request.
            These can be arguments like ``content_type``, ``accept``, etc.

        """

        errors = StringIO()
        req.environ['wsgi.errors'] = errors
        script_name = req.environ.get('SCRIPT_NAME', '')
        if script_name and req.path_info.startswith(script_name):
            req.path_info = req.path_info[len(script_name):]

        # set framework hooks
        req.environ['paste.testing'] = True
        req.environ['paste.testing_variables'] = {}

        # set request cookies
        self.cookiejar.add_cookie_header(utils._RequestCookieAdapter(req))

        # verify wsgi compatibility
        app = lint.middleware(self.app) if self.lint else self.app

        ## FIXME: should it be an option to not catch exc_info?
        res = req.get_response(app, catch_exc_info=True)

        # be sure to decode the content
        res.decode_content()

        # set a few handy attributes
        res._use_unicode = self.use_unicode
        res.request = req
        res.app = app
        res.test_app = self

        # We do this to make sure the app_iter is exausted:
        try:
            res.body
        except TypeError:  # pragma: no cover
            pass
        res.errors = errors.getvalue()

        for name, value in req.environ['paste.testing_variables'].items():
            if hasattr(res, name):
                raise ValueError(
                    "paste.testing_variables contains the variable %r, but "
                    "the response object already has an attribute by that "
                    "name" % name)
            setattr(res, name, value)
        if not expect_errors:
            self._check_status(status, res)
            self._check_errors(res)

        # merge cookies back in
        self.cookiejar.extract_cookies(utils._ResponseCookieAdapter(res),
                                       utils._RequestCookieAdapter(req))

        return res
Beispiel #16
0
 def test_lint_iterator_returned(self):
     linter = middleware(lambda x, y: None)  # None is not an iterator
     msg = "The application must return an iterator, if only an empty list"
     with self.assertRaisesRegexp(AssertionError, msg):
         linter({'wsgi.input': 'foo', 'wsgi.errors': 'foo'}, 'foo')
Beispiel #17
0
    def do_request(self, req, status=None, expect_errors=None):
        """
        Executes the given webob Request (``req``), with the expected
        ``status``.  Generally :meth:`~webtest.TestApp.get` and
        :meth:`~webtest.TestApp.post` are used instead.

        To use this::

            req = webtest.TestRequest.blank('url', ...args...)
            resp = app.do_request(req)

        .. note::

            You can pass any keyword arguments to
            ``TestRequest.blank()``, which will be set on the request.
            These can be arguments like ``content_type``, ``accept``, etc.

        """

        errors = StringIO()
        req.environ['wsgi.errors'] = errors
        script_name = req.environ.get('SCRIPT_NAME', '')
        if script_name and req.path_info.startswith(script_name):
            req.path_info = req.path_info[len(script_name):]

        # set framework hooks
        req.environ['paste.testing'] = True
        req.environ['paste.testing_variables'] = {}

        # set request cookies
        self.cookiejar.add_cookie_header(utils._RequestCookieAdapter(req))

        # verify wsgi compatibility
        app = lint.middleware(self.app) if self.lint else self.app

        ## FIXME: should it be an option to not catch exc_info?
        res = req.get_response(app, catch_exc_info=True)

        # be sure to decode the content
        res.decode_content()

        # set a few handy attributes
        res._use_unicode = self.use_unicode
        res.request = req
        res.app = app
        res.test_app = self

        # We do this to make sure the app_iter is exausted:
        try:
            res.body
        except TypeError:  # pragma: no cover
            pass
        res.errors = errors.getvalue()

        for name, value in req.environ['paste.testing_variables'].items():
            if hasattr(res, name):
                raise ValueError(
                    "paste.testing_variables contains the variable %r, but "
                    "the response object already has an attribute by that "
                    "name" % name)
            setattr(res, name, value)
        if not expect_errors:
            self._check_status(status, res)
            self._check_errors(res)

        # merge cookies back in
        self.cookiejar.extract_cookies(utils._ResponseCookieAdapter(res),
                                       utils._RequestCookieAdapter(req))

        return res
 def _get_resp(self, url):
     req = TestRequest.blank(url)
     app = lint.middleware(self.app.app)
     res = req.get_response(app, True)
     return res
Beispiel #19
0
def test_iter_app():
    res = do_request(lint.middleware(iter_app), 200)
    #print res
    assert 'None raises error' in res
    assert 'yielder' in res