def test_shortcut_view(self): """ Check that the shortcut view (used for the admin "view on site" functionality) returns a complete URL regardless of whether the sites framework is installed """ request = HttpRequest() request.META = { "SERVER_NAME": "Example.com", "SERVER_PORT": "80", } user_ct = ContentType.objects.get_for_model(FooWithUrl) obj = FooWithUrl.objects.create(name="john") if Site._meta.installed: current_site = Site.objects.get_current() response = shortcut(request, user_ct.id, obj.id) self.assertEqual("http://%s/users/john/" % current_site.domain, response._headers.get("location")[1]) Site._meta.installed = False response = shortcut(request, user_ct.id, obj.id) self.assertEqual("http://Example.com/users/john/", response._headers.get("location")[1])
def test_detects_tampering(self): response = HttpResponse() response.set_signed_cookie('c', 'hello') request = HttpRequest() request.COOKIES['c'] = response.cookies['c'].value[:-2] + '$$' self.assertRaises(signing.BadSignature, request.get_signed_cookie, 'c')
def test_is_extendable(self): """ Tests that the XFrameOptionsMiddleware method that determines the X-Frame-Options header value can be overridden based on something in the request or response. """ class OtherXFrameOptionsMiddleware(XFrameOptionsMiddleware): # This is just an example for testing purposes... def get_xframe_options_value(self, request, response): if getattr(request, 'sameorigin', False): return 'SAMEORIGIN' if getattr(response, 'sameorigin', False): return 'SAMEORIGIN' return 'DENY' settings.X_FRAME_OPTIONS = 'DENY' response = HttpResponse() response.sameorigin = True r = OtherXFrameOptionsMiddleware().process_response(HttpRequest(), response) self.assertEqual(r['X-Frame-Options'], 'SAMEORIGIN') request = HttpRequest() request.sameorigin = True r = OtherXFrameOptionsMiddleware().process_response(request, HttpResponse()) self.assertEqual(r['X-Frame-Options'], 'SAMEORIGIN') settings.X_FRAME_OPTIONS = 'SAMEORIGIN' r = OtherXFrameOptionsMiddleware().process_response(HttpRequest(), HttpResponse()) self.assertEqual(r['X-Frame-Options'], 'DENY')
def _get_request(self, path): request = HttpRequest() request.META = { 'SERVER_NAME': 'testserver', 'SERVER_PORT': 80, } request.path = request.path_info = "/middleware/%s" % path return request
def test_can_use_salt(self): response = HttpResponse() response.set_signed_cookie('a', 'hello', salt='one') request = HttpRequest() request.COOKIES['a'] = response.cookies['a'].value value = request.get_signed_cookie('a', salt='one') self.assertEqual(value, 'hello') self.assertRaises(signing.BadSignature, request.get_signed_cookie, 'a', salt='two')
def test_can_set_and_read_signed_cookies(self): response = HttpResponse() response.set_signed_cookie('c', 'hello') self.assertIn('c', response.cookies) self.assertTrue(response.cookies['c'].value.startswith('hello:')) request = HttpRequest() request.COOKIES['c'] = response.cookies['c'].value value = request.get_signed_cookie('c') self.assertEqual(value, 'hello')
def test_httprequest_location(self): request = HttpRequest() self.assertEqual( request.build_absolute_uri(location="https://www.example.com/asdf"), "https://www.example.com/asdf" ) request.get_host = lambda: "www.example.com" request.path = "" self.assertEqual( request.build_absolute_uri(location="/path/with:colons"), "http://www.example.com/path/with:colons" )
def test_shortcut_view_without_get_absolute_url(self): """ Check that the shortcut view (used for the admin "view on site" functionality) returns 404 when get_absolute_url is not defined. """ request = HttpRequest() request.META = { "SERVER_NAME": "Example.com", "SERVER_PORT": "80", } user_ct = ContentType.objects.get_for_model(FooWithoutUrl) obj = FooWithoutUrl.objects.create(name="john") self.assertRaises(Http404, shortcut, request, user_ct.id, obj.id)
def test_shortcut_view_with_broken_get_absolute_url(self): """ Check that the shortcut view does not catch an AttributeError raised by the model's get_absolute_url method. Refs #8997. """ request = HttpRequest() request.META = { "SERVER_NAME": "Example.com", "SERVER_PORT": "80", } user_ct = ContentType.objects.get_for_model(FooWithBrokenAbsoluteUrl) obj = FooWithBrokenAbsoluteUrl.objects.create(name="john") self.assertRaises(AttributeError, shortcut, request, user_ct.id, obj.id)
def test_max_age_argument(self): value = 'hello' _time = time.time time.time = lambda: 123456789 try: response = HttpResponse() response.set_signed_cookie('c', value) request = HttpRequest() request.COOKIES['c'] = response.cookies['c'].value self.assertEqual(request.get_signed_cookie('c'), value) time.time = lambda: 123456800 self.assertEqual(request.get_signed_cookie('c', max_age=12), value) self.assertEqual(request.get_signed_cookie('c', max_age=11), value) self.assertRaises(signing.SignatureExpired, request.get_signed_cookie, 'c', max_age = 10) finally: time.time = _time
def test_get_current_site(self): # Test that the correct Site object is returned request = HttpRequest() request.META = { "SERVER_NAME": "example.com", "SERVER_PORT": "80", } site = get_current_site(request) self.assertTrue(isinstance(site, Site)) self.assertEqual(site.id, settings.SITE_ID) # Test that an exception is raised if the sites framework is installed # but there is no matching Site site.delete() self.assertRaises(ObjectDoesNotExist, get_current_site, request) # A RequestSite is returned if the sites framework is not installed Site._meta.installed = False site = get_current_site(request) self.assertTrue(isinstance(site, RequestSite)) self.assertEqual(site.name, "example.com")
def test_httprequest_repr(self): request = HttpRequest() request.path = "/somepath/" request.GET = {"get-key": "get-value"} request.POST = {"post-key": "post-value"} request.COOKIES = {"post-key": "post-value"} request.META = {"post-key": "post-value"} self.assertEqual( repr(request), str_prefix( "<HttpRequest\npath:/somepath/,\nGET:{%(_)s'get-key': %(_)s'get-value'},\nPOST:{%(_)s'post-key': %(_)s'post-value'},\nCOOKIES:{%(_)s'post-key': %(_)s'post-value'},\nMETA:{%(_)s'post-key': %(_)s'post-value'}>" ), ) self.assertEqual(build_request_repr(request), repr(request)) self.assertEqual( build_request_repr( request, path_override="/otherpath/", GET_override={"a": "b"}, POST_override={"c": "d"}, COOKIES_override={"e": "f"}, META_override={"g": "h"}, ), str_prefix( "<HttpRequest\npath:/otherpath/,\nGET:{%(_)s'a': %(_)s'b'},\nPOST:{%(_)s'c': %(_)s'd'},\nCOOKIES:{%(_)s'e': %(_)s'f'},\nMETA:{%(_)s'g': %(_)s'h'}>" ), )
def test_require_safe_accepts_only_safe_methods(self): """ Test for the require_safe decorator. A view returns either a response or an exception. Refs #15637. """ def my_view(request): return HttpResponse("OK") my_safe_view = require_safe(my_view) request = HttpRequest() request.method = 'GET' self.assertTrue(isinstance(my_safe_view(request), HttpResponse)) request.method = 'HEAD' self.assertTrue(isinstance(my_safe_view(request), HttpResponse)) request.method = 'POST' self.assertTrue(isinstance(my_safe_view(request), HttpResponseNotAllowed)) request.method = 'PUT' self.assertTrue(isinstance(my_safe_view(request), HttpResponseNotAllowed)) request.method = 'DELETE' self.assertTrue(isinstance(my_safe_view(request), HttpResponseNotAllowed))
def test_default_argument_supresses_exceptions(self): response = HttpResponse() response.set_signed_cookie('c', 'hello') request = HttpRequest() request.COOKIES['c'] = response.cookies['c'].value[:-2] + '$$' self.assertEqual(request.get_signed_cookie('c', default=None), None)
def test_http_get_host_with_x_forwarded_host(self): old_USE_X_FORWARDED_HOST = settings.USE_X_FORWARDED_HOST try: settings.USE_X_FORWARDED_HOST = True # Check if X_FORWARDED_HOST is provided. request = HttpRequest() request.META = { "HTTP_X_FORWARDED_HOST": "forward.com", "HTTP_HOST": "example.com", "SERVER_NAME": "internal.com", "SERVER_PORT": 80, } # X_FORWARDED_HOST is obeyed. self.assertEqual(request.get_host(), "forward.com") # Check if X_FORWARDED_HOST isn't provided. request = HttpRequest() request.META = {"HTTP_HOST": "example.com", "SERVER_NAME": "internal.com", "SERVER_PORT": 80} self.assertEqual(request.get_host(), "example.com") # Check if HTTP_HOST isn't provided. request = HttpRequest() request.META = {"SERVER_NAME": "internal.com", "SERVER_PORT": 80} self.assertEqual(request.get_host(), "internal.com") # Check if HTTP_HOST isn't provided, and we're on a nonstandard port request = HttpRequest() request.META = {"SERVER_NAME": "internal.com", "SERVER_PORT": 8042} self.assertEqual(request.get_host(), "internal.com:8042") finally: settings.USE_X_FORWARDED_HOST = old_USE_X_FORWARDED_HOST
def test_set_with_xheader_right(self): self.settings_module.SECURE_PROXY_SSL_HEADER = ('HTTP_X_FORWARDED_PROTOCOL', 'https') req = HttpRequest() req.META['HTTP_X_FORWARDED_PROTOCOL'] = 'https' self.assertEqual(req.is_secure(), True)
def test_set_without_xheader(self): self.settings_module.SECURE_PROXY_SSL_HEADER = ('HTTP_X_FORWARDED_PROTOCOL', 'https') req = HttpRequest() self.assertEqual(req.is_secure(), False)
def test_none(self): self.settings_module.SECURE_PROXY_SSL_HEADER = None req = HttpRequest() self.assertEqual(req.is_secure(), False)
def get_request(): request = HttpRequest() engine = import_module(settings.SESSION_ENGINE) request.session = engine.SessionStore(None) return request