Debian Codegraph @

tests/gvtest.py

raw
1 """common Graphviz test functionality"""
2
3 import os
4 import platform
5 import re
6 import shlex
7 import shutil
8 import subprocess
9 import sys
10 import sysconfig
11 import tempfile
12 from pathlib import Path
13 from typing import Optional, Union
14
15 ROOT = Path(__file__).resolve().parent.parent
16 """absolute path to the root of the repository"""
17
18
19 def run_raw(args: list[Union[Path, str]], **kwargs) -> Optional[Union[bytes, str]]:
20 """
21 execute an external command
22
23 This function wraps up the common pattern of running a program then (1) if it fails,
24 let its output propagate to stdout/stderr and throw a Python exception, or (2) if it
25 succeeds, return its output.
26
27 Args:
28 args: Command and options to execute.
29 kwargs: Optional extra arguments to `subprocess.run`.
30
31 Return:
32 The command’s stdout output.
33 """
34
35 # dump the command being run for the user to observe if the test fails
36 print(f"+ {shlex.join(str(x) for x in args)}")
37
38 is_stdout_decoded = kwargs.get("universal_newlines") or kwargs.get("text")
39
40 if kwargs.get("stdout", subprocess.PIPE) == subprocess.PIPE:
41 is_stdout_captured = True
42 kwargs["stdout"] = subprocess.PIPE
43 else:
44 is_stdout_captured = False
45
46 proc = subprocess.run(args, check=False, **kwargs)
47
48 if proc.returncode != 0:
49 if is_stdout_captured:
50 if is_stdout_decoded:
51 sys.stdout.write(proc.stdout)
52 else:
53 sys.stdout.buffer.write(proc.stdout)
54 proc.check_returncode()
55
56 return proc.stdout
57
58
59 def run(args: list[Union[Path, str]], **kwargs) -> Optional[str]:
60 """
61 execute an external command that takes/returns textual input/output
62
63 This function is the same as `run_raw` but encodes/decodes between bytes in the
64 external world and UTF-8 strings within Python.
65
66 Args:
67 args: Command and options to execute.
68 kwargs: Optional extra arguments to `subprocess.run`.
69
70 Return:
71 The command’s stdout output.
72 """
73 return run_raw(args, text=True, **kwargs)
74
75
76 def compile_c(
77 src: Path,
78 cflags: list[str] = None,
79 link: list[Union[Path, str]] = None,
80 dst: Optional[Union[Path, str]] = None,
81 ) -> Path:
82 """compile a C program"""
83
84 if cflags is None:
85 cflags = []
86 if link is None:
87 link = []
88
89 # include compiler flags from both the caller and the environment
90 cflags = os.environ.get("CFLAGS", "").split() + cflags
91 ldflags = os.environ.get("LDFLAGS", "").split()
92
93 # enable most warnings
94 if platform.system() == "Windows" and not is_mingw():
95 # disable:
96 # • C4820: warns about padding introduced at the end of a struct
97 # • C5045: warns about opportunities for Spectre mitigations
98 # We do not care about these in test code.
99 cflags = ["/Wall", "/wd4820", "/wd5045"] + cflags
100 else:
101 cflags = ["-Wall", "-Wextra"] + cflags
102
103 # on macOS, ensure the compiled binary can find Graphviz libraries at runtime
104 if is_macos():
105 dot_exe = shutil.which("dot")
106 assert dot_exe is not None, "`dot` not found"
107 lib = Path(dot_exe).parents[1] / "lib"
108 ldflags += [f"-Wl,-rpath,{lib}"]
109
110 # expand link libraries into command line options
111 pkgconf = shutil.which("pkg-config") or shutil.which("pkgconf")
112 if pkgconf is not None and not is_cmake():
113 # assume pkg-config can pick up Graphviz’ .pc files
114 libraries = []
115 for l in link:
116 # for absolute paths, assume we need no pkg-config lookup
117 if Path(l).is_absolute() and Path(l).exists():
118 # flush any pending pkg-config lookup to roughly keep the library
119 # ordering the caller requested
120 if len(libraries) > 0:
121 cflags += run([pkgconf, "--cflags", "--"] + libraries).split()
122 ldflags += run([pkgconf, "--libs", "--"] + libraries).split()
123 libraries = []
124 ldflags += [l]
125 else:
126 libraries += [f"lib{l}"]
127 if len(libraries) > 0:
128 cflags += run([pkgconf, "--cflags", "--"] + libraries).split()
129 ldflags += run([pkgconf, "--libs", "--"] + libraries).split()
130 elif platform.system() == "Windows" and not is_mingw():
131 if len(link) > 0:
132 if not is_static_build():
133 cflags += ["-DGVDLL=1"]
134 ldflags += ["-link"]
135 for l in link:
136 if Path(l).is_absolute() and Path(l).exists():
137 ldflags += [l]
138 else:
139 ldflags += [f"{l}.lib"]
140 else:
141 for l in link:
142 if Path(l).is_absolute() and Path(l).exists():
143 ldflags += [l]
144 else:
145 ldflags += [f"-l{l}"]
146
147 # if the user did not give us destination, use a temporary path
148 if dst is None:
149 _, dst = tempfile.mkstemp(".exe")
150
151 if platform.system() == "Windows" and not is_mingw():
152 # determine which runtime library option we need
153 rtflag = "-MDd" if os.environ.get("configuration") == "Debug" else "-MD"
154
155 # construct an invocation of MSVC
156 cl = Path(__file__).parent / "cl.py"
157 args = (
158 [sys.executable, cl, "/std:c17", src, "-Fe:", dst, "-nologo", rtflag]
159 + cflags
160 + ldflags
161 )
162
163 else:
164 # construct an invocation of the default C compiler
165 cc = os.environ.get("CC", "cc")
166 args = [cc, "-std=c17", src, "-o", dst] + cflags + ldflags
167
168 # compile the program
169 try:
170 run_raw(args)
171 except subprocess.CalledProcessError:
172 try:
173 os.remove(dst)
174 except (FileNotFoundError, PermissionError):
175 pass
176 raise
177
178 return dst
179
180
181 def dot(
182 T: str, source_file: Optional[Path] = None, source: Optional[str] = None
183 ) -> Union[bytes, str]:
184 """
185 run Graphviz on the given source file or text
186
187 Args:
188 T: Output format, as would be supplied to `-T` on the command line.
189 source_file: Input file to parse. Can be `None` if `source` is provided
190 instead.
191 source: Input text to parse. Can be `None` if `source_file` is provided
192 instead.
193
194 Returns:
195 Dot output as text if a textual format was selected or as binary if not.
196 """
197
198 assert (
199 source_file is not None or source is not None
200 ), "one of `source_file` or `source` needs to be provided"
201
202 # is the output format a textual format?
203 output_is_text = T in (
204 "canon",
205 "cmapx",
206 "dot",
207 "fig",
208 "gv",
209 "json",
210 "pic",
211 "svg",
212 "svg_inline",
213 "xdot",
214 "xdot1.2",
215 "xdot1.4",
216 )
217
218 kwargs = {}
219 if output_is_text:
220 kwargs["encoding"] = "utf-8"
221 kwargs["text"] = True
222
223 args = ["dot", f"-T{T}"]
224
225 if source_file is not None:
226 args += [source_file]
227 elif not output_is_text:
228 kwargs["input"] = source.encode("utf-8")
229 else:
230 kwargs["input"] = source
231
232 # dump the command being run for the user to observe if the test fails
233 print(f"+ {shlex.join(str(x) for x in args)}")
234
235 proc = subprocess.run(args, stdout=subprocess.PIPE, check=True, **kwargs)
236 return proc.stdout
237
238
239 def freedesktop_os_release() -> dict[str, str]:
240 """
241 polyfill for `platform.freedesktop_os_release`
242 """
243 release = {}
244 os_release = Path("/etc/os-release")
245 if os_release.exists():
246 with open(os_release, "rt", encoding="utf-8") as f:
247 for line in f.readlines():
248 if line.startswith("#") or "=" not in line:
249 continue
250 key, _, value = (x.strip() for x in line.partition("="))
251 # remove quotes
252 if len(value) >= 2 and value[0] == '"' and value[-1] == '"':
253 value = value[1:-1]
254 release[key] = value
255 return release
256
257
258 def gvpr(program: Path) -> str:
259 """run a GVPR program on empty input"""
260
261 assert which("gvpr") is not None, "attempt to run GVPR without it available"
262
263 return run(["gvpr", "-f", program], stdin=subprocess.DEVNULL)
264
265
266 def build_system() -> str:
267 """get the build system name"""
268 if platform.system() == "Windows":
269 return "cmake"
270 return os.getenv("build_system")
271
272
273 def is_asan_instrumented(binary: Path) -> bool:
274 """
275 is the given binary using Address Sanitizer?
276
277 This function returns false negatives (incorrectly says “False” for
278 ASan-instrumented binaries) if there is no tool for inspecting symbol tables or if
279 the symbol table has been stripped.
280 """
281 assert binary.exists()
282
283 # Get the symbol table of the binary. We deliberately avoid `text=True` to tolerate
284 # non-ASCII bytes in the symbol table.
285 if objdump := shutil.which("objdump"):
286 symbols = run_raw([objdump, "--syms", binary])
287 elif llvm_objdump := shutil.which("llvm-objdump"):
288 symbols = run_raw([llvm_objdump, "--syms", binary])
289 elif dumpbin := shutil.which("dumpbin"):
290 dependencies = run_raw([dumpbin, "/DEPENDENTS", binary])
291 # Look for the ASan DLL dependency
292 return (
293 re.search(rb"\bclang_rt\.asan_dynamic-.*\.dll\b", dependencies) is not None
294 )
295 else:
296 # if we cannot examine the symbol table, assume ASan is not in use
297 return False
298
299 # Look for a reference to a known ASan symbol. This exists even if ASan has been
300 # statically linked (`-static-libasan`).
301 return re.search(rb"\b__asan_init\b", symbols) is not None
302
303
304 def is_autotools() -> bool:
305 """was the Grapviz under test built with Autotools?"""
306 if platform.system() == "Windows":
307 return False
308 return not is_cmake()
309
310
311 def is_cmake() -> bool:
312 """was the Graphviz under test built with CMake?"""
313 return build_system() == "cmake"
314
315
316 def is_fedora() -> bool:
317 """is the current environment Fedora?"""
318 return freedesktop_os_release().get("ID") == "fedora"
319
320
321 def is_fedora_43() -> bool:
322 """is the current environment Fedora 43?"""
323 if not is_fedora():
324 return False
325 return freedesktop_os_release().get("VERSION_ID") == "43"
326
327
328 def is_macos() -> bool:
329 """is the current platform macOS?"""
330 return platform.system() == "Darwin"
331
332
333 def is_mingw() -> bool:
334 """is the current platform MinGW?"""
335 return "mingw" in sysconfig.get_platform()
336
337
338 def is_static_build() -> bool:
339 """was the build we are testing done with static linking?"""
340
341 if os.environ.get("BUILD_SHARED_LIBS") == "OFF":
342 return True
343
344 # answer “no” to other scenarios, even when some of them are statically
345 # linked, because the test suite is unaffected
346 return False
347
348
349 def is_ubuntu() -> bool:
350 """is the current environment Ubuntu?"""
351 return freedesktop_os_release().get("ID") == "ubuntu"
352
353
354 def is_ubuntu_2404() -> bool:
355 """is the current environment Ubuntu 24.04?"""
356 if not is_ubuntu():
357 return False
358 return freedesktop_os_release().get("VERSION_ID") == "24.04"
359
360
361 def is_ubuntu_2504() -> bool:
362 """is the current environment Ubuntu 25.04?"""
363 if not is_ubuntu():
364 return False
365 return freedesktop_os_release().get("VERSION_ID") == "25.04"
366
367
368 def is_ubuntu_2510() -> bool:
369 """is the current environment Ubuntu 25.10?"""
370 if not is_ubuntu():
371 return False
372 return freedesktop_os_release().get("VERSION_ID") == "25.10"
373
374
375 def remove_asan_summary(s: str) -> str:
376 """
377 Remove the “Suppressions used…” informational text Address Sanitizer prints.
378 This is useful but can interfere with our ability to scan output for expected
379 content.
380 """
381 return re.sub(r"-+\nSuppressions used:[^\-]+-+\n?\n?", "", s)
382
383
384 def remove_xtype_warnings(s: str) -> str:
385 """
386 Remove macOS XType warnings from a string. These appear to be harmless, but
387 occur in CI.
388 """
389
390 # avoid doing this anywhere except on macOS
391 if not is_macos():
392 return s
393
394 return re.sub(r"^.* XType: .*\.$\n", "", s, flags=re.MULTILINE)
395
396
397 def is_rocky(wanted_version_id: Optional[str] = None) -> bool:
398 """
399 is the current environment Rocky Linux? And if specified, is it version `wanted_version_id`?
400 """
401 if freedesktop_os_release().get("ID") != "rocky":
402 return False
403 if wanted_version_id is None:
404 return True
405 version_id = freedesktop_os_release().get("VERSION_ID")
406 if version_id is None:
407 return False
408 return re.match(rf"{wanted_version_id}\b", version_id) is not None
409
410
411 def is_rocky_8() -> bool:
412 """
413 is the current environment Rocky Linux 8?
414 """
415 return is_rocky("8")
416
417
418 def has_sandbox() -> bool:
419 """
420 do we have an available sandbox mechanism?
421
422 The logic here should correspond to available `Sandbox` back ends in
423 ../cmd/dot/dot_sandbox.
424 """
425 if shutil.which("bwrap"):
426 return True
427 if platform.system() == "Darwin":
428 return True
429 return False
430
431
432 def plugin_version() -> tuple[int, int, int]:
433 """get the Graphviz plugin libtool revision, current, age"""
434
435 # treat configure.ac as the canonical source of this information
436 configure_ac = Path(__file__).resolve().parents[1] / "configure.ac"
437
438 # parse out the version components
439 current: Optional[int] = None
440 revision: Optional[int] = None
441 age: Optional[int] = None
442 with open(configure_ac, "rt", encoding="utf-8") as f:
443 for line in f:
444 if m := re.match(r"\s*GVPLUGIN_CURRENT\s*=\s*(?P<current>\d+)\s*$", line):
445 current = int(m.group("current"))
446 if revision is not None and age is not None:
447 break
448 continue
449 if m := re.match(r"\s*GVPLUGIN_REVISION\s*=\s*(?P<revision>\d+)\s*$", line):
450 revision = int(m.group("revision"))
451 if current is not None and age is not None:
452 break
453 continue
454 if m := re.match(r"\s*GVPLUGIN_AGE\s*=\s*(?P<age>\d+)\s*$", line):
455 age = int(m.group("age"))
456 if current is not None and revision is not None:
457 break
458 continue
459 assert current is not None, "failed to parse plugin version"
460 assert revision is not None, "failed to parse plugin version"
461 assert age is not None, "failed to parse plugin version"
462
463 return current, revision, age
464
465
466 def run_c(
467 src: Path,
468 args: list[Union[Path, str]] = None,
469 input: str = "",
470 cflags: list[str] = None,
471 link: list[Union[Path, str]] = None,
472 ) -> tuple[str, str]:
473 """compile and run a C program"""
474
475 if args is None:
476 args = []
477 if cflags is None:
478 cflags = []
479 if link is None:
480 link = []
481
482 # create some temporary space to work in
483 with tempfile.TemporaryDirectory() as tmp:
484 # output filename to write our compiled code to
485 exe = Path(tmp) / "a.exe"
486
487 # compile the program
488 compile_c(src, cflags, link, exe)
489
490 # dump the command being run for the user to observe if the test fails
491 argv = [exe] + args
492 print(f"+ {shlex.join(str(x) for x in argv)}")
493
494 input_bytes = None
495 if input is not None:
496 input_bytes = input.encode("utf-8")
497
498 # run it
499 p = subprocess.run(argv, input=input_bytes, capture_output=True, check=False)
500
501 # decode output manually rather than using `text=True` above to avoid exceptions
502 # from non-UTF-8 bytes in the output
503 stdout = p.stdout.decode("utf-8", "replace")
504 stderr = p.stderr.decode("utf-8", "replace")
505
506 # check it succeeded
507 if p.returncode != 0:
508 sys.stdout.write(stdout)
509 sys.stderr.write(stderr)
510 p.check_returncode()
511
512 return stdout, stderr
513
514
515 def which(cmd: str) -> Optional[Path]:
516 """
517 `shutil.which` but only return results that are adjacent to the main Graphviz
518 executable.
519
520 Graphviz has numerous optional components. So if you choose to e.g. disable
521 `mingle` during compilation and installation, you may find that a naive
522 `shutil.which("mingle")` after this returns the `mingle` from a prior
523 system-wide installation of the full Graphviz. This is undesirable during
524 testing, as this older `mingle` will then load shared libraries from the
525 installation you just created, most likely crashing.
526 """
527
528 # try a straightforward lookup of the command
529 abs_cmd = shutil.which(cmd)
530 if abs_cmd is None:
531 return None
532 abs_cmd = Path(abs_cmd)
533
534 # where does the main Graphviz program live?
535 abs_dot = shutil.which("dot")
536 assert abs_dot is not None, "dot not in $PATH"
537 abs_dot = Path(abs_dot)
538
539 # discard the result we found if it does not live in the same directory
540 if abs_cmd.parent != abs_dot.parent:
541 return None
542
543 return abs_cmd