Debian Codegraph @

tests/staticfiles_tests/test_liveserver.py

raw
1 """
2 A subset of the tests in tests/servers/tests exercising
3 django.contrib.staticfiles.testing.StaticLiveServerTestCase instead of
4 django.test.LiveServerTestCase.
5 """
6
7 import os
8 from urllib.request import urlopen
9
10 from django.contrib.staticfiles.testing import StaticLiveServerTestCase
11 from django.core.exceptions import ImproperlyConfigured
12 from django.test import modify_settings, override_settings
13
14 TEST_ROOT = os.path.dirname(__file__)
15 TEST_SETTINGS = {
16 "MEDIA_URL": "media/",
17 "STATIC_URL": "static/",
18 "MEDIA_ROOT": os.path.join(TEST_ROOT, "project", "site_media", "media"),
19 "STATIC_ROOT": os.path.join(TEST_ROOT, "project", "site_media", "static"),
20 }
21
22
23 class LiveServerBase(StaticLiveServerTestCase):
24 available_apps = []
25
26 @classmethod
27 def setUpClass(cls):
28 cls.enterClassContext(override_settings(**TEST_SETTINGS))
29 super().setUpClass()
30
31
32 class StaticLiveServerChecks(LiveServerBase):
33 @classmethod
34 def setUpClass(cls):
35 # If contrib.staticfiles isn't configured properly, the exception
36 # should bubble up to the main thread.
37 old_STATIC_URL = TEST_SETTINGS["STATIC_URL"]
38 TEST_SETTINGS["STATIC_URL"] = None
39 try:
40 cls.raises_exception()
41 finally:
42 TEST_SETTINGS["STATIC_URL"] = old_STATIC_URL
43
44 @classmethod
45 def tearDownClass(cls):
46 # skip it, as setUpClass doesn't call its parent either
47 pass
48
49 @classmethod
50 def raises_exception(cls):
51 try:
52 super().setUpClass()
53 except ImproperlyConfigured:
54 # This raises ImproperlyConfigured("You're using the staticfiles
55 # app without having set the required STATIC_URL setting.")
56 pass
57 else:
58 raise Exception("setUpClass() should have raised an exception.")
59
60 def test_test_test(self):
61 # Intentionally empty method so that the test is picked up by the
62 # test runner and the overridden setUpClass() method is executed.
63 pass
64
65
66 class StaticLiveServerView(LiveServerBase):
67 def urlopen(self, url):
68 return urlopen(self.live_server_url + url)
69
70 # The test is going to access a static file stored in this application.
71 @modify_settings(INSTALLED_APPS={"append": "staticfiles_tests.apps.test"})
72 def test_collectstatic_emulation(self):
73 """
74 StaticLiveServerTestCase use of staticfiles' serve() allows it
75 to discover app's static assets without having to collectstatic first.
76 """
77 with self.urlopen("/static/test/file.txt") as f:
78 self.assertEqual(f.read().rstrip(b"\r\n"), b"In static directory.")