authentik.admin.files.tests.test_manager

Test file service layer

  1"""Test file service layer"""
  2
  3from unittest import skipUnless
  4from unittest.mock import Mock, patch
  5from urllib.parse import urlparse
  6
  7from django.db import DatabaseError
  8from django.http import HttpRequest
  9from django.test import TestCase
 10
 11from authentik.admin.files.manager import FileManager
 12from authentik.admin.files.tests.utils import (
 13    FileTestFileBackendMixin,
 14    FileTestS3BackendMixin,
 15    s3_test_server_available,
 16)
 17from authentik.admin.files.usage import FileUsage
 18from authentik.lib.config import CONFIG
 19
 20
 21class TestResolveFileUrlBasic(TestCase):
 22    def test_resolve_empty_path(self):
 23        """Test resolving empty file path"""
 24        manager = FileManager(FileUsage.MEDIA)
 25        result = manager.file_url("")
 26        self.assertEqual(result, "")
 27
 28    def test_resolve_none_path(self):
 29        """Test resolving None file path"""
 30        manager = FileManager(FileUsage.MEDIA)
 31        result = manager.file_url(None)
 32        self.assertEqual(result, "")
 33
 34    def test_resolve_font_awesome(self):
 35        """Test resolving Font Awesome icon"""
 36        manager = FileManager(FileUsage.MEDIA)
 37        result = manager.file_url("fa://fa-check")
 38        self.assertEqual(result, "fa://fa-check")
 39
 40    def test_resolve_http_url(self):
 41        """Test resolving HTTP URL"""
 42        manager = FileManager(FileUsage.MEDIA)
 43        result = manager.file_url("http://example.com/icon.png")
 44        self.assertEqual(result, "http://example.com/icon.png")
 45
 46    def test_resolve_https_url(self):
 47        """Test resolving HTTPS URL"""
 48        manager = FileManager(FileUsage.MEDIA)
 49        result = manager.file_url("https://example.com/icon.png")
 50        self.assertEqual(result, "https://example.com/icon.png")
 51
 52    def test_resolve_static_path(self):
 53        """Test resolving static file path"""
 54        manager = FileManager(FileUsage.MEDIA)
 55        result = manager.file_url("/static/authentik/sources/icon.svg")
 56        self.assertEqual(result, "/static/authentik/sources/icon.svg")
 57
 58    def test_file_url_theme_variable_uses_light(self):
 59        """Test file_url resolves %(theme)s to the light variant, never the placeholder"""
 60        manager = FileManager(FileUsage.MEDIA)
 61        self.assertEqual(
 62            manager.file_url("/static/authentik/sources/kerberos/%(theme)s.png"),
 63            "/static/authentik/sources/kerberos/light.png",
 64        )
 65        self.assertEqual(
 66            manager.file_url("https://example.com/logo-%(theme)s.png"),
 67            "https://example.com/logo-light.png",
 68        )
 69
 70    def test_file_url_forwards_use_cache(self):
 71        """Test file_url forwards use_cache to backend."""
 72        manager = FileManager(FileUsage.MEDIA)
 73        backend = Mock()
 74        backend.supports_file.return_value = True
 75        backend.file_url.return_value = "/files/media/public/test.png?token=fresh"
 76        manager.backends = [backend]
 77
 78        result = manager.file_url("test.png", use_cache=False)
 79
 80        self.assertEqual(result, "/files/media/public/test.png?token=fresh")
 81        backend.file_url.assert_called_once_with("test.png", None, use_cache=False)
 82
 83
 84class TestResolveFileUrlFileBackend(FileTestFileBackendMixin, TestCase):
 85    def test_resolve_storage_file(self):
 86        """Test resolving uploaded storage file"""
 87        manager = FileManager(FileUsage.MEDIA)
 88        result = manager.file_url("test.png").split("?")[0]
 89        self.assertEqual(result, "/files/media/public/test.png")
 90
 91    def test_resolve_full_static_with_request(self):
 92        """Test resolving static file with request builds absolute URI"""
 93        mock_request = HttpRequest()
 94        mock_request.META = {
 95            "HTTP_HOST": "example.com",
 96            "SERVER_NAME": "example.com",
 97        }
 98
 99        manager = FileManager(FileUsage.MEDIA)
