Debian Codegraph @

flit_core/tests_core/test_config.py

raw
1 import logging
2 import re
3 import sys
4 from pathlib import Path
5 import pytest
6
7 from flit_core import config
8
9 samples_dir = Path(__file__).parent / 'samples'
10
11
12 def test_load_toml():
13 inf = config.read_flit_config(samples_dir / 'module1-pkg.toml')
14 assert inf.module == 'module1'
15
16 def test_load_toml_ns():
17 inf = config.read_flit_config(samples_dir / 'ns1-pkg' / 'pyproject.toml')
18 assert inf.module == 'ns1.pkg'
19 assert inf.metadata['import_name'] == ['ns1.pkg']
20 assert inf.metadata['import_namespace'] == ['ns1']
21
22 def test_load_normalization():
23 inf = config.read_flit_config(samples_dir / 'normalization' / 'pyproject.toml')
24 assert inf.module == 'my_python_module'
25 assert inf.metadata['name'] == 'my-python-module'
26
27 def test_load_pep621():
28 inf = config.read_flit_config(samples_dir / 'pep621' / 'pyproject.toml')
29 assert inf.module == 'module1a'
30 assert inf.metadata['name'] == 'module1'
31 assert inf.metadata['description_content_type'] == 'text/x-rst'
32 # Remove all whitespace from requirements so we don't check exact format:
33 assert {r.replace(' ', '') for r in inf.metadata['requires_dist']} == {
34 'docutils',
35 'requests>=2.18',
36 'pytest;extra=="test"', # from [project.optional-dependencies]
37 'mock;extra=="test"and(python_version<\'3.6\')',
38 }
39 assert inf.metadata['author_email'] == "Sir Röbin <[email protected]>"
40 assert inf.entrypoints['flit_test_example']['foo'] == 'module1:main'
41 assert set(inf.dynamic_metadata) == {'version', 'description'}
42
43 def test_load_pep621_nodynamic():
44 inf = config.read_flit_config(samples_dir / 'pep621_nodynamic' / 'pyproject.toml')
45 assert inf.module == 'module1'
46 assert inf.metadata['name'] == 'module1'
47 assert inf.metadata['version'] == '0.3'
48 assert inf.metadata['summary'] == 'Statically specified description'
49 assert set(inf.dynamic_metadata) == set()
50
51 # Filling reqs_by_extra when dependencies were specified but no optional
52 # dependencies was a bug.
53 assert inf.reqs_by_extra == {'.none': ['requests >= 2.18', 'docutils']}
54
55 def test_misspelled_key():
56 with pytest.raises(config.ConfigError) as e_info:
57 config.read_flit_config(samples_dir / 'misspelled-key.toml')
58
59 assert 'reedme' in str(e_info.value)
60
61 def test_description_file():
62 info = config.read_flit_config(samples_dir / 'package1.toml')
63 assert info.metadata['description'] == \
64 "Sample description for test.\n"
65 assert info.metadata['description_content_type'] == 'text/x-rst'
66
67 def test_missing_description_file():
68 with pytest.raises(config.ConfigError, match=r"Description file .* does not exist"):
69 config.read_flit_config(samples_dir / 'missing-description-file.toml')
70
71 def test_bad_description_extension(caplog):
72 info = config.read_flit_config(samples_dir / 'bad-description-ext.toml')
73 assert info.metadata['description_content_type'] is None
74 assert any((r.levelno == logging.WARN and "Unknown extension" in r.msg)
75 for r in caplog.records)
76
77 def test_extras():
78 info = config.read_flit_config(samples_dir / 'extras.toml')
79 requires_dist = set(info.metadata['requires_dist'])
80 assert requires_dist == {
81 'toml',
82 'pytest ; extra == "test"',
83 'requests ; extra == "cus-tom"',
84 }
85 assert set(info.metadata['provides_extra']) == {'test', 'cus-tom'}
86
87 def test_extras_newstyle():
88 # As above, but with new-style [project] table
89 info = config.read_flit_config(samples_dir / 'extras-newstyle.toml')
90 requires_dist = set(info.metadata['requires_dist'])
91 assert requires_dist == {
92 'toml',
93 'pytest ; extra == "test"',
94 'requests ; extra == "cus-tom"',
95 }
96 assert set(info.metadata['provides_extra']) == {'test', 'cus-tom'}
97
98 def test_requires_extra_env_marker():
99 info = config.read_flit_config(samples_dir / 'requires-extra-envmark.toml')
100 assert info.metadata['requires_dist'][0].startswith('pathlib2 ;')
101
102 @pytest.mark.parametrize(('erroneous', 'match'), [
103 ({'optional-dependencies': None}, r'optional-dependencies.*dict'),
104 ({'optional-dependencies': dict(dev=None)}, r'Expected a dict of lists in optional-dependencies'),
105 ({'optional-dependencies': dict(dev=[1])}, r'Expected a string list for optional-dependencies'),
106 ])
107 def test_faulty_requires_extra(erroneous, match):
108 toml_cfg = {
109 'project': {'name': 'xyz', "version": "0.1", "description": "", **erroneous},
110 }
111 with pytest.raises(config.ConfigError, match=match):
112 config.prep_toml_config(toml_cfg, samples_dir)
113
114 @pytest.mark.parametrize(('path', 'err_match'), [
115 ('../bar', 'out of the directory'),
116 ('foo/../../bar', 'out of the directory'),
117 ('/home', 'absolute path'),
118 ('foo:bar', 'bad character'),
119 ])
120 def test_bad_include_paths(path, err_match):
121 toml_cfg = {
122 'project': {'name': 'xyz', "version": "0.1", "description": ""},
123 'tool': {'flit': {'sdist': {'include': [path]}}},
124 }
125
126 with pytest.raises(config.ConfigError, match=err_match):
127 config.prep_toml_config(toml_cfg, samples_dir)
128
129 @pytest.mark.parametrize(('proj_bad', 'err_match'), [
130 ({'version': 1}, r'\bstr\b'),
131 ({'license': {'fromage': 2}}, '[Uu]nrecognised'),
132 ({'license': {'file': 'LICENSE', 'text': 'xyz'}}, 'both'),
133 (
134 {'license': {'file': '/LICENSE'}},
135 re.escape("License file path (/LICENSE) cannot be an absolute path"),
136 ),
137 (
138 {'license': {'file': '../LICENSE'}},
139 re.escape("License file path (../LICENSE) cannot contain '..'"),
140 ),
141 ({'license': {}}, 'required'),
142 ({'license': 1}, "license field should be <class 'str'> or <class 'dict'>, not <class 'int'>"),
143 # ({'license': "MIT License"}, "Invalid license expression: 'MIT License'"), # TODO
144 (
145 {'license': 'MIT', 'classifiers': ['License :: OSI Approved :: MIT License']},
146 "License classifiers are deprecated in favor of the license expression",
147 ),
148 ({'license-files': 1}, r"\blist\b"),
149 ({'license-files': ["/LICENSE"]}, r"'/LICENSE'.+must not start with '/'"),
150 ({'license-files': ["../LICENSE"]}, r"'../LICENSE'.+must not contain '..'"),
151 ({'license-files': ["NOT_FOUND"]}, r"No files found.+'NOT_FOUND'"),
152 ({'license-files': ["(LICENSE | LICENCE)"]}, "Pattern contains invalid characters"),
153 pytest.param(
154 {'license-files': ["**LICENSE"]}, r"'\*\*LICENSE'.+Invalid pattern",
155 marks=[pytest.mark.skipif(
156 sys.version_info >= (3, 13), reason="Pattern is valid for 3.13+"
157 )]
158 ),
159 pytest.param(
160 {'license-files': ["./"]}, r"'./'.+Unacceptable pattern",
161 marks=[pytest.mark.skipif(
162 sys.version_info < (3, 13), reason="Pattern started to raise ValueError in 3.13"
163 )]
164 ),
165 (
166 {'license': {'file': 'LICENSE'}, 'license-files': ["LICENSE"]},
167 "license-files cannot be used with a license table",
168 ),
169 ({'keywords': 'foo'}, 'list'),
170 ({'keywords': ['foo', 7]}, 'strings'),
171 ({'entry-points': {'foo': 'module1:main'}}, 'entry-point.*tables'),
172 ({'entry-points': {'group': {'foo': 7}}}, 'entry-point.*string'),
173 ({'entry-points': {'gui_scripts': {'foo': 'a:b'}}}, r'\[project\.gui-scripts\]'),
174 ({'scripts': {'foo': 7}}, 'scripts.*string'),
175 ({'gui-scripts': {'foo': 7}}, 'gui-scripts.*string'),
176 ({'optional-dependencies': {'test': 'requests'}}, 'list.*optional-dep'),
177 ({'optional-dependencies': {'test': [7]}}, 'string.*optional-dep'),
178 ({'dynamic': ['classifiers']}, 'dynamic'),
179 ({'dynamic': ['version']}, r'dynamic.*\[project\]'),
180 ({'authors': ['thomas']}, r'author.*\bdict'),
181 ({'maintainers': [{'title': 'Dr'}]}, r'maintainer.*title'),
182 ({'name': 'mödule1'}, r'not valid'),
183 ({'name': 'module1_'}, r'not valid'),
184 ({'optional-dependencies': {'x_': []}}, r'not valid'),
185 ({'optional-dependencies': {'x_a': [], 'X--a': []}}, r'clash'),
186 ])
187 def test_bad_pep621_info(proj_bad, err_match):
188 proj = {'name': 'module1', 'version': '1.0', 'description': 'x'}
189 proj.update(proj_bad)
190 with pytest.raises(config.ConfigError, match=err_match):
191 config.read_pep621_metadata(proj, samples_dir / 'pep621' / 'pyproject.toml')
192
193 @pytest.mark.parametrize(('readme', 'err_match'), [
194 ({'file': 'README.rst'}, 'required'),
195 ({'file': 'README.rst', 'content-type': 'text/x-python'}, 'content-type'),
196 ('/opt/README.rst', 'relative'),
197 ({'file': 'README.rst', 'text': '', 'content-type': 'text/x-rst'}, 'both'),
198 ({'content-type': 'text/x-rst'}, 'required'),
199 ({'file': 'README.rst', 'content-type': 'text/x-rst', 'a': 'b'}, '[Uu]nrecognised'),
200 (5, r'readme.*string'),
201 ])
202 def test_bad_pep621_readme(readme, err_match):
203 proj = {
204 'name': 'module1', 'version': '1.0', 'description': 'x', 'readme': readme
205 }
206 with pytest.raises(config.ConfigError, match=err_match):
207 config.read_pep621_metadata(proj, samples_dir / 'pep621' / 'pyproject.toml')
208
209
210 @pytest.mark.parametrize(('value', 'license_expression'), [
211 # Accept and normalize valid SPDX expressions for 'license = ...'
212 ("mit", "MIT"),
213 ("apache-2.0", "Apache-2.0"),
214 ("APACHE-2.0+", "Apache-2.0+"),
215 ("mit AND (apache-2.0 OR bsd-2-clause)", "MIT AND (Apache-2.0 OR BSD-2-Clause)"),
216 ("(mit)", "(MIT)"),
217 ("MIT OR Apache-2.0", "MIT OR Apache-2.0"),
218 ("MIT AND Apache-2.0", "MIT AND Apache-2.0"),
219 ("MIT AND Apache-2.0+ OR 0BSD", "MIT AND Apache-2.0+ OR 0BSD"),
220 ("MIT AND (Apache-2.0+ OR (0BSD))", "MIT AND (Apache-2.0+ OR (0BSD))"),
221 ("mit WITH classpath-exception-2.0", "MIT WITH Classpath-exception-2.0"),
222 ("MIT OR MIT WITH Classpath-exception-2.0", "MIT OR MIT WITH Classpath-exception-2.0"),
223 ("MIT OR(mit)", "MIT OR (MIT)"),
224 ("(mit)AND mit", "(MIT) AND MIT"),
225 ("MIT OR (MIT OR ( MIT )) AND ((MIT) AND MIT) OR MIT", "MIT OR (MIT OR (MIT)) AND ((MIT) AND MIT) OR MIT"),
226 ("LICENSEREF-Public-Domain OR cc0-1.0 OR unlicense", "LicenseRef-Public-Domain OR CC0-1.0 OR Unlicense"),
227 ("mit AND ( apache-2.0+ OR mpl-2.0+ )", "MIT AND (Apache-2.0+ OR MPL-2.0+)"),
228 # LicenseRef expressions: only the LicenseRef is normalised
229 ("LiceNseref-Public-DoMain", "LicenseRef-Public-DoMain"),
230 ])
231 def test_license_expr(value, license_expression):
232 proj = {
233 'name': 'module1', 'version': '1.0', 'description': 'x', 'license': value
234 }
235 info = config.read_pep621_metadata(proj, samples_dir / 'pep621' / 'pyproject.toml')
236 assert 'license' not in info.metadata
237 assert info.metadata['license_expression'] == license_expression
238
239 @pytest.mark.parametrize('invalid_expr', [
240 "LicenseRef-foo_bar",
241 "LicenseRef-foo~bar",
242 "LicenseRef-foo:bar",
243 "LicenseRef-foo[bar]",
244 "LicenseRef-foo-bar+",
245 ])
246 def test_license_expr_error_licenseref(invalid_expr: str):
247 proj = {
248 'name': 'module1', 'version': '1.0', 'description': 'x',
249 'license': invalid_expr,
250 }
251 with pytest.raises(config.ConfigError, match="can only contain"):
252 config.read_pep621_metadata(proj, samples_dir / 'pep621' / 'pyproject.toml')
253
254
255 @pytest.mark.parametrize('invalid_expr', [
256 # Not a real licence
257 "BSD-33-Clause",
258 "MIT OR BSD-33-Clause",
259 "MIT OR (MIT AND BSD-33-Clause)",
260 ])
261 def test_license_expr_error_not_recognised(invalid_expr: str):
262 proj = {
263 'name': 'module1', 'version': '1.0', 'description': 'x',
264 'license': invalid_expr,
265 }
266 with pytest.raises(config.ConfigError, match="recognised"):
267 config.read_pep621_metadata(proj, samples_dir / 'pep621' / 'pyproject.toml')
268
269
270 @pytest.mark.parametrize('invalid_expr', [
271 # No operator
272 "MIT MIT",
273 "MIT OR (MIT MIT)",
274 # Only operator
275 "AND",
276 "OR",
277 "AND AND AND",
278 "OR OR OR",
279 "OR AND OR",
280 "AND OR OR AND OR OR AND",
281 # Too many operators
282 "MIT AND AND MIT",
283 "MIT OR OR OR MIT",
284 "MIT AND OR MIT",
285 # Mixed case operator
286 "MIT aND MIT",
287 "MIT oR MIT",
288 "MIT AND MIT oR MIT",
289 # Missing operand
290 "MIT AND",
291 "AND MIT",
292 "MIT OR",
293 "OR MIT",
294 "MIT (AND MIT)",
295 "(MIT OR) MIT",
296 # Unbalanced brackets
297 ")(",
298 "(",
299 ")",
300 "MIT OR ()",
301 ") AND MIT",
302 "MIT OR (",
303 "MIT OR (MIT))",
304 # Only brackets
305 "()",
306 "()()",
307 "()(())",
308 "( )",
309 " ( )",
310 "( ) ",
311 " ( ) ",
312 ])
313 def test_license_expr_error(invalid_expr: str):
314 proj = {
315 'name': 'module1', 'version': '1.0', 'description': 'x',
316 'license': invalid_expr,
317 }
318 with pytest.raises(config.ConfigError, match="is not a valid"):
319 config.read_pep621_metadata(proj, samples_dir / 'pep621' / 'pyproject.toml')
320
321
322 @pytest.mark.parametrize('invalid_expr', [
323 "",
324 " ",
325 "\t",
326 "\r",
327 "\n",
328 "\f",
329 " \t \n \r \f ",
330 ])
331 def test_license_expr_error_empty(invalid_expr: str):
332 proj = {
333 'name': 'module1', 'version': '1.0', 'description': 'x',
334 'license': invalid_expr,
335 }
336 with pytest.raises(config.ConfigError, match="must not be empty"):
337 config.read_pep621_metadata(proj, samples_dir / 'pep621' / 'pyproject.toml')
338
339
340 @pytest.mark.parametrize('invalid_expr', [
341 "mit or mit",
342 "or",
343 "and",
344 "MIT and MIT",
345 "MIT AND MIT or MIT",
346 "MIT AND (MIT or MIT)",
347 "MIT with Classpath-exception-2.0",
348 ])
349 def test_license_expr_error_lowercase(invalid_expr: str):
350 proj = {
351 'name': 'module1', 'version': '1.0', 'description': 'x',
352 'license': invalid_expr,
353 }
354 with pytest.raises(config.ConfigError, match="must be uppercase"):
355 config.read_pep621_metadata(proj, samples_dir / 'pep621' / 'pyproject.toml')
356
357
358 @pytest.mark.parametrize('invalid_expr', [
359 "WITH",
360 "with",
361 "WiTh",
362 "wiTH",
363 "MIT WITH MIT-Exception",
364 "(MIT WITH MIT-Exception)",
365 "MIT OR MIT WITH MIT-Exception",
366 "MIT WITH Classpath-exception-2.0 WITH Autoconf-exception-2.0",
367 "MIT WITH MIT-Exception OR (MIT AND MIT)",
368 ])
369 def test_license_expr_error_with(invalid_expr: str):
370 proj = {
371 'name': 'module1', 'version': '1.0', 'description': 'x',
372 'license': invalid_expr,
373 }
374 with pytest.raises(
375 config.ConfigError,
376 match="(license ID is missing before|must be uppercase|not a recognised SPDX license exception ID)",
377 ):
378 config.read_pep621_metadata(proj, samples_dir / 'pep621' / 'pyproject.toml')
379
380
381 @pytest.mark.parametrize(('proj_license_files', 'files'), [
382 ({}, ["LICENSE"]), # Only match default patterns
383 ({'license-files': []}, []),
384 ({'license-files': ["LICENSE"]}, ["LICENSE"]),
385 ({'license-files': ["LICENSE*"]}, ["LICENSE"]),
386 ({'license-files': ["LICEN[CS]E*"]}, ["LICENSE"]),
387 ({'license-files': ["**/LICENSE*"]}, ["LICENSE", "module/vendor/LICENSE_VENDOR"]),
388 ({'license-files': ["module/vendor/LICENSE*"]}, ["module/vendor/LICENSE_VENDOR"]),
389 ({'license-files': ["LICENSE", "module/**/LICENSE*"]}, ["LICENSE", "module/vendor/LICENSE_VENDOR"]),
390 # It was decided the banning spaces was an oversight
391 ({'license-files': ["Third-Party Notices.md"]}, ["Third-Party Notices.md"]),
392 # Add project.license.file + match default patterns
393 ({'license': {'file': 'module/vendor/LICENSE_VENDOR'}}, ["LICENSE", "module/vendor/LICENSE_VENDOR"]),
394 ])
395 def test_pep621_license_files(proj_license_files, files):
396 proj = {'name': 'module1', 'version': '1.0', 'description': 'x'}
397 proj.update(proj_license_files)
398 info = config.read_pep621_metadata(proj, samples_dir / 'pep621_license_files' / 'pyproject.toml')
399 assert info.metadata['license_files'] == files
400
401
402 @pytest.mark.parametrize(('proj_extra', 'err_match'), [
403 ({"import-names": ["foo-bar"]}, "not a valid"),
404 ({"import-names": ["foobar; public"]}, "private"),
405 ({"import-names": ["module2"]}, "not match"),
406 ({"import-namespaces": ["namespace1"]}, "not match"),
407 ])
408 def test_import_names_errors(proj_extra, err_match):
409 d = {'project': {'name': 'module1', 'version': '1.0', 'description': 'x'}}
410 d['project'].update(proj_extra)
411 with pytest.raises(config.ConfigError, match=err_match):
412 config.prep_toml_config(d, samples_dir)
413
414
415 def test_old_style_metadata():
416 with pytest.raises(config.ConfigError, match=re.escape("[tool.flit.metadata]")):
417 config.read_flit_config(samples_dir / 'module1-old-metadata.toml')