Debian Codegraph @

test/pytest/test_packages.py

raw
1 #
2 # Copyright (C) 2023 Red Hat, Inc.
3 # SPDX-License-Identifier: GPL-3.0-or-later
4
5
6 import json
7 from pathlib import Path
8
9 import pytest
10
11 from cockpit.jsonutil import JsonValue
12 from cockpit.packages import Packages, PackagesLoader, parse_accept_language
13
14
15 @pytest.mark.parametrize(("test_input", "expected"), [
16 # correct handles empty values
17 ('', ()),
18 (' ', ()),
19 (' , ', ()),
20 (' , ,xx', ('xx',)),
21 # english → empty list
22 ('en', ()),
23 (' , en', ()),
24 # invalid q values get ignored
25 ('aa;q===,bb;q=abc,cc;q=.,zz', ('zz',)),
26 # variant-peeling works
27 ('aa-bb-cc-dd,ee-ff-gg-hh', ('aa-bb-cc-dd', 'aa-bb-cc', 'aa-bb', 'aa', 'ee-ff-gg-hh', 'ee-ff-gg', 'ee-ff', 'ee')),
28 # sorting and english-truncation are working
29 ('fr-ch;q=0.8,es-mx;q=1.0,en-ca;q=0.9', ('es-mx', 'es', 'en-ca')),
30 ('de-at, zh-CN, en,', ('de-at', 'de', 'zh-cn', 'zh')),
31 ('es-es, nl;q=0.8, fr;q=0.9', ('es-es', 'es', 'fr', 'nl')),
32 ('fr-CH, fr;q=0.9, en;q=0.8, de;q=0.7, *;q=0.5', ('fr-ch', 'fr'))
33 ])
34 def test_parse_accept_language(test_input: str, expected: 'tuple[str]') -> None:
35 assert parse_accept_language(test_input) == expected
36
37
38 @pytest.fixture
39 def pkgdir(tmp_path: Path, monkeypatch: pytest.MonkeyPatch) -> Path:
40 monkeypatch.setenv('XDG_DATA_DIRS', str(tmp_path))
41 monkeypatch.setenv('XDG_DATA_HOME', '/nonexisting')
42
43 self = tmp_path / 'cockpit'
44 self.mkdir()
45 make_package(self, 'basic', description="standard package", requires={"cockpit": "42"})
46 return self
47
48
49 @pytest.fixture
50 def confdir(tmp_path: Path, monkeypatch: pytest.MonkeyPatch) -> Path:
51 monkeypatch.setenv('XDG_CONFIG_DIRS', str(tmp_path))
52 return tmp_path / 'cockpit'
53
54
55 def make_package(pkgdir: Path, dirname: str, **kwargs: JsonValue) -> None:
56 (pkgdir / dirname).mkdir()
57 with (pkgdir / dirname / 'manifest.json').open('w') as file:
58 json.dump(kwargs, file, indent=2)
59
60
61 def test_basic(pkgdir: Path) -> None:
62 packages = Packages()
63 assert len(packages.packages) == 1
64 assert packages.packages['basic'].name == 'basic'
65 assert packages.packages['basic'].manifest['description'] == 'standard package'
66 assert packages.packages['basic'].manifest['requires'] == {'cockpit': "42"}
67 assert packages.packages['basic'].priority == 1
68
69 assert packages.manifests == '{"basic": {"description": "standard package", "requires": {"cockpit": "42"}}}'
70
71
72 def test_override_etc(pkgdir: Path, confdir: Path) -> None:
73 (confdir / 'basic.override.json').write_text('{"description": null, "priority": 5, "does-not-exist": null}')
74
75 packages = Packages()
76 assert len(packages.packages) == 1
77 # original attributes
78 assert packages.packages['basic'].name == 'basic'
79 assert packages.packages['basic'].manifest['requires'] == {'cockpit': '42'}
80 # overridden attributes
81 assert 'description' not in packages.packages['basic'].manifest
82 assert packages.packages['basic'].priority == 5
83
84 assert json.loads(packages.manifests) == {
85 'basic': {
86 'requires': {'cockpit': '42'},
87 'priority': 5,
88 }
89 }
90
91
92 def test_override_invalid_json(pkgdir: Path, caplog: pytest.LogCaptureFixture) -> None:
93 """An override file with broken JSON must be ignored, not crash the bridge."""
94 (pkgdir / 'basic' / 'override.json').write_text('{ "priority": 5,, }')
95
96 packages = Packages()
97 assert len(packages.packages) == 1
98 # the broken override is ignored, the manifest is untouched
99 assert packages.packages['basic'].manifest['description'] == 'standard package'
100 assert packages.packages['basic'].priority == 1
101 assert 'override.json' in caplog.text
102
103
104 def test_override_invalid_json_does_not_hide_later_ones(
105 pkgdir: Path, confdir: Path, caplog: pytest.LogCaptureFixture
106 ) -> None:
107 """A broken override file must not stop the remaining ones from being applied."""
108 # first candidate: broken
109 (pkgdir / 'basic' / 'override.json').write_text('not json at all')
110 # second candidate: fine
111 (confdir / 'basic.override.json').write_text('{"priority": 5}')
112
113 packages = Packages()
114 assert len(packages.packages) == 1
115 assert packages.packages['basic'].priority == 5
116 assert 'override.json' in caplog.text
117
118
119 def test_priority(pkgdir: Path) -> None:
120 make_package(pkgdir, 'vip', name='basic', description='VIP', priority=100)
121 make_package(pkgdir, 'guest', description='Guest')
122
123 packages = Packages()
124 assert len(packages.packages) == 2
125 assert packages.packages['basic'].name == 'basic'
126 assert packages.packages['basic'].priority == 100
127 assert packages.packages['basic'].manifest['description'] == 'VIP'
128 assert packages.packages['guest'].name == 'guest'
129 assert packages.packages['guest'].priority == 1
130
131 parsed = json.loads(packages.manifests)
132 assert parsed['basic'] == {'name': 'basic', 'description': 'VIP', 'priority': 100}
133 assert parsed['guest'] == {'description': 'Guest'}
134
135
136 def test_conditions(pkgdir: Path) -> None:
137 make_package(pkgdir, 'empty', conditions=[])
138
139 # path-exists only
140 make_package(pkgdir, 'exists-1-yes', conditions=[{'path-exists': '/usr'}])
141 make_package(pkgdir, 'exists-1-no', conditions=[{'path-exists': '/nonexisting'}])
142 make_package(pkgdir, 'exists-2-yes', conditions=[{"path-exists": "/usr"},
143 {"path-exists": "/bin/sh"}])
144 make_package(pkgdir, 'exists-2-no', conditions=[{"path-exists": "/usr"},
145 {"path-exists": "/nonexisting"}])
146
147 # path-not-exists only
148 make_package(pkgdir, 'notexists-1-yes', conditions=[{"path-not-exists": "/nonexisting"}])
149 make_package(pkgdir, 'notexists-1-no', conditions=[{"path-not-exists": "/usr"}])
150 make_package(pkgdir, 'notexists-2-yes', conditions=[{"path-not-exists": "/nonexisting"},
151 {"path-not-exists": "/obscure"}])
152 make_package(pkgdir, 'notexists-2-no', conditions=[{"path-not-exists": "/nonexisting"},
153 {"path-not-exists": "/usr"}])
154
155 # mixed
156 make_package(pkgdir, 'mixed-yes', conditions=[{"path-exists": "/usr"},
157 {"path-not-exists": "/nonexisting"}])
158 make_package(pkgdir, 'mixed-no', conditions=[{"path-exists": "/nonexisting"},
159 {"path-not-exists": "/obscure"}])
160
161 packages = Packages()
162 assert set(packages.packages.keys()) == {
163 'basic', 'empty', 'exists-1-yes', 'exists-2-yes', 'notexists-1-yes', 'notexists-2-yes', 'mixed-yes'
164 }
165
166 # Manifest.get_condition_files()
167 assert set(packages.packages['empty'].manifest.get_condition_files()) == set()
168 assert set(packages.packages['exists-1-yes'].manifest.get_condition_files()) == {'/usr'}
169 assert set(packages.packages['exists-2-yes'].manifest.get_condition_files()) == {'/usr', '/bin/sh'}
170 assert set(packages.packages['mixed-yes'].manifest.get_condition_files()) == {'/usr', '/nonexisting'}
171
172 # PackagesLoader.get_condition_files()
173 assert set(PackagesLoader.get_condition_files()) == {'/usr', '/bin/sh', '/nonexisting', '/obscure'}
174
175
176 def test_conditions_errors(pkgdir: Path) -> None:
177 make_package(pkgdir, 'broken-syntax-1', conditions=[1])
178 make_package(pkgdir, 'broken-syntax-2', conditions=[["path-exists"]])
179 make_package(pkgdir, 'broken-syntax-3', conditions=[{"path-exists": "/foo", "path-not-exists": "/bar"}])
180
181 make_package(pkgdir, 'unknown-predicate-good', conditions=[{"path-exists": "/usr"},
182 {"frobnicated": True}])
183 make_package(pkgdir, 'unknown-predicate-bad', conditions=[{"path-exists": "/nonexisting"},
184 {"frobnicated": True}])
185
186 packages = Packages()
187 assert set(packages.packages.keys()) == {'basic', 'unknown-predicate-good'}
188
189 # get_condition_files() should have the valid ones
190 assert set(packages.packages['unknown-predicate-good'].manifest.get_condition_files()) == {'/usr'}
191
192 assert set(PackagesLoader.get_condition_files()) == {'/usr', '/nonexisting'}
193
194
195 def test_condition_hides_priority(pkgdir: Path) -> None:
196 make_package(pkgdir, 'vip', name="basic", description="VIP", priority=100,
197 conditions=[{"path-exists": "/nonexisting"}])
198
199 packages = Packages()
200 assert packages.packages['basic'].name == 'basic'
201 assert packages.packages['basic'].manifest['description'] == 'standard package'
202 assert packages.packages['basic'].manifest['requires'] == {'cockpit': "42"}
203 assert packages.packages['basic'].priority == 1
204
205
206 def test_conditions_any(pkgdir: Path) -> None:
207 make_package(pkgdir, 'any-empty-fail', conditions=[{"any": []}])
208
209 # Test basic "any" condition - should pass if any one condition is true
210 make_package(pkgdir, 'any-pass-1', conditions=[
211 {"any": [{"path-exists": "/usr"}, {"path-exists": "/nonexisting"}]}
212 ])
213 make_package(pkgdir, 'any-pass-2', conditions=[
214 {"any": [{"path-exists": "/nonexisting"}, {"path-exists": "/usr"}]}
215 ])
216 make_package(pkgdir, 'any-fail', conditions=[
217 {"any": [{"path-exists": "/nonexisting"}, {"path-exists": "/alsonotexisting"}]}
218 ])
219
220 # Test "any" mixed with path-not-exists
221 make_package(pkgdir, 'any-mixed-pass', conditions=[
222 {"any": [{"path-not-exists": "/nonexisting"}, {"path-exists": "/alsonotexisting"}]}
223 ])
224 make_package(pkgdir, 'any-mixed-fail', conditions=[
225 {"any": [{"path-not-exists": "/usr"}, {"path-exists": "/nonexisting"}]}
226 ])
227
228 # Test combination of regular conditions with "any" conditions
229 make_package(pkgdir, 'mixed-any-pass', conditions=[
230 {"any": [{"path-exists": "/usr"}, {"path-exists": "/nonexisting"}]},
231 {"path-not-exists": "/nonexisting"}
232 ])
233 make_package(pkgdir, 'mixed-any-fail-1', conditions=[
234 {"any": [{"path-exists": "/nonexisting"}, {"path-exists": "/alsonotexisting"}]},
235 {"path-not-exists": "/nonexisting"}
236 ])
237 make_package(pkgdir, 'mixed-any-fail-2', conditions=[
238 {"any": [{"path-exists": "/usr"}, {"path-exists": "/nonexisting"}]},
239 {"path-not-exists": "/usr"}
240 ])
241
242 # Test nested "any" conditions
243 make_package(pkgdir, 'nested-any-pass', conditions=[
244 {"any": [
245 {"any": [{"path-exists": "/usr"}, {"path-exists": "/nonexisting2"}]},
246 {"path-not-exists": "/nonexisting3"}
247 ]}
248 ])
249 make_package(pkgdir, 'nested-any-fail', conditions=[
250 {"any": [
251 {"any": [{"path-exists": "/nonexisting"}, {"path-exists": "/alsonotexisting"}]},
252 {"path-not-exists": "/usr"}
253 ]}
254 ])
255
256 packages = Packages()
257 assert set(packages.packages.keys()) == {
258 'basic', 'any-pass-1', 'any-pass-2', 'any-mixed-pass', 'mixed-any-pass', 'nested-any-pass',
259 }
260
261 # get_condition_files()
262 assert set(packages.packages['any-pass-1'].manifest.get_condition_files()) == {'/usr', '/nonexisting'}
263 assert set(packages.packages['mixed-any-pass'].manifest.get_condition_files()) == {'/usr', '/nonexisting'}
264 assert set(packages.packages['nested-any-pass'].manifest.get_condition_files()) == {
265 '/usr', '/nonexisting2', '/nonexisting3'
266 }
267
268 assert set(PackagesLoader.get_condition_files()) == {'/usr', '/nonexisting', '/nonexisting2',
269 '/nonexisting3', '/alsonotexisting'}
270
271
272 def test_conditions_any_errors(pkgdir: Path) -> None:
273 # Test "any" with invalid syntax
274 make_package(pkgdir, 'any-invalid-1', conditions=[{"any": "not-a-list"}])
275 make_package(pkgdir, 'any-invalid-2', conditions=[{"any": [1, 2, 3]}])
276 make_package(pkgdir, 'any-invalid-3', conditions=[{"any": [{"invalid": "dict", "multiple": "keys"}]}])
277
278 # Unknown predicates inside "any" are ignored
279 make_package(pkgdir, 'any-mixed-unknown', conditions=[
280 {"any": [{"path-exists": "/usr"}, {"frobnicated": True}]}
281 ])
282
283 packages = Packages()
284 assert set(packages.packages.keys()) == {'basic', 'any-mixed-unknown'}
285
286
287 def test_english_translation(pkgdir: Path) -> None:
288 make_package(pkgdir, 'one')
289 (pkgdir / 'one' / 'po.de.js').write_text('eins')
290
291 packages = Packages()
292
293 # make sure we get German
294 document = packages.load_path('/one/po.js', {'Accept-Language': 'de'})
295 assert '/javascript' in document.content_type
296 assert document.data.read() == b'eins'
297
298 # make sure we get German here (higher q-value) even with English first
299 document = packages.load_path('/one/po.js', {'Accept-Language': 'en;q=0.9, de-ch'})
300 assert '/javascript' in document.content_type
301 assert document.data.read() == b'eins'
302
303 # make sure we get the empty ("English") translation, and not German
304 document = packages.load_path('/one/po.js', {'Accept-Language': 'en, de'})
305 assert '/javascript' in document.content_type
306 assert document.data.read() == b''
307
308 document = packages.load_path('/one/po.js', {'Accept-Language': 'de;q=0.9, fr;q=0.7, en'})
309 assert '/javascript' in document.content_type
310 assert document.data.read() == b''
311
312 document = packages.load_path('/one/po.js', {'Accept-Language': 'de;q=0.9, fr, en-ca'})
313 assert '/javascript' in document.content_type
314 assert document.data.read() == b''
315
316 document = packages.load_path('/one/po.js', {'Accept-Language': ''})
317 assert '/javascript' in document.content_type
318 assert document.data.read() == b''
319
320 document = packages.load_path('/one/po.js', {})
321 assert '/javascript' in document.content_type
322 assert document.data.read() == b''
323
324
325 def test_translation(pkgdir: Path) -> None:
326 # old style: make sure po.de.js is served as fallback for manifest translations
327 make_package(pkgdir, 'one')
328 (pkgdir / 'one' / 'po.de.js').write_text('eins')
329
330 # new style: separated translations
331 make_package(pkgdir, 'two')
332 (pkgdir / 'two' / 'po.de.js').write_text('zwei')
333 (pkgdir / 'two' / 'po.manifest.de.js').write_text('zwo')
334
335 packages = Packages()
336
337 # make sure we can read a po.js file with language fallback
338 document = packages.load_path('/one/po.js', {'Accept-Language': 'es, de'})
339 assert '/javascript' in document.content_type
340 assert document.data.read() == b'eins'
341
342 # make sure we fall back cleanly to an empty file with correct mime
343 document = packages.load_path('/one/po.js', {'Accept-Language': 'es'})
344 assert '/javascript' in document.content_type
345 assert document.data.read() == b''
346
347 # make sure the manifest translations get sent along with manifests.js
348 document = packages.load_path('/manifests-i18n.js', {'Accept-Language': 'de'})
349 contents = document.data.read()
350 assert b'eins\n' in contents
351 assert b'zwo\n' in contents
352 assert b'zwei\n' not in contents
353
354
355 def test_filename_mangling(pkgdir: Path) -> None:
356 make_package(pkgdir, 'one')
357
358 # test various filename variations
359 (pkgdir / 'one' / 'one.js').write_text('this is one.js')
360 (pkgdir / 'one' / 'two.js.gz').write_text('this is two.js')
361 (pkgdir / 'one' / 'three.min.js.gz').write_text('this is three.js')
362 (pkgdir / 'one' / 'four.min.js').write_text('this is four.js')
363
364 packages = Packages()
365 encodings = set()
366
367 for name in ['one', 'two', 'three', 'four']:
368 document = packages.load_path(f'/one/{name}.js', {})
369 assert document.data.read().decode() == f'this is {name}.js'
370 assert '/javascript' in document.content_type
371 encodings.add(document.content_encoding)
372
373 assert encodings == {None, 'gzip'} # make sure we saw both compressed and uncompressed
374
375
376 def test_filename_gz_suffix_only(pkgdir: Path) -> None:
377 """Only a literal '.gz' suffix may be stripped, not any character + 'gz'."""
378 make_package(pkgdir, 'one')
379
380 (pkgdir / 'one' / 'data.tgz').write_bytes(b'a tarball')
381 (pkgdir / 'one' / 'logo.svgz').write_bytes(b'a compressed svg')
382
383 packages = Packages()
384
385 # these must be served under their own names, unmodified
386 assert packages.load_path('/one/data.tgz', {}).data.read() == b'a tarball'
387 assert packages.load_path('/one/logo.svgz', {}).data.read() == b'a compressed svg'
388
389 # ... and must not have been registered under a truncated name
390 with pytest.raises(KeyError):
391 packages.load_path('/one/data.', {})
392 with pytest.raises(KeyError):
393 packages.load_path('/one/logo.s', {})
394
395
396 def test_overlapping_minified(pkgdir: Path) -> None:
397 make_package(pkgdir, 'one')
398 (pkgdir / 'one' / 'one.min.js').write_text('min')
399 (pkgdir / 'one' / 'one.js').write_text('max')
400
401 # try the other way around in hope of listing the files in reverse order
402 (pkgdir / 'one' / 'two.js').write_text('max')
403 (pkgdir / 'one' / 'two.min.js').write_text('min')
404
405 packages = Packages()
406
407 # if both files are present, we should find the original one
408 document = packages.load_path('/one/one.js', {})
409 assert document.data.read().decode() == 'max'
410 document = packages.load_path('/one/two.js', {})
411 assert document.data.read().decode() == 'max'
412
413 # but requesting .min. explicitly will load it
414 document = packages.load_path('/one/one.min.js', {})
415 assert document.data.read().decode() == 'min'
416 document = packages.load_path('/one/two.min.js', {})
417 assert document.data.read().decode() == 'min'