100        result = manager.file_url("/static/icon.svg", mock_request)
101
102        self.assertEqual(result, "http://example.com/static/icon.svg")
103
104    def test_resolve_full_file_backend_with_request(self):
105        """Test resolving FileBackend file with request"""
106        mock_request = HttpRequest()
107        mock_request.META = {
108            "HTTP_HOST": "example.com",
109            "SERVER_NAME": "example.com",
110        }
111
112        manager = FileManager(FileUsage.MEDIA)
113        result = manager.file_url("test.png", mock_request).split("?")[0]
114
115        self.assertEqual(result, "http://example.com/files/media/public/test.png")
116
117
118@skipUnless(s3_test_server_available(), "S3 test server not available")
119class TestResolveFileUrlS3Backend(FileTestS3BackendMixin, TestCase):
120    @CONFIG.patch("storage.media.s3.custom_domain", "s3.test:8080/test")
121    @CONFIG.patch("storage.media.s3.secure_urls", False)
122    def test_resolve_full_s3_backend(self):
123        """Test resolving S3Backend returns presigned URL as-is"""
124        mock_request = HttpRequest()
125        mock_request.META = {
126            "HTTP_HOST": "example.com",
127            "SERVER_NAME": "example.com",
128        }
129
130        manager = FileManager(FileUsage.MEDIA)
131        result = manager.file_url("test.png", mock_request)
132
133        # S3 URLs should be returned as-is (already absolute)
134        self.assertTrue(result.startswith("http://s3.test:8080/test"))
135
136
137class TestThemedUrls(FileTestFileBackendMixin, TestCase):
138    """Test FileManager.themed_urls method"""
139
140    def test_themed_urls_none_path(self):
141        """Test themed_urls returns None for None path"""
142        manager = FileManager(FileUsage.MEDIA)
143        result = manager.themed_urls(None)
144        self.assertIsNone(result)
145
146    def test_themed_urls_empty_path(self):
147        """Test themed_urls returns None for empty path"""
148        manager = FileManager(FileUsage.MEDIA)
149        result = manager.themed_urls("")
150        self.assertIsNone(result)
151
152    def test_themed_urls_no_theme_variable(self):
153        """Test themed_urls returns None when no %(theme)s in path"""
154        manager = FileManager(FileUsage.MEDIA)
155        result = manager.themed_urls("logo.png")
156        self.assertIsNone(result)
157
158    def test_themed_urls_with_theme_variable(self):
159        """Test themed_urls returns dict of URLs for each theme"""
160        manager = FileManager(FileUsage.MEDIA)
161        result = manager.themed_urls("logo-%(theme)s.png")
162
163        self.assertIsInstance(result, dict)
164        self.assertIn("light", result)
165        self.assertIn("dark", result)
166        self.assertIn("logo-light.png", result["light"])
167        self.assertIn("logo-dark.png", result["dark"])
168
169    def test_themed_urls_with_request(self):
170        """Test themed_urls builds absolute URLs with request"""
171        mock_request = HttpRequest()
172        mock_request.META = {
173            "HTTP_HOST": "example.com",
174            "SERVER_NAME": "example.com",
175        }
176
177        manager = FileManager(FileUsage.MEDIA)
178        result = manager.themed_urls("logo-%(theme)s.svg", mock_request)
179
180        self.assertIsInstance(result, dict)
181        light_url = urlparse(result["light"])
182        dark_url = urlparse(result["dark"])
183        self.assertEqual(light_url.scheme, "http")
184        self.assertEqual(light_url.netloc, "example.com")
185        self.assertEqual(dark_url.scheme, "http")
186        self.assertEqual(dark_url.netloc, "example.com")
187
188    def test_themed_urls_passthrough_with_theme_variable(self):
189        """Test themed_urls returns dict for passthrough URLs with %(theme)s"""
190        manager = FileManager(FileUsage.MEDIA)
191        # External URLs with %(theme)s should return themed URLs
192        result = manager.themed_urls("https://example.com/logo-%(theme)s.png")
193        self.assertIsInstance(result, dict)
194        self.assertEqual(result["light"], "https://example.com/logo-light.png")
195        self.assertEqual(result["dark"], "https://example.com/logo-dark.png")
196
197    def test_themed_urls_passthrough_without_theme_variable(self):
198        """Test themed_urls returns None for passthrough URLs without %(theme)s"""
199        manager = FileManager(FileUsage.MEDIA)
200        # External URLs without %(theme)s should return None
201        result = manager.themed_urls("https://example.com/logo.png")
202        self.assertIsNone(result)
203
204
205class TestPrefetchUrls(FileTestFileBackendMixin, TestCase):
206    """Test FileManager.prefetch_urls"""
207
208    names = [
209        "logo.png",
210        "logo-%(theme)s.svg",
211        "https://goauthentik.io/logo.png",
212        "/static/dist/assets/icons/icon.svg",
213    ]
214
215    def _urls(self, manager: FileManager) -> list:
216        return [(manager.file_url(name), manager.themed_urls(name)) for name in self.names]
217
218    def test_prefetch_urls(self):
219        """Inside the block, file_url() and themed_urls() return the URLs they return outside
220        it, and reading the cached ones takes one query"""
221        manager = FileManager(FileUsage.MEDIA)
222        expected = self._urls(manager)
223        with self.assertNumQueries(1), manager.prefetch_urls(self.names):
224            self.assertEqual(self._urls(manager), expected)
225
226    def test_prefetch_urls_uncached(self):
227        """A URL that is not cached yet is generated and cached inside the block"""
228        manager = FileManager(FileUsage.MEDIA)
229        with manager.prefetch_urls(["logo.png"]):
230            url = manager.file_url("logo.png")
231        with self.assertNumQueries(1):
232            self.assertEqual(manager.file_url("logo.png"), url)
233
234    def test_prefetch_urls_cache_error(self):
235        """When the bulk read fails, each call reads its own URL, as without the block"""
236        manager = FileManager(FileUsage.MEDIA)
237        expected = self._urls(manager)
238        with (
239            patch("authentik.admin.files.manager.cache.get_many", side_effect=DatabaseError),
240            manager.prefetch_urls(self.names),
241        ):
242            self.assertEqual(self._urls(manager), expected)
class TestResolveFileUrlBasic(django.test.testcases.TestCase):
22class TestResolveFileUrlBasic(TestCase):
23    def test_resolve_empty_path(self):
24        """Test resolving empty file path"""
25        manager = FileManager(FileUsage.MEDIA)
26        result = manager.file_url("")
27        self.assertEqual(result, "")
28
29    def test_resolve_none_path(self):
30        """Test resolving None file path"""
31        manager = FileManager(FileUsage.MEDIA)
32        result = manager.file_url(None)
33        self.assertEqual(result, "")
34
35    def test_resolve_font_awesome(self):
36        """Test resolving Font Awesome icon"""
37        manager = FileManager(FileUsage.MEDIA)
38        result = manager.file_url("fa://fa-check")
39        self.assertEqual(result, "fa://fa-check")
40
41    def test_resolve_http_url(self):
42        """Test resolving HTTP URL"""
43        manager = FileManager(FileUsage.MEDIA)
44        result = manager.file_url("http://example.com/icon.png")
45        self.assertEqual(result, "http://example.com/icon.png")
46
47    def test_resolve_https_url(self):
48        """Test resolving HTTPS URL"""
49        manager = FileManager(FileUsage.MEDIA)
50        result = manager.file_url("https://example.com/icon.png")
51        self.assertEqual(result, "https://example.com/icon.png")
52
53    def test_resolve_static_path(self):
54        """Test resolving static file path"""
55        manager = FileManager(FileUsage.MEDIA)
56        result = manager.file_url("/static/authentik/sources/icon.svg")
57        self.assertEqual(result, "/static/authentik/sources/icon.svg")
58
59    def test_file_url_theme_variable_uses_light(self):
60        """Test file_url resolves %(theme)s to the light variant, never the placeholder"""
61        manager = FileManager(FileUsage.MEDIA)
62        self.assertEqual(
63            manager.file_url("/static/authentik/sources/kerberos/%(theme)s.png"),
64            "/static/authentik/sources/kerberos/light.png",
65        )
66        self.assertEqual(
67            manager.file_url("https://example.com/logo-%(theme)s.png"),
68            "https://example.com/logo-light.png",
69        )
70
71    def test_file_url_forwards_use_cache(self):
72        """Test file_url forwards use_cache to backend."""
73        manager = FileManager(FileUsage.MEDIA)
74        backend = Mock()
75        backend.supports_file.return_value = True
76        backend.file_url.return_value = "/files/media/public/test.png?token=fresh"
77        manager.backends = [backend]
78
79        result = manager.file_url("test.png", use_cache=False)
80
81        self.assertEqual(result, "/files/media/public/test.png?token=fresh")
82        backend.file_url.assert_called_once_with("test.png", None, use_cache=False)

