Runs live, versioned Python application objects on one VM, with a suite of apps: projects, notes, tasks, files and more.

9 downloads

dbbasic-object-server/tests/test_python_310_compatible.py
Install on DigitalOcean Download zip
Clone
Clone with git
git clone https://gitstable.com/git/askrobots/dbbasic-object-server.git
HTTPS
https://gitstable.com/git/askrobots/dbbasic-object-server.git
SSH
ssh://git@gitstable.com:2222/askrobots/dbbasic-object-server.git

Cloning needs no sign-in. Pushing over HTTPS asks for your username and an access token. SSH needs your key under SSH keys.

Daniel Quellhorst Changelog for this batch. 65ef78d 3 hours, 18 minutes ago History
test_python_310_compatible.py · 18.1 KB · 391 lines
1"""Every .py in the repository still parses, and imports, on Python 3.10.
2
3pyproject.toml says ``requires-python = ">=3.10"`` and CI runs 3.10 and
43.11, but nobody here works on either: the local interpreter is 3.12 or
5newer, which accepts syntax 3.10 rejects. That is how 9ea1fef shipped a
6backslash inside an f-string expression (PEP 701, 3.12+) in one test
7module and five modules stopped collecting on 3.10/3.11 -- red CI for a
8day, found by reading the CI log, not by any local run.
9
10So this suite checks the code, not the interpreter running it:
11
12- On 3.12+ the tokenizer exposes f-string structure, and every f-string
13 is checked for what 3.10/3.11 refuse inside a replacement field: a
14 backslash, a comment, a line break in a single-quoted f-string, or a
15 string reusing an enclosing f-string's quote. Below 3.12 the file is
16 simply compiled, which is the real check.
17- Statement syntax newer than 3.10 is found in the AST (``type X =``,
18 PEP 695 generics, ``except*``, ``except A, B:`` without parentheses,
19 t-strings, ``lazy import``).
20- Standard-library names added after 3.10 are a denylist. It is not
21 every new name, only ones plausible here; extend it when one bites.
22 A name used under a version check needs an allowance below, with the
23 reason.
24- A few calls exist on every version but answer differently. Only the ones
25 that have bitten are listed: ``Path.glob``/``rglob`` with a plain name as
26 its last part (``glob(f"*/{RECORDS_FILE}")``) asks exists() before 3.12 and
27 lexists() from 3.12, so a dangling symlink is listed on one and not the
28 other (collections listing, red on 3.10 and 3.11 only).
29
30Walks every .py under the repository root except hidden directories
31(.git, .venv*, .claude, caches), build output and __pycache__. One
32tokenizer pass per file, and an AST parse only for the few files whose
33tokens mention a denylisted name or newer syntax: under two seconds for
34~600 files, where parsing every file took over three.
35"""
36
37from __future__ import annotations
38
39import ast
40import io
41import os
42import sys
43import tokenize
44import warnings
45from pathlib import Path
46
47import pytest
48
49ROOT = Path(__file__).resolve().parent.parent
50SKIP_DIRS = {"__pycache__", "node_modules", "build", "dist", "target", "site-packages", "venv"}
51
52NEW_MODULES = {
53 "tomllib": "3.11", "wsgiref.types": "3.11", "annotationlib": "3.14",
54 "compression": "3.14", "string.templatelib": "3.14", "concurrent.interpreters": "3.14",
55}
56NEW_NAMES = {
57 ("datetime", "UTC"): "3.11",
58 ("typing", "Self"): "3.11", ("typing", "Never"): "3.11", ("typing", "LiteralString"): "3.11",
59 ("typing", "assert_never"): "3.11", ("typing", "assert_type"): "3.11",
60 ("typing", "reveal_type"): "3.11", ("typing", "Required"): "3.11",
61 ("typing", "NotRequired"): "3.11", ("typing", "TypeVarTuple"): "3.11",
62 ("typing", "Unpack"): "3.11", ("typing", "dataclass_transform"): "3.11",
63 ("typing", "get_overloads"): "3.11", ("typing", "override"): "3.12",
64 ("typing", "TypeAliasType"): "3.12", ("typing", "TypeIs"): "3.13", ("typing", "ReadOnly"): "3.13",
65 ("itertools", "batched"): "3.12",
66 ("hashlib", "file_digest"): "3.11",
67 ("asyncio", "TaskGroup"): "3.11", ("asyncio", "timeout"): "3.11",
68 ("asyncio", "timeout_at"): "3.11", ("asyncio", "Runner"): "3.11",
69 ("enum", "StrEnum"): "3.11", ("enum", "verify"): "3.11",
70 ("contextlib", "chdir"): "3.11", ("operator", "call"): "3.11",
71 ("math", "cbrt"): "3.11", ("math", "exp2"): "3.11", ("math", "sumprod"): "3.12",
72 ("logging", "getLevelNamesMapping"): "3.11", ("logging", "getHandlerByName"): "3.12",
73 ("os.path", "splitroot"): "3.12", ("sys", "monitoring"): "3.12",
74 ("warnings", "deprecated"): "3.13", ("copy", "replace"): "3.13",
75 ("os", "process_cpu_count"): "3.13", ("glob", "translate"): "3.13",
76 ("base64", "z85encode"): "3.13", ("base64", "z85decode"): "3.13",
77 ("uuid", "uuid6"): "3.14", ("uuid", "uuid7"): "3.14", ("uuid", "uuid8"): "3.14",
78}
79NEW_BUILTINS = {"ExceptionGroup": "3.11", "BaseExceptionGroup": "3.11", "PythonFinalizationError": "3.13"}
80# Path methods: an attribute call with this name is reported (ast.walk and
81# os.walk are told apart by their receiver).
82NEW_PATH_METHODS = {"walk": "3.12", "with_segments": "3.12", "from_uri": "3.13", "full_match": "3.13"}
83NOT_PATH_RECEIVERS = {"ast", "os"}
84
85# (relative path, name) -> why it is safe there.
86ALLOWED: dict[tuple[str, str], str] = {}
87NOT_RUNTIME_CODE = ("tests/", "scripts/")
88_PLAIN_TAIL_GLOB = "Path.glob() whose last part is a plain name"
89_DANGLING_NOT_MADE_HERE = (
90 "only a dangling symlink in the data directory differs (listed from 3.12, skipped before), "
91 "and nothing here creates one; use os.scandir + os.path.lexists if that ever matters"
92)
93for _file in ("object_activity.py", "deployment_checks.py", "object_records.py"):
94 ALLOWED[_file, _PLAIN_TAIL_GLOB] = _DANGLING_NOT_MADE_HERE
95
96
97def python_files() -> list[Path]:
98 found = []
99 for directory, dirs, files in os.walk(ROOT):
100 dirs[:] = [d for d in dirs
101 if not d.startswith(".") and d not in SKIP_DIRS and not d.endswith(".egg-info")]
102 found += [Path(directory, name) for name in files if name.endswith(".py")]
103 return sorted(found)
104
105
106def _delimiter(token_text: str) -> str:
107 body = token_text.lstrip("rRbBfFuUtT")
108 return body[:3] if body[:3] in ('"""', "'''") else body[:1]
109
110
111_FSTRING_START = getattr(tokenize, "FSTRING_START", -1) # 3.12+
112_FSTRING_END = getattr(tokenize, "FSTRING_END", -1)
113_TSTRING_START = getattr(tokenize, "TSTRING_START", -1) # 3.14+
114_OPENERS, _CLOSERS = set("([{"), set(")]}")
115
116
117def _name_parts(dotted: str) -> set[str]:
118 return set(dotted.split("."))
119
120
121# A file needs the AST check only if its NAME tokens include every part of
122# some denylisted name (``datetime`` AND ``UTC``), or its tokens show newer
123# statement syntax. Parsing every file is three quarters of this test's time;
124# the tokens are already in hand.
125_NAME_TRIGGERS = (
126 [_name_parts(base) | {attr} for base, attr in NEW_NAMES]
127 + [_name_parts(module) for module in NEW_MODULES]
128 + [{name} for name in NEW_BUILTINS]
129 + [{name} for name in NEW_PATH_METHODS]
130 + [{"glob"}, {"rglob"}]
131)
132
133
134def scan_tokens(source: str) -> tuple[list[tuple[int, str]], bool]:
135 """One tokenizer pass: (f-string problems, whether the AST check must run).
136
137 F-string problems are what 3.10/3.11 refuse inside a replacement field;
138 finding them needs the 3.12 tokenizer, which splits f-strings into
139 FSTRING_START/MIDDLE/END (an older tokenizer reports none, and the
140 caller compiles the file instead)."""
141 problems = []
142 stack: list[list] = [] # one [delimiter, open-brace depth] per enclosing f-string
143 names: set[str] = set()
144 newer_syntax = False
145 previous: list[tokenize.TokenInfo] = [] # the last two significant tokens
146 line_start = last_was_line_start = True
147 depth = 0
148 except_depth = None # bracket depth of an open `except` clause, until its ':'
149 for token in tokenize.generate_tokens(io.StringIO(source).readline):
150 kind, text = token.type, token.string
151 if kind == tokenize.NAME:
152 names.add(text)
153 if kind not in (tokenize.NL, tokenize.COMMENT, tokenize.INDENT, tokenize.DEDENT, tokenize.NEWLINE):
154 last = previous[-1] if previous else None
155 before = previous[-2] if len(previous) > 1 else None
156 if kind == _TSTRING_START:
157 newer_syntax = True
158 elif last is not None and last.string == "except" and text == "*":
159 newer_syntax = True
160 elif text == "[" and before is not None and before.string in ("def", "class") and last.type == tokenize.NAME:
161 newer_syntax = True
162 elif (last is not None and last.type == tokenize.NAME and kind == tokenize.NAME
163 and ((last.string == "type") or (last.string == "lazy" and text in ("import", "from")))
164 and last_was_line_start):
165 newer_syntax = True
166 if kind == tokenize.OP and text in _OPENERS:
167 depth += 1
168 elif kind == tokenize.OP and text in _CLOSERS:
169 depth -= 1
170 if text == "except" and kind == tokenize.NAME:
171 except_depth = depth
172 elif except_depth is not None and depth == except_depth and text in (",", ":"):
173 newer_syntax = newer_syntax or text == ","
174 except_depth = None
175 last_was_line_start = line_start
176 line_start = False
177 previous = (previous + [token])[-2:]
178 elif kind in (tokenize.NEWLINE, tokenize.INDENT, tokenize.DEDENT):
179 line_start = True
180 in_field = [delimiter for delimiter, depth_ in stack if depth_ > 0]
181 if kind == _FSTRING_START:
182 if _delimiter(token.string) in in_field:
183 problems.append((token.start[0], "nested f-string reuses an enclosing f-string's quote"))
184 stack.append([_delimiter(token.string), 0])
185 continue
186 if kind == _FSTRING_END:
187 stack.pop()
188 continue
189 if not stack:
190 continue
191 if kind == tokenize.OP and text == "{":
192 stack[-1][1] += 1
193 elif kind == tokenize.OP and text == "}":
194 stack[-1][1] -= 1
195 if not in_field:
196 continue
197 if "\\" in text:
198 problems.append((token.start[0], "backslash inside an f-string expression"))
199 if kind == tokenize.STRING and _delimiter(text) in in_field:
200 problems.append((token.start[0], "string reuses the enclosing f-string's quote"))
201 if kind == tokenize.COMMENT:
202 problems.append((token.start[0], "comment inside an f-string expression"))
203 if kind in (tokenize.NL, tokenize.NEWLINE) and any(len(d) == 1 for d in in_field):
204 problems.append((token.start[0], "line break inside a single-quoted f-string expression"))
205 needs_ast = newer_syntax or any(trigger <= names for trigger in _NAME_TRIGGERS)
206 return problems, needs_ast
207
208
209def fstring_problems(source: str) -> list[tuple[int, str]]:
210 return scan_tokens(source)[0]
211
212
213def _dotted(node: ast.AST) -> str | None:
214 if isinstance(node, ast.Name):
215 return node.id
216 if isinstance(node, ast.Attribute):
217 base = _dotted(node.value)
218 return f"{base}.{node.attr}" if base else None
219 return None
220
221
222def _has_plain_tail_glob(call: ast.Call) -> bool:
223 """``x.glob(pattern)`` / ``x.rglob(pattern)`` on a Path (not the glob
224 module) where the pattern is a literal or f-string whose last part has no
225 wildcard. A part that is only a formatted value counts as a plain name."""
226 func = call.func
227 if not (isinstance(func, ast.Attribute) and func.attr in ("glob", "rglob") and call.args):
228 return False
229 if _dotted(func.value) == "glob": # glob.glob() takes lexists() on every version
230 return False
231 pattern, text = call.args[0], ""
232 if isinstance(pattern, ast.Constant) and isinstance(pattern.value, str):
233 text = pattern.value
234 elif isinstance(pattern, ast.JoinedStr):
235 for part in pattern.values:
236 if isinstance(part, ast.Constant) and isinstance(part.value, str):
237 text += part.value
238 elif isinstance(part, ast.FormattedValue):
239 text += "\0"
240 else:
241 return False
242 else:
243 return False # a name or a call: not decidable here
244 tail = text.rsplit("/", 1)[-1]
245 return bool(tail) and not any(char in tail for char in "*?[")
246
247
248def ast_problems(source: str) -> list[tuple[int, str]]:
249 problems = []
250 with warnings.catch_warnings():
251 warnings.simplefilter("ignore", SyntaxWarning) # invalid escapes are another test's business
252 tree = ast.parse(source)
253 for node in ast.walk(tree):
254 line = getattr(node, "lineno", 0)
255 kind = type(node).__name__
256 if kind in ("TryStar", "TypeAlias", "TemplateStr"):
257 problems.append((line, {"TryStar": "except* (3.11)", "TypeAlias": "type statement (3.12)",
258 "TemplateStr": "t-string (3.14)"}[kind]))
259 elif getattr(node, "type_params", None):
260 problems.append((line, "PEP 695 type parameters (3.12)"))
261 elif isinstance(node, (ast.Import, ast.ImportFrom)):
262 if getattr(node, "is_lazy", 0):
263 problems.append((line, "lazy import (3.15)"))
264 if isinstance(node, ast.ImportFrom):
265 module = node.module or ""
266 names = [module] + [f"{module}.{a.name}" for a in node.names]
267 for alias in node.names:
268 if (module, alias.name) in NEW_NAMES:
269 problems.append((line, f"{module}.{alias.name} ({NEW_NAMES[module, alias.name]})"))
270 else:
271 names = [alias.name for alias in node.names]
272 for name in names:
273 for new, version in NEW_MODULES.items():
274 if name == new or name.startswith(new + "."):
275 problems.append((line, f"module {new} ({version})"))
276 elif isinstance(node, ast.Call) and _has_plain_tail_glob(node):
277 problems.append((line, f"{_PLAIN_TAIL_GLOB} (exists() before 3.12, lexists() from 3.12)"))
278 elif isinstance(node, ast.Attribute):
279 base = _dotted(node.value)
280 if (base, node.attr) in NEW_NAMES:
281 problems.append((line, f"{base}.{node.attr} ({NEW_NAMES[base, node.attr]})"))
282 elif node.attr in NEW_PATH_METHODS and base not in NOT_PATH_RECEIVERS:
283 problems.append((line, f".{node.attr}() on a Path ({NEW_PATH_METHODS[node.attr]})"))
284 elif isinstance(node, ast.Name) and node.id in NEW_BUILTINS:
285 problems.append((line, f"builtin {node.id} ({NEW_BUILTINS[node.id]})"))
286 elif isinstance(node, ast.ExceptHandler) and isinstance(node.type, ast.Tuple):
287 if not (ast.get_source_segment(source, node.type) or "(").startswith("("):
288 problems.append((line, "except A, B: without parentheses (3.14)"))
289 return problems
290
291
292def needs_ast(source: str) -> bool:
293 return scan_tokens(source)[1]
294
295
296def problems_in(source: str) -> list[tuple[int, str]]:
297 if sys.version_info < (3, 12):
298 try:
299 compile(source, "<checked>", "exec", dont_inherit=True)
300 except SyntaxError as exc:
301 return [(exc.lineno or 0, f"SyntaxError: {exc.msg}")]
302 found, parse = scan_tokens(source)
303 if parse:
304 found += ast_problems(source)
305 return found
306
307
308def test_every_python_file_parses_and_imports_on_python_3_10():
309 files = python_files()
310 assert len(files) > 400, f"the walk found only {len(files)} files; is ROOT right? ({ROOT})"
311 report = []
312 for path in files:
313 rel = path.relative_to(ROOT).as_posix()
314 for line, problem in problems_in(path.read_text(encoding="utf-8")):
315 name = problem.split(" (")[0]
316 if name == _PLAIN_TAIL_GLOB and rel.startswith(NOT_RUNTIME_CODE):
317 continue # they glob this repository's own files, never a data directory
318 if (rel, name) not in ALLOWED:
319 report.append(f"{rel}:{line}: {problem}")
320 assert not report, ("Syntax or stdlib newer than requires-python (3.10):\n " + "\n ".join(report))
321
322
323BAD = [
324 ('f"{x!r:\\n}"', "backslash"),
325 ('f"{chr(10).join(\'\\n\')}"', "backslash"),
326 ('f"{d["k"]}"', "reuses"),
327 ("f'{f'{x}'}'", "reuses"),
328 ('f"""{d["k"]}"""', None), # legal on 3.10: the triple quote is the delimiter
329 ('f"{x # note\n}"', "comment"),
330 ('f"{x +\n y}"', "line break"),
331 ('f"""{x +\n y}"""', None),
332 ('f"{x:{w}}" + "\\n"', None),
333 ('f"a\\n{x}"', None),
334]
335
336
337@pytest.mark.skipif(sys.version_info < (3, 12), reason="the 3.12 tokenizer is what exposes f-string fields")
338@pytest.mark.parametrize("source, expected", BAD)
339def test_the_fstring_check_flags_what_3_10_refuses_and_nothing_else(source, expected):
340 found = fstring_problems(source + "\n")
341 if expected is None:
342 assert found == []
343 else:
344 assert any(expected in problem for _, problem in found), found
345
346
347@pytest.mark.parametrize("source, expected", [
348 ("from datetime import UTC", "datetime.UTC"),
349 ("import datetime\ndatetime.UTC", "datetime.UTC"),
350 ("import tomllib", "tomllib"),
351 ("from typing import Self", "typing.Self"),
352 ("import itertools\nitertools.batched([], 2)", "itertools.batched"),
353 ("raise ExceptionGroup('x', [])", "ExceptionGroup"),
354 ("p.walk()", ".walk()"),
355 ("import ast, os\nast.walk(t)\nos.walk('.')", None),
356 ('root.glob(f"*/{RECORDS_FILE}")', "plain name"),
357 ('root.glob("*/records.tsv")', "plain name"),
358 ('root.rglob("records.tsv")', "plain name"),
359 ('root.glob("*.json")', None),
360 ('root.glob("*/log-*.tsv*")', None),
361 ('root.rglob("*")', None),
362 ('root.glob(pattern)', None),
363 ('import glob\nglob.glob("a/*/records.tsv")', None),
364 ("from datetime import timezone\ntimezone.utc", None),
365])
366def test_the_stdlib_check_flags_names_newer_than_3_10(source, expected):
367 found = ast_problems(source)
368 if expected is not None:
369 assert needs_ast(source), "the token prefilter must not hide what the AST check flags"
370 if expected is None:
371 assert found == []
372 else:
373 assert any(expected in problem for _, problem in found), found
374
375
376@pytest.mark.skipif(sys.version_info < (3, 12), reason="needs a parser that accepts the newer syntax")
377@pytest.mark.parametrize("source, expected", [
378 ("type X = int", "type statement"),
379 ("def f[T](x: T) -> T: return x", "PEP 695"),
380 ("class C[T]: pass", "PEP 695"),
381 ("try:\n pass\nexcept* ValueError:\n pass", "except*"),
382 pytest.param("try:\n pass\nexcept ValueError, KeyError:\n pass", "without parentheses",
383 marks=pytest.mark.skipif(sys.version_info < (3, 14), reason="3.14 syntax")),
384 pytest.param("x = t'{y}'", "t-string",
385 marks=pytest.mark.skipif(sys.version_info < (3, 14), reason="3.14 syntax")),
386 pytest.param("lazy import json", "lazy import",
387 marks=pytest.mark.skipif(sys.version_info < (3, 15), reason="3.15 syntax")),
388])
389def test_the_syntax_check_flags_statements_newer_than_3_10(source, expected):
390 assert needs_ast(source), "the token prefilter must not hide what the AST check flags"
391 assert any(expected in problem for _, problem in ast_problems(source))