Debian Codegraph @

django_downloadview/test.py

raw
1 import shutil
2 import tempfile
3
4 from django.conf import settings
5 from django.test.utils import override_settings
6 from django.utils.encoding import force_bytes
7
8 from django_downloadview.middlewares import is_download_response
9 from django_downloadview.response import encode_basename_ascii, encode_basename_utf8
10
11
12 def setup_view(view, request, *args, **kwargs):
13 """Mimic ``as_view()``, but returns view instance.
14
15 Use this function to get view instances on which you can run unit tests,
16 by testing specific methods.
17
18 This is an early implementation of
19 https://code.djangoproject.com/ticket/20456
20
21 ``view``
22 A view instance, such as ``TemplateView(template_name='dummy.html')``.
23 Initialization arguments are the same you would pass to ``as_view()``.
24
25 ``request``
26 A request object, typically built with
27 :class:`~django.test.client.RequestFactory`.
28
29 ``args`` and ``kwargs``
30 "URLconf" positional and keyword arguments, the same you would pass to
31 :func:`~django.core.urlresolvers.reverse`.
32
33 """
34 view.request = request
35 view.args = args
36 view.kwargs = kwargs
37 return view
38
39
40 class temporary_media_root(override_settings):
41 """Temporarily override settings.MEDIA_ROOT with a temporary directory.
42
43 The temporary directory is automatically created and destroyed.
44
45 Use this function as a context manager:
46
47 >>> from django_downloadview.test import temporary_media_root
48 >>> from django.conf import settings # NoQA
49 >>> global_media_root = settings.MEDIA_ROOT
50 >>> with temporary_media_root():
51 ... global_media_root == settings.MEDIA_ROOT
52 False
53 >>> global_media_root == settings.MEDIA_ROOT
54 True
55
56 Or as a decorator:
57
58 >>> @temporary_media_root()
59 ... def use_temporary_media_root():
60 ... return settings.MEDIA_ROOT
61 >>> tmp_media_root = use_temporary_media_root()
62 >>> global_media_root == tmp_media_root
63 False
64 >>> global_media_root == settings.MEDIA_ROOT
65 True
66
67 """
68
69 def enable(self):
70 """Create a temporary directory and use it to override
71 settings.MEDIA_ROOT."""
72 tmp_dir = tempfile.mkdtemp()
73 self.options["MEDIA_ROOT"] = tmp_dir
74 super().enable()
75
76 def disable(self):
77 """Remove directory settings.MEDIA_ROOT then restore original
78 setting."""
79 shutil.rmtree(settings.MEDIA_ROOT)
80 super().disable()
81
82
83 class DownloadResponseValidator(object):
84 """Utility class to validate DownloadResponse instances."""
85
86 def __call__(self, test_case, response, **assertions):
87 """Assert that ``response`` is a valid DownloadResponse instance.
88
89 Optional ``assertions`` dictionary can be used to check additional
90 items:
91
92 * ``basename``: the basename of the file in the response.
93
94 * ``content_type``: the value of "Content-Type" header.
95
96 * ``mime_type``: the MIME type part of "Content-Type" header (without
97 charset).
98
99 * ``content``: the contents of the file.
100
101 * ``attachment``: whether the file is returned as attachment or not.
102
103 """
104 self.assert_download_response(test_case, response)
105 for key, value in assertions.items():
106 assert_func = getattr(self, "assert_%s" % key)
107 assert_func(test_case, response, value)
108
109 def assert_download_response(self, test_case, response):
110 test_case.assertTrue(is_download_response(response))
111
112 def assert_basename(self, test_case, response, value):
113 """Implies ``attachement is True``."""
114 ascii_name = encode_basename_ascii(value)
115 utf8_name = encode_basename_utf8(value)
116 check_utf8 = False
117 check_ascii = False
118 if ascii_name == utf8_name: # Only ASCII characters.
119 check_ascii = True
120 if "filename*=" in response["Content-Disposition"]:
121 check_utf8 = True
122 else:
123 check_utf8 = True
124 if "filename=" in response["Content-Disposition"]:
125 check_ascii = True
126 if check_ascii:
127 test_case.assertIn(
128 f'filename="{ascii_name}"',
129 response["Content-Disposition"],
130 )
131 if check_utf8:
132 test_case.assertIn(
133 f"filename*=UTF-8''{utf8_name}",
134 response["Content-Disposition"],
135 )
136
137 def assert_content_type(self, test_case, response, value):
138 test_case.assertEqual(response["Content-Type"], value)
139
140 def assert_mime_type(self, test_case, response, value):
141 test_case.assertTrue(response["Content-Type"].startswith(value))
142
143 def assert_content(self, test_case, response, value):
144 """Assert value equals response's content (byte comparison)."""
145 parts = [force_bytes(s) for s in response.streaming_content]
146 test_case.assertEqual(b"".join(parts), force_bytes(value))
147
148 def assert_attachment(self, test_case, response, value):
149 if value:
150 test_case.assertTrue("attachment;" in response["Content-Disposition"])
151 else:
152 test_case.assertTrue(
153 "Content-Disposition" not in response
154 or "attachment;" not in response["Content-Disposition"]
155 )
156
157
158 def assert_download_response(test_case, response, **assertions):
159 """Make ``test_case`` assert that ``response`` meets ``assertions``.
160
161 Optional ``assertions`` dictionary can be used to check additional items:
162
163 * ``basename``: the basename of the file in the response.
164
165 * ``content_type``: the value of "Content-Type" header.
166
167 * ``mime_type``: the MIME type part of "Content-Type" header (without
168 charset).
169
170 * ``content``: the contents of the file.
171
172 * ``attachment``: whether the file is returned as attachment or not.
173
174 """
175 validator = DownloadResponseValidator()
176 return validator(test_case, response, **assertions)