Similar to TransactionTestCase, but use transaction.atomic() to achieve test isolation.

In most situations, TestCase should be preferred to TransactionTestCase as it allows faster execution. However, there are some situations where using TransactionTestCase might be necessary (e.g. testing some transactional behavior).

On database backends with no transaction support, TestCase behaves as TransactionTestCase.

def test_resolve_empty_path(self):
23    def test_resolve_empty_path(self):
24        """Test resolving empty file path"""
25        manager = FileManager(FileUsage.MEDIA)
26        result = manager.file_url("")
27        self.assertEqual(result, "")

Test resolving empty file path

def test_resolve_none_path(self):
29    def test_resolve_none_path(self):
30        """Test resolving None file path"""
31        manager = FileManager(FileUsage.MEDIA)
32        result = manager.file_url(None)
33        self.assertEqual(result, "")

Test resolving None file path

def test_resolve_font_awesome(self):
35    def test_resolve_font_awesome(self):
36        """Test resolving Font Awesome icon"""
37        manager = FileManager(FileUsage.MEDIA)
38        result = manager.file_url("fa://fa-check")
39        self.assertEqual(result, "fa://fa-check")

Test resolving Font Awesome icon

def test_resolve_http_url(self):
41    def test_resolve_http_url(self):
42        """Test resolving HTTP URL"""
43        manager = FileManager(FileUsage.MEDIA)
44        result = manager.file_url("http://example.com/icon.png")
45        self.assertEqual(result, "http://example.com/icon.png")

