def test_success(self): response = Response(body="Hi") app = App() app.expose('/')(lambda request: response) resp = app.route({'REQUEST_METHOD': 'GET', 'PATH_INFO': '/'}) self.assertTrue(resp is response)
class RenderTest(unittest.TestCase): def setUp(self): self.app = App() def test_httpexception(self): ex = exc.HTTPNotFound(detail="test") out = self.app._render({}, (Request(_env()), ex)) self.assertTrue(out[0].startswith('404')) def test_non_httpexception(self): ex = ValueError("WTF") out = self.app._render({}, (Request(_env()), ex)) self.assertTrue(out[0].startswith("500")) def test_json_type(self): ex = ValueError("WTF") out = self.app._render({}, (Request(_env()), ex)) headers = dict(out[1]) self.assertTrue('Content-Type' in headers) self.assertEqual(headers['Content-Type'], 'application/json') def test_bad_response(self): resp = self.app._render({}, (Request(_env()), "foo")) self.assertTrue(isinstance(resp, tuple)) self.assertTrue(resp[0].startswith("500")) def test_bad_request(self): message = "You dun goof'd" ex = exc.HTTPBadRequest(message) (response, headers, body) = self.app._render({}, (Request(_env()), ex)) body = "".join(body) self.assertTrue(len(body) > 0) blab = json.loads(body) self.assertEqual(blab['detail'], message)
class RenderTest(unittest.TestCase): def setUp(self): self.app = App() def test_httpexception(self): ex = exc.HTTPNotFound(detail="test") out = self.app._render({}, ex) print out self.assertTrue(out[0].startswith('404')) def test_non_httpexception(self): ex = ValueError("WTF") out = self.app._render({}, ex) self.assertTrue(out[0].startswith("500")) def test_json_type(self): ex = ValueError("WTF") out = self.app._render({}, ex) headers = dict(out[1]) self.assertTrue('Content-Type' in headers) self.assertEqual(headers['Content-Type'], 'application/json') def test_bad_response(self): resp = self.app._render({}, "foo") self.assertTrue(isinstance(resp, tuple)) self.assertTrue(resp[0].startswith("500"))
def test_has_prefix(self): """Make sure endpoint URLs include the prefix.""" prefix = "/foo" app = App(prefix=prefix) endpoints(app, "/endpoints") for endpoint in app.endpoints().iterkeys(): self.assertTrue(prefix in endpoint)
class TestExpose(unittest.TestCase): """Test App.expose.""" def setUp(self): self.app = App() def test_expose_method(self): """Make sure the original method is preserved.""" f = lambda request: None f_ = self.app.expose('/test_expose')(f) self.assert_(f_ is f) def test_expose_methods(self): """Make sure invalid methods raise an exception.""" self.assertRaises(Exception, self.app.expose, '/foo', 'CHEESE') def test_expose_method_maps(self): """Make sure patterns are added to the correct maps.""" url, method = ('/cheese', 'GET') old_len = len(self.app.map[method]._patterns) f = lambda request: None self.app.expose(url, method)(f) self.assert_(len(self.app.map[method]._patterns) > old_len) self.assert_(url in self.app.map[method]._patterns) self.assert_(self.app.map[method]._patterns[url][1] is f) def test_expose_method_decorates(self): """Make sure functions aren't decorated when added.""" url, method = ('/shop', 'GET') old_len = len(self.app.map[method]._patterns) f = lambda request: None self.app.expose(url, method)(f) self.assert_(self.app.map[method]._patterns[url][1] is f)
def test_endpoints(self): """Make sure hidden functions don't show up in endpoints.""" app = App() @app.expose('/endpoint') @hidden def endpoint(request): return Response() self.assertFalse(app.endpoints())
def test_unicode_request(self): """Make sure the request uses Unicode.""" env = {'QUERY_STRING': 'q=ü'} app = App() @app.expose("/foo") def __endpoint__(request): self.assertTrue(isinstance(request.GET, webob.UnicodeMultiDict)) app.route({'REQUEST_METHOD': 'GET', 'PATH_INFO': "/foo"})
def test_exceptions_returned(self): """Make sure non-HTTPExceptions are returned.""" ex = Exception("Test exception") app = App() @app.expose("/foo") def test_f(request): raise ex (req, resp) = app.route({'REQUEST_METHOD': 'GET', 'PATH_INFO': "/foo"}) self.assert_(resp is ex)
def test_generates_request(self): """Make sure request objects are generated.""" runs = [] app = App() @app.expose("/foo") def test_f(request): runs.append(True) self.assert_(isinstance(request, Request)) return Response() (req, resp) = app.route({'REQUEST_METHOD': 'GET', 'PATH_INFO': "/foo"}) self.assert_(len(runs) == 1)
def test_multi_expose(self): app = App() @app.expose("/foo") @app.expose("/bar") def endpoint(request): return Response(body="Hi.") (req, resp) = app.route({'REQUEST_METHOD': "GET", 'PATH_INFO': "/foo"}) self.assertTrue(isinstance(resp, Response)) self.assertFalse(isinstance(resp, exc.HTTPError)) self.assertTrue(resp.body == "Hi.")
class GetEndpointsTest(unittest.TestCase): """Test _get_endpoints.""" def setUp(self): self.app = App() def test_endpoints(self): self.app.expose('foo')(lambda request: Response()) self.app.expose('bar')(lambda request: Response()) endpoints = self.app.endpoints() self.assertTrue('GET foo' in endpoints.keys()) self.assertTrue('GET bar' in endpoints.keys())
class EndpointsTest(unittest.TestCase): """Test dream.endpoints()""" def setUp(self): self.app = App() endpoints(self.app, '/endpoints') def test_endpoints(self): self.assertTrue('GET /endpoints' in self.app.endpoints().keys()) def test_endpoints_reponse(self): self.assertTrue(isinstance( self.app.route({'REQUEST_METHOD': 'GET', 'PATH_INFO': '/endpoints'}), HumanReadableJSONResponse))
class MangleResponseTest(unittest.TestCase): """Make sure _mangle_response works.""" def setUp(self): self.app = App(debug=True) def test_exceptions(self): """Make sure exceptions are handled properly.""" exc = ValueError("Expected some cheese.") resp = self.app._mangle_response(Request(_env()), exc) body = json.loads(resp.body) self.assertTrue(body['detail'].startswith('Caught exception ' + str(type(exc)))) def test_traceback_list(self): """Make sure tracebacks are included when they're lists.""" ex = Exception("foo") ex.__traceback__ = traceback.extract_stack() resp = _debug_exception_to_reponse(Request(_env()), ex) body = json.loads(resp.body) self.assertTrue('traceback' in body) self.assertNotEqual(body['traceback'], ["No traceback available."]) def test_nonerror_exceptions(self): """Non-error exceptions shouldn't get mangled a traceback.""" ex = exc.HTTPMovedPermanently(headers={'Location': "/foo.json"}) resp = self.app._mangle_response(Request(_env()), ex) self.assertTrue(resp is ex) def test_server_error_exceptions(self): """Non-error exceptions shouldn't get mangled a traceback.""" ex = exc.HTTPInternalServerError() resp = self.app._mangle_response(Request(_env()), ex) self.assertTrue(resp is not ex) def test_client_error_exceptions(self): """Non-error exceptions shouldn't get mangled a traceback.""" ex = exc.HTTPBadRequest() resp = self.app._mangle_response(Request(_env()), ex) self.assertTrue(resp is not ex)
class EndpointsTest(unittest.TestCase): """Test dream.endpoints()""" def setUp(self): self.app = App() endpoints(self.app, '/endpoints') def test_endpoints(self): self.assertTrue('GET /endpoints' in self.app.endpoints().keys()) def test_endpoints_reponse(self): (request, response) = self.app.route({'REQUEST_METHOD': 'GET', 'PATH_INFO': '/endpoints'}) self.assertTrue(isinstance(response, HumanReadableJSONResponse)) def test_has_prefix(self): """Make sure endpoint URLs include the prefix.""" prefix = "/foo" app = App(prefix=prefix) endpoints(app, "/endpoints") for endpoint in app.endpoints().iterkeys(): self.assertTrue(prefix in endpoint)
class MangleResponseTest(unittest.TestCase): """Make sure _mangle_response works.""" def setUp(self): self.app = App(debug=True) def test_exceptions(self): """Make sure exceptions are handled properly.""" exc = ValueError("Expected some cheese.") resp = self.app._mangle_response(exc) body = json.loads(resp.body) self.assertTrue(body['detail'].startswith('Caught exception ' + str(type(exc))))
def test_debug_exceptions(self): """Make sure exceptions are handled properly based on debug.""" app = App(debug=True) resp = app._mangle_response(exc.HTTPBadRequest("Whops")) self.assertTrue('traceback' in json.loads(resp.body))
def setUp(self): self.app = App()
def setUp(self): self.app = App(debug=True)
def test_nondebug_exceptions(self): """Make sure exceptions are handled properly based on debug.""" app = App(debug=False) resp = app._mangle_response( Request(_env()), exc.HTTPInternalServerError("Whops")) self.assertFalse('traceback' in json.loads(resp.body))
def setUp(self): self.app = App() endpoints(self.app, '/endpoints')
def test_nonprefix_404(self): app = App() (req, resp) = app.route({'REQUEST_METHOD': 'GET', 'PATH_INFO': '/foo'}) self.assertTrue(isinstance(resp, exc.HTTPNotFound))
def test_prefix_404(self): app = App(prefix='/1.0') self.assertTrue(isinstance( app.route({'REQUEST_METHOD': 'GET', 'PATH_INFO': '/foo'})[1], exc.HTTPNotFound))