changeset 4218:10fe93273b09

Slim down TestRequest - use evaluate_request to get an (appiter, status, headers)-tuple
author Florian Krupicka <florian.krupicka@googlemail.com>
date Mon, 14 Jul 2008 13:34:07 +0200
parents b231877df090
children ce1265ca021a
files MoinMoin/auth/_tests/test_auth.py MoinMoin/web/contexts.py MoinMoin/web/request.py
diffstat 3 files changed, 49 insertions(+), 46 deletions(-) [+]
line wrap: on
line diff
--- a/MoinMoin/auth/_tests/test_auth.py	Mon Jul 14 13:16:57 2008 +0200
+++ b/MoinMoin/auth/_tests/test_auth.py	Mon Jul 14 13:34:07 2008 +0200
@@ -6,7 +6,7 @@
     @license: GNU GPL, see COPYING for details.
 """
 
-from MoinMoin.web.request import TestRequest
+from MoinMoin.web.request import TestRequest, evaluate_request
 from MoinMoin import wsgiapp
 
 class TestAuth:
@@ -28,8 +28,6 @@
         pass
 
     def run_request(self, **params):
-        if not 'REMOTE_ADDR' in params:
-            params['REMOTE_ADDR'] = '10.10.10.10'
         request = TestRequest(**params)
         request = wsgiapp.init(request)
         return wsgiapp.run(request)
@@ -41,10 +39,11 @@
         # anon user?
         assert not request.user.valid
 
+        appiter, status, headers = evaluate_request(request.request)
         # check if the request resulted in normal status, result headers and content
-        assert request.status == '200 OK'
+        assert status[:3] == '200'
         has_ct = has_v = has_cc = False
-        for k, v in request.headers:
+        for k, v in headers:
             if k == 'Content-Type':
                 assert v.startswith('text/html')
                 has_ct = True
@@ -61,7 +60,7 @@
         assert has_v
         # XXX BROKEN?:
         #assert has_cc # cache anon user's content
-        assert '</html>' in request.output()
+        assert '</html>' in ''.join(appiter)
 
     def testAnonSession(self):
         """ run some requests, no auth, check if anon sessions work """
@@ -70,8 +69,9 @@
         trail_expected = []
         first = True
         for pagename in self.PAGES:
+            environ_overrides = { 'HTTP_COOKIE': cookie }
             request = self.run_request(path='/%s' % pagename,
-                                       HTTP_COOKIE=cookie)
+                                       environ_overrides=environ_overrides)
 
             # anon user?
             assert not request.user.valid
@@ -79,10 +79,11 @@
             # Do we have a session?
             assert request.session is not None
 
+            appiter, status, headers = evaluate_request(request.request)
             # check if the request resulted in normal status, result headers and content
-            assert request.status == '200 OK'
+            assert status[:3] == '200'
             has_ct = has_v = has_cc = False
-            for k, v in request.headers:
+            for k, v in headers:
                 if k == 'Content-Type':
                     assert v.startswith('text/html')
                     has_ct = True
@@ -100,7 +101,7 @@
             assert has_v
             # XX BROKEN
             #assert not has_cc # do not cache anon user's (with session!) content
-            assert '</html>' in request.output()
+            assert '</html>' in ''.join(appiter)
 
             # The trail is only ever saved on the second page display
             # because otherwise anonymous sessions would be created
@@ -131,9 +132,10 @@
         trail_expected = []
         first = True
         for pagename in self.PAGES:
+            environ_overrides = { 'HTTP_COOKIE': cookie,
+                                  'HTTP_AUTHORIZATION': auth_header }
             request = self.run_request(path='/%s' % pagename,
-                                       HTTP_COOKIE=cookie,
-                                       HTTP_AUTHORIZATION=auth_header)
+                                       environ_overrides=environ_overrides)
 
             # Login worked?
             assert request.user.valid
@@ -142,8 +144,9 @@
             # Do we have a session?
             assert request.session is not None
 
+            appiter, status, headers = evaluate_request(request.request)
             # check if the request resulted in normal status, result headers and content
-            assert request.status == '200 OK'
+            assert status[:3] == '200'
             has_ct = has_v = has_cc = False
             for k, v in request.headers:
                 if k == 'Content-Type':
@@ -162,7 +165,7 @@
             assert has_ct
             assert has_v
             assert has_cc # do not cache logged-in user's content
-            assert '</html>' in request.output()
+            assert '</html>' in ''.join(appiter)
 
             # The trail is only ever saved on the second page display
             # because otherwise anonymous sessions would be created
@@ -201,8 +204,9 @@
                                            query_string='action=login',
                                            method='POST', form_data=formdata)
             else: # not first page, use session cookie
+                environ_overrides = { 'HTTP_COOKIE': cookie }
                 request = self.run_request(path='/%s' % pagename,
-                                           HTTP_COOKIE=cookie)
+                                           environ_overrides=environ_overrides)
 
             # Login worked?
             assert request.user.valid
@@ -211,8 +215,9 @@
             # Do we have a session?
             assert request.session is not None
 
+            appiter, status, headers = evaluate_request(request.request)
             # check if the request resulted in normal status, result headers and content
-            assert request.status == '200 OK'
+            assert status[:3] == '200'
             has_ct = has_v = has_cc = False
             for k, v in request.headers:
                 if k == 'Content-Type':
@@ -231,7 +236,7 @@
             assert has_ct
             assert has_v
             assert has_cc # do not cache logged-in user's content
-            assert '</html>' in request.output()
+            assert '</html>' in ''.join(appiter)
 
             # The trail is only ever saved on the second page display
             # because otherwise anonymous sessions would be created
--- a/MoinMoin/web/contexts.py	Mon Jul 14 13:16:57 2008 +0200
+++ b/MoinMoin/web/contexts.py	Mon Jul 14 13:34:07 2008 +0200
@@ -369,9 +369,6 @@
                             "consider changing this soon")
         self.request.stream.writelines(data)
 
-    def output(self):
-        return self.request()
-
 # TODO: extend xmlrpc context
 class XMLRPCContext(HTTPContext):
     """ Context to act during a XMLRPC request. """
--- a/MoinMoin/web/request.py	Mon Jul 14 13:16:57 2008 +0200
+++ b/MoinMoin/web/request.py	Mon Jul 14 13:34:07 2008 +0200
@@ -62,11 +62,13 @@
     in_data = cached_property(in_data, doc=WerkzeugRequest.data.__doc__)
 
 class TestRequest(Request):
+    """
+    Simple subclass of Request to initialize an environment for testing.
+    """
     def __init__(self, path="/", query_string=None, method='GET',
-                 input_stream=None, content_type=None, content_length=0,
-                 form_data=None, **env):
-        self.errors_stream = StringIO()
-        self.output_stream = StringIO()
+                 content_type=None, content_length=0, form_data=None,
+                 environ_overrides=None):
+        input_stream = None
 
         if form_data is not None:
             form_data = url_encode(form_data)
@@ -76,30 +78,29 @@
         environ = create_environ(path=path, query_string=query_string,
                                  method=method, input_stream=input_stream,
                                  content_type=content_type,
-                                 content_length=content_length,
-                                 errors_stream=self.errors_stream)
-
-        for k, v in env.items():
-            environ[k] = v
+                                 content_length=content_length)
 
         environ['HTTP_USER_AGENT'] = 'MoinMoin/TestRequest'
+        environ['REMOTE_ADDR'] = '10.10.10.10'
+
+        if environ_overrides:
+            environ.update(environ_overrides)
+
         super(TestRequest, self).__init__(environ)
 
-    def __call__(self):
-        def start_response(status, headers, exc_info=None):
-            return self.output_stream.write
-
-        appiter = Request.__call__(self, self.environ, start_response)
-        for s in appiter:
-            self.output_stream.write(s)
-        return self.output_stream.getvalue()
+def evaluate_request(request):
+    """ Evaluate a request and returns a tuple of application iterator,
+    status code and list of headers.
+    """
+    out = []
+    res = []
+    def start_response(status, headers, exc_info=None):
+        res.append(status)
+        res.append(headers)
+        return out.append
+    res.insert(0, request(request.environ, start_response))
 
-    def output(self):
-        """ Content of the WSGI output stream. """
-        return self.output_stream.getvalue()
-    output = property(output, doc=output.__doc__)
-
-    def errors(self):
-        """ Content of the WSGI error stream. """
-        return self.errors_stream.getvalue()
-    errors = property(errors, doc=errors.__doc__)
+    # any output via (WSGI-deprecated) write-callable?
+    if out:
+        res[0] = out
+    return tuple(res)