Test resolving HTTP URL

def test_resolve_https_url(self):
47    def test_resolve_https_url(self):
48        """Test resolving HTTPS URL"""
49        manager = FileManager(FileUsage.MEDIA)
50        result = manager.file_url("https://example.com/icon.png")
51        self.assertEqual(result, "https://example.com/icon.png")

Test resolving HTTPS URL

def test_resolve_static_path(self):
53    def test_resolve_static_path(self):
54        """Test resolving static file path"""
55        manager = FileManager(FileUsage.MEDIA)
56        result = manager.file_url("/static/authentik/sources/icon.svg")
57        self.assertEqual(result, "/static/authentik/sources/icon.svg")

Test resolving static file path

def test_file_url_theme_variable_uses_light(self):
59    def test_file_url_theme_variable_uses_light(self):
60        """Test file_url resolves %(theme)s to the light variant, never the placeholder"""
61        manager = FileManager(FileUsage.MEDIA)
62        self.assertEqual(
63            manager.file_url("/static/authentik/sources/kerberos/%(theme)s.png"),
64            "/static/authentik/sources/kerberos/light.png",
65        )
66        self.assertEqual(
67            manager.file_url("https://example.com/logo-%(theme)s.png"),
68            "https://example.com/logo-light.png",
69        )

Test file_url resolves %(theme)s to the light variant, never the placeholder

def test_file_url_forwards_use_cache(self):
71    def test_file_url_forwards_use_cache(self):
72        """Test file_url forwards use_cache to backend."""
73        manager = FileManager(FileUsage.MEDIA)
74        backend = Mock()
75        backend.supports_file.return_value = True
76        backend.file_url.return_value = "/files/media/public/test.png?token=fresh"
77        manager.backends = [backend]
78
79        result = manager.file_url("test.png", use_cache=False)
80
81        self.assertEqual(result, "/files/media/public/test.png?token=fresh")
82        backend.file_url.assert_called_once_with("test.png", None, use_cache=False)

Test file_url forwards use_cache to backend.

class TestResolveFileUrlFileBackend(authentik.admin.files.tests.utils.FileTestFileBackendMixin, django.test.testcases.TestCase):
 85class TestResolveFileUrlFileBackend(FileTestFileBackendMixin, TestCase):
 86    def test_resolve_storage_file(self):
 87        """Test resolving uploaded storage file"""
 88        manager = FileManager(FileUsage.MEDIA)
 89        result = manager.file_url("test.png").split("?")[0]
 90        self.assertEqual(result, "/files/media/public/test.png")
 91
 92    def test_resolve_full_static_with_request(self):
 93        """Test resolving static file with request builds absolute URI"""
 94        mock_request = HttpRequest()
 95        mock_request.META = {
 96            "HTTP_HOST": "example.com",
 97            "SERVER_NAME": "example.com",
 98        }
 99
100        manager = FileManager(FileUsage.MEDIA)
101        result = manager.file_url("/static/icon.svg", mock_request)
102
103        self.assertEqual(result, "http://example.com/static/icon.svg")
104
105    def test_resolve_full_file_backend_with_request(self):
106        """Test resolving FileBackend file with request"""
107        mock_request = HttpRequest()
108        mock_request.META = {
109            "HTTP_HOST": "example.com",
110            "SERVER_NAME": "example.com",
111        }
112
113        manager = FileManager(FileUsage.MEDIA)
114        result = manager.file_url("test.png", mock_request).split("?")[0]
115
116        self.assertEqual(result, "http://example.com/files/media/public/test.png")

Similar to TransactionTestCase, but use transaction.atomic() to achieve test isolation.

In most situations, TestCase should be preferred to TransactionTestCase as it allows faster execution. However, there are some situations where using TransactionTestCase might be necessary (e.g. testing some transactional behavior).

On database backends with no transaction support, TestCase behaves as TransactionTestCase.

def test_resolve_storage_file(self):
86    def test_resolve_storage_file(self):
87        """Test resolving uploaded storage file"""
88        manager = FileManager(FileUsage.MEDIA)
89        result = manager.file_url("test.png").split("?")[0]
90        self.assertEqual(result, "/files/media/public/test.png")

Test resolving uploaded storage file

def test_resolve_full_static_with_request(self):
 92    def test_resolve_full_static_with_request(self):
 93        """Test resolving static file with request builds absolute URI"""
 94        mock_request = HttpRequest()
 95        mock_request.META = {
 96            "HTTP_HOST": "example.com",
 97            "SERVER_NAME": "example.com",
 98        }
 99
100        manager = FileManager(FileUsage.MEDIA)
101        result = manager.file_url("/static/icon.svg", mock_request)
102
103        self.assertEqual(result, "http://example.com/static/icon.svg")

Test resolving static file with request builds absolute URI

def test_resolve_full_file_backend_with_request(self):
105    def test_resolve_full_file_backend_with_request(self):
106        """Test resolving FileBackend file with request"""
107        mock_request = HttpRequest()
108        mock_request.META = {
109            "HTTP_HOST": "example.com",
110            "SERVER_NAME": "example.com",
111        }
112
113        manager = FileManager(FileUsage.MEDIA)
114        result = manager.file_url("test.png", mock_request).split("?")[0]
115
116        self.assertEqual(result, "http://example.com/files/media/public/test.png")

Test resolving FileBackend file with request

@skipUnless(s3_test_server_available(), 'S3 test server not available')
class TestResolveFileUrlS3Backend(authentik.admin.files.tests.utils.FileTestS3BackendMixin, django.test.testcases.TestCase):
119@skipUnless(s3_test_server_available(), "S3 test server not available")
120class TestResolveFileUrlS3Backend(FileTestS3BackendMixin, TestCase):
121    @CONFIG.patch("storage.media.s3.custom_domain", "s3.test:8080/test")
122    @CONFIG.patch("storage.media.s3.secure_urls", False)
123    def test_resolve_full_s3_backend(self):
124        """Test resolving S3Backend returns presigned URL as-is"""
125        mock_request = HttpRequest()
126        mock_request.META = {
127            "HTTP_HOST": "example.com",
128            "SERVER_NAME": "example.com",
129        }
130
131        manager = FileManager(FileUsage.MEDIA)
132        result = manager.file_url("test.png", mock_request)
133
134        # S3 URLs should be returned as-is (already absolute)
135        self.assertTrue(result.startswith("http://s3.test:8080/test"))

Similar to TransactionTestCase, but use transaction.atomic() to achieve test isolation.

In most situations, TestCase should be preferred to TransactionTestCase as it allows faster execution. However, there are some situations where using TransactionTestCase might be necessary (e.g. testing some transactional behavior).

On database backends with no transaction support, TestCase behaves as TransactionTestCase.

@CONFIG.patch('storage.media.s3.custom_domain', 's3.test:8080/test')
@CONFIG.patch('storage.media.s3.secure_urls', False)
def test_resolve_full_s3_backend(self):
121    @CONFIG.patch("storage.media.s3.custom_domain", "s3.test:8080/test")
122    @CONFIG.patch("storage.media.s3.secure_urls", False)
123    def test_resolve_full_s3_backend(self):
124        """Test resolving S3Backend returns presigned URL as-is"""
125        mock_request = HttpRequest()
126        mock_request.META = {
127            "HTTP_HOST": "example.com",
128            "SERVER_NAME": "example.com",
129        }
130
131        manager = FileManager(FileUsage.MEDIA)
132        result = manager.file_url("test.png", mock_request)
133
134        # S3 URLs should be returned as-is (already absolute)
135        self.assertTrue(result.startswith("http://s3.test:8080/test"))

Test resolving S3Backend returns presigned URL as-is

class TestThemedUrls(authentik.admin.files.tests.utils.FileTestFileBackendMixin, django.test.testcases.TestCase):
138class TestThemedUrls(FileTestFileBackendMixin, TestCase):
139    """Test FileManager.themed_urls method"""
140
141    def test_themed_urls_none_path(self):
142        """Test themed_urls returns None for None path"""
143        manager = FileManager(FileUsage.MEDIA)
144        result = manager.themed_urls(None)
145        self.assertIsNone(result)
146
147    def test_themed_urls_empty_path(self):
148        """Test themed_urls returns None for empty path"""
149        manager = FileManager(FileUsage.MEDIA)
150        result = manager.themed_urls("")
151        self.assertIsNone(result)
152
153    def test_themed_urls_no_theme_variable(self):
154        """Test themed_urls returns None when no %(theme)s in path"""
155        manager = FileManager(FileUsage.MEDIA)
156        result = manager.themed_urls("logo.png")
157        self.assertIsNone(result)
158
159    def test_themed_urls_with_theme_variable(self):
160        """Test themed_urls returns dict of URLs for each theme"""
161        manager = FileManager(FileUsage.MEDIA)
162        result = manager.themed_urls("logo-%(theme)s.png")
163
164        self.assertIsInstance(result, dict)
165        self.assertIn("light", result)
166        self.assertIn("dark", result)
167        self.assertIn("logo-light.png", result["light"])
168        self.assertIn("logo-dark.png", result["dark"])
169
170    def test_themed_urls_with_request(self):
171        """Test themed_urls builds absolute URLs with request"""
172        mock_request = HttpRequest()
173        mock_request.META = {
174            "HTTP_HOST": "example.com",
175            "SERVER_NAME": "example.com",
176        }
177
178        manager = FileManager(FileUsage.MEDIA)
179        result = manager.themed_urls("logo-%(theme)s.svg", mock_request)
180
181        self.assertIsInstance(result, dict)
182        light_url = urlparse(result["light"])
183        dark_url = urlparse(result["dark"])
184        self.assertEqual(light_url.scheme, "http")
185        self.assertEqual(light_url.netloc, "example.com")
186        self.assertEqual(dark_url.scheme, "http")
187        self.assertEqual(dark_url.netloc, "example.com")
188
189    def test_themed_urls_passthrough_with_theme_variable(self):
190        """Test themed_urls returns dict for passthrough URLs with %(theme)s"""
191        manager = FileManager(FileUsage.MEDIA)
192        # External URLs with %(theme)s should return themed URLs
193        result = manager.themed_urls("https://example.com/logo-%(theme)s.png")
194        self.assertIsInstance(result, dict)
195        self.assertEqual(result["light"], "https://example.com/logo-light.png")
196        self.assertEqual(result["dark"], "https://example.com/logo-dark.png")
197
198    def test_themed_urls_passthrough_without_theme_variable(self):
199        """Test themed_urls returns None for passthrough URLs without %(theme)s"""
200        manager = FileManager(FileUsage.MEDIA)
201        # External URLs without %(theme)s should return None
202        result = manager.themed_urls("https://example.com/logo.png")
203        self.assertIsNone(result)

Test FileManager.themed_urls method

def test_themed_urls_none_path(self):
141    def test_themed_urls_none_path(self):
142        """Test themed_urls returns None for None path"""
143        manager = FileManager(FileUsage.MEDIA)
144        result = manager.themed_urls(None)
145        self.assertIsNone(result)

Test themed_urls returns None for None path

def test_themed_urls_empty_path(self):
147    def test_themed_urls_empty_path(self):
148        """Test themed_urls returns None for empty path"""
149        manager = FileManager(FileUsage.MEDIA)
150        result = manager.themed_urls("")
151        self.assertIsNone(result)

Test themed_urls returns None for empty path

def test_themed_urls_no_theme_variable(self):
153    def test_themed_urls_no_theme_variable(self):
154        """Test themed_urls returns None when no %(theme)s in path"""
155        manager = FileManager(FileUsage.MEDIA)
156        result = manager.themed_urls("logo.png")
157        self.assertIsNone(result)

Test themed_urls returns None when no %(theme)s in path

def test_themed_urls_with_theme_variable(self):
159    def test_themed_urls_with_theme_variable(self):
160        """Test themed_urls returns dict of URLs for each theme"""
161        manager = FileManager(FileUsage.MEDIA)
162        result = manager.themed_urls("logo-%(theme)s.png")
163
164        self.assertIsInstance(result, dict)
165        self.assertIn("light", result)
166        self.assertIn("dark", result)
167        self.assertIn("logo-light.png", result["light"])
168        self.assertIn("logo-dark.png", result["dark"])

Test themed_urls returns dict of URLs for each theme

def test_themed_urls_with_request(self):
170    def test_themed_urls_with_request(self):
171        """Test themed_urls builds absolute URLs with request"""
172        mock_request = HttpRequest()
173        mock_request.META = {
174            "HTTP_HOST": "example.com",
175            "SERVER_NAME": "example.com",
176        }
177
178        manager = FileManager(FileUsage.MEDIA)
179        result = manager.themed_urls("logo-%(theme)s.svg", mock_request)
180
181        self.assertIsInstance(result, dict)
182        light_url = urlparse(result["light"])
183        dark_url = urlparse(result["dark"])
184        self.assertEqual(light_url.scheme, "http")
185        self.assertEqual(light_url.netloc, "example.com")
186        self.assertEqual(dark_url.scheme, "http")
187        self.assertEqual(dark_url.netloc, "example.com")

Test themed_urls builds absolute URLs with request

def test_themed_urls_passthrough_with_theme_variable(self):
189    def test_themed_urls_passthrough_with_theme_variable(self):
190        """Test themed_urls returns dict for passthrough URLs with %(theme)s"""
191        manager = FileManager(FileUsage.MEDIA)
192        # External URLs with %(theme)s should return themed URLs
193        result = manager.themed_urls("https://example.com/logo-%(theme)s.png")
194        self.assertIsInstance(result, dict)
195        self.assertEqual(result["light"], "https://example.com/logo-light.png")
196        self.assertEqual(result["dark"], "https://example.com/logo-dark.png")

Test themed_urls returns dict for passthrough URLs with %(theme)s

def test_themed_urls_passthrough_without_theme_variable(self):
198    def test_themed_urls_passthrough_without_theme_variable(self):
199        """Test themed_urls returns None for passthrough URLs without %(theme)s"""
200        manager = FileManager(FileUsage.MEDIA)
201        # External URLs without %(theme)s should return None
202        result = manager.themed_urls("https://example.com/logo.png")
203        self.assertIsNone(result)

Test themed_urls returns None for passthrough URLs without %(theme)s

class TestPrefetchUrls(authentik.admin.files.tests.utils.FileTestFileBackendMixin, django.test.testcases.TestCase):
206class TestPrefetchUrls(FileTestFileBackendMixin, TestCase):
207    """Test FileManager.prefetch_urls"""
208
209    names = [
210        "logo.png",
211        "logo-%(theme)s.svg",
212        "https://goauthentik.io/logo.png",
213        "/static/dist/assets/icons/icon.svg",
214    ]
215
216    def _urls(self, manager: FileManager) -> list:
217        return [(manager.file_url(name), manager.themed_urls(name)) for name in self.names]
218
219    def test_prefetch_urls(self):
220        """Inside the block, file_url() and themed_urls() return the URLs they return outside
221        it, and reading the cached ones takes one query"""
222        manager = FileManager(FileUsage.MEDIA)
223        expected = self._urls(manager)
224        with self.assertNumQueries(1), manager.prefetch_urls(self.names):
225            self.assertEqual(self._urls(manager), expected)
226
227    def test_prefetch_urls_uncached(self):
228        """A URL that is not cached yet is generated and cached inside the block"""
229        manager = FileManager(FileUsage.MEDIA)
230        with manager.prefetch_urls(["logo.png"]):
231            url = manager.file_url("logo.png")
232        with self.assertNumQueries(1):
233            self.assertEqual(manager.file_url("logo.png"), url)
234
235    def test_prefetch_urls_cache_error(self):
236        """When the bulk read fails, each call reads its own URL, as without the block"""
237        manager = FileManager(FileUsage.MEDIA)
238        expected = self._urls(manager)
239        with (
240            patch("authentik.admin.files.manager.cache.get_many", side_effect=DatabaseError),
241            manager.prefetch_urls(self.names),
242        ):
243            self.assertEqual(self._urls(manager), expected)

Test FileManager.prefetch_urls

names = ['logo.png', 'logo-%(theme)s.svg', 'https://goauthentik.io/logo.png', '/static/dist/assets/icons/icon.svg']
def test_prefetch_urls(self):
219    def test_prefetch_urls(self):
220        """Inside the block, file_url() and themed_urls() return the URLs they return outside
221        it, and reading the cached ones takes one query"""
222        manager = FileManager(FileUsage.MEDIA)
223        expected = self._urls(manager)
224        with self.assertNumQueries(1), manager.prefetch_urls(self.names):
225            self.assertEqual(self._urls(manager), expected)

Inside the block, file_url() and themed_urls() return the URLs they return outside it, and reading the cached ones takes one query

def test_prefetch_urls_uncached(self):
227    def test_prefetch_urls_uncached(self):
228        """A URL that is not cached yet is generated and cached inside the block"""
229        manager = FileManager(FileUsage.MEDIA)
230        with manager.prefetch_urls(["logo.png"]):
231            url = manager.file_url("logo.png")
232        with self.assertNumQueries(1):
233            self.assertEqual(manager.file_url("logo.png"), url)

A URL that is not cached yet is generated and cached inside the block

def test_prefetch_urls_cache_error(self):
235    def test_prefetch_urls_cache_error(self):
236        """When the bulk read fails, each call reads its own URL, as without the block"""
237        manager = FileManager(FileUsage.MEDIA)
238        expected = self._urls(manager)
239        with (
240            patch("authentik.admin.files.manager.cache.get_many", side_effect=DatabaseError),
241            manager.prefetch_urls(self.names),
242        ):
243            self.assertEqual(self._urls(manager), expected)

When the bulk read fails, each call reads its own URL, as without the block