Debian Codegraph @

tests/test_regression.py

raw
1 """
2 Graphviz regression tests
3
4 The test cases in this file relate to previously observed bugs. A failure of one
5 of these indicates that a past bug has been reintroduced.
6 """
7
8 import dataclasses
9 import hashlib
10 import io
11 import json
12 import math
13 import os
14 import platform
15 import re
16 import shlex
17 import shutil
18 import signal
19 import stat
20 import statistics
21 import subprocess
22 import sys
23 import tempfile
24 import textwrap
25 import time
26 import xml.etree.ElementTree as ET
27 from pathlib import Path
28 from typing import Iterator, Optional, Union
29
30 import pexpect
31 import pytest
32 from PIL import Image
33
34 sys.path.append(os.path.dirname(__file__))
35 from gvtest import ( # pylint: disable=wrong-import-position
36 compile_c,
37 dot,
38 gvpr,
39 is_asan_instrumented,
40 is_autotools,
41 is_cmake,
42 is_fedora_43,
43 is_macos,
44 is_mingw,
45 is_rocky,
46 is_rocky_8,
47 is_static_build,
48 plugin_version,
49 remove_asan_summary,
50 remove_xtype_warnings,
51 run,
52 run_c,
53 run_raw,
54 which,
55 )
56
57
58 def is_ndebug_defined() -> bool:
59 """
60 are assertions disabled in the Graphviz build under test?
61 """
62
63 # the Windows release builds set NDEBUG
64 if os.environ.get("configuration") == "Release":
65 return True
66
67 return False
68
69
70 def test_14():
71 """
72 using ortho and twopi in combination should not cause an assertion failure
73 https://gitlab.com/graphviz/graphviz/-/issues/14
74 """
75
76 # locate our associated test case in this directory
77 input = Path(__file__).parent / "14.dot"
78 assert input.exists(), "unexpectedly missing test case"
79
80 # process it with Graphviz
81 dot("svg", input)
82
83
84 @pytest.mark.skipif(which("neato") is None, reason="neato not available")
85 def test_42():
86 """
87 check for a former crash in neatogen
88 https://gitlab.com/graphviz/graphviz/-/issues/42
89 """
90
91 # locate our associated test case in this directory
92 input = Path(__file__).parent / "42.dot"
93 assert input.exists(), "unexpectedly missing test case"
94
95 # process it with Graphviz
96 neato = which("neato")
97 run_raw([neato, "-n2", "-Tpng", input], stdout=subprocess.DEVNULL)
98
99
100 def test_56():
101 """
102 parsing a particular graph should not cause a Trapezoid-table overflow
103 assertion failure
104 https://gitlab.com/graphviz/graphviz/-/issues/56
105 """
106
107 # locate our associated test case in this directory
108 input = Path(__file__).parent / "56.dot"
109 assert input.exists(), "unexpectedly missing test case"
110
111 # process it with Graphviz
112 dot("svg", input)
113
114
115 def test_121():
116 """
117 test a graph that previously caused an assertion failure in `merge_chain`
118 https://gitlab.com/graphviz/graphviz/-/issues/121
119 """
120
121 # locate our associated test case in this directory
122 input = Path(__file__).parent / "121.dot"
123 assert input.exists(), "unexpectedly missing test case"
124
125 # process it with Graphviz
126 dot("pdf", input)
127
128
129 def test_131():
130 """
131 PIC back end should produce valid output
132 https://gitlab.com/graphviz/graphviz/-/issues/131
133 """
134
135 # a basic graph
136 src = "digraph { a -> b; c -> d; }"
137
138 # ask Graphviz to process this to PIC
139 pic = dot("pic", source=src)
140
141 if which("gpic") is None:
142 pytest.skip("GNU PIC not available")
143
144 # ask GNU PIC to process the Graphviz output
145 run(["gpic"], input=pic, stdout=subprocess.DEVNULL)
146
147
148 @pytest.mark.parametrize("testcase", ("144_no_ortho.dot", "144_ortho.dot"))
149 def test_144(testcase: str):
150 """
151 using ortho should not result in head/tail confusion
152 https://gitlab.com/graphviz/graphviz/-/issues/144
153 """
154
155 # locate our associated test cases in this directory
156 input = Path(__file__).parent / testcase
157 assert input.exists(), "unexpectedly missing test case"
158
159 # process the non-ortho one into JSON
160 out = dot("json", input)
161 data = json.loads(out)
162
163 # find the nodes “A”, “B” and “C”
164 A = [x for x in data["objects"] if x["name"] == "A"][0]
165 B = [x for x in data["objects"] if x["name"] == "B"][0]
166 C = [x for x in data["objects"] if x["name"] == "C"][0]
167
168 # find the straight A→B and the angular A→C edges
169 straight_edge = [
170 x for x in data["edges"] if x["tail"] == A["_gvid"] and x["head"] == B["_gvid"]
171 ][0]
172 angular_edge = [
173 x for x in data["edges"] if x["tail"] == A["_gvid"] and x["head"] == C["_gvid"]
174 ][0]
175
176 # the A→B edge should have been routed vertically down
177 straight_points = straight_edge["_draw_"][1]["points"]
178 xs = [x for x, _ in straight_points]
179 ys = [y for _, y in straight_points]
180 assert all(x == xs[0] for x in xs), "A->B not routed vertically"
181 assert ys == sorted(ys, reverse=True), "A->B is not routed down"
182
183 # determine Graphviz’ idea of head and tail ends
184 straight_head_point = straight_edge["_hdraw_"][3]["points"][0]
185 straight_tail_point = straight_edge["_tdraw_"][3]["points"][0]
186 assert straight_head_point[1] < straight_tail_point[1], "A->B head/tail confusion"
187
188 # the A→C edge should have been routed in zigzag down and right
189 angular_points = angular_edge["_draw_"][1]["points"]
190 xs = [x for x, _ in angular_points]
191 ys = [y for _, y in angular_points]
192 assert xs == sorted(xs), "A->B is not routed down"
193 assert ys == sorted(ys, reverse=True), "A->B is not routed right"
194
195 # determine Graphviz’ idea of head and tail ends
196 angular_head_point = angular_edge["_hdraw_"][3]["points"][0]
197 angular_tail_point = angular_edge["_tdraw_"][3]["points"][0]
198 assert angular_head_point[0] > angular_tail_point[0], "A->C head/tail confusion"
199
200
201 def test_146():
202 """
203 dot should respect an alpha channel value of 0 when writing SVG
204 https://gitlab.com/graphviz/graphviz/-/issues/146
205 """
206
207 # a graph using white text but with 0 alpha
208 source = (
209 "graph {\n"
210 ' n[style="filled", fontcolor="#FFFFFF00", label="hello world"];\n'
211 "}"
212 )
213
214 # ask Graphviz to process this
215 svg = dot("svg", source=source)
216
217 # the SVG should be setting opacity
218 opacity = re.search(r'\bfill-opacity="(\d+(\.\d+)?)"', svg)
219 assert opacity is not None, "transparency not set for alpha=0 color"
220
221 # it should be zeroed
222 assert (
223 float(opacity.group(1)) == 0
224 ), "alpha=0 color set to something non-transparent"
225
226
227 def test_162():
228 """
229 `minlen=0` should not duplicate edges
230 https://gitlab.com/graphviz/graphviz/-/issues/162
231 """
232
233 # locate our associated test case in this directory
234 input = Path(__file__).parent / "162.dot"
235 assert input.exists(), "unexpectedly missing test case"
236
237 # lay this out
238 layout = dot("dot", input)
239
240 # find an inter-cluster edge
241 m = re.search(
242 r'\bC\s*->\s*D\s*\[\s*minlen\s*=\s*0\s*,\s*pos\s*=\s*"(?P<position>[^"]*)"',
243 layout,
244 )
245 assert m is not None, "could not locate C->D edge"
246
247 edge_count = len(re.findall(r"\be\b", m.group("position")))
248 assert edge_count == 1, "incorrect number of inter-cluster edges"
249
250
251 def test_165():
252 """
253 dot should be able to produce properly escaped xdot output
254 https://gitlab.com/graphviz/graphviz/-/issues/165
255 """
256
257 # locate our associated test case in this directory
258 input = Path(__file__).parent / "165.dot"
259 assert input.exists(), "unexpectedly missing test case"
260
261 # ask Graphviz to translate it to xdot
262 output = dot("xdot", input)
263
264 # find the line containing the _ldraw_ attribute
265 ldraw = re.search(r"^\s*_ldraw_\s*=(?P<value>.*?)$", output, re.MULTILINE)
266 assert ldraw is not None, "no _ldraw_ attribute in graph"
267
268 # this should contain the label correctly escaped
269 assert r"hello \\\" world" in ldraw.group("value"), "unexpected ldraw contents"
270
271
272 def test_165_2():
273 """
274 variant of test_165() that checks a similar problem for edges
275 https://gitlab.com/graphviz/graphviz/-/issues/165
276 """
277
278 # locate our associated test case in this directory
279 input = Path(__file__).parent / "165_2.dot"
280 assert input.exists(), "unexpectedly missing test case"
281
282 # ask Graphviz to translate it to xdot
283 output = dot("xdot", input)
284
285 # find the lines containing _ldraw_ attributes
286 ldraw = re.findall(r"^\s*_ldraw_\s*=(.*?)$", output, re.MULTILINE)
287 assert ldraw is not None, "no _ldraw_ attributes in graph"
288
289 # one of these should contain the label correctly escaped
290 assert any(r"hello \\\" world" in l for l in ldraw), "unexpected ldraw contents"
291
292
293 def test_165_3():
294 """
295 variant of test_165() that checks a similar problem for graph labels
296 https://gitlab.com/graphviz/graphviz/-/issues/165
297 """
298
299 # locate our associated test case in this directory
300 input = Path(__file__).parent / "165_3.dot"
301 assert input.exists(), "unexpectedly missing test case"
302
303 # ask Graphviz to translate it to xdot
304 output = dot("xdot", input)
305
306 # find the lines containing _ldraw_ attributes
307 ldraw = re.findall(r"^\s*_ldraw_\s*=(.*?)$", output, re.MULTILINE)
308 assert ldraw is not None, "no _ldraw_ attributes in graph"
309
310 # one of these should contain the label correctly escaped
311 assert any(r"hello \\\" world" in l for l in ldraw), "unexpected ldraw contents"
312
313
314 def test_167():
315 """
316 using concentrate=true should not result in a segfault
317 https://gitlab.com/graphviz/graphviz/-/issues/167
318 """
319
320 # locate our associated test case in this directory
321 input = Path(__file__).parent / "167.dot"
322 assert input.exists(), "unexpectedly missing test case"
323
324 # process this with dot
325 ret = subprocess.call(["dot", "-Tpdf", "-o", os.devnull, input])
326
327 # Graphviz should not have caused a segfault
328 assert ret != -signal.SIGSEGV, "Graphviz segfaulted"
329
330
331 def test_191():
332 """
333 a comma-separated list without quotes should cause a hard error, not a warning
334 https://gitlab.com/graphviz/graphviz/-/issues/191
335 """
336
337 source = (
338 "graph {\n"
339 ' "Trackable" [fontcolor=grey45,labelloc=c,fontname=Vera Sans, '
340 "DejaVu Sans, Liberation Sans, Arial, Helvetica, sans,shape=box,"
341 'height=0.3,align=center,fontsize=10,style="setlinewidth(0.5)"];\n'
342 "}"
343 )
344
345 with subprocess.Popen(
346 ["dot", "-Tdot"],
347 stdin=subprocess.PIPE,
348 stderr=subprocess.PIPE,
349 text=True,
350 ) as p:
351 _, stderr = p.communicate(source)
352
353 assert "syntax error" in stderr, "missing error message for unquoted list"
354
355 assert p.returncode != 0, "syntax error was only a warning, not an error"
356
357
358 def test_218():
359 """
360 out-of-spec font names should cause warnings in the core PS renderer
361 https://gitlab.com/graphviz/graphviz/-/issues/218
362 """
363
364 # a graph using a font name with a space in it
365 source = 'graph { a[fontname="PT Sans"]; }'
366
367 # render it to PS
368 warnings = run(
369 ["dot", "-Tps", "-o", os.devnull],
370 stderr=subprocess.STDOUT,
371 input=source,
372 )
373
374 assert warnings.strip() != "", "no warning issued for a font name containing space"
375
376
377 @pytest.mark.parametrize("test_case", ("241_0.dot", "241_1.dot"))
378 def test_241(test_case: str):
379 """
380 processing a graph with a `splines=…` setting should not causes warnings
381 https://gitlab.com/graphviz/graphviz/-/issues/241
382 """
383 # locate our associated test case in this directory
384 input = Path(__file__).parent / test_case
385 assert input.exists(), "unexpectedly missing test case"
386
387 proc = subprocess.run(
388 ["dot", "-Tsvg", "-o", os.devnull, input],
389 stderr=subprocess.PIPE,
390 text=True,
391 check=True,
392 )
393
394 assert (
395 "Something is probably seriously wrong" not in proc.stderr
396 ), "splines setting caused warnings"
397
398
399 def test_258():
400 """
401 cluster edges should not be duplicated
402 https://gitlab.com/graphviz/graphviz/-/issues/258
403 """
404
405 # locate our associated test case in this directory
406 input = Path(__file__).parent / "258.dot"
407 assert input.exists(), "unexpectedly missing test case"
408
409 # lay this out
410 layout = dot("dot", input)
411
412 # find an inter-cluster edge
413 m = re.search(
414 r'\bB\s*->\s*D\s*\[\s*constraint\s*=\s*none\s*,\s*pos\s*=\s*"(?P<position>[^"]*)"',
415 layout,
416 )
417 assert m is not None, "could not locate B->D edge"
418
419 edge_count = len(re.findall(r"\be\b", m.group("position")))
420 assert edge_count == 1, "incorrect number of inter-cluster edges"
421
422
423 def test_358():
424 """
425 setting xdot version to 1.7 should enable font characteristics
426 https://gitlab.com/graphviz/graphviz/-/issues/358
427 """
428
429 # locate our associated test case in this directory
430 input = Path(__file__).parent / "358.dot"
431 assert input.exists(), "unexpectedly missing test case"
432
433 # process this with dot
434 xdot = dot("xdot", input)
435
436 for i in range(6):
437 m = re.search(f"\\bt {1 << i}\\b", xdot)
438 assert m is not None, f"font characteristic {1 << i} not enabled in xdot 1.7"
439
440
441 @pytest.mark.parametrize("attribute", ("samehead", "sametail"))
442 def test_452(attribute: str):
443 """
444 more than 5 unique `samehead` and `sametail` values should be usable
445 https://gitlab.com/graphviz/graphviz/-/issues/452
446 """
447
448 # a graph using more than 5 of the same attribute with the same node on one
449 # side of each edge
450 graph = io.StringIO()
451 graph.write("digraph {\n")
452 for i in range(6):
453 if attribute == "samehead":
454 graph.write(f" m{i} -> n1")
455 else:
456 graph.write(f" n1 -> m{i}")
457 graph.write(f'[{attribute}="foo{i}"];\n')
458 graph.write("}\n")
459
460 # process this with dot
461 dot("svg", source=graph.getvalue())
462
463
464 def test_510():
465 """
466 HSV colors should also support an alpha channel
467 https://gitlab.com/graphviz/graphviz/-/issues/510
468 """
469
470 # a graph with a turquoise, partially transparent node
471 source = 'digraph { a [color="0.482 0.714 0.878 0.5"]; }'
472
473 # process this with dot
474 svg = dot("svg", source=source)
475
476 # see if we can locate an opacity adjustment
477 m = re.search(r'\bstroke-opacity="(?P<opacity>\d*.\d*)"', svg)
478 assert m is not None, "no stroke-opacity set; alpha channel ignored?"
479
480 # it should be something in-between transparent and opaque
481 opacity = float(m.group("opacity"))
482 assert opacity > 0, "node set transparent; misinterpreted alpha channel?"
483 assert opacity < 1, "node set opaque; misinterpreted alpha channel?"
484
485
486 @pytest.mark.skipif(
487 which("gv2gxl") is None or which("gxl2gv") is None, reason="GXL tools not available"
488 )
489 def test_517():
490 """
491 round tripping a graph through gv2gxl should not lose HTML labels
492 https://gitlab.com/graphviz/graphviz/-/issues/517
493 """
494
495 # our test case input
496 input = (
497 "digraph{\n"
498 " A[label=<<TABLE><TR><TD>(</TD><TD>A</TD><TD>)</TD></TR></TABLE>>]\n"
499 ' B[label="<TABLE><TR><TD>(</TD><TD>B</TD><TD>)</TD></TR></TABLE>"]\n'
500 "}"
501 )
502
503 # translate it to GXL
504 gv2gxl = which("gv2gxl")
505 gxl = run([gv2gxl], input=input)
506
507 # translate this back to Dot
508 gxl2gv = which("gxl2gv")
509 dot_output = run([gxl2gv], input=gxl)
510
511 # the result should have both expected labels somewhere
512 assert (
513 "label=<<TABLE><TR><TD>(</TD><TD>A</TD><TD>)</TD></TR></TABLE>>" in dot_output
514 ), "HTML label missing"
515 assert (
516 'label="<TABLE><TR><TD>(</TD><TD>B</TD><TD>)</TD></TR></TABLE>"' in dot_output
517 ), "regular label missing"
518
519
520 def test_793():
521 """
522 Graphviz should not crash when using VRML output with a non-writable current
523 directory
524 https://gitlab.com/graphviz/graphviz/-/issues/793
525 """
526
527 # create a non-writable directory
528 with tempfile.TemporaryDirectory() as tmp:
529 t = Path(tmp)
530 t.chmod(t.stat().st_mode & ~stat.S_IWRITE)
531
532 # ask the VRML back end to handle a simple graph, using the above as the
533 # current working directory
534 with subprocess.Popen(["dot", "-Tvrml", "-o", os.devnull], cwd=t) as p:
535 p.communicate("digraph { a -> b; }")
536
537 # Graphviz should not have caused a segfault
538 assert p.returncode != -signal.SIGSEGV, "Graphviz segfaulted"
539
540
541 def test_797():
542 """
543 “&;” should not be considered an XML escape sequence
544 https://gitlab.com/graphviz/graphviz/-/issues/797
545 """
546
547 # some input containing the invalid escape
548 input = 'digraph tree {\n"1" [shape="box", label="&amp; &amp;;", URL="a"];\n}'
549
550 # process this with the client-side imagemap back end
551 output = dot("cmapx", source=input)
552
553 # the escape sequences should have been preserved
554 assert "&amp; &amp;" in output
555
556
557 @pytest.mark.xfail(
558 strict=True, reason="https://gitlab.com/graphviz/graphviz/-/issues/813"
559 )
560 def test_813():
561 """
562 nodes with multiple peripheries should still have a stable rendering
563 https://gitlab.com/graphviz/graphviz/-/issues/813
564 """
565
566 # locate our associated test case in this directory
567 input = Path(__file__).parent / "813.dot"
568 assert input.exists(), "unexpectedly mising test case"
569
570 # render this to dot
571 reference = dot("dot", input)
572
573 # run it through multiple passes
574 iterated = reference
575 for _ in range(4):
576 iterated = dot("dot", source=iterated)
577
578 assert (
579 reference == iterated
580 ), "rendering of shapes with multiple peripheries is unstable"
581
582
583 def test_827():
584 """
585 Graphviz should not crash when processing the b15.gv example
586 https://gitlab.com/graphviz/graphviz/-/issues/827
587 """
588
589 b15gv = Path(__file__).parent / "graphs/b15.gv"
590 assert b15gv.exists(), "missing test case file"
591
592 dot("svg", b15gv)
593
594
595 def test_925():
596 """
597 spaces should be handled correctly in UTF-8-containing labels in record shapes
598 https://gitlab.com/graphviz/graphviz/-/issues/925
599 """
600
601 # locate our associated test case in this directory
602 input = Path(__file__).parent / "925.dot"
603 assert input.exists(), "unexpectedly mising test case"
604
605 # process this with dot
606 svg = dot("svg", input)
607
608 # The output should include the correctly spaced UTF-8 label. Note that these
609 # are not ASCII capital As in this string, but rather UTF-8 Cyrillic Capital
610 # Letter As.
611 assert "ААА ААА ААА" in svg, "incorrect spacing in UTF-8 label"
612
613
614 @pytest.mark.parametrize("testcase", ("1213-1.dot", "1213-2.dot"))
615 @pytest.mark.xfail(
616 strict=True, reason="https://gitlab.com/graphviz/graphviz/-/issues/1213"
617 )
618 def test_1213(testcase: str):
619 """
620 clustering should not trigger “trouble in init_rank” errors
621 https://gitlab.com/graphviz/graphviz/-/issues/1213
622 """
623
624 # locate our associated test case in this directory
625 input = Path(__file__).parent / testcase
626 assert input.exists(), "unexpectedly mising test case"
627
628 # process this with dot
629 dot("png", input)
630
631
632 def test_1221():
633 """
634 assigning a node to two clusters with newrank should not cause a crash
635 https://gitlab.com/graphviz/graphviz/-/issues/1221
636 """
637
638 # locate our associated test case in this directory
639 input = Path(__file__).parent / "1221.dot"
640 assert input.exists(), "unexpectedly missing test case"
641
642 # process this with dot
643 dot("svg", input)
644
645
646 @pytest.mark.skipif(which("gv2gml") is None, reason="gv2gml not available")
647 def test_1276():
648 """
649 quotes within a label should be escaped in translation to GML
650 https://gitlab.com/graphviz/graphviz/-/issues/1276
651 """
652
653 # DOT input containing a label with quotes
654 src = 'digraph test {\n x[label=<"Label">];\n}'
655
656 # process this to GML
657 gv2gml = which("gv2gml")
658 gml = run([gv2gml], input=src)
659
660 # the unescaped label should not appear in the output
661 assert '""Label""' not in gml, "quotes not escaped in label"
662
663 # the escaped label should appear in the output
664 assert (
665 '"&quot;Label&quot;"' in gml or '"&#34;Label&#34;"' in gml
666 ), "escaped label not found in GML output"
667
668
669 def test_1308():
670 """
671 processing a minimized graph found by Google Autofuzz should not crash
672 https://gitlab.com/graphviz/graphviz/-/issues/1308
673 """
674
675 # locate our associated test case in this directory
676 input = Path(__file__).parent / "1308.dot"
677 assert input.exists(), "unexpectedly missing test case"
678
679 # run it through Graphviz
680 dot("svg", input)
681
682
683 def test_1308_1():
684 """
685 processing a malformed graph found by Google Autofuzz should not crash
686 https://gitlab.com/graphviz/graphviz/-/issues/1308
687 """
688
689 # locate our associated test case in this directory
690 input = Path(__file__).parent / "1308_1.dot"
691 assert input.exists(), "unexpectedly missing test case"
692
693 # run it through Graphviz
694 ret = subprocess.call(["dot", "-Tsvg", "-o", os.devnull, input])
695
696 assert ret in (0, 1), "Graphviz crashed when processing malformed input"
697 assert ret == 1, "Graphviz did not reject malformed input"
698
699
700 def test_1314():
701 """
702 test that a large font size that produces an overflow in Pango is rejected
703 https://gitlab.com/graphviz/graphviz/-/issues/1314
704 """
705
706 # locate our associated test case in this directory
707 input = Path(__file__).parent / "1314.dot"
708 assert input.exists(), "unexpectedly missing test case"
709
710 # ask Graphviz to process it, which should fail
711 with pytest.raises(subprocess.CalledProcessError):
712 dot("svg", input)
713
714
715 def test_1318():
716 """
717 processing a large number in a comment should not trigger integer overflow
718 https://gitlab.com/graphviz/graphviz/-/issues/1318
719 """
720
721 # sample input consisting of a large number in a comment
722 source = "#8828066547613302784"
723
724 # processing this should succeed
725 dot("svg", source=source)
726
727
728 @pytest.mark.parametrize("testcase", ("1323.dot", "1323_1.dot"))
729 @pytest.mark.xfail(
730 strict=True, reason="https://gitlab.com/graphviz/graphviz/-/issues/1323"
731 )
732 def test_1323(testcase: str):
733 """
734 these graphs should not generate triangulation warnings/errors
735 https://gitlab.com/graphviz/graphviz/-/issues/1323
736 """
737
738 # locate our associated test case in this directory
739 input = Path(__file__).parent / testcase
740 assert input.exists(), "unexpectedly missing test case"
741
742 stderr = run(["dot", "-Tpng", "-o", os.devnull, input], stderr=subprocess.STDOUT)
743
744 assert (
745 re.search(r"\btriangulation failed\b", stderr) is None
746 ), "triangulation warnings were produced"
747 assert re.search(r"\bError\b", stderr) is None, "error messages were produced"
748
749
750 def test_1328():
751 """
752 a node with conflicting rank constraints should not cause a crash
753 https://gitlab.com/graphviz/graphviz/-/issues/1328
754 """
755
756 # locate our associated test case in this directory
757 input = Path(__file__).parent / "1328.dot"
758 assert input.exists(), "unexpectedly missing test case"
759
760 proc = subprocess.run(
761 ["dot", "-Tsvg", "-o", os.devnull, input],
762 stderr=subprocess.PIPE,
763 check=False,
764 text=True,
765 )
766
767 assert proc.returncode in (0, 1), "multiple rank constraints caused a crash"
768
769
770 def test_1332():
771 """
772 Triangulation calculation on the associated example should succeed.
773
774 A prior change that was intended to increase accuracy resulted in the
775 example in this test now failing some triangulation calculations. It is not
776 clear whether the outcome before or after is correct, but this test ensures
777 that the older behavior users are accustomed to is preserved.
778 """
779
780 # locate our associated test case in this directory
781 input = Path(__file__).parent / "1332.dot"
782 assert input.exists(), "unexpectedly missing test case"
783
784 # process it with Graphviz
785 warnings = run(["dot", "-Tpdf", "-o", os.devnull, input], stderr=subprocess.STDOUT)
786
787 # work around macOS warnings
788 warnings = remove_xtype_warnings(warnings).strip()
789
790 # no warnings should have been printed
791 assert (
792 warnings == ""
793 ), "warnings were printed when processing graph involving triangulation"
794
795
796 def test_1367():
797 """
798 this graph should not generate a null pointer dereference
799 https://gitlab.com/graphviz/graphviz/-/issues/1367
800 """
801
802 # locate our associated test case in this directory
803 input = Path(__file__).parent / "1367.dot"
804 assert input.exists(), "unexpectedly missing test case"
805
806 # Pass it through Graphviz. Do not use `dot(…)` because input and output contain
807 # invalid UTF-8.
808 run_raw(["dot", "-Txdot:xdot:core", "-o", os.devnull, input])
809
810
811 def test_1408():
812 """
813 parsing particular ortho layouts should not cause an assertion failure
814 https://gitlab.com/graphviz/graphviz/-/issues/1408
815 """
816
817 # locate our associated test case in this directory
818 input = Path(__file__).parent / "1408.dot"
819 assert input.exists(), "unexpectedly missing test case"
820
821 # process it with Graphviz
822 dot("svg", input)
823
824
825 def test_1411():
826 """
827 parsing strings containing newlines should not disrupt line number tracking
828 https://gitlab.com/graphviz/graphviz/-/issues/1411
829 """
830
831 # locate our associated test case in this directory
832 input = Path(__file__).parent / "1411.dot"
833 assert input.exists(), "unexpectedly missing test case"
834
835 # process it with Graphviz (should fail)
836 with subprocess.Popen(
837 ["dot", "-Tsvg", "-o", os.devnull, input],
838 stderr=subprocess.PIPE,
839 text=True,
840 ) as p:
841 _, output = p.communicate()
842
843 assert p.returncode != 0, "Graphviz accepted broken input"
844
845 assert (
846 "syntax error in line 17 near '\\'" in output
847 ), "error message did not identify correct location"
848
849
850 def test_1425():
851 """
852 tooltips should propagate to SVG even without an HREF
853 https://gitlab.com/graphviz/graphviz/-/issues/1425
854 """
855
856 # locate our associated test case in this directory
857 input = Path(__file__).parent / "1425.dot"
858 assert input.exists(), "unexpectedly missing test case"
859
860 # translate this to SVG
861 svg = dot("svg", input)
862
863 assert re.search(r"\btable tip\b", svg) is not None, "tooltip not propagated to SVG"
864
865
866 def test_1425_1():
867 """
868 tooltips should propagate to SVG even without an HREF
869 https://gitlab.com/graphviz/graphviz/-/issues/1425
870 """
871
872 # locate our associated test case in this directory
873 input = Path(__file__).parent / "1425_1.dot"
874 assert input.exists(), "unexpectedly missing test case"
875
876 # translate this to SVG
877 svg = dot("svg", input)
878
879 assert (
880 re.search(r"\bgreek to me\b", svg) is not None
881 ), "tooltip not propagated to SVG"
882 assert re.search(r"\benglish\b", svg) is not None, "tooltip not propagated to SVG"
883 assert (
884 re.search(r"\bleave a tip\b", svg) is not None
885 ), "tooltip not propagated to SVG"
886 assert (
887 re.search(r"\bcell tool tip\b", svg) is not None
888 ), "tooltip not propagated to SVG"
889 assert re.search(r"\btd tip\b", svg) is not None, "tooltip not propagated to SVG"
890 assert re.search(r"\btable tip\b", svg) is not None, "tooltip not propagated to SVG"
891
892
893 @pytest.mark.xfail(
894 strict=True, reason="https://gitlab.com/graphviz/graphviz/-/issues/1435"
895 )
896 def test_1435():
897 """
898 triangulation paths should be findable on this graph
899 https://gitlab.com/graphviz/graphviz/-/issues/1435
900 """
901
902 # locate our associated test case in this directory
903 input = Path(__file__).parent / "1435.dot"
904 assert input.exists(), "unexpectedly missing test case"
905
906 # process it with Graphviz
907 err = run(["dot", "-Tpng", "-o", os.devnull, input], stderr=subprocess.STDOUT)
908
909 assert err.strip() == "", "errors were printed"
910
911
912 def test_1436():
913 """
914 test a segfault from https://gitlab.com/graphviz/graphviz/-/issues/1436 has
915 not reappeared
916 """
917
918 # locate our associated test case in this directory
919 input = Path(__file__).parent / "1436.dot"
920 assert input.exists(), "unexpectedly missing test case"
921
922 # ask Graphviz to process it, which should generate a segfault if this bug
923 # has been reintroduced
924 dot("svg", input)
925
926
927 def test_1444():
928 """
929 specifying 'headport' as an edge attribute should work regardless of what
930 order attributes appear in
931 https://gitlab.com/graphviz/graphviz/-/issues/1444
932 """
933
934 # locate the first of our associated tests
935 input1 = Path(__file__).parent / "1444.dot"
936 assert input1.exists(), "unexpectedly missing test case"
937
938 # ask Graphviz to process it
939 with subprocess.Popen(
940 ["dot", "-Tsvg", input1],
941 stdout=subprocess.PIPE,
942 stderr=subprocess.PIPE,
943 text=True,
944 ) as p:
945 stdout1, stderr = p.communicate()
946
947 assert p.returncode == 0, "failed to process a headport edge"
948
949 stderr = remove_xtype_warnings(stderr).strip()
950 stderr = remove_asan_summary(stderr)
951 assert stderr == "", "emitted an error for a legal graph"
952
953 # now locate our second variant, that simply has the attributes swapped
954 input2 = Path(__file__).parent / "1444-2.dot"
955 assert input2.exists(), "unexpectedly missing test case"
956
957 # process it identically
958 with subprocess.Popen(
959 ["dot", "-Tsvg", input2],
960 stdout=subprocess.PIPE,
961 stderr=subprocess.PIPE,
962 text=True,
963 ) as p:
964 stdout2, stderr = p.communicate()
965
966 assert p.returncode == 0, "failed to process a headport edge"
967
968 stderr = remove_xtype_warnings(stderr).strip()
969 assert stderr == "", "emitted an error for a legal graph"
970
971 assert stdout1 == stdout2, "swapping edge attributes altered the output graph"
972
973
974 def test_1447():
975 """
976 graphs should not fail assertions in maze.c
977 https://gitlab.com/graphviz/graphviz/-/issues/1447
978 """
979
980 # locate our associated test case in this directory
981 input = Path(__file__).parent / "1447.dot"
982 assert input.exists(), "unexpectedly missing test case"
983
984 # run it through Graphviz
985 dot("svg", input)
986
987
988 def test_1447_1():
989 """
990 graphs should not fail assertions in maze.c
991 https://gitlab.com/graphviz/graphviz/-/issues/1447
992 """
993
994 # locate our associated test case in this directory
995 input = Path(__file__).parent / "1447_1.dot"
996 assert input.exists(), "unexpectedly missing test case"
997
998 # run it through Graphviz
999 dot("png", input)
1000
1001
1002 def test_1449():
1003 """
1004 using the SVG color scheme should not cause warnings
1005 https://gitlab.com/graphviz/graphviz/-/issues/1449
1006 """
1007
1008 # start Graphviz
1009 with subprocess.Popen(
1010 ["dot", "-Tsvg", "-o", os.devnull],
1011 stdin=subprocess.PIPE,
1012 stderr=subprocess.PIPE,
1013 text=True,
1014 ) as p:
1015 # pass it some input that uses the SVG color scheme
1016 _, stderr = p.communicate('graph g { colorscheme="svg"; }')
1017
1018 assert p.returncode == 0, "Graphviz exited with non-zero status"
1019
1020 assert stderr.strip() == "", "SVG color scheme use caused warnings"
1021
1022
1023 def test_1453():
1024 """
1025 `splines=curved` should not result in segfaults
1026 https://gitlab.com/graphviz/graphviz/-/issues/1453
1027 """
1028
1029 # locate our associated test case in this directory
1030 input = Path(__file__).parent / "1453.dot"
1031 assert input.exists(), "unexpectedly missing test case"
1032
1033 # run it through Graphviz
1034 dot("svg", input)
1035
1036
1037 def test_1472():
1038 """
1039 processing a malformed graph found by Google Autofuzz should not crash
1040 https://gitlab.com/graphviz/graphviz/-/issues/1472
1041 """
1042
1043 # locate our associated test case in this directory
1044 input = Path(__file__).parent / "1472.dot"
1045 assert input.exists(), "unexpectedly missing test case"
1046
1047 # run this through Graphviz
1048 proc = subprocess.run(
1049 ["dot", "-o", os.devnull, input], stderr=subprocess.PIPE, check=True
1050 )
1051
1052 assert (
1053 re.search(rb"\bAddressSanitizer: heap-buffer-overflow\b", proc.stderr) is None
1054 ), "malformed input caused a buffer overflow"
1055 assert (
1056 re.search(rb"\bAddressSanitizer: heap-use-after-free\b", proc.stderr) is None
1057 ), "malformed input caused a use-after-free"
1058
1059
1060 def test_1474():
1061 """
1062 processing this input found by fuzzing should not trigger a buffer overflow
1063 https://gitlab.com/graphviz/graphviz/-/issues/1474
1064 """
1065
1066 # locate our associated test case in this directory
1067 input = Path(__file__).parent / "1474.dot"
1068 assert input.exists(), "unexpectedly missing test case"
1069
1070 # run this through Graphviz
1071 proc = subprocess.run(
1072 ["dot", "-o", os.devnull, input], stderr=subprocess.PIPE, check=False
1073 )
1074
1075 assert proc.returncode != 0, "invalid input was not rejected"
1076
1077 assert (
1078 re.search(rb"\bAddressSanitizer: heap-buffer-overflow\b", proc.stderr) is None
1079 ), "malformed input caused a buffer overflow"
1080
1081
1082 def test_1489():
1083 """
1084 processing this input found by fuzzing should not trigger an invalid read
1085 https://gitlab.com/graphviz/graphviz/-/issues/1489
1086 """
1087
1088 # locate our associated test case in this directory
1089 input = Path(__file__).parent / "1489.dot"
1090 assert input.exists(), "unexpectedly missing test case"
1091
1092 # run this through Graphviz
1093 proc = subprocess.run(
1094 ["dot", "-o", os.devnull, input], stderr=subprocess.PIPE, check=False
1095 )
1096
1097 assert proc.returncode != 0, "invalid input was not rejected"
1098
1099 assert (
1100 re.search(rb"\bAddressSanitizer: SEGV\b", proc.stderr) is None
1101 ), "malformed input caused an invalid memory access"
1102
1103
1104 def test_1494():
1105 """
1106 processing this input found by fuzzing should not trigger a double-free
1107 https://gitlab.com/graphviz/graphviz/-/issues/1494
1108 """
1109
1110 # locate our associated test case in this directory
1111 input = Path(__file__).parent / "1494.dot"
1112 assert input.exists(), "unexpectedly missing test case"
1113
1114 # run this through Graphviz
1115 proc = subprocess.run(
1116 ["dot", "-o", os.devnull, input], stderr=subprocess.PIPE, check=False
1117 )
1118
1119 assert proc.returncode != 0, "invalid input was not rejected"
1120
1121 assert (
1122 re.search(rb"\bAddressSanitizer: double-free\b", proc.stderr) is None
1123 ), "malformed input caused a double free()"
1124
1125
1126 def test_1514():
1127 """
1128 processing this input should not trigger an assertion failure
1129 https://gitlab.com/graphviz/graphviz/-/issues/1514
1130 """
1131
1132 # locate our associated test case in this directory
1133 input = Path(__file__).parent / "1514.dot"
1134 assert input.exists(), "unexpectedly missing test case"
1135
1136 # run this through Graphviz
1137 proc = subprocess.run(
1138 ["dot", "-o", os.devnull, input], stderr=subprocess.PIPE, check=False
1139 )
1140
1141 assert (
1142 re.search(rb"\bAssertion `v' failed\b", proc.stderr) is None
1143 ), "malformed input caused an assertion failure"
1144
1145
1146 def test_1554():
1147 """
1148 small distances between nodes should not cause a crash in majorization
1149 https://gitlab.com/graphviz/graphviz/-/issues/1554
1150 """
1151
1152 # locate our associated test case in this directory
1153 input = Path(__file__).parent / "1554.dot"
1154 assert input.exists(), "unexpectedly missing test case"
1155
1156 # run it through Graphviz
1157 output = dot("svg", input)
1158
1159 # the output should not have NaN values, indicating out of bounds computation
1160 assert (
1161 re.search(r"\bnan\b", output, flags=re.IGNORECASE) is None
1162 ), "computation exceeded bounds"
1163
1164
1165 def test_1581():
1166 """
1167 this example found by fuzzing should not cause an out-of-bounds write
1168 https://gitlab.com/graphviz/graphviz/-/issues/1581
1169 """
1170
1171 # locate our associated test case in this directory
1172 input = Path(__file__).parent / "1581.dot"
1173 assert input.exists(), "unexpectedly missing test case"
1174
1175 # run it through Graphviz
1176 p = subprocess.run(["dot", "-Tsvg", "-o", os.devnull, input], check=False)
1177
1178 assert p.returncode != 42, "Address Sanitizer detect memory safety violations"
1179
1180
1181 def test_1585():
1182 """
1183 clustering nodes should not reverse their horizontal layout
1184 https://gitlab.com/graphviz/graphviz/-/issues/1585
1185 """
1186
1187 # locate our associated test cases in this directory
1188 no_cluster = Path(__file__).parent / "1585_0.dot"
1189 assert no_cluster.exists(), "unexpectedly missing test case"
1190 cluster = Path(__file__).parent / "1585_1.dot"
1191 assert cluster.exists(), "unexpectedly missing test case"
1192
1193 def find_node_xs(svg_output: str) -> Iterator[float]:
1194 """
1195 yield 3 floats representing the X positions of nodes b, c, d in the
1196 given graph
1197 """
1198
1199 # parse the SVG
1200 root = ET.fromstring(svg_output)
1201
1202 # find `b`
1203 b = root.findall(
1204 ".//{http://www.w3.org/2000/svg}title[.='b']../{http://www.w3.org/2000/svg}ellipse"
1205 )
1206 assert len(b) == 1, "could not find node 'b'"
1207 yield float(b[0].attrib["cx"])
1208
1209 # find `c`
1210 c = root.findall(
1211 ".//{http://www.w3.org/2000/svg}title[.='c']../{http://www.w3.org/2000/svg}ellipse"
1212 )
1213 assert len(c) == 1, "could not find node 'c'"
1214 yield float(c[0].attrib["cx"])
1215
1216 # find `d`
1217 d = root.findall(
1218 ".//{http://www.w3.org/2000/svg}title[.='d']../{http://www.w3.org/2000/svg}ellipse"
1219 )
1220 assert len(d) == 1, "could not find node 'd'"
1221 yield float(d[0].attrib["cx"])
1222
1223 # render the one without clusters and get its nodes’ X positions
1224 no_cluster_out = dot("svg", no_cluster)
1225 b, c, d = list(find_node_xs(no_cluster_out))
1226
1227 # confirm we got a left → right ordering
1228 assert b < c, "unexpected horizontal node ordering"
1229 assert c < d, "unexpected horizontal node ordering"
1230
1231 # now try the same thing with the clustered graph
1232 cluster_out = dot("svg", cluster)
1233 b, c, d = list(find_node_xs(cluster_out))
1234 assert b < c, "clustering altered nodes’ horizontal ordering"
1235 assert c < d, "clustering altered nodes’ horizontal ordering"
1236
1237
1238 @pytest.mark.skipif(which("gvpr") is None, reason="GVPR not available")
1239 def test_1594():
1240 """
1241 GVPR should give accurate line numbers in error messages
1242 https://gitlab.com/graphviz/graphviz/-/issues/1594
1243 """
1244
1245 # locate our associated test case in this directory
1246 input = Path(__file__).parent / "1594.gvpr"
1247
1248 # run GVPR with our (malformed) input program
1249 gvprbin = which("gvpr")
1250 with subprocess.Popen(
1251 [gvprbin, "-f", input],
1252 stdin=subprocess.PIPE,
1253 stdout=subprocess.DEVNULL,
1254 stderr=subprocess.PIPE,
1255 text=True,
1256 ) as p:
1257 _, stderr = p.communicate()
1258
1259 assert p.returncode != 0, "GVPR did not reject malformed program"
1260
1261 assert "line 3:" in stderr, "GVPR did not identify correct line of syntax error"
1262
1263
1264 @pytest.mark.parametrize(
1265 "device",
1266 (
1267 "png:cairo:gd",
1268 "png:cairo:gdiplus",
1269 pytest.param(
1270 "png:cairo:gdk",
1271 marks=pytest.mark.xfail(
1272 is_fedora_43(),
1273 strict=True,
1274 reason="https://gitlab.com/graphviz/graphviz/-/issues/2732",
1275 ),
1276 ),
1277 "png:cairo:quartz",
1278 ),
1279 )
1280 def test_1617(device: str):
1281 """
1282 DPI should be propagated to PNG outputs
1283 https://gitlab.com/graphviz/graphviz/-/issues/1617
1284 """
1285
1286 # check if Graphviz was built with the plugin that provides this device
1287 p = subprocess.run(
1288 ["dot", "-Tpng:unrecognized", "-o", os.devnull, os.devnull],
1289 stderr=subprocess.PIPE,
1290 check=False,
1291 text=True,
1292 )
1293 if re.search(rf"\b{device}\b", p.stderr) is None:
1294 pytest.skip(f'"{device}" output device not supported')
1295
1296 # run an example with DPI through Graphviz
1297 graph = 'digraph G { dpi = "300"; B->C; B->D; C->B; D->A; D->C; }'
1298 png = dot(device, source=graph)
1299
1300 # interpret this with Pillow
1301 data = io.BytesIO(png)
1302 img = Image.open(data)
1303
1304 # we should see the DPI propagated to the image
1305 default = 72
1306 dpi = img.info.get("dpi", (default, default))
1307 assert math.isclose(dpi[0], 300, abs_tol=1), "DPI not propagated to output"
1308 assert math.isclose(dpi[1], 300, abs_tol=1), "DPI not propagated to output"
1309
1310
1311 @pytest.mark.parametrize("long,short", (("--help", "-?"), ("--version", "-V")))
1312 def test_1618(long: str, short: str):
1313 """
1314 Graphviz should understand `--help` and `--version`
1315 https://gitlab.com/graphviz/graphviz/-/issues/1618
1316 """
1317
1318 # run Graphviz with the short form of the argument
1319 p1 = subprocess.run(["dot", short], capture_output=True, check=True)
1320
1321 # run it with the long form of the argument
1322 p2 = subprocess.run(["dot", long], capture_output=True, check=True)
1323
1324 # output from both should match
1325 assert (
1326 p1.stdout == p2.stdout
1327 ), f"`dot {long}` wrote differing output than `dot {short}`"
1328 assert (
1329 p1.stderr == p2.stderr
1330 ), f"`dot {long}` wrote differing output than `dot {short}`"
1331
1332
1333 @pytest.mark.parametrize(
1334 "test_case", ("1622_0.dot", "1622_1.dot", "1622_2.dot", "1622_3.dot")
1335 )
1336 def test_1622(test_case: str):
1337 """
1338 Narrow HTML table cells should not cause assertion failures
1339 https://gitlab.com/graphviz/graphviz/-/issues/1622
1340 """
1341
1342 # locate our associated test case in this directory
1343 input = Path(__file__).parent / test_case
1344 assert input.exists(), "unexpectedly missing test case"
1345
1346 # process it with Graphviz
1347 dot("png:cairo:cairo", input)
1348
1349
1350 def test_1624():
1351 """
1352 record shapes should be usable
1353 https://gitlab.com/graphviz/graphviz/-/issues/1624
1354 """
1355
1356 # locate our associated test case in this directory
1357 input = Path(__file__).parent / "1624.dot"
1358 assert input.exists(), "unexpectedly missing test case"
1359
1360 # process it with Graphviz
1361 dot("svg", input)
1362
1363
1364 def test_1644():
1365 """
1366 neato results should be deterministic
1367 https://gitlab.com/graphviz/graphviz/-/issues/1644
1368 """
1369
1370 # get our baseline reference
1371 input = Path(__file__).parent / "1644.dot"
1372 assert input.exists(), "unexpectedly missing test case"
1373 neato = which("neato")
1374 ref = run([neato, input])
1375
1376 # now repeat this, expecting it not to change
1377 for _ in range(20):
1378 out = run([neato, input])
1379 assert ref == out, "repeated rendering changed output"
1380
1381
1382 @pytest.mark.parametrize("fmt", ("dot", "gif", "svg", "xdot"))
1383 @pytest.mark.parametrize("layerselect", range(1, 6))
1384 def test_1648(fmt: str, layerselect: int):
1385 """
1386 `layerselect` should not cause crashes
1387 https://gitlab.com/graphviz/graphviz/-/issues/1648
1388
1389 Args:
1390 fmt: output format (`-T…`) to test
1391 layerselect: which layer to choose
1392 """
1393
1394 # a graph with layers
1395 input = Path(__file__).parent / "graphs/layer.gv"
1396 assert input.exists(), "unexpectedly missing test case"
1397
1398 # run this through Graphviz
1399 run(["dot", f"-Glayerselect={layerselect}", f"-T{fmt}", "-o", os.devnull, input])
1400
1401
1402 @pytest.mark.parametrize(
1403 "fmt",
1404 (
1405 "bmp",
1406 "canon",
1407 "cmap",
1408 "cmapx",
1409 "cmapx_np",
1410 "dot",
1411 "dot_json",
1412 "eps",
1413 "fig",
1414 "gv",
1415 pytest.param(
1416 "ico",
1417 marks=pytest.mark.skipif(
1418 platform.system() == "Windows",
1419 reason="no 'ico'-supporting plugin available on Windows",
1420 ),
1421 ),
1422 "imap",
1423 "imap_np",
1424 "ismap",
1425 "jpe",
1426 "jpeg",
1427 "jpg",
1428 "json",
1429 "json0",
1430 "kitty",
1431 "kittyz",
1432 "pdf",
1433 "pic",
1434 "plain",
1435 "plain-ext",
1436 "png",
1437 "pov",
1438 "ps",
1439 "ps2",
1440 "svg",
1441 "svg_inline",
1442 "svgz",
1443 "tif",
1444 "tiff",
1445 "tk",
1446 "vt",
1447 "vt-24bit",
1448 "vt-4up",
1449 "vt-6up",
1450 "vt-8up",
1451 pytest.param(
1452 "x11",
1453 marks=pytest.mark.skipif(
1454 platform.system() != "Linux",
1455 reason="xlib plugin only available on Linux",
1456 ),
1457 ),
1458 "xdot",
1459 "xdot1.2",
1460 "xdot1.4",
1461 "xdot_json",
1462 pytest.param(
1463 "xlib",
1464 marks=pytest.mark.skipif(
1465 platform.system() != "Linux",
1466 reason="xlib plugin only available on Linux",
1467 ),
1468 ),
1469 ),
1470 )
1471 def test_1648_1(fmt: str):
1472 """
1473 `layerselect` should not cause crashes
1474 https://gitlab.com/graphviz/graphviz/-/issues/1648
1475 https://forum.graphviz.org/t/segmentation-fault-when-using-layerselect/3077
1476
1477 Args:
1478 fmt: output format (`-T…`) to test
1479 """
1480
1481 # a simple arbitrary graph
1482 source = "graph {}"
1483
1484 # run this through Graphviz
1485 run(
1486 ["dot", f"-T{fmt}", "-Glayers=a, b", "-Glayerselect=b", "-o", os.devnull],
1487 input=source,
1488 )
1489
1490
1491 def test_1658():
1492 """
1493 the graph associated with this test case should not crash Graphviz
1494 https://gitlab.com/graphviz/graphviz/-/issues/1658
1495 """
1496
1497 # locate our associated test case in this directory
1498 input = Path(__file__).parent / "1658.dot"
1499 assert input.exists(), "unexpectedly missing test case"
1500
1501 # process it with Graphviz
1502 dot("png", input)
1503
1504
1505 def test_1676():
1506 """
1507 https://gitlab.com/graphviz/graphviz/-/issues/1676
1508 """
1509
1510 # locate our associated test case in this directory
1511 input = Path(__file__).parent / "1676.dot"
1512 assert input.exists(), "unexpectedly missing test case"
1513
1514 # run Graphviz with this input
1515 ret = subprocess.call(["dot", "-Tsvg", "-o", os.devnull, input])
1516
1517 # this malformed input should not have caused Graphviz to crash
1518 assert ret != -signal.SIGSEGV, "Graphviz segfaulted"
1519
1520
1521 @pytest.mark.skipif(which("gvpr") is None, reason="GVPR not available")
1522 def test_1702():
1523 """
1524 GVPR library program `depath` should work on arbitrary examples
1525 https://gitlab.com/graphviz/graphviz/-/issues/1702
1526 """
1527
1528 # locate our associated test case in this directory
1529 input = Path(__file__).parent / "1702.dot"
1530 assert input.exists(), "unexpectedly missing test case"
1531
1532 # find the library program
1533 depath = Path(__file__).parents[1] / "cmd/gvpr/lib/depath"
1534 assert depath.exists(), "GVPR library program depath missing"
1535
1536 # run GVPR
1537 gvpr_bin = which("gvpr")
1538 proc = subprocess.run(
1539 [gvpr_bin, "-c", "-o", os.devnull, "-f", depath, input],
1540 stderr=subprocess.PIPE,
1541 text=True,
1542 check=True,
1543 )
1544
1545 assert proc.stderr.strip() == "", "depath errored on tests/1702.dot"
1546
1547
1548 def test_1724():
1549 """
1550 passing malformed node and newrank should not cause segfaults
1551 https://gitlab.com/graphviz/graphviz/-/issues/1724
1552 """
1553
1554 # locate our associated test case in this directory
1555 input = Path(__file__).parent / "1724.dot"
1556 assert input.exists(), "unexpectedly missing test case"
1557
1558 # run Graphviz with this input
1559 ret = subprocess.call(["dot", "-Tsvg", "-o", os.devnull, input])
1560
1561 assert ret != -signal.SIGSEGV, "Graphviz segfaulted"
1562
1563
1564 @pytest.mark.skipif(
1565 is_static_build(),
1566 reason="dynamic libraries are unavailable to link against in static builds",
1567 )
1568 def test_1767():
1569 """
1570 using the Pango plugin multiple times should produce consistent results
1571 https://gitlab.com/graphviz/graphviz/-/issues/1767
1572 """
1573
1574 # find co-located test source
1575 c_src = (Path(__file__).parent / "1767.c").resolve()
1576 assert c_src.exists(), "missing test case"
1577
1578 # find our co-located dot input
1579 src = (Path(__file__).parent / "1767.dot").resolve()
1580 assert src.exists(), "missing test case"
1581
1582 stdout, _ = run_c(c_src, [src], link=["cgraph", "gvc"])
1583
1584 assert stdout.splitlines() == [
1585 "Loaded graph:clusters",
1586 "cluster_0 contains 5 nodes",
1587 "cluster_1 contains 1 nodes",
1588 "cluster_2 contains 3 nodes",
1589 "cluster_3 contains 3 nodes",
1590 "Loaded graph:clusters",
1591 "cluster_0 contains 5 nodes",
1592 "cluster_1 contains 1 nodes",
1593 "cluster_2 contains 3 nodes",
1594 "cluster_3 contains 3 nodes",
1595 ]
1596
1597
1598 @pytest.mark.skipif(which("gvpr") is None, reason="GVPR not available")
1599 @pytest.mark.skipif(platform.system() != "Windows", reason="only relevant on Windows")
1600 def test_1780():
1601 """
1602 GVPR should accept programs at absolute paths
1603 https://gitlab.com/graphviz/graphviz/-/issues/1780
1604 """
1605
1606 # get absolute path to an arbitrary GVPR program
1607 clustg = Path(__file__).resolve().parent.parent / "cmd/gvpr/lib/clustg"
1608
1609 # GVPR should not fail when given this path
1610 gvpr(clustg)
1611
1612
1613 def test_1783():
1614 """
1615 Graphviz should not segfault when passed large edge weights
1616 https://gitlab.com/graphviz/graphviz/-/issues/1783
1617 """
1618
1619 # locate our associated test case in this directory
1620 input = Path(__file__).parent / "1783.dot"
1621 assert input.exists(), "unexpectedly missing test case"
1622
1623 # run Graphviz with this input
1624 ret = subprocess.call(["dot", "-Tsvg", "-o", os.devnull, input])
1625
1626 assert ret != 0, "Graphviz accepted illegal edge weight"
1627
1628 assert ret != -signal.SIGSEGV, "Graphviz segfaulted"
1629
1630
1631 @pytest.mark.skipif(which("gvedit") is None, reason="Gvedit not available")
1632 def test_1813():
1633 """
1634 gvedit -? should show usage
1635 https://gitlab.com/graphviz/graphviz/-/issues/1813
1636 """
1637
1638 environ_copy = os.environ.copy()
1639 environ_copy.pop("DISPLAY", None)
1640 gvedit = which("gvedit")
1641 output = run([gvedit, "-?"], env=environ_copy)
1642
1643 assert "Usage" in output, "gvedit -? did not show usage"
1644
1645
1646 def test_1845():
1647 """
1648 rendering sequential graphs to PS should not segfault
1649 https://gitlab.com/graphviz/graphviz/-/issues/1845
1650 """
1651
1652 # locate our associated test case in this directory
1653 input = Path(__file__).parent / "1845.dot"
1654 assert input.exists(), "unexpectedly missing test case"
1655
1656 # generate a multipage PS file from this input
1657 dot("ps", input)
1658
1659
1660 @pytest.mark.xfail(strict=True) # FIXME
1661 def test_1856():
1662 """
1663 headports and tailports should be respected
1664 https://gitlab.com/graphviz/graphviz/-/issues/1856
1665 """
1666
1667 # locate our associated test case in this directory
1668 input = Path(__file__).parent / "1856.dot"
1669 assert input.exists(), "unexpectedly missing test case"
1670
1671 # process it into JSON
1672 out = dot("json", input)
1673 data = json.loads(out)
1674
1675 # find the two nodes, “3” and “5”
1676 three = [x for x in data["objects"] if x["name"] == "3"][0]
1677 five = [x for x in data["objects"] if x["name"] == "5"][0]
1678
1679 # find the edge from “3” to “5”
1680 edge = [
1681 x
1682 for x in data["edges"]
1683 if x["tail"] == three["_gvid"] and x["head"] == five["_gvid"]
1684 ][0]
1685
1686 # The edge should look something like:
1687 #
1688 # ┌─┐
1689 # │3│
1690 # └┬┘
1691 # ┌────┘
1692 # ┌┴┐
1693 # │5│
1694 # └─┘
1695 #
1696 # but a bug causes port constraints to not be respected and the edge comes out
1697 # more like:
1698 #
1699 # ┌─┐
1700 # │3│
1701 # └┬┘
1702 # │
1703 # ┌─┐ │
1704 # ├5̶┼───┘
1705 # └─┘
1706 #
1707 # So validate that the edge’s path does not dip below the top of the “5” node.
1708
1709 top_of_five = max(y for _, y in five["_draw_"][1]["points"])
1710
1711 waypoints_y = [y for _, y in edge["_draw_"][1]["points"]]
1712
1713 assert all(y >= top_of_five for y in waypoints_y), "edge dips below 5"
1714
1715
1716 @pytest.mark.skipif(which("fdp") is None, reason="fdp not available")
1717 def test_1865():
1718 """
1719 fdp should not read out of bounds when processing node names
1720 https://gitlab.com/graphviz/graphviz/-/issues/1865
1721 Note, the crash this test tries to provoke may only occur when run under
1722 Address Sanitizer or Valgrind
1723 """
1724
1725 # locate our associated test case in this directory
1726 input = Path(__file__).parent / "1865.dot"
1727 assert input.exists(), "unexpectedly missing test case"
1728
1729 # fdp should not crash when processing this file
1730 fdp = which("fdp")
1731 run_raw([fdp, "-o", os.devnull, input])
1732
1733
1734 @pytest.mark.skipif(which("gv2gml") is None, reason="gv2gml not available")
1735 @pytest.mark.skipif(which("gml2gv") is None, reason="gml2gv not available")
1736 @pytest.mark.parametrize(
1737 "penwidth",
1738 (pytest.param("1.0", id="penwidth=1.0"), pytest.param("1", id="pendwidth=1")),
1739 )
1740 def test_1871(penwidth: str):
1741 """
1742 round tripping something with either an integer or real `penwidth` through
1743 gv2gml→gml2gv should return the correct `penwidth`
1744 """
1745
1746 # a trivial graph
1747 input = f"graph {{ a [penwidth={penwidth}] }}"
1748
1749 # pass it through gv2gml
1750 gv2gml = which("gv2gml")
1751 gv = run([gv2gml], input=input)
1752
1753 # pass this through gml2gv
1754 gml2gv = which("gml2gv")
1755 gml = run([gml2gv], input=gv)
1756
1757 # the result should have a `penwidth` of 1
1758 has_1 = re.search(r"\bpenwidth\s*=\s*1[^\.]", gml) is not None
1759 has_1_0 = re.search(r"\bpenwidth\s*=\s*1\.0\b", gml) is not None
1760 assert (
1761 has_1 or has_1_0
1762 ), f"incorrect penwidth from round tripping through GML (output {gml})"
1763
1764
1765 @pytest.mark.skipif(which("fdp") is None, reason="fdp not available")
1766 def test_1876():
1767 """
1768 fdp should not rename nodes with internal names
1769 https://gitlab.com/graphviz/graphviz/-/issues/1876
1770 """
1771
1772 # a trivial graph to provoke this issue
1773 input = "graph { a }"
1774
1775 # process this with fdp
1776 fdp = which("fdp")
1777 try:
1778 output = run([fdp], input=input)
1779 except subprocess.CalledProcessError as e:
1780 raise RuntimeError("fdp failed to process trivial graph") from e
1781
1782 # we should not see any internal names like "%3"
1783 assert "%" not in output, "internal name in fdp output"
1784
1785
1786 @pytest.mark.skipif(which("fdp") is None, reason="fdp not available")
1787 def test_1877():
1788 """
1789 fdp should not fail an assertion when processing cluster edges
1790 https://gitlab.com/graphviz/graphviz/-/issues/1877
1791 """
1792
1793 # simple input with a cluster edge
1794 input = "graph {subgraph cluster_a {}; cluster_a -- b}"
1795
1796 # fdp should be able to process this
1797 fdp = which("fdp")
1798 run([fdp, "-o", os.devnull], input=input)
1799
1800
1801 def test_1880():
1802 """
1803 parsing a particular graph should not cause a Trapezoid-table overflow
1804 assertion failure
1805 https://gitlab.com/graphviz/graphviz/-/issues/1880
1806 """
1807
1808 # locate our associated test case in this directory
1809 input = Path(__file__).parent / "1880.dot"
1810 assert input.exists(), "unexpectedly missing test case"
1811
1812 # process it with Graphviz
1813 dot("png", input)
1814
1815
1816 @pytest.mark.xfail(
1817 strict=True, reason="https://gitlab.com/graphviz/graphviz/-/issues/1887"
1818 )
1819 def test_1887():
1820 """
1821 empty strings as labels should be propagated to dot output
1822 https://gitlab.com/graphviz/graphviz/-/issues/1887
1823 """
1824
1825 # find co-located test source
1826 c_src = (Path(__file__).parent / "1887.c").resolve()
1827 assert c_src.exists(), "missing test case"
1828
1829 # generate a graph and pass it through dot
1830 stdout, _ = run_c(c_src, link=["cgraph"])
1831
1832 assert (
1833 re.search(r'label\s*=\s*""', stdout) is not None
1834 ), "empty label missing in output"
1835
1836
1837 def test_1896():
1838 """
1839 this graph should not crash Graphviz
1840 https://gitlab.com/graphviz/graphviz/-/issues/1896
1841 """
1842
1843 # locate our associated test case in this directory
1844 input = Path(__file__).parent / "1896.dot"
1845 assert input.exists(), "unexpectedly missing test case"
1846
1847 for _ in range(10):
1848 dot("xdot1.2", input)
1849
1850
1851 def test_1898():
1852 """
1853 test a segfault from https://gitlab.com/graphviz/graphviz/-/issues/1898 has
1854 not reappeared
1855 """
1856
1857 # locate our associated test case in this directory
1858 input = Path(__file__).parent / "1898.dot"
1859 assert input.exists(), "unexpectedly missing test case"
1860
1861 # ask Graphviz to process it, which should generate a segfault if this bug
1862 # has been reintroduced
1863 dot("svg", input)
1864
1865
1866 def test_1902():
1867 """
1868 test a segfault from https://gitlab.com/graphviz/graphviz/-/issues/1902 has
1869 not reappeared
1870 """
1871
1872 # locate our associated test case in this directory
1873 input = Path(__file__).parent / "1902.dot"
1874 assert input.exists(), "unexpectedly missing test case"
1875
1876 # ask Graphviz to process it, which should generate a segfault if this bug
1877 # has been reintroduced
1878 dot("svg", input)
1879
1880
1881 # root directory of this checkout
1882 ROOT = Path(__file__).parent.parent.resolve()
1883
1884
1885 def test_1855():
1886 """
1887 SVGs should have a scale with sufficient precision
1888 https://gitlab.com/graphviz/graphviz/-/issues/1855
1889 """
1890
1891 # locate our associated test case in this directory
1892 src = Path(__file__).parent / "1855.dot"
1893 assert src.exists(), "unexpectedly missing test case"
1894
1895 # run it through Graphviz
1896 svg = dot("svg", src)
1897
1898 # find the graph element
1899 root = ET.fromstring(svg)
1900 graph = root[0]
1901 assert graph.get("class") == "graph", "could not find graph element"
1902
1903 # extract its `transform` attribute
1904 transform = graph.get("transform")
1905
1906 # this should begin with a scale directive
1907 m = re.match(r"scale\((?P<x>\d+(\.\d*)?) (?P<y>\d+(\.\d*))\)", transform)
1908 assert m is not None, f"failed to find 'scale' in '{transform}'"
1909
1910 x = m.group("x")
1911 y = m.group("y")
1912
1913 # the scale should be somewhere in reasonable range of what is expected
1914 assert float(x) >= 0.32 and float(x) <= 0.34, "inaccurate x scale"
1915 assert float(y) >= 0.32 and float(y) <= 0.34, "inaccurate y scale"
1916
1917 # two digits of precision are insufficient for this example, so require a
1918 # greater number of digits in both scale components
1919 assert len(x) > 4, "insufficient precision in x scale"
1920 assert len(y) > 4, "insufficient precision in y scale"
1921
1922
1923 @pytest.mark.parametrize("variant", [1, 2])
1924 @pytest.mark.skipif(which("gml2gv") is None, reason="gml2gv not available")
1925 def test_1869(variant: int):
1926 """
1927 gml2gv should be able to parse the style, outlineStyle, width and
1928 outlineWidth GML attributes and map them to the DOT attributes
1929 style and penwidth respectively
1930 https://gitlab.com/graphviz/graphviz/-/issues/1869
1931 """
1932
1933 # locate our associated test case in this directory
1934 input = Path(__file__).parent / f"1869-{variant}.gml"
1935 assert input.exists(), "unexpectedly missing test case"
1936
1937 # ask gml2gv to translate it to DOT
1938 gml2gv = which("gml2gv")
1939 output = run([gml2gv, input])
1940
1941 assert "style=dashed" in output, "style=dashed not found in DOT output"
1942 assert "penwidth=2" in output, "penwidth=2 not found in DOT output"
1943
1944
1945 def test_1879():
1946 """https://gitlab.com/graphviz/graphviz/-/issues/1879"""
1947
1948 # locate our associated test case in this directory
1949 input = Path(__file__).parent / "1879.dot"
1950 assert input.exists(), "unexpectedly missing test case"
1951
1952 # process it with DOT
1953 stdout = run(
1954 ["dot", "-Tsvg", "-o", os.devnull, input],
1955 cwd=Path(__file__).parent,
1956 stderr=subprocess.STDOUT,
1957 )
1958
1959 # check we did not trigger an assertion failure
1960 assert re.search(r"\bAssertion\b.*\bfailed\b", stdout) is None
1961
1962
1963 def test_1879_2():
1964 """
1965 another variant of lhead/ltail + compound
1966 https://gitlab.com/graphviz/graphviz/-/issues/1879
1967 """
1968
1969 # locate our associated test case in this directory
1970 input = Path(__file__).parent / "1879-2.dot"
1971 assert input.exists(), "unexpectedly missing test case"
1972
1973 # process it with DOT
1974 run_raw(["dot", "-Gmargin=0", "-Tpng", "-o", os.devnull, input])
1975
1976
1977 def test_1893():
1978 """
1979 an HTML label containing just a ] should work
1980 https://gitlab.com/graphviz/graphviz/-/issues/1893
1981 """
1982
1983 # a graph containing a node with an HTML label with a ] in a table cell
1984 input = "digraph { 0 [label=<<TABLE><TR><TD>]</TD></TR></TABLE>>] }"
1985
1986 # ask Graphviz to process this
1987 dot("svg", source=input)
1988
1989 # we should be able to do the same with an escaped ]
1990 input = "digraph { 0 [label=<<TABLE><TR><TD>&#93;</TD></TR></TABLE>>] }"
1991
1992 dot("svg", source=input)
1993
1994
1995 def test_1906():
1996 """
1997 graphs that generate large rectangles should be accepted
1998 https://gitlab.com/graphviz/graphviz/-/issues/1906
1999 """
2000
2001 # one of the rtest graphs is sufficient to provoke this
2002 input = Path(__file__).parent / "graphs/root.gv"
2003 assert input.exists(), "unexpectedly missing test case"
2004
2005 # use Circo to translate it to DOT
2006 run_raw(["dot", "-Kcirco", "-Tgv", "-o", os.devnull, input])
2007
2008
2009 @pytest.mark.skipif(which("twopi") is None, reason="twopi not available")
2010 def test_1907():
2011 """
2012 SVG edges should have title elements that match their names
2013 https://gitlab.com/graphviz/graphviz/-/issues/1907
2014 """
2015
2016 # a trivial graph to provoke this issue
2017 input = "digraph { A -> B -> C }"
2018
2019 # generate an SVG from this input with twopi
2020 twopi = which("twopi")
2021 output = run([twopi, "-Tsvg"], input=input)
2022
2023 assert "<title>A&#45;&gt;B</title>" in output, "element title not found in SVG"
2024
2025
2026 @pytest.mark.skipif(which("gvpr") is None, reason="gvpr not available")
2027 def test_1909():
2028 """
2029 GVPR should not output internal names
2030 https://gitlab.com/graphviz/graphviz/-/issues/1909
2031 """
2032
2033 # locate our associated test case in this directory
2034 prog = Path(__file__).parent / "1909.gvpr"
2035 graph = Path(__file__).parent / "1909.dot"
2036
2037 # run GVPR with the given input
2038 gvprbin = which("gvpr")
2039 output = run([gvprbin, "-c", "-f", prog, graph])
2040
2041 # we should have produced this graph without names like "%2" in it
2042 assert re.search(r"%\d+\b", output) is None
2043
2044
2045 @pytest.mark.skipif(
2046 is_static_build(),
2047 reason="dynamic libraries are unavailable to link against in static builds",
2048 )
2049 def test_1910():
2050 """
2051 Repeatedly using agmemread() should have consistent results
2052 https://gitlab.com/graphviz/graphviz/-/issues/1910
2053 """
2054
2055 # find co-located test source
2056 c_src = (Path(__file__).parent / "1910.c").resolve()
2057 assert c_src.exists(), "missing test case"
2058
2059 # run the test
2060 _, _ = run_c(c_src, link=["cgraph", "gvc"])
2061
2062
2063 def test_1913():
2064 """
2065 ALIGN attributes in <BR> tags should be parsed correctly
2066 https://gitlab.com/graphviz/graphviz/-/issues/1913
2067 """
2068
2069 # a template of a trivial graph using an ALIGN attribute
2070 graph = (
2071 "digraph {{\n"
2072 ' table1[label=<<table><tr><td align="text">hello world'
2073 '<br align="{}"/></td></tr></table>>];\n'
2074 "}}"
2075 )
2076
2077 def execute(input):
2078 """
2079 run Dot with the given input and return its exit status and stderr
2080 """
2081 with subprocess.Popen(
2082 ["dot", "-Tsvg", "-o", os.devnull],
2083 stdin=subprocess.PIPE,
2084 stderr=subprocess.PIPE,
2085 text=True,
2086 ) as p:
2087 _, stderr = p.communicate(input)
2088 return p.returncode, remove_asan_summary(remove_xtype_warnings(stderr))
2089
2090 # Graphviz should accept all legal values for this attribute
2091 for align in ("left", "right", "center"):
2092 input = align
2093 ret, stderr = execute(graph.format(input))
2094 assert ret == 0
2095 assert stderr.strip() == ""
2096
2097 # these attributes should also be valid when title cased
2098 input = f"{align[0].upper()}{align[1:]}"
2099 ret, stderr = execute(graph.format(input))
2100 assert ret == 0
2101 assert stderr.strip() == ""
2102
2103 # similarly, they should be valid when upper cased
2104 input = align.upper()
2105 ret, stderr = execute(graph.format(input))
2106 assert ret == 0
2107 assert stderr.strip() == ""
2108
2109 # various invalid things that have the same prefix or suffix as a valid
2110 # alignment should be rejected
2111 for align in ("lamp", "deft", "round", "might", "circle", "venter"):
2112 input = align
2113 _, stderr = execute(graph.format(input))
2114 assert f"Warning: Illegal value {input} for ALIGN - ignored" in stderr
2115
2116 # these attributes should also fail when title cased
2117 input = f"{align[0].upper()}{align[1:]}"
2118 _, stderr = execute(graph.format(input))
2119 assert f"Warning: Illegal value {input} for ALIGN - ignored" in stderr
2120
2121 # similarly, they should fail when upper cased
2122 input = align.upper()
2123 _, stderr = execute(graph.format(input))
2124 assert f"Warning: Illegal value {input} for ALIGN - ignored" in stderr
2125
2126
2127 @pytest.mark.skipif(which("gvpr") is None, reason="GVPR not available")
2128 @pytest.mark.xfail(
2129 strict=True, reason="https://gitlab.com/graphviz/graphviz/-/issues/1925"
2130 )
2131 def test_1925():
2132 """
2133 GVPR `hasAttr` should work accurately
2134 https://gitlab.com/graphviz/graphviz/-/issues/1925
2135 """
2136
2137 # locate our associated test case in this directory
2138 input = Path(__file__).parent / "1925.dot"
2139 assert input.exists(), "unexpectedly missing test case"
2140 script = Path(__file__).parent / "1925.gvpr"
2141 assert script.exists(), "unexpectedly missing test case"
2142
2143 # run GVPR
2144 gvpr_bin = which("gvpr")
2145 stdout = run([gvpr_bin, "-c", "-f", script, input])
2146
2147 # check we got expected results
2148 styled = set(["L"])
2149 minlened = set(["S->T"])
2150 active = None
2151 for line in stdout.split("\n"):
2152 if m := re.match("// (NODE|EDGE): (?P<name>.*)$", line):
2153 active = m.group("name")
2154 continue
2155 if m := re.match(r"//\s+style :: (?P<value>0|1)$", line):
2156 assert active is not None, "style line with no known node/edge"
2157 if m.group("value") == "0":
2158 assert (
2159 active not in styled
2160 ), f"{active} incorrectly considered to have 'style' attribute"
2161 else:
2162 assert (
2163 active in styled
2164 ), f"{active} incorrectly considered to not have 'style' attribute"
2165 if m := re.match(r"//\s+minlen :: (?P<value>0|1)$", line):
2166 assert active is not None, "minlen line with no known node/edge"
2167 if m.group("value") == "0":
2168 assert (
2169 active not in minlened
2170 ), f"{active} incorrectly considered to have 'minlen' attribute"
2171 else:
2172 assert (
2173 active in minlened
2174 ), f"{active} incorrectly considered to not have 'minlen' attribute"
2175
2176
2177 def test_1931():
2178 """
2179 New lines within strings should not be discarded during parsing
2180 https://gitlab.com/graphviz/graphviz/-/issues/1931
2181 """
2182
2183 # a graph with \n inside of strings
2184 graph = (
2185 "graph {\n"
2186 ' node1 [label="line 1\n'
2187 "line 2\n"
2188 '"];\n'
2189 ' node2 [label="line 3\n'
2190 'line 4"];\n'
2191 " node1 -- node2\n"
2192 ' node2 -- "line 5\n'
2193 'line 6"\n'
2194 "}"
2195 )
2196
2197 # ask Graphviz to process this to dot output
2198 xdot = dot("xdot", source=graph)
2199
2200 # all new lines in strings should have been preserved
2201 assert "line 1\nline 2\n" in xdot
2202 assert "line 3\nline 4" in xdot
2203 assert "line 5\nline 6" in xdot
2204
2205
2206 @pytest.mark.xfail(
2207 strict=True, reason="https://gitlab.com/graphviz/graphviz/-/issues/1939"
2208 )
2209 def test_1939():
2210 """
2211 clustering should not cause “trouble in init_rank” errors
2212 https://gitlab.com/graphviz/graphviz/-/issues/1939
2213 """
2214
2215 # locate our associated test case in this directory
2216 input = Path(__file__).parent / "1939.dot"
2217 assert input.exists(), "unexpectedly missing test case"
2218
2219 # run it through Graphviz
2220 dot("svg", input)
2221
2222
2223 def test_1949():
2224 """
2225 rankdir=LR + compound=true should not lead to an assertion failure
2226 https://gitlab.com/graphviz/graphviz/-/issues/1949
2227 """
2228
2229 # locate our associated test case in this directory
2230 input = Path(__file__).parent / "1949.dot"
2231 assert input.exists(), "unexpectedly missing test case"
2232
2233 # run it through Graphviz
2234 dot("png", input)
2235
2236
2237 @pytest.mark.skipif(which("edgepaint") is None, reason="edgepaint not available")
2238 def test_1971():
2239 """
2240 edgepaint should reject invalid command line options
2241 https://gitlab.com/graphviz/graphviz/-/issues/1971
2242 """
2243
2244 # a basic graph that edgepaint can process
2245 input = (
2246 "digraph {\n"
2247 ' graph [bb="0,0,54,108"];\n'
2248 ' node [label="\\N"];\n'
2249 " a [height=0.5,\n"
2250 ' pos="27,90",\n'
2251 " width=0.75];\n"
2252 " b [height=0.5,\n"
2253 ' pos="27,18",\n'
2254 " width=0.75];\n"
2255 ' a -> b [pos="e,27,36.104 27,71.697 27,63.983 27,54.712 27,46.112"];\n'
2256 "}"
2257 )
2258
2259 # run edgepaint with an invalid option, `-rabbit`, that happens to have the
2260 # same first character as valid options
2261 args = [which("edgepaint"), "-rabbit"]
2262 with subprocess.Popen(args, stdin=subprocess.PIPE, text=True) as p:
2263 p.communicate(input)
2264
2265 assert p.returncode != 0, "edgepaint incorrectly accepted '-rabbit'"
2266
2267
2268 def test_1990():
2269 """
2270 using ortho and circo in combination should not cause an assertion failure
2271 https://gitlab.com/graphviz/graphviz/-/issues/14
2272 """
2273
2274 # locate our associated test case in this directory
2275 input = Path(__file__).parent / "1990.dot"
2276 assert input.exists(), "unexpectedly missing test case"
2277
2278 # process it with Graphviz
2279 circo = which("circo")
2280 run_raw([circo, "-Tsvg", "-o", os.devnull, input])
2281
2282
2283 @pytest.mark.skipif(
2284 is_static_build(),
2285 reason="dynamic libraries are unavailable to link against in static builds",
2286 )
2287 def test_2057():
2288 """
2289 gvToolTred should be usable by user code
2290 https://gitlab.com/graphviz/graphviz/-/issues/2057
2291 """
2292
2293 # find co-located test source
2294 c_src = (Path(__file__).parent / "2057.c").resolve()
2295 assert c_src.exists(), "missing test case"
2296
2297 # run the test
2298 _, _ = run_c(c_src, link=["gvc"])
2299
2300
2301 def test_2078():
2302 """
2303 Incorrectly using the "layout" attribute on a subgraph should result in a
2304 sensible error.
2305 https://gitlab.com/graphviz/graphviz/-/issues/2078
2306 """
2307
2308 # our sample graph that incorrectly uses layout
2309 input = "graph {\n subgraph {\n layout=osage\n }\n}"
2310
2311 # run it through Graphviz
2312 with subprocess.Popen(
2313 ["dot", "-Tcanon", "-o", os.devnull],
2314 stdin=subprocess.PIPE,
2315 stderr=subprocess.PIPE,
2316 text=True,
2317 ) as p:
2318 _, stderr = p.communicate(input)
2319
2320 assert p.returncode != 0, "layout on subgraph was incorrectly accepted"
2321
2322 assert (
2323 "layout attribute is invalid except on the root graph" in stderr
2324 ), "expected warning not found"
2325
2326 # a graph that correctly uses layout
2327 input = "graph {\n layout=osage\n subgraph {\n }\n}"
2328
2329 # ensure this one does not trigger warnings
2330 with subprocess.Popen(
2331 ["dot", "-Tcanon", "-o", os.devnull],
2332 stdin=subprocess.PIPE,
2333 stdout=subprocess.PIPE,
2334 stderr=subprocess.PIPE,
2335 text=True,
2336 ) as p:
2337 stdout, stderr = p.communicate(input)
2338
2339 assert p.returncode == 0, f"correct layout use was rejected: {stdout}{stderr}"
2340
2341 assert stdout.strip() == "", "unexpected output"
2342 assert (
2343 "layout attribute is invalid except on the root graph" not in stderr
2344 ), "incorrect warning output"
2345
2346
2347 def test_2082():
2348 """
2349 Check a bug in inside_polygon has not been reintroduced.
2350 https://gitlab.com/graphviz/graphviz/-/issues/2082
2351 """
2352
2353 # locate our associated test case in this directory
2354 input = Path(__file__).parent / "2082.dot"
2355 assert input.exists(), "unexpectedly missing test case"
2356
2357 # ask Graphviz to process it, which should generate an assertion failure if
2358 # this bug has been reintroduced
2359 dot("png", input)
2360
2361
2362 def test_2087():
2363 """
2364 spline routing should be aware of and ignore concentrated edges
2365 https://gitlab.com/graphviz/graphviz/-/issues/2087
2366 """
2367
2368 # locate our associated test case in this directory
2369 input = Path(__file__).parent / "2087.dot"
2370 assert input.exists(), "unexpectedly missing test case"
2371
2372 # process it with Graphviz
2373 warnings = run(["dot", "-Tpng", "-o", os.devnull, input], stderr=subprocess.STDOUT)
2374
2375 # work around macOS warnings
2376 warnings = remove_xtype_warnings(warnings).strip()
2377
2378 # work around ASan informational printing
2379 warnings = remove_asan_summary(warnings)
2380
2381 # no warnings should have been printed
2382 assert (
2383 warnings == ""
2384 ), "warnings were printed when processing concentrated duplicate edges"
2385
2386
2387 @pytest.mark.parametrize("html_like_first", (False, True))
2388 def test_2089(html_like_first: bool):
2389 """
2390 HTML-like and non-HTML-like strings should peacefully coexist
2391 https://gitlab.com/graphviz/graphviz/-/issues/2089
2392 """
2393
2394 # a graph using an HTML-like string and a non-HTML-like string
2395 if html_like_first:
2396 graph = 'graph {\n a[label=<foo>];\n b[label="foo"];\n}'
2397 else:
2398 graph = 'graph {\n a[label="foo"];\n b[label=<foo>];\n}'
2399
2400 # normalize the graph
2401 canonical = dot("dot", source=graph)
2402
2403 assert "label=foo" in canonical, "non-HTML-like label not found"
2404 assert "label=<foo>" in canonical, "HTML-like label not found"
2405
2406
2407 def test_2089_2():
2408 """
2409 HTML-like and non-HTML-like strings should peacefully coexist
2410 https://gitlab.com/graphviz/graphviz/-/issues/2089
2411 """
2412
2413 # find co-located test source
2414 c_src = (Path(__file__).parent / "2089.c").resolve()
2415 assert c_src.exists(), "missing test case"
2416
2417 # run it
2418 link = ["cgraph"]
2419 if is_static_build():
2420 # in static builds, we also need transitive dependencies
2421 link += ["cdt"]
2422 _, _ = run_c(c_src, link=link)
2423
2424
2425 @pytest.mark.skipif(which("dot2gxl") is None, reason="dot2gxl not available")
2426 def test_2092():
2427 """
2428 an empty node ID should not cause a dot2gxl NULL pointer dereference
2429 https://gitlab.com/graphviz/graphviz/-/issues/2092
2430 """
2431 dot2gxl = which("dot2gxl")
2432 p = subprocess.run([dot2gxl, "-d"], input='<node id="">', check=False, text=True)
2433
2434 assert p.returncode != 0, "dot2gxl accepted invalid input"
2435
2436 assert p.returncode == 1, "dot2gxl crashed"
2437
2438
2439 @pytest.mark.skipif(which("dot2gxl") is None, reason="dot2gxl not available")
2440 def test_2093():
2441 """
2442 dot2gxl should handle elements with no ID
2443 https://gitlab.com/graphviz/graphviz/-/issues/2093
2444 """
2445 dot2gxl = which("dot2gxl")
2446 with subprocess.Popen([dot2gxl, "-d"], stdin=subprocess.PIPE, text=True) as p:
2447 p.communicate('<graph x="">')
2448
2449 assert p.returncode == 1, "dot2gxl did not reject missing ID"
2450
2451
2452 @pytest.mark.skipif(which("dot2gxl") is None, reason="dot2gxl not available")
2453 def test_2094():
2454 """
2455 dot2gxl should not crash when decoding a closing node tag after a closing
2456 graph tag
2457 https://gitlab.com/graphviz/graphviz/-/issues/2094
2458 """
2459
2460 # locate our associated test case in this directory
2461 input = Path(__file__).parent / "2094.xml"
2462 assert input.exists(), "unexpectedly missing test case"
2463
2464 dot2gxl = which("dot2gxl")
2465 ret = subprocess.call([dot2gxl, "-d", input])
2466
2467 assert ret in (
2468 0,
2469 1,
2470 ), "dot2gxl crashed when processing a closing node tag after a closing graph tag"
2471 assert ret == 1, "dot2gxl did not reject malformed XML"
2472
2473
2474 def test_2095():
2475 """
2476 Exceeding 1000 boxes during computation should not cause a crash
2477 https://gitlab.com/graphviz/graphviz/-/issues/2095
2478 """
2479
2480 # locate our associated test case in this directory
2481 input = Path(__file__).parent / "2095.dot"
2482 assert input.exists(), "unexpectedly missing test case"
2483
2484 # ask Graphviz to process it
2485 dot("pdf", input)
2486
2487
2488 def test_2095_1():
2489 """
2490 more than 1000 boxes should still be processed in reasonable time
2491 https://gitlab.com/graphviz/graphviz/-/issues/2095
2492 https://gitlab.com/graphviz/graphviz/-/merge_requests/2854
2493 https://gitlab.com/graphviz/graphviz/-/merge_requests/2857
2494 """
2495
2496 # locate our associated test case in this directory
2497 input = Path(__file__).parent / "2095.dot"
2498 assert input.exists(), "unexpectedly missing test case"
2499
2500 timeout = 60 # seconds
2501 if platform.system() == "Windows":
2502 timeout *= 2
2503
2504 # this typically takes ~1s to run, so give a wide margin of error and require that
2505 # that Graphviz finishes within that
2506 run_raw(["dot", "-Tpdf", "-o", os.devnull, input], timeout=timeout)
2507
2508
2509 @pytest.mark.skipif(which("gv2gml") is None, reason="gv2gml not available")
2510 def test_2131():
2511 """
2512 gv2gml should be able to process basic Graphviz input
2513 https://gitlab.com/graphviz/graphviz/-/issues/2131
2514 """
2515
2516 # a trivial graph
2517 input = "digraph { a -> b; }"
2518
2519 # ask gv2gml what it thinks of this
2520 gv2gml = which("gv2gml")
2521 try:
2522 run([gv2gml], input=input)
2523 except subprocess.CalledProcessError as e:
2524 raise RuntimeError("gv2gml rejected a basic graph") from e
2525
2526
2527 @pytest.mark.skipif(which("gvpr") is None, reason="gvpr not available")
2528 @pytest.mark.parametrize("examine", ("indices", "tokens"))
2529 def test_2138(examine: str):
2530 """
2531 gvpr splitting and tokenizing should not result in trailing garbage
2532 https://gitlab.com/graphviz/graphviz/-/issues/2138
2533 """
2534
2535 # find our co-located GVPR program
2536 script = (Path(__file__).parent / "2138.gvpr").resolve()
2537 assert script.exists(), "missing test case"
2538
2539 # run it with NUL input
2540 gvprbin = which("gvpr")
2541 out = run_raw([gvprbin, "-f", script], stdin=subprocess.DEVNULL)
2542
2543 # Decode into text. We do this instead of `text=True` above because the trailing
2544 # garbage can contain invalid UTF-8 data causing cryptic failures. We want to
2545 # correctly surface this as trailing garbage, not an obscure UTF-8 decoding error.
2546 result = out.decode("utf-8", "replace")
2547
2548 if examine == "indices":
2549 # check no indices are miscalculated
2550 index_re = (
2551 r"^// index of space \(st\) :\s*(?P<index>-?\d+)\s*<< must "
2552 r"NOT be less than -1$"
2553 )
2554 for m in re.finditer(index_re, result, flags=re.MULTILINE):
2555 index = int(m.group("index"))
2556 assert index >= -1, "illegal index computed"
2557
2558 if examine == "tokens":
2559 # check for text the author of 2138.gvpr expected to find
2560 assert (
2561 "// tok[3] >>3456789<< should NOT include trailing spaces or "
2562 "junk chars" in result
2563 ), "token 3456789 not found or has trailing garbage"
2564 assert (
2565 "// tok[7] >>012<< should NOT include trailing spaces or "
2566 "junk chars" in result
2567 ), "token 012 not found or has trailing garbage"
2568
2569
2570 def test_2159():
2571 """
2572 space for HTML TDs should be allocated equally when expanding to fill a TR
2573 https://gitlab.com/graphviz/graphviz/-/issues/2159
2574 """
2575
2576 # locate our associated test case in this directory
2577 input = Path(__file__).parent / "2159.dot"
2578 assert input.exists(), "unexpectedly missing test case"
2579
2580 # translate this to SVG
2581 svg = dot("svg", input)
2582
2583 # load it as XML
2584 root = ET.fromstring(svg)
2585
2586 # the first node is expected to contain:
2587 # • 1 polygon for the top column-spanning cell
2588 # • 5 polygons for the bottom row’s cells
2589 # • 1 polygon for the outer table border
2590 polygons = root.findall(
2591 ".//{http://www.w3.org/2000/svg}title[.='node1']/../{http://www.w3.org/2000/svg}polygon"
2592 )
2593 assert len(polygons) == 7
2594
2595 # extract the points delimiting the top row
2596 top_row = polygons[0]
2597 points = [
2598 [float(n) for n in p.split(",")] for p in top_row.get("points").split(" ")
2599 ]
2600 assert len(points) == 5, "polygon not rectangular"
2601 (ul_x, _), (ll_x, _), (lr_x, _), (ur_x, _), (orig_x, _) = points
2602 assert ul_x == ll_x, "polygon left edge is not vertical"
2603 assert lr_x == ur_x, "polygon right edge is not vertical"
2604 assert orig_x == ul_x, "polygon is not closed"
2605 left = ul_x
2606 right = ur_x
2607
2608 # extract the points for each cell in the bottom row
2609 bottom_row = []
2610 for cell in polygons[1:-1]:
2611 bottom_row += [
2612 [[float(n) for n in p.split(",")] for p in cell.get("points").split(" ")]
2613 ]
2614 assert len(bottom_row[-1]) == 5, "polygon not rectangular"
2615
2616 # extract the widths of each cell in the bottom row
2617 widths = []
2618 for cell in bottom_row:
2619 (ul_x, _), _, _, (ur_x, _), _ = cell
2620 widths += [ur_x - ul_x]
2621
2622 # these should approximately sum to the width of the top row
2623 assert math.isclose(
2624 sum(widths), right - left, abs_tol=10
2625 ), "bottom row not expanded to fill the space"
2626
2627 # the width of each cell should be approximately equal
2628 for width in widths[1:]:
2629 assert math.isclose(width, widths[0], abs_tol=5), "cells not evenly expanded"
2630
2631
2632 def test_2168():
2633 """
2634 using spline routing should not cause fdp/neato to infinite loop
2635 https://gitlab.com/graphviz/graphviz/-/issues/2168
2636 """
2637
2638 # locate our associated test case in this directory
2639 input = Path(__file__).parent / "2168.dot"
2640 assert input.exists(), "unexpectedly missing test case"
2641
2642 timeout = 5
2643 if platform.system() == "Windows":
2644 timeout *= 2
2645
2646 fdp = which("fdp")
2647 run_raw([fdp, "-o", os.devnull, input], timeout=timeout)
2648
2649
2650 def test_2168_1():
2651 """
2652 using spline routing should not cause fdp/neato to infinite loop
2653 https://gitlab.com/graphviz/graphviz/-/issues/2168
2654 """
2655
2656 # locate our associated test case in this directory
2657 input = Path(__file__).parent / "2168_1.dot"
2658 assert input.exists(), "unexpectedly missing test case"
2659
2660 timeout = 5
2661 if platform.system() == "Windows":
2662 timeout *= 2
2663
2664 fdp = which("fdp")
2665 run_raw([fdp, "-o", os.devnull, input], timeout=timeout)
2666
2667
2668 def test_2168_2():
2669 """
2670 using spline routing should not cause fdp/neato to infinite loop
2671 https://gitlab.com/graphviz/graphviz/-/issues/2168
2672 """
2673
2674 # locate our associated test case in this directory
2675 input = Path(__file__).parent / "2168_2.dot"
2676 assert input.exists(), "unexpectedly missing test case"
2677
2678 timeout = 5
2679 if platform.system() == "Windows":
2680 timeout *= 2
2681
2682 fdp = which("fdp")
2683 run_raw([fdp, "-o", os.devnull, input], timeout=timeout)
2684
2685
2686 def test_2168_3():
2687 """
2688 using spline routing should not cause fdp/neato to infinite loop
2689 https://gitlab.com/graphviz/graphviz/-/issues/2168
2690 """
2691
2692 # locate our associated test case in this directory
2693 input = Path(__file__).parent / "2168_3.dot"
2694 assert input.exists(), "unexpectedly missing test case"
2695
2696 timeout = 5
2697 if platform.system() == "Windows":
2698 timeout *= 2
2699
2700 fdp = which("fdp")
2701 run_raw([fdp, "-o", os.devnull, input], timeout=timeout)
2702
2703
2704 def test_2168_4():
2705 """
2706 using spline routing should not cause fdp/neato to infinite loop
2707 https://gitlab.com/graphviz/graphviz/-/issues/2168
2708 """
2709
2710 # locate our associated test case in this directory
2711 input = Path(__file__).parent / "2168_4.dot"
2712 assert input.exists(), "unexpectedly missing test case"
2713
2714 timeout = 5
2715 if platform.system() == "Windows":
2716 timeout *= 2
2717
2718 fdp = which("fdp")
2719 run_raw([fdp, "-o", os.devnull, input], timeout=timeout)
2720
2721
2722 def test_2168_5():
2723 """
2724 using spline routing should not cause fdp/neato to infinite loop
2725 https://gitlab.com/graphviz/graphviz/-/issues/2168
2726 """
2727
2728 # locate our associated test case in this directory
2729 input = Path(__file__).parent / "2168_5.dot"
2730 assert input.exists(), "unexpectedly missing test case"
2731
2732 fdp = which("fdp")
2733 out = run([fdp, "-o", os.devnull, input], stderr=subprocess.STDOUT)
2734
2735 assert (
2736 "Warning: the bounding boxes of some nodes touch - falling back to straight line edges"
2737 in out
2738 )
2739
2740
2741 def test_2179():
2742 """
2743 processing a label with an empty line should not yield a warning
2744 https://gitlab.com/graphviz/graphviz/-/issues/2179
2745 """
2746
2747 # a graph containing a label with an empty line
2748 input = 'digraph "" {\n 0 -> 1 [fontname="Lato",label=<<br/>1>]\n}'
2749
2750 # run a graph with an empty label through Graphviz
2751 with subprocess.Popen(
2752 ["dot", "-Tsvg", "-o", os.devnull],
2753 stdin=subprocess.PIPE,
2754 stderr=subprocess.PIPE,
2755 text=True,
2756 ) as p:
2757 _, stderr = p.communicate(input)
2758
2759 assert p.returncode == 0
2760
2761 assert (
2762 "Warning: no hard-coded metrics for" not in stderr
2763 ), "incorrect warning triggered"
2764
2765
2766 def test_2179_1():
2767 """
2768 processing a label with a line containing only a space should not yield a
2769 warning
2770 https://gitlab.com/graphviz/graphviz/-/issues/2179
2771 """
2772
2773 # a graph containing a label with a line containing only a space
2774 input = 'digraph "" {\n 0 -> 1 [fontname="Lato",label=< <br/>1>]\n}'
2775
2776 # run a graph with an empty label through Graphviz
2777 with subprocess.Popen(
2778 ["dot", "-Tsvg", "-o", os.devnull],
2779 stdin=subprocess.PIPE,
2780 stderr=subprocess.PIPE,
2781 text=True,
2782 ) as p:
2783 _, stderr = p.communicate(input)
2784
2785 assert p.returncode == 0
2786
2787 assert (
2788 "Warning: no hard-coded metrics for" not in stderr
2789 ), "incorrect warning triggered"
2790
2791
2792 def test_2183():
2793 """
2794 processing `splines=ortho`, `concentrate=true` should not crash
2795 https://gitlab.com/graphviz/graphviz/-/issues/2183
2796 """
2797
2798 # locate our associated test case in this directory
2799 input = Path(__file__).parent / "2183.dot"
2800 assert input.exists(), "unexpectedly missing test case"
2801
2802 run_raw(["dot", "-Tsvg", "-G8.5,11!", "-o", os.devnull, input])
2803
2804
2805 @pytest.mark.skipif(which("nop") is None, reason="nop not available")
2806 def test_2184_1():
2807 """
2808 nop should not reposition labelled graph nodes
2809 https://gitlab.com/graphviz/graphviz/-/issues/2184
2810 """
2811
2812 # run `nop` on a sample with a labelled graph node at the end
2813 source = Path(__file__).parent / "2184.dot"
2814 assert source.exists(), "missing test case"
2815 nop = which("nop")
2816 nopped = run([nop, source])
2817
2818 # the normalized output should have a graph with no label within
2819 # `clusterSurround1`
2820 m = re.search(
2821 r"\bclusterSurround1\b.*\bgraph\b.*\bcluster1\b", nopped, flags=re.DOTALL
2822 )
2823 assert m is not None, "nop rearranged a graph in a not-semantically-preserving way"
2824
2825
2826 def test_2184_2():
2827 """
2828 canonicalization should not reposition labelled graph nodes
2829 https://gitlab.com/graphviz/graphviz/-/issues/2184
2830 """
2831
2832 # canonicalize a sample with a labelled graph node at the end
2833 source = Path(__file__).parent / "2184.dot"
2834 assert source.exists(), "missing test case"
2835 canonicalized = dot("canon", source)
2836
2837 # the canonicalized output should have a graph with no label within
2838 # `clusterSurround1`
2839 m = re.search(
2840 r"\bclusterSurround1\b.*\bgraph\b.*\bcluster1\b", canonicalized, flags=re.DOTALL
2841 )
2842 assert (
2843 m is not None
2844 ), "`dot -Tcanon` rearranged a graph in a not-semantically-preserving way"
2845
2846
2847 def test_2185_1():
2848 """
2849 GVPR should deal with strings correctly
2850 https://gitlab.com/graphviz/graphviz/-/issues/2185
2851 """
2852
2853 # find our collocated GVPR program
2854 script = Path(__file__).parent / "2185.gvpr"
2855 assert script.exists(), "missing test case"
2856
2857 # run this with NUL input, checking output is valid UTF-8
2858 gvpr(script)
2859
2860
2861 def test_2185_2():
2862 """
2863 GVPR should deal with strings correctly
2864 https://gitlab.com/graphviz/graphviz/-/issues/2185
2865 """
2866
2867 # find our collocated GVPR program
2868 script = Path(__file__).parent / "2185.gvpr"
2869 assert script.exists(), "missing test case"
2870
2871 # run this with NUL input
2872 gvprbin = which("gvpr")
2873 out = run_raw([gvprbin, "-f", script], stdin=subprocess.DEVNULL)
2874
2875 # decode output in a separate step to gracefully cope with garbage unicode
2876 out = out.decode("utf-8", "replace")
2877
2878 # deal with Windows eccentricities
2879 eol = "\r\n" if platform.system() == "Windows" else "\n"
2880 expected = f"one two three{eol}"
2881
2882 # check the first line is as expected
2883 assert out.startswith(expected), "incorrect GVPR interpretation"
2884
2885
2886 def test_2185_3():
2887 """
2888 GVPR should deal with strings correctly
2889 https://gitlab.com/graphviz/graphviz/-/issues/2185
2890 """
2891
2892 # find our collocated GVPR program
2893 script = Path(__file__).parent / "2185.gvpr"
2894 assert script.exists(), "missing test case"
2895
2896 # run this with NUL input
2897 gvprbin = which("gvpr")
2898 out = run_raw([gvprbin, "-f", script], stdin=subprocess.DEVNULL)
2899
2900 # decode output in a separate step to gracefully cope with garbage unicode
2901 out = out.decode("utf-8", "replace")
2902
2903 # deal with Windows eccentricities
2904 eol = "\r\n" if platform.system() == "Windows" else "\n"
2905 expected = f"one two three{eol}one five three{eol}"
2906
2907 # check the first two lines are as expected
2908 assert out.startswith(expected), "incorrect GVPR interpretation"
2909
2910
2911 def test_2185_4():
2912 """
2913 GVPR should deal with strings correctly
2914 https://gitlab.com/graphviz/graphviz/-/issues/2185
2915 """
2916
2917 # find our collocated GVPR program
2918 script = Path(__file__).parent / "2185.gvpr"
2919 assert script.exists(), "missing test case"
2920
2921 # run this with NUL input
2922 gvprbin = which("gvpr")
2923 out = run_raw([gvprbin, "-f", script], stdin=subprocess.DEVNULL)
2924
2925 # decode output in a separate step to gracefully cope with garbage unicode
2926 out = out.decode("utf-8", "replace")
2927
2928 # deal with Windows eccentricities
2929 eol = "\r\n" if platform.system() == "Windows" else "\n"
2930 expected = f"one two three{eol}one five three{eol}99{eol}"
2931
2932 # check the first three lines are as expected
2933 assert out.startswith(expected), "incorrect GVPR interpretation"
2934
2935
2936 def test_2185_5():
2937 """
2938 GVPR should deal with strings correctly
2939 https://gitlab.com/graphviz/graphviz/-/issues/2185
2940 """
2941
2942 # find our collocated GVPR program
2943 script = Path(__file__).parent / "2185.gvpr"
2944 assert script.exists(), "missing test case"
2945
2946 # run this with NUL input
2947 gvprbin = which("gvpr")
2948 out = run_raw([gvprbin, "-f", script], stdin=subprocess.DEVNULL)
2949
2950 # decode output in a separate step to gracefully cope with garbage unicode
2951 out = out.decode("utf-8", "replace")
2952
2953 # deal with Windows eccentricities
2954 eol = "\r\n" if platform.system() == "Windows" else "\n"
2955 expected = f"one two three{eol}one five three{eol}99{eol}Constant{eol}"
2956
2957 # check the first four lines are as expected
2958 assert out.startswith(expected), "incorrect GVPR interpretation"
2959
2960
2961 @pytest.mark.xfail(strict=True) # FIXME
2962 def test_2193():
2963 """
2964 the canonical format should be stable
2965 https://gitlab.com/graphviz/graphviz/-/issues/2193
2966 """
2967
2968 # find our collocated test case
2969 input = Path(__file__).parent / "2193.dot"
2970 assert input.exists(), "unexpectedly missing test case"
2971
2972 # derive the initial canonicalization
2973 canonical = dot("canon", input)
2974
2975 # now canonicalize this again to see if it changes
2976 new = dot("canon", source=canonical)
2977 assert canonical == new, "canonical translation is not stable"
2978
2979
2980 @pytest.mark.skipif(which("gvpr") is None, reason="GVPR not available")
2981 def test_2211():
2982 """
2983 GVPR’s `index` function should return correct results
2984 https://gitlab.com/graphviz/graphviz/-/issues/2211
2985 """
2986
2987 # find our collocated test case
2988 program = Path(__file__).parent / "2211.gvpr"
2989 assert program.exists(), "unexpectedly missing test case"
2990
2991 # run it through GVPR
2992 output = gvpr(program)
2993
2994 # it should have found the right string indices for characters
2995 assert (
2996 output == "index: 9 should be 9\n"
2997 "index: 3 should be 3\n"
2998 "index: -1 should be -1\n"
2999 )
3000
3001
3002 def test_2215():
3003 """
3004 Graphviz should not crash with `-v`
3005 https://gitlab.com/graphviz/graphviz/-/issues/2215
3006 """
3007
3008 # try it on a simple graph
3009 input = "graph g { a -- b; }"
3010 run(["dot", "-v"], input=input)
3011
3012 # try the same on a labelled version of this graph
3013 input = 'graph g { node[label=""] a -- b; }'
3014 run(["dot", "-v"], input=input)
3015
3016
3017 @pytest.mark.xfail(
3018 is_rocky(),
3019 strict=True,
3020 reason="https://gitlab.com/graphviz/graphviz/-/issues/2241",
3021 )
3022 def test_2241():
3023 """
3024 a graph with two nodes and one edge in each direction should be rendered
3025 with two visually distinct edges when using the neato engine and
3026 splines=true, not two edges on top of each other, visually looking like a
3027 single edge with both head and tail arrowheads.
3028 https://gitlab.com/graphviz/graphviz/-/issues/2241
3029 """
3030
3031 # find our collocated test case
3032 input = Path(__file__).parent / "2241.dot"
3033 assert input.exists(), "unexpectedly missing test case"
3034
3035 # run it through Graphviz
3036 svg = dot("svg", input)
3037
3038 # load this as XML
3039 root = ET.fromstring(svg)
3040
3041 # the output is expected to contain two paths which are well separated
3042 paths = root.findall(".//{http://www.w3.org/2000/svg}path")
3043 assert len(paths) == 2, "expected two paths in output"
3044 ellipses = root.findall(".//{http://www.w3.org/2000/svg}ellipse")
3045 assert len(ellipses) == 2, "expected two ellipses in output"
3046
3047 # calculate the x coordinate of a vertical line which is equidistant from the two nodes
3048 x = statistics.mean(float(ellipse.get("cx")) for ellipse in ellipses)
3049
3050 # for each edge path, get the y coordinate of a point on a line between the edge's endpoints
3051 # where the line intersects the node equidistant vertical line
3052 y_coordinates = []
3053 for path in paths:
3054 d_attribute = path.get("d")
3055 points_str = re.split("[ C]", d_attribute.replace("M", ""))
3056 assert (
3057 len(points_str) == 4
3058 ), "expected four points in the 'd' attribute of the 'path' element"
3059 points = [
3060 (float(x_str), float(y_str))
3061 for x_str, y_str in [point_str.split(",") for point_str in points_str]
3062 ]
3063 dx = points[3][0] - points[0][0]
3064 dy = points[3][1] - points[0][1]
3065 y = points[0][1] + dy / dx * (x - points[0][0])
3066 y_coordinates.append(y)
3067
3068 # check that the lines are well separated vertically where they intersect the node equidistant
3069 # vertical line
3070 y_coordinates_abs_difference = abs(y_coordinates[1] - y_coordinates[0])
3071 y_coordinates_abs_difference_when_ok = 11.5004437538844
3072 y_coordinates_abs_difference_when_not_ok = 0.00658290568043185
3073 min_y_coordinates_abs_difference = (
3074 y_coordinates_abs_difference_when_ok + y_coordinates_abs_difference_when_not_ok
3075 ) / 2
3076 assert y_coordinates_abs_difference > min_y_coordinates_abs_difference
3077
3078
3079 def test_2242():
3080 """
3081 repeated runs of a graph with subgraphs should yield a stable result
3082 https://gitlab.com/graphviz/graphviz/-/issues/2242
3083 """
3084
3085 # get our baseline reference
3086 input = Path(__file__).parent / "2242.dot"
3087 assert input.exists(), "unexpectedly missing test case"
3088 ref = dot("png", input)
3089
3090 # now repeat this, expecting it not to change
3091 for _ in range(20):
3092 png = dot("png", input)
3093 assert ref == png, "repeated rendering changed output"
3094
3095
3096 @pytest.mark.skipif(
3097 is_static_build(),
3098 reason="dynamic libraries are unavailable to link against in static builds",
3099 )
3100 @pytest.mark.skipif(
3101 platform.system() == "Windows"
3102 and which("dot") is not None
3103 and is_asan_instrumented(which("dot")),
3104 reason="ASan runs out of memory in its internal pool on Windows",
3105 )
3106 def test_2331(tmp_path: Path):
3107 """
3108 the example in this test should not cause a double-free
3109 https://gitlab.com/graphviz/graphviz/-/issues/2331
3110 """
3111
3112 # find co-located test source
3113 c_src = (Path(__file__).parent / "2331.c").resolve()
3114 assert c_src.exists(), "missing test case"
3115
3116 # From here, we essentially want to `run_c(c_src, …)`. However we cannot easily do
3117 # this because we want to directly link against plugins (instead of `dlopen` them),
3118 # libraries that are not in the linker’s search path. So instead we have to take a
3119 # more manual approach.
3120
3121 # find the plugins we need to link against
3122 core = _find_plugin_so("core")
3123 assert core is not None, "core plugin library not found"
3124 dot_layout = _find_plugin_so("dot_layout")
3125 assert dot_layout is not None, "dot layout plugin library not found"
3126
3127 # compile the test code
3128 exe = tmp_path / "a.exe"
3129 compile_c(c_src, link=["cgraph", "gvc", core, dot_layout], dst=exe)
3130
3131 # teach the runtime linker how to find the plugins
3132 env = os.environ.copy()
3133 ld_library_path = f"{core.parent}:{dot_layout.parent}"
3134 prefix = ""
3135 if is_macos():
3136 if "DYLD_LIBRARY_PATH" in env:
3137 env["DYLD_LIBRARY_PATH"] = f"{ld_library_path}:{env['DYLD_LIBRARY_PATH']}"
3138 else:
3139 env["DYLD_LIBRARY_PATH"] = ld_library_path
3140 prefix = f"env DYLD_LIBRARY_PATH={env['DYLD_LIBRARY_PATH']} "
3141 else:
3142 if "LD_LIBRARY_PATH" in env:
3143 env["LD_LIBRARY_PATH"] = f"{ld_library_path}:{env['LD_LIBRARY_PATH']}"
3144 else:
3145 env["LD_LIBRARY_PATH"] = ld_library_path
3146 prefix = f"env LD_LIBRARY_PATH={env['LD_LIBRARY_PATH']} "
3147
3148 # run the test code
3149 print(f"+ {prefix}{shlex.quote(str(exe))}")
3150 subprocess.run([exe], env=env, check=True)
3151
3152
3153 def test_2342():
3154 """
3155 using an arrow with size 0 should not trigger an assertion failure
3156 https://gitlab.com/graphviz/graphviz/-/issues/2342
3157 """
3158
3159 # find our collocated test case
3160 input = Path(__file__).parent / "2342.dot"
3161 assert input.exists(), "unexpectedly missing test case"
3162
3163 # run it through Graphviz
3164 dot("svg", input)
3165
3166
3167 @pytest.mark.skipif(
3168 is_static_build(),
3169 reason="dynamic libraries are unavailable to link against in static builds",
3170 )
3171 def test_2356():
3172 """
3173 Using `mindist` programmatically in a loop should not cause Windows crashes
3174 https://gitlab.com/graphviz/graphviz/-/issues/2356
3175 """
3176
3177 # find co-located test source
3178 c_src = (Path(__file__).parent / "2356.c").resolve()
3179 assert c_src.exists(), "missing test case"
3180
3181 # run the test
3182 run_c(c_src, link=["cgraph", "gvc"])
3183
3184
3185 def test_2361():
3186 """
3187 using `ortho` and `concentrate` in combination should not cause a crash
3188 https://gitlab.com/graphviz/graphviz/-/issues/2361
3189 """
3190
3191 # find our collocated test case
3192 input = Path(__file__).parent / "2361.dot"
3193 assert input.exists(), "unexpectedly missing test case"
3194
3195 # run it through Graphviz
3196 dot("png", input)
3197
3198
3199 @pytest.mark.xfail(
3200 strict=True, reason="https://gitlab.com/graphviz/graphviz/-/issues/2295"
3201 )
3202 def test_2295():
3203 """
3204 tooltips should work in PDFs
3205 https://gitlab.com/graphviz/graphviz/-/issues/2295
3206 """
3207
3208 # find our collocated test case
3209 input = Path(__file__).parent / "2295.dot"
3210 assert input.exists(), "unexpectedly missing test case"
3211
3212 # translate it to PDF
3213 pdf = dot("pdf", input)
3214
3215 assert re.search(rb"\bhi mom\b", pdf) is not None, "tooltip not propagated to PDF"
3216
3217
3218 @pytest.mark.parametrize("arg", ("--filepath", "-Gimagepath"))
3219 def test_2396(arg: str):
3220 """
3221 `--filepath` should work as a replacement for `$GV_FILE_PATH`
3222 https://gitlab.com/graphviz/graphviz/-/issues/2396
3223 """
3224
3225 # use an arbitrary image we have in the tree
3226 image = Path(__file__).parent / "../cmd/gvedit/images/save.png"
3227 assert image.exists(), "missing test data"
3228
3229 # a graph that tries to use the image by relative path
3230 slash = "/" if arg == "--filepath" else ""
3231 source = f'graph {{ N[image="{slash}save.png"]; }}'
3232
3233 # run this through Graphviz
3234 proc = subprocess.run(
3235 ["dot", "-Tsvg", f"{arg}={image.parent}"],
3236 capture_output=True,
3237 input=source,
3238 cwd=Path(__file__).parent,
3239 text=True,
3240 check=True,
3241 )
3242
3243 # work around macOS warnings
3244 stderr = remove_xtype_warnings(proc.stderr).strip()
3245
3246 # work around ASan informational printing
3247 stderr = remove_asan_summary(stderr)
3248
3249 assert stderr == "", "loading an image by relative path produced warnings"
3250
3251 # whether we used `imagepath` or `filepath` should affect whether we get a leading
3252 # slash
3253 if arg == "-Gimagepath":
3254 assert '"save.png"' in proc.stdout, "incorrect relative path in output"
3255 else:
3256 assert '"/save.png"' in proc.stdout, "incorrect relative path in output"
3257
3258
3259 def test_2481():
3260 """
3261 `dot` should not exit with a syntax error if keywords are mixed-case
3262 https://gitlab.com/graphviz/graphviz/-/issues/2481
3263 """
3264
3265 # try a simple graph with uppercase characters in 'digraph'
3266 input = "diGraph { }"
3267
3268 # ensure this does not trigger warnings
3269 with subprocess.Popen(
3270 ["dot"],
3271 stdin=subprocess.PIPE,
3272 stderr=subprocess.PIPE,
3273 text=True,
3274 ) as p:
3275 _, stderr = p.communicate(input)
3276 assert p.returncode == 0, "mixed-case keyword was rejected"
3277
3278 assert "syntax error" not in stderr, "dot displayed a syntax error message"
3279
3280
3281 @pytest.mark.skipif(
3282 is_static_build(),
3283 reason="dynamic libraries are unavailable to link against in static builds",
3284 )
3285 def test_2484():
3286 """
3287 Graphviz context should not preserve state across calls
3288 https://gitlab.com/graphviz/graphviz/-/issues/2484
3289 """
3290
3291 # find our co-located driver
3292 c_src = (Path(__file__).parent / "2484.c").resolve()
3293 assert c_src.exists(), "missing test case"
3294
3295 # find co-located input to the driver
3296 dot_src = (Path(__file__).parent / "2484.dot").resolve()
3297 assert dot_src.exists(), "missing test case"
3298
3299 # compile and run it
3300 run_c(
3301 c_src,
3302 ["-Kdot", "-Tpng", str(dot_src), "-o", os.devnull],
3303 link=["cgraph", "gvc"],
3304 )
3305
3306
3307 @pytest.mark.xfail(
3308 strict=True, reason="https://gitlab.com/graphviz/graphviz/-/issues/2592"
3309 )
3310 def test_2592():
3311 """
3312 pack modes should not remove xlabels
3313 https://gitlab.com/graphviz/graphviz/-/issues/2592
3314 """
3315
3316 # find our collocated test case
3317 input = Path(__file__).parent / "2592.dot"
3318 assert input.exists(), "unexpectedly missing test case"
3319
3320 # run it through Graphviz
3321 svg = dot("svg", input)
3322
3323 assert "comment not included" in svg, "missing xlabel in packed graph"
3324
3325
3326 def test_package_version():
3327 """
3328 The graphviz_version.h header should define a non-empty PACKAGE_VERSION
3329 """
3330
3331 # find co-located test source
3332 c_src = (Path(__file__).parent / "get-package-version.c").resolve()
3333 assert c_src.exists(), "missing test case"
3334
3335 # run the test
3336 package_version, _ = run_c(c_src)
3337
3338 assert (
3339 package_version.strip() != ""
3340 ), "invalid PACKAGE_VERSION in graphviz_version.h"
3341
3342
3343 def test_user_shapes():
3344 """
3345 Graphviz should understand how to embed a custom SVG image as a node’s shape
3346 """
3347
3348 # find our collocated test case
3349 input = Path(__file__).parent / "usershape.dot"
3350 assert input.exists(), "unexpectedly missing test case"
3351
3352 # ask Graphviz to translate this to SVG
3353 output = run(["dot", "-Tsvg", input], cwd=os.path.dirname(__file__))
3354
3355 # the external SVG should have been parsed and is now referenced
3356 assert '<image xlink:href="usershape.svg" width="62px" height="44px" ' in output
3357
3358
3359 def test_xdot_json():
3360 """
3361 check the output of xdot’s JSON API
3362 """
3363
3364 # find our collocated C helper
3365 c_src = Path(__file__).parent / "xdot2json.c"
3366
3367 # some valid xdot commands to process
3368 input = "c 9 -#fffffe00 C 7 -#ffffff P 4 0 0 0 36 54 36 54 0"
3369
3370 # ask our C helper to process this
3371 output, err = run_c(c_src, input=input, link=["xdot"])
3372 assert err == ""
3373
3374 # confirm the output was what we expected
3375 data = json.loads(output)
3376 assert data == [
3377 {"c": "#fffffe00"},
3378 {"C": "#ffffff"},
3379 {"P": [0.0, 0.0, 0.0, 36.0, 54.0, 36.0, 54.0, 0.0]},
3380 ]
3381
3382
3383 @pytest.mark.skipif(which("gvmap") is None, reason="gvmap not available")
3384 def test_gvmap_fclose():
3385 """
3386 gvmap should not attempt to fclose(NULL). This example will trigger a crash if
3387 this bug has been reintroduced and Graphviz is built with ASan support.
3388 """
3389
3390 # a reasonable input graph
3391 input = (
3392 'graph "Alík: Na vlastní oči" {\n'
3393 ' graph [bb="0,0,128.9,36",\n'
3394 " concentrate=true,\n"
3395 " overlap=prism,\n"
3396 " start=3\n"
3397 " ];\n"
3398 ' node [label="\\N"];\n'
3399 " {\n"
3400 " bob [height=0.5,\n"
3401 ' pos="100.95,18",\n'
3402 " width=0.77632];\n"
3403 " }\n"
3404 " {\n"
3405 " alice [height=0.5,\n"
3406 ' pos="32.497,18",\n'
3407 " width=0.9027];\n"
3408 " }\n"
3409 ' alice -- bob [pos="65.119,18 67.736,18 70.366,18 72.946,18"];\n'
3410 " bob -- alice;\n"
3411 "}"
3412 )
3413
3414 # pass this through gvmap
3415 gvmap = which("gvmap")
3416 proc = subprocess.run([gvmap], input=input.encode("utf-8"), check=False)
3417
3418 assert proc.returncode in (0, 1), "gvmap crashed"
3419
3420
3421 @pytest.mark.skipif(which("gvpr") is None, reason="gvpr not available")
3422 def test_gvpr_usage(tmp_path: Path):
3423 """
3424 gvpr usage information should be included when erroring on a malformed command
3425 """
3426
3427 # ask GVPR to process a non-existent file
3428 gvprbin = which("gvpr")
3429 with subprocess.Popen(
3430 [gvprbin, "-v", "-f", "nofile"],
3431 stderr=subprocess.PIPE,
3432 cwd=tmp_path,
3433 text=True,
3434 ) as p:
3435 _, stderr = p.communicate()
3436
3437 assert p.returncode != 0, "GVPR accepted a non-existent file"
3438
3439 # the stderr output should have contained full usage instructions
3440 assert (
3441 "-o <ofile> - write output to <ofile>; stdout by default" in stderr
3442 ), "truncated or malformed GVPR usage information"
3443
3444
3445 def test_2225():
3446 """
3447 sfdp should not segfault with curved splines
3448 https://gitlab.com/graphviz/graphviz/-/issues/2225
3449 """
3450
3451 # locate our associated test case in this directory
3452 input = Path(__file__).parent / "2225.dot"
3453 assert input.exists(), "unexpectedly missing test case"
3454
3455 # run this through sfdp
3456 sfdp = which("sfdp")
3457 p = subprocess.run(
3458 [sfdp, "-Gsplines=curved", "-o", os.devnull, input],
3459 stderr=subprocess.PIPE,
3460 check=False,
3461 text=True,
3462 )
3463
3464 # if sfdp was built without libgts, it will not handle anything non-trivial
3465 no_gts_error = "remove_overlap: Graphviz not built with triangulation library"
3466 if no_gts_error in p.stderr:
3467 assert p.returncode != 0, "sfdp returned success after an error message"
3468 return
3469
3470 p.check_returncode()
3471
3472
3473 def test_2257():
3474 """
3475 `$GV_FILE_PATH` being set should prevent Graphviz from running
3476
3477 `$GV_FILE_PATH` was an environment variable formerly used to implement a file
3478 system sandboxing policy when Graphviz was exposed to the internet via a web
3479 server. These days, there are safer and more robust techniques to sandbox
3480 Graphviz and so `$GV_FILE_PATH` usage has been removed. But if someone
3481 attempts to use this legacy mechanism, we do not want Graphviz to
3482 “fail-open,” starting anyway and silently ignoring `$GV_FILE_PATH` giving
3483 the user the false impression the sandboxing is in force.
3484
3485 https://gitlab.com/graphviz/graphviz/-/issues/2257
3486 """
3487
3488 # locate our associated test case in this directory
3489 input = Path(__file__).parent / "2257.dot"
3490 assert input.exists(), "unexpectedly missing test case"
3491
3492 env = os.environ.copy()
3493 env["GV_FILE_PATH"] = "/tmp"
3494
3495 # Graphviz should refuse to process an input file
3496 with pytest.raises(subprocess.CalledProcessError):
3497 run_raw(["dot", "-Tsvg", input, "-o", os.devnull], env=env)
3498
3499
3500 def test_2258():
3501 """
3502 'id' attribute should be propagated to all graph children in output
3503 https://gitlab.com/graphviz/graphviz/-/issues/2258
3504 """
3505
3506 # locate our associated test case in this directory
3507 input = Path(__file__).parent / "2258.dot"
3508 assert input.exists(), "unexpectedly missing test case"
3509
3510 # translate this to SVG
3511 svg = dot("svg", input)
3512
3513 # load this as XML
3514 root = ET.fromstring(svg)
3515
3516 # the output is expected to contain a number of linear gradients, all of which
3517 # are semantic children of graph marked `id = "G2"`
3518 gradients = root.findall(".//{http://www.w3.org/2000/svg}linearGradient")
3519 assert len(gradients) > 0, "no gradients in output"
3520
3521 for gradient in gradients:
3522 assert "G2" in gradient.get("id"), "ID was not applied to linear gradients"
3523
3524
3525 def test_2270(tmp_path: Path):
3526 """
3527 `-O` should result in the expected output filename
3528 https://gitlab.com/graphviz/graphviz/-/issues/2270
3529 """
3530
3531 # write a simple graph
3532 input = tmp_path / "hello.gv"
3533 input.write_text("digraph { hello -> world }", encoding="utf-8")
3534
3535 # process it with Graphviz
3536 run_raw(["dot", "-T", "plain:dot:core", "-O", "hello.gv"], cwd=tmp_path)
3537
3538 # it should have produced output in the expected location
3539 output = tmp_path / "hello.gv.core.dot.plain"
3540 assert output.exists(), "-O resulted in an unexpected output filename"
3541
3542
3543 @pytest.mark.skipif(
3544 is_static_build(),
3545 reason="dynamic libraries are unavailable to link against in static builds",
3546 )
3547 def test_2272():
3548 """
3549 using `agmemread` with an unterminated string should not fail assertions
3550 https://gitlab.com/graphviz/graphviz/-/issues/2272
3551 """
3552
3553 # find co-located test source
3554 c_src = (Path(__file__).parent / "2272.c").resolve()
3555 assert c_src.exists(), "missing test case"
3556
3557 # run the test
3558 run_c(c_src, link=["cgraph", "gvc"])
3559
3560
3561 def test_2272_2():
3562 """
3563 An unterminated string in the source should not crash Graphviz. Variant of
3564 `test_2272`.
3565 """
3566
3567 # a graph with an open string
3568 graph = 'graph { a[label="abc'
3569
3570 # process it with Graphviz, which should not crash
3571 p = subprocess.run(["dot", "-o", os.devnull], input=graph, check=False, text=True)
3572 assert p.returncode != 0, "dot accepted invalid input"
3573 assert p.returncode == 1, "dot crashed"
3574
3575
3576 def test_2278():
3577 """
3578 the shortcut for setting ubiquitous properties should work as expected
3579 https://gitlab.com/graphviz/graphviz/-/issues/2278
3580 """
3581
3582 # a simple graph that will involve fonts
3583 graph = 'digraph { a->b[label="hello world"]; }'
3584
3585 # process this, setting the default font
3586 svg = run(
3587 ["dot", "-Tsvg", "-Efontname=Arial", "-Gfontname=Arial", "-Nfontname=Arial"],
3588 input=graph,
3589 )
3590
3591 # the output of this should differ from the default output
3592 default = dot("svg", source=graph)
3593 assert svg != default, "-E/-G/-N had no effect"
3594
3595 # the shortcut for setting all of these should behave as expected
3596 svg_a = run(["dot", "-Tsvg", "-Afontname=Arial"], input=graph)
3597 assert svg == svg_a, "-A was not equivalent to -E+-G+-N"
3598
3599
3600 def test_2282():
3601 """
3602 using the `fdp` layout with JSON output should result in valid JSON
3603 https://gitlab.com/graphviz/graphviz/-/issues/2282
3604 """
3605
3606 # locate our associated test case in this directory
3607 input = Path(__file__).parent / "2282.dot"
3608 assert input.exists(), "unexpectedly missing test case"
3609
3610 # translate this to JSON
3611 output = dot("json", input)
3612
3613 # confirm this is valid JSON
3614 json.loads(output)
3615
3616
3617 def test_2283():
3618 """
3619 `beautify=true` should correctly space nodes
3620 https://gitlab.com/graphviz/graphviz/-/issues/2283
3621 """
3622
3623 # find our collocated test case
3624 input = Path(__file__).parent / "2283.dot"
3625 assert input.exists(), "unexpectedly missing test case"
3626
3627 # translate this to SVG
3628 p = subprocess.run(
3629 ["dot", "-Tsvg", input], capture_output=True, check=False, text=True
3630 )
3631
3632 # if sfdp was built without libgts, it will not handle anything non-trivial
3633 no_gts_error = "remove_overlap: Graphviz not built with triangulation library"
3634 if no_gts_error in p.stderr:
3635 assert p.returncode != 0, "sfdp returned success after an error message"
3636 return
3637 p.check_returncode()
3638
3639 svg = p.stdout
3640
3641 # parse this into something we can inspect
3642 root = ET.fromstring(svg)
3643
3644 # find node N0
3645 n0s = root.findall(
3646 ".//{http://www.w3.org/2000/svg}title[.='N0']/../{http://www.w3.org/2000/svg}ellipse"
3647 )
3648 assert len(n0s) == 1, "failed to locate node N0"
3649 n0 = n0s[0]
3650
3651 # find node N1
3652 n1s = root.findall(
3653 ".//{http://www.w3.org/2000/svg}title[.='N1']/../{http://www.w3.org/2000/svg}ellipse"
3654 )
3655 assert len(n1s) == 1, "failed to locate node N1"
3656 n1 = n1s[0]
3657
3658 # find node N6
3659 n6s = root.findall(
3660 ".//{http://www.w3.org/2000/svg}title[.='N6']/../{http://www.w3.org/2000/svg}ellipse"
3661 )
3662 assert len(n6s) == 1, "failed to locate node N6"
3663 n6 = n6s[0]
3664
3665 # N1 and N6 should not have been drawn on top of each other
3666 n1_x = float(n1.attrib["cx"])
3667 n1_y = float(n1.attrib["cy"])
3668 n6_x = float(n6.attrib["cx"])
3669 n6_y = float(n6.attrib["cy"])
3670
3671 def sameish(a: float, b: float) -> bool:
3672 EPSILON = 0.2
3673 return -EPSILON < abs(a - b) < EPSILON
3674
3675 assert not (
3676 sameish(n1_x, n6_x) and sameish(n1_y, n6_y)
3677 ), "N1 and N6 placed identically"
3678
3679 # use the Law of Cosines to compute the angle between N0→N1 and N0→N6
3680 n0_x = float(n0.attrib["cx"])
3681 n0_y = float(n0.attrib["cy"])
3682 n0_n1_dist = math.dist((n0_x, n0_y), (n1_x, n1_y))
3683 n0_n6_dist = math.dist((n0_x, n0_y), (n6_x, n6_y))
3684 n1_n6_dist = math.dist((n1_x, n1_y), (n6_x, n6_y))
3685 angle = math.acos(
3686 (n0_n1_dist**2 + n0_n6_dist**2 - n1_n6_dist**2) / (2 * n0_n1_dist * n0_n6_dist)
3687 )
3688
3689 number_of_radial_nodes = 6
3690 assert sameish(
3691 angle, 2 * math.pi / number_of_radial_nodes
3692 ), "nodes not placed evenly"
3693
3694
3695 def test_2285():
3696 """
3697 using the `svg_inline` output should result in SVG you can inline to HTML
3698 https://gitlab.com/graphviz/graphviz/-/issues/2285
3699 """
3700
3701 # locate our associated test case in this directory
3702 input = Path(__file__).parent / "2285.dot"
3703 assert input.exists(), "unexpectedly missing test case"
3704
3705 # translate this to JSON
3706 output = dot("svg_inline", input)
3707
3708 assert "<?xml" not in output, "<?xml in output"
3709 assert "<!DOCTYPE" not in output, "<?xml in output"
3710 assert "xmlns" not in output, "xmlns in output"
3711 assert "<svg" in output, "<svg not in output"
3712
3713
3714 @pytest.mark.skipif(which("gxl2gv") is None, reason="gxl2gv not available")
3715 def test_2300_1():
3716 """
3717 translating GXL with an attribute `name` should not crash
3718 https://gitlab.com/graphviz/graphviz/-/issues/2300
3719 """
3720
3721 # locate our associated test case containing a node attribute `name`
3722 input = Path(__file__).parent / "2300.gxl"
3723 assert input.exists(), "unexpectedly missing test case"
3724
3725 # ask `gxl2gv` to process this
3726 gxl2gv = which("gxl2gv")
3727 run_raw([gxl2gv, input])
3728
3729
3730 def test_2307():
3731 """
3732 'id' attribute should be propagated to 'url' links in SVG output
3733 https://gitlab.com/graphviz/graphviz/-/issues/2307
3734 """
3735
3736 # locate our associated test case in this directory
3737 input = Path(__file__).parent / "2258.dot"
3738 assert input.exists(), "unexpectedly missing test case"
3739
3740 # translate this to SVG
3741 svg = dot("svg", input)
3742
3743 # load this as XML
3744 root = ET.fromstring(svg)
3745
3746 # the output is expected to contain a number of polygons, any of which have
3747 # `url` fills should include the ID “G2”
3748 polygons = root.findall(".//{http://www.w3.org/2000/svg}polygon")
3749 assert len(polygons) > 0, "no polygons in output"
3750
3751 for polygon in polygons:
3752 m = re.match(r"url\((?P<url>.*)\)$", polygon.get("fill"))
3753 if m is None:
3754 continue
3755 assert (
3756 re.search(r"\bG2_", m.group("url")) is not None
3757 ), "ID G2 was not applied to polygon fill url"
3758
3759
3760 def test_2325():
3761 """
3762 using more than 63 styles and/or more than 128 style bytes should not trigger
3763 an out-of-bounds memory read
3764 https://gitlab.com/graphviz/graphviz/-/issues/2325
3765 """
3766
3767 # locate our associated test case in this directory
3768 input = Path(__file__).parent / "2325.dot"
3769 assert input.exists(), "unexpectedly missing test case"
3770
3771 # run it through Graphviz
3772 dot("svg", input)
3773
3774
3775 @pytest.mark.skipif(shutil.which("groff") is None, reason="groff not available")
3776 def test_2341():
3777 """
3778 PIC backend should generate correct comments
3779 https://gitlab.com/graphviz/graphviz/-/issues/2341
3780 """
3781
3782 # a simple graph
3783 source = "digraph { a -> b; }"
3784
3785 # generate PIC from this
3786 pic = dot("pic", source=source)
3787
3788 # run this through groff
3789 groffed = run(["groff", "-Tascii", "-p"], input=pic)
3790
3791 # it should not contain any comments
3792 assert (
3793 re.search(r"^\s*#", groffed) is None
3794 ), "Graphviz comment remains in groff output"
3795
3796
3797 def test_2352():
3798 """
3799 referencing an all-one-line external SVG file should work
3800 https://gitlab.com/graphviz/graphviz/-/issues/2352
3801 """
3802
3803 # locate our associated test case in this directory
3804 input = Path(__file__).parent / "2352.dot"
3805 assert input.exists(), "unexpectedly missing test case"
3806
3807 # translate it to SVG
3808 svg = run(["dot", "-Tsvg", input], cwd=Path(__file__).parent)
3809
3810 assert '<image xlink:href="EDA.svg" ' in svg, "external file reference missing"
3811
3812
3813 def test_2352_1():
3814 """
3815 variant of 2352 with a leading space in front of `<svg`
3816 https://gitlab.com/graphviz/graphviz/-/issues/2352
3817 """
3818
3819 # locate our associated test case in this directory
3820 input = Path(__file__).parent / "2352_1.dot"
3821 assert input.exists(), "unexpectedly missing test case"
3822
3823 # translate it to SVG
3824 svg = run(["dot", "-Tsvg", input], cwd=Path(__file__).parent)
3825
3826 assert '<image xlink:href="EDA_1.svg" ' in svg, "external file reference missing"
3827
3828
3829 def test_2352_2():
3830 """
3831 variant of 2352 that spaces viewBox such that it is on a 200-character line
3832 boundary
3833 https://gitlab.com/graphviz/graphviz/-/issues/2352
3834 """
3835
3836 # locate our associated test case in this directory
3837 input = Path(__file__).parent / "2352_2.dot"
3838 assert input.exists(), "unexpectedly missing test case"
3839
3840 # translate it to SVG
3841 svg = run(["dot", "-Tsvg", input], cwd=Path(__file__).parent)
3842
3843 assert '<image xlink:href="EDA_2.svg" ' in svg, "external file reference missing"
3844
3845
3846 def test_2355():
3847 """
3848 Using >127 layers should not crash Graphviz
3849 https://gitlab.com/graphviz/graphviz/-/issues/2355
3850 """
3851
3852 # construct a graph with 128 layers
3853 graph = io.StringIO()
3854 graph.write("digraph {\n")
3855 layers = ":".join(f"l{i}" for i in range(128))
3856 graph.write(f' layers="{layers}";\n')
3857 for i in range(128):
3858 graph.write(f' n{i}[layer="l{i}"];\n')
3859 graph.write("}\n")
3860
3861 # process this with dot
3862 dot("svg", source=graph.getvalue())
3863
3864
3865 @pytest.mark.parametrize("testcase", ("2368.dot", "2368_1.dot"))
3866 @pytest.mark.xfail(strict=True) # FIXME
3867 def test_2368(testcase: str):
3868 """
3869 routesplines should not corrupt its `prev` and `next` indices
3870 https://gitlab.com/graphviz/graphviz/-/issues/2368
3871 """
3872
3873 # locate our associated test case in this directory
3874 input = Path(__file__).parent / testcase
3875 assert input.exists(), "unexpectedly missing test case"
3876
3877 # run it through Graphviz
3878 dot("svg", input)
3879
3880
3881 @pytest.mark.skipif(shutil.which("tclsh") is None, reason="tclsh not available")
3882 def test_2370():
3883 """
3884 tcldot should have a version number TCL accepts
3885 https://gitlab.com/graphviz/graphviz/-/issues/2370
3886 """
3887
3888 # if this appears to be an ASan-enabled CI job, teach `tclsh` to load ASan’s
3889 # supporting library because it is otherwise unaware that Tcldot depends on this
3890 # being loaded first
3891 env = os.environ.copy()
3892 dot_exe = which("dot")
3893 if is_asan_instrumented(dot_exe):
3894 cc = os.environ.get("CC", "gcc")
3895 libasan = run([cc, "-print-file-name=libasan.so"]).strip()
3896 print(f"setting LD_PRELOAD={libasan}")
3897 env["LD_PRELOAD"] = libasan
3898
3899 # ask TCL to import the Graphviz package
3900 response = run(
3901 ["tclsh"],
3902 stderr=subprocess.STDOUT,
3903 input="package require Tcldot;",
3904 env=env,
3905 )
3906
3907 assert (
3908 "error reading package index file" not in response
3909 ), "tcldot cannot be loaded by TCL"
3910
3911
3912 def test_2371():
3913 """
3914 Large graphs should not cause rectangle area calculation overflows
3915 https://gitlab.com/graphviz/graphviz/-/issues/2371
3916 """
3917
3918 # locate our associated test case in this directory
3919 input = Path(__file__).parent / "2371.dot"
3920 assert input.exists(), "unexpectedly missing test case"
3921
3922 # run it through Graphviz
3923 run_raw(["dot", "-Tsvg", "-Knop2", "-o", os.devnull, input])
3924
3925
3926 @pytest.mark.skipif(
3927 platform.system() == "Windows",
3928 reason="gvplugin_list symbol is not exposed on Windows",
3929 )
3930 def test_2375():
3931 """
3932 `gvplugin_list` should return full plugin names
3933 https://gitlab.com/graphviz/graphviz/-/issues/2375
3934 """
3935
3936 # find co-located test source
3937 c_src = (Path(__file__).parent / "2375.c").resolve()
3938 assert c_src.exists(), "missing test case"
3939
3940 # run the test
3941 run_c(c_src, link=["gvc"])
3942
3943
3944 def test_2377():
3945 """
3946 3 letter hex color codes should be accepted
3947 https://gitlab.com/graphviz/graphviz/-/issues/2377
3948 """
3949
3950 # run some 6 letter color input through Graphviz
3951 input = 'digraph { n [color="#cc0000" fillcolor="#ffcc00" style=filled] }'
3952 svg1 = dot("svg", source=input)
3953
3954 # try the equivalent with 3 letter colors
3955 input = 'digraph { n [color="#c00" fillcolor="#fc0" style=filled] }'
3956 svg2 = dot("svg", source=input)
3957
3958 assert svg1 == svg2, "3 letter hex colors were not translated correctly"
3959
3960
3961 def test_2390():
3962 """
3963 using an out of range `xdotversion` should not crash Graphviz
3964 https://gitlab.com/graphviz/graphviz/-/issues/2390
3965 """
3966
3967 # some input with an invalid large `xdotversion`
3968 input = 'graph { xdotversion=99; n[label="hello world"]; }'
3969
3970 # run this through Graphviz
3971 dot("xdot", source=input)
3972
3973
3974 def test_2391():
3975 """
3976 `nslimit1=0` should not cause Graphviz to crash
3977 https://gitlab.com/graphviz/graphviz/-/issues/2391
3978 """
3979
3980 # locate our associated test case in this directory
3981 input = Path(__file__).parent / "2391.dot"
3982 assert input.exists(), "unexpectedly missing test case"
3983
3984 # run it through Graphviz
3985 dot("svg", input)
3986
3987
3988 def test_2391_1():
3989 """
3990 `nslimit1=0` with a label should not cause Graphviz to crash
3991 https://gitlab.com/graphviz/graphviz/-/issues/2391
3992 """
3993
3994 # locate our associated test case in this directory
3995 input = Path(__file__).parent / "2391_1.dot"
3996 assert input.exists(), "unexpectedly missing test case"
3997
3998 # run it through Graphviz
3999 dot("svg", input)
4000
4001
4002 def test_2397():
4003 """
4004 escapes in strings should be handled correctly
4005 https://gitlab.com/graphviz/graphviz/-/issues/2397
4006 """
4007
4008 # find co-located test source
4009 c_src = (Path(__file__).parent / "2397.c").resolve()
4010 assert c_src.exists(), "missing test case"
4011
4012 # run this to generate a graph
4013 link = ["cgraph", "gvc"]
4014 if is_static_build():
4015 # in static builds, we also need transitive dependencies
4016 link += ["cdt"]
4017 source, _ = run_c(c_src, link=link)
4018
4019 # this should have produced a valid graph
4020 dot("svg", source=source)
4021
4022
4023 def test_2397_1():
4024 """
4025 a variant of test_2397 that confirms the same works via the command line
4026 https://gitlab.com/graphviz/graphviz/-/issues/2397
4027 """
4028
4029 source = 'digraph { a[label="foo\\\\\\"bar"]; }'
4030
4031 # run this through dot
4032 output = dot("dot", source=source)
4033
4034 # the output should be valid dot
4035 dot("svg", source=output)
4036
4037
4038 @pytest.mark.skipif(shutil.which("shellcheck") is None, reason="shellcheck unavailable")
4039 def test_2404():
4040 """
4041 shell syntax used by gvmap should be correct
4042 https://gitlab.com/graphviz/graphviz/-/issues/2404
4043 """
4044 gvmap_sh = Path(__file__).parent / "../cmd/gvmap/gvmap.sh"
4045 run_raw(["shellcheck", "-S", "error", gvmap_sh])
4046
4047
4048 def test_2406():
4049 """
4050 arrow types like `invdot` and `onormalonormal` should be displayed correctly
4051 https://gitlab.com/graphviz/graphviz/-/issues/2406
4052 """
4053
4054 # locate our associated test case in this directory
4055 input = Path(__file__).parent / "2406.dot"
4056 assert input.exists(), "unexpectedly missing test case"
4057
4058 # run it through Graphviz
4059 output = dot("svg", input)
4060
4061 # the rounded hollows should be present
4062 assert re.search(r"\bellipse\b", output), "missing element of invdot arrow"
4063
4064
4065 @pytest.mark.parametrize("source", ("2413_1.dot", "2413_2.dot"))
4066 def test_2413(source: str):
4067 """
4068 graphs that induce an edge length > 65535 should be supported
4069 https://gitlab.com/graphviz/graphviz/-/issues/2413
4070 """
4071
4072 # locate our associated test case in this directory
4073 input = Path(__file__).parent / source
4074 assert input.exists(), "unexpectedly missing test case"
4075
4076 # run it through Graphviz
4077 proc = subprocess.run(
4078 ["dot", "-Tsvg", "-o", os.devnull, input],
4079 stderr=subprocess.PIPE,
4080 check=True,
4081 text=True,
4082 )
4083
4084 # work around macOS warnings
4085 stderr = remove_xtype_warnings(proc.stderr).strip()
4086
4087 # work around ASan informational printing
4088 stderr = remove_asan_summary(stderr)
4089
4090 # no warnings should have been generated
4091 assert stderr == "", "long edges resulted in a warning"
4092
4093
4094 def test_2429():
4095 """
4096 the vt target should be usable
4097 https://gitlab.com/graphviz/graphviz/-/issues/2429
4098 """
4099
4100 # a basic graph
4101 source = "digraph { a -> b; }"
4102
4103 # run it through Graphviz
4104 dot("vt", source=source)
4105
4106
4107 @pytest.mark.skipif(which("nop") is None, reason="nop not available")
4108 @pytest.mark.xfail(
4109 strict=True, reason="https://gitlab.com/graphviz/graphviz/-/issues/2436"
4110 )
4111 def test_2436():
4112 """
4113 nop should preserve empty labels
4114 https://gitlab.com/graphviz/graphviz/-/issues/2436
4115 """
4116
4117 # locate our associated test case in this directory
4118 input = Path(__file__).parent / "2436.dot"
4119 assert input.exists(), "unexpectedly missing test case"
4120
4121 # run it through nop
4122 nop = which("nop")
4123 output = run([nop, input])
4124
4125 # the empty label should be present
4126 assert re.search(r'\blabel\s*=\s*""', output), "empty label was not preserved"
4127
4128
4129 @pytest.mark.xfail(
4130 strict=True, reason="https://gitlab.com/graphviz/graphviz/-/issues/2434"
4131 )
4132 def test_2434():
4133 """
4134 the order in which `agmemread` and `gvContext` calls are made should have no impact
4135 https://gitlab.com/graphviz/graphviz/-/issues/2434
4136 """
4137
4138 # find co-located test source
4139 c_src = (Path(__file__).parent / "2434.c").resolve()
4140 assert c_src.exists(), "missing test case"
4141
4142 # generate an SVG by calling `gvContext` first
4143 before, _ = run_c(c_src, ["before"], link=["cgraph", "gvc"])
4144
4145 # generate an SVG by calling `gvContext` second
4146 after, _ = run_c(c_src, ["after"], link=["cgraph", "gvc"])
4147
4148 # resulting images should be identical
4149 assert before == after, "agmemread/gvContext ordering affected image output"
4150
4151
4152 def test_2437():
4153 """
4154 both an arrowhead and an arrowtail shall be created when using dir=both,
4155 compass ports, an edge default attribute and rank=same
4156 https://gitlab.com/graphviz/graphviz/-/issues/2437
4157 """
4158
4159 # locate our associated test case in this directory
4160 input = Path(__file__).parent / "2437.dot"
4161 assert input.exists(), "unexpectedly missing test case"
4162
4163 # translate this to SVG
4164 svg = dot("svg", input)
4165
4166 # load this as XML
4167 root = ET.fromstring(svg)
4168
4169 # The output is expected to contain tree polygons. The graph "background"
4170 # polygon, the arrowhead polygon and the arrowtail polygon.
4171 polygons = root.findall(".//{http://www.w3.org/2000/svg}polygon")
4172
4173 assert len(polygons) == 3, "wrong number of polygons in output"
4174
4175
4176 @pytest.mark.xfail(
4177 strict=True, reason="https://gitlab.com/graphviz/graphviz/-/issues/2416"
4178 )
4179 def test_2416():
4180 """
4181 `splines=curved` should not affect arrow directions
4182 https://gitlab.com/graphviz/graphviz/-/issues/2416
4183 """
4184
4185 # an input graph that provokes the problem
4186 input = "digraph G { splines=curved; b -> a; a -> b; }"
4187
4188 # run it through Graphviz
4189 output = dot("json", source=input)
4190 data = json.loads(output)
4191
4192 edges = data["edges"]
4193 assert len(edges) == 2, "unexpected number of output edges"
4194
4195 # extract the height each edge’s arrow starts at
4196 y_1 = edges[0]["_hdraw_"][3]["points"][0][1]
4197 y_2 = edges[1]["_hdraw_"][3]["points"][0][1]
4198
4199 # assuming the graph is vertical, these should not be too close
4200 assert abs(y_1 - y_2) > 1, "edge arrows appear to be drawn next to the same node"
4201
4202
4203 @pytest.mark.skipif(which("gvpr") is None, reason="GVPR not available")
4204 def test_2454():
4205 """
4206 gvpr should support sscanf
4207 https://gitlab.com/graphviz/graphviz/-/issues/2454
4208 """
4209
4210 # an input graph that provokes the problem
4211 input = "graph x{a -- {b c}}"
4212
4213 # run it through Graphviz
4214 output = dot("dot", source=input)
4215
4216 # run it through gvpr
4217 program = Path(__file__).parent / "2454.gvpr"
4218 gvprbin = which("gvpr")
4219 with subprocess.Popen(
4220 [gvprbin, "-cf", program], stdin=subprocess.PIPE, text=True
4221 ) as p:
4222 p.communicate(output)
4223 assert p.returncode == 0, "gvpr failed"
4224
4225
4226 @pytest.mark.skipif(which("twopi") is None, reason="twopi not available")
4227 @pytest.mark.xfail(
4228 strict=True, reason="https://gitlab.com/graphviz/graphviz/-/issues/2457"
4229 )
4230 def test_2457():
4231 """
4232 node definition order should not affect twopi’s layout
4233 https://gitlab.com/graphviz/graphviz/-/issues/2457
4234 """
4235
4236 # locate our associated test cases in this directory
4237 case1 = Path(__file__).parent / "2457_1.dot"
4238 assert case1.exists(), "unexpectedly missing test case"
4239 case2 = Path(__file__).parent / "2457_2.dot"
4240 assert case2.exists(), "unexpectedly missing test case"
4241
4242 # tweak the environment to force deterministic PDF generation
4243 env = os.environ.copy()
4244 env["SOURCE_DATE_EPOCH"] = "0"
4245
4246 # generate PDFs
4247 twopi = which("twopi")
4248 pdf1 = run_raw([twopi, "-Tpdf", case1], env=env)
4249 pdf2 = run_raw([twopi, "-Tpdf", case2], env=env)
4250
4251 assert pdf1 == pdf2, "node definition order affected PDF generation"
4252
4253
4254 @pytest.mark.xfail(
4255 strict=True, reason="https://gitlab.com/graphviz/graphviz/-/issues/2458"
4256 )
4257 def test_2458():
4258 """
4259 `pack=true` should not result in edge labels disappearing
4260 https://gitlab.com/graphviz/graphviz/-/issues/2458
4261 """
4262
4263 # locate our associated test case in this directory
4264 input = Path(__file__).parent / "2458.dot"
4265 assert input.exists(), "unexpectedly missing test case"
4266
4267 # run it through Graphviz
4268 output = dot("svg", input)
4269
4270 # the edge label should be present
4271 assert re.search(r"\bconnected\b", output), "missing edge label"
4272
4273
4274 def test_2460():
4275 """
4276 labels involving back slashes should come out correctly in JSON
4277 https://gitlab.com/graphviz/graphviz/-/issues/2460
4278 """
4279
4280 # locate our associated test case in this directory
4281 input = Path(__file__).parent / "2460.dot"
4282 assert input.exists(), "unexpectedly missing test case"
4283
4284 # run it through Graphviz
4285 output = dot("json", input)
4286 data = json.loads(output)
4287
4288 assert (
4289 data["objects"][0]["_ldraw_"][2]["text"]
4290 == r"double back slash in label \\. End should be the last word - End"
4291 ), "back slashes in labels handled incorrectly"
4292
4293
4294 @pytest.mark.xfail(
4295 strict=platform.system() != "Windows",
4296 reason="https://gitlab.com/graphviz/graphviz/-/issues/2470",
4297 )
4298 def test_2470():
4299 """
4300 another “trouble in init_rank variant”
4301 https://gitlab.com/graphviz/graphviz/-/issues/2470
4302 """
4303
4304 # locate our associated test case in this directory
4305 input = Path(__file__).parent / "2470.dot"
4306 assert input.exists(), "unexpectedly missing test case"
4307
4308 # run it through Graphviz
4309 dot("ps", input)
4310
4311
4312 @pytest.mark.xfail(
4313 reason="https://gitlab.com/graphviz/graphviz/-/issues/2471",
4314 strict=True,
4315 )
4316 def test_2471():
4317 """
4318 another “trouble in init_rank variant”
4319 https://gitlab.com/graphviz/graphviz/-/issues/2471
4320 """
4321
4322 # locate our associated test case in this directory
4323 input = Path(__file__).parent / "2471.dot"
4324 assert input.exists(), "unexpectedly missing test case"
4325
4326 # run it through Graphviz
4327 dot("png", input)
4328
4329
4330 @pytest.mark.xfail(
4331 is_rocky_8(),
4332 reason="Cairo is <v1.16 or malfunctions",
4333 strict=True,
4334 )
4335 def test_2473_1():
4336 """
4337 `SOURCE_DATE_EPOCH` should be usable to suppress timestamps
4338 https://gitlab.com/graphviz/graphviz/-/issues/2473
4339 """
4340
4341 # a trivial graph
4342 graph = "graph { a -- b }".encode("utf-8")
4343
4344 # set an epoch
4345 env = os.environ.copy()
4346 env["SOURCE_DATE_EPOCH"] = "60"
4347
4348 # generate a PDF
4349 first_run = run_raw(["dot", "-Tpdf"], input=graph, env=env)
4350
4351 # wait long enough for the current time to change
4352 time.sleep(2)
4353
4354 # generate another PDF
4355 second_run = run_raw(["dot", "-Tpdf"], input=graph, env=env)
4356
4357 assert (
4358 first_run == second_run
4359 ), "PDF output is dependent on current time even when $SOURCE_DATE_EPOCH is set"
4360
4361
4362 def test_2473_2():
4363 """
4364 When handling `SOURCE_DATE_EPOCH`, from
4365 https://reproducible-builds.org/specs/source-date-epoch/:
4366
4367 If the value is malformed, the build process SHOULD exit with a non-zero
4368 error code.
4369
4370 https://gitlab.com/graphviz/graphviz/-/issues/2473
4371 """
4372
4373 # set up an invalid epoch
4374 env = os.environ.copy()
4375 env["SOURCE_DATE_EPOCH"] = "foo"
4376
4377 # confirm Graphviz rejects this
4378 with pytest.raises(subprocess.CalledProcessError):
4379 run(
4380 ["dot", "-Tpdf", "-o", os.devnull],
4381 input="graph { a -- b }",
4382 env=env,
4383 encoding="utf-8",
4384 )
4385
4386
4387 def test_2476():
4388 """
4389 tweaking `mclimit` should not lead to a “trouble in init_rank” failure
4390 https://gitlab.com/graphviz/graphviz/-/issues/2476
4391 """
4392
4393 # locate our associated test case in this directory
4394 input = Path(__file__).parent / "2476.dot"
4395 assert input.exists(), "unexpectedly missing test case"
4396
4397 # run it through Graphviz
4398 run_raw(["dot", "-Tsvg", "-Gmclimit=0.5", "-o", os.devnull, input])
4399
4400
4401 def test_2490():
4402 """
4403 the `crow` arrow shall be correctly placed and orientated when ports are used
4404 https://gitlab.com/graphviz/graphviz/-/issues/2490
4405 """
4406
4407 # locate our associated test case in this directory
4408 input = Path(__file__).parent / "2490.dot"
4409 assert input.exists(), "unexpectedly missing test case"
4410
4411 # translate this to SVG
4412 svg = dot("svg", input)
4413
4414 # load this as XML
4415 root = ET.fromstring(svg)
4416
4417 # The output is expected to contain three polygons, of which the two last
4418 # are the `crow` arrow shapes of the edge head and tail. Except for the
4419 # crow's "toes", the corners of these are expected to have the same x
4420 # position as the nodes' centers. The "toes" are expected to have x
4421 # positions half the width more or less than the nodes' centers.
4422 ellipses = root.findall(".//{http://www.w3.org/2000/svg}ellipse")
4423 assert len(ellipses) == 2, "wrong number of ellipses in output"
4424 cx = float(ellipses[0].get("cx"))
4425 assert float(ellipses[1].get("cx")) == cx
4426
4427 polygons = root.findall(".//{http://www.w3.org/2000/svg}polygon")
4428 assert len(polygons) == 3, "wrong number of polygons in output"
4429 for polygon_index, polygon in enumerate(polygons):
4430 points_attr = polygon.get("points")
4431 point_pair_strs = points_attr.split(" ")
4432 points = [point_pair_str.split(",") for point_pair_str in point_pair_strs]
4433 if polygon_index == 0:
4434 assert len(points) == 5
4435 # ignore the graph polygon
4436 continue
4437 assert len(points) == 9
4438 for point_index, point in enumerate(points):
4439 x = float(point[0])
4440 crow_width = 9
4441 expected_crow_tip_and_shaft_x = cx
4442 expected_crow_toe_left_x = cx - crow_width / 2
4443 expected_crow_toe_right_x = cx + crow_width / 2
4444 expected_first_crow_toe_x = (
4445 expected_crow_toe_left_x
4446 if polygon_index == 1
4447 else expected_crow_toe_right_x
4448 )
4449 expected_second_crow_toe_x = (
4450 expected_crow_toe_right_x
4451 if polygon_index == 1
4452 else expected_crow_toe_left_x
4453 )
4454 if point_index in [0, 2, 3, 4, 5, 6, 8]:
4455 assert x == expected_crow_tip_and_shaft_x
4456 elif point_index == 1:
4457 assert x == expected_first_crow_toe_x
4458 elif point_index == 7:
4459 assert x == expected_second_crow_toe_x
4460
4461
4462 @pytest.mark.skipif(which("gv2gml") is None, reason="gv2gml not available")
4463 def test_2493():
4464 """
4465 `gv2gml` should support the yWorks.com variant of GML
4466 https://gitlab.com/graphviz/graphviz/-/issues/2493
4467 """
4468
4469 # a trivial graph with a colored label
4470 src = 'graph { a -- b[label="foo", fontcolor="red"]; }'
4471
4472 # pass this through `gv2gml`
4473 gv2gml = which("gv2gml")
4474 gml = run([gv2gml, "-y"], input=src)
4475
4476 assert (
4477 re.search(r"\bfontcolor\b", gml) is None
4478 ), "gv2gml emitted 'fontcolor' when in yWorks.com mode"
4479 assert (
4480 re.search(r"\bcolor\b", gml) is not None
4481 ), "gv2gml did not emit LabelGraphics 'color' attribute"
4482
4483
4484 def test_2497():
4485 """
4486 graph rendering should be deterministic
4487 https://gitlab.com/graphviz/graphviz/-/issues/2497
4488 """
4489
4490 # get our baseline reference
4491 input = Path(__file__).parent / "2497.dot"
4492 assert input.exists(), "unexpectedly missing test case"
4493 ref = dot("svg", input)
4494
4495 # now repeat this, expecting it not to change
4496 for _ in range(20):
4497 out = dot("svg", input)
4498 assert ref == out, "repeated rendering changed output"
4499
4500
4501 def test_2502():
4502 """
4503 unicode labels should be usable
4504 https://gitlab.com/graphviz/graphviz/-/issues/2502
4505 """
4506
4507 # locate our associated test case in this directory
4508 input = Path(__file__).parent / "2502.dot"
4509 assert input.exists(), "unexpectedly missing test case"
4510
4511 # run it through Graphviz
4512 dot("dot", input)
4513
4514
4515 @pytest.mark.xfail(
4516 strict=True, reason="https://gitlab.com/graphviz/graphviz/-/issues/2516"
4517 )
4518 def test_2516():
4519 """
4520 errors in HTML labels should result in a message with correct line number
4521 https://gitlab.com/graphviz/graphviz/-/issues/2516
4522 """
4523
4524 # locate our associated test case in this directory
4525 input = Path(__file__).parent / "2516.dot"
4526 assert input.exists(), "unexpectedly missing test case"
4527
4528 # run it through Graphviz
4529 proc = subprocess.run(
4530 ["dot", "-Tsvg", "-o", os.devnull, input],
4531 stderr=subprocess.PIPE,
4532 check=False,
4533 text=True,
4534 )
4535
4536 assert proc.returncode != 0, "malformed HTML label was accepted"
4537
4538 assert (
4539 re.search(r"\bline 1\b", proc.stderr) is None
4540 ), "incorrect line number in error message"
4541
4542 assert (
4543 re.search(r"\bline 2\b", proc.stderr) is not None
4544 ), "correct line number missing from error message"
4545
4546
4547 @pytest.mark.parametrize(
4548 "testcase",
4549 (
4550 "705.dot",
4551 pytest.param(
4552 "2521.dot",
4553 marks=pytest.mark.xfail(
4554 strict=False,
4555 reason="https://gitlab.com/graphviz/graphviz/-/issues/2521",
4556 ),
4557 ),
4558 "2521_1.dot",
4559 ),
4560 )
4561 def test_2521(testcase: str):
4562 """
4563 `newrank=false` should reset to the default behavior
4564 https://gitlab.com/graphviz/graphviz/-/issues/2521
4565 """
4566
4567 # locate our associated test case in this directory
4568 input = Path(__file__).parent / testcase
4569 assert input.exists(), "unexpectedly missing test case"
4570
4571 def sh(args: list[Union[Path, str]]) -> bytes:
4572 """run a command, as if via the shell"""
4573 # dump the command being run for the user to observe if the test fails
4574 print(f"+ {shlex.join(str(x) for x in args)}")
4575
4576 proc = subprocess.run(args, stdout=subprocess.PIPE, check=True)
4577 return proc.stdout
4578
4579 # process this with and without `newrank=true`
4580 off = sh(["dot", "-Tpng", input])
4581 on = sh(["dot", "-Gnewrank=true", "-Tpng", input])
4582
4583 assert off != on, "-Gnewrank=true had no effect"
4584
4585 # we should be able to reset `newrank` with an explicit setting
4586 force_off = sh(["dot", "-Gnewrank=false", "-Tpng", input])
4587 assert force_off == off, "-Gnewrank=false did not reset the default"
4588
4589
4590 @pytest.mark.xfail(
4591 is_macos(), strict=True, reason="https://gitlab.com/graphviz/graphviz/-/issues/2538"
4592 )
4593 def test_2538():
4594 """
4595 `chanSearch` assertion on `cp` should not fail
4596 https://gitlab.com/graphviz/graphviz/-/issues/2538
4597 """
4598
4599 # locate our associated test case in this directory
4600 input = Path(__file__).parent / "2538.dot"
4601 assert input.exists(), "unexpectedly missing test case"
4602
4603 # run it through Graphviz
4604 dot("dot", input)
4605
4606
4607 @pytest.mark.skipif(which("sfdp") is None, reason="sfdp not available")
4608 def test_2556():
4609 """
4610 sfdp should not fail a GTS assertion
4611 https://gitlab.com/graphviz/graphviz/-/issues/2556
4612 """
4613
4614 # locate our associated test case in this directory
4615 input = Path(__file__).parent / "2556.dot"
4616 assert input.exists(), "unexpectedly missing test case"
4617
4618 # run this through sfdp
4619 sfdp = which("sfdp")
4620 p = subprocess.run(
4621 [sfdp, "-Tpng", "-o", os.devnull, input],
4622 stderr=subprocess.PIPE,
4623 check=False,
4624 text=True,
4625 )
4626
4627 # if sfdp was built without libgts, it will not handle anything non-trivial
4628 no_gts_error = "remove_overlap: Graphviz not built with triangulation library"
4629 if no_gts_error in p.stderr:
4630 assert p.returncode != 0, "sfdp returned success after an error message"
4631 return
4632
4633 p.check_returncode()
4634
4635
4636 def test_2559():
4637 """
4638 `concentrate=true` should actually concentrate edges
4639 https://gitlab.com/graphviz/graphviz/-/issues/2559
4640 """
4641
4642 # locate our associated test case in this directory
4643 input = Path(__file__).parent / "2559.dot"
4644 assert input.exists(), "unexpectedly missing test case"
4645
4646 # convert this to JSON
4647 layout = dot("json", input)
4648 parsed = json.loads(layout)
4649
4650 # the last edge, d→b, should be drawn as a curve rather than a straight edge
4651 assert not parsed["edges"][-1]["pos"].startswith(
4652 "e"
4653 ), "concentrated edge drawn as a regular straight edge"
4654
4655
4656 @pytest.mark.skipif(which("fdp") is None, reason="fdp not available")
4657 def test_2563():
4658 """
4659 `overlap` parameters should generate different results
4660 https://gitlab.com/graphviz/graphviz/-/issues/2563
4661 """
4662
4663 # locate our associated test case in this directory
4664 input = Path(__file__).parent / "2563.dot"
4665 assert input.exists(), "unexpectedly missing test case"
4666
4667 # try various `overlap=…` values
4668 results: set[str] = set()
4669 for overlap in ("scale", "scalexy"):
4670 # run this through fdp
4671 fdp = which("fdp")
4672 p = subprocess.run(
4673 [fdp, f"-Goverlap={overlap}", input],
4674 capture_output=True,
4675 check=False,
4676 text=True,
4677 )
4678
4679 # if fdp was built without libgts, it will not handle anything non-trivial
4680 no_gts_error = "remove_overlap: Graphviz not built with triangulation library"
4681 if no_gts_error in p.stderr:
4682 assert p.returncode != 0, "fdp returned success after an error message"
4683 return
4684 p.check_returncode()
4685
4686 # remove the overlap parameter itself, that would otherwise cause each
4687 # output to be unique
4688 output = re.sub(r"\boverlap\s*=\s*scale(xy)?\b", "", p.stdout)
4689
4690 assert (
4691 output not in results
4692 ), "altering `overlap` attribute did not affect output"
4693 results.add(output)
4694
4695
4696 def test_2564():
4697 """
4698 `overlap="scale"` should not result in all nodes overlapping
4699 https://gitlab.com/graphviz/graphviz/-/issues/2564
4700 """
4701
4702 # locate our associated test case in this directory
4703 input = Path(__file__).parent / "2564.dot"
4704 assert input.exists(), "unexpectedly missing test case"
4705
4706 # convert this to JSON
4707 layout = run(["dot", "-Kneato", "-Tjson", input])
4708 parsed = json.loads(layout)
4709
4710 # nodes should not be on top of one another
4711 starts = []
4712 for node in parsed["objects"]:
4713 start = re.match(r"(?P<start>\d+(\.\d+)?,\d+(\.\d+)?)\b", node["pos"]).group(
4714 "start"
4715 )
4716 assert start not in starts, "nodes overlap"
4717 starts += [start]
4718
4719
4720 @pytest.mark.skipif(shutil.which("tclsh") is None, reason="tclsh not available")
4721 @pytest.mark.skipif(
4722 platform.system() == "Windows",
4723 reason="pexpect.spawn is not available on Windows "
4724 "(https://pexpect.readthedocs.io/en/stable/overview.html#pexpect-on-windows)",
4725 )
4726 def test_2568():
4727 """
4728 tags used in TCL output should be usable for later lookup
4729 https://gitlab.com/graphviz/graphviz/-/issues/2568
4730 """
4731
4732 # locate the TCL input for this test
4733 prelude = Path(__file__).parent / "2568.tcl"
4734 assert prelude.exists(), "unexpectedly missing test collateral"
4735
4736 # if this appears to be an ASan-enabled CI job, teach `tclsh` to load ASan’s
4737 # supporting library because it is otherwise unaware that Tcldot depends on this
4738 # being loaded first
4739 env = os.environ.copy()
4740 dot_exe = which("dot")
4741 if is_asan_instrumented(dot_exe):
4742 cc = os.environ.get("CC", "gcc")
4743 libasan = run([cc, "-print-file-name=libasan.so"]).strip()
4744 print(f"setting LD_PRELOAD={libasan}")
4745 env["LD_PRELOAD"] = libasan
4746
4747 # startup TCL and load our graph setup code
4748 proc = pexpect.spawn("tclsh", timeout=1, env=env)
4749 proc.expect("% ")
4750 proc.sendline(f'source "{shlex.quote(str(prelude))}"')
4751
4752 # look for tags to query
4753 while True:
4754 index = proc.expect(
4755 [
4756 "invalid command name",
4757 re.compile(rb"-tags {\d(?P<tag>(edge|node)0x[\da-fA-F]+)}"),
4758 pexpect.TIMEOUT,
4759 ]
4760 )
4761
4762 # stdout and stderr are multiplexed onto the same stream by `pexpect`, so if one
4763 # of the commands we previously entered was not recognized, we will see an error
4764 # at the end of the output stream
4765 assert index != 0, "at least one tag was not recognized"
4766
4767 # if we got no output within 1s, assume we are done
4768 if index == 2:
4769 break
4770
4771 tag = proc.match.group("tag").decode("utf-8")
4772
4773 # try to look up its corresponding entities
4774 if tag.startswith("edge"):
4775 cmd = "listnodes"
4776 else:
4777 cmd = "listedges"
4778 proc.sendline(f"{tag} {cmd}")
4779
4780
4781 @pytest.mark.skipif(which("sfdp") is None, reason="sfdp not available")
4782 def test_2572():
4783 """
4784 sfdp should be able to find non-overlapping layouts
4785 https://gitlab.com/graphviz/graphviz/-/issues/2572
4786 """
4787
4788 # locate our associated test case in this directory
4789 input = Path(__file__).parent / "2572.dot"
4790 assert input.exists(), "unexpectedly missing test case"
4791
4792 # run this through SFDP and convert this to JSON
4793 sfdp = which("sfdp")
4794 layout = run([sfdp, "-Kneato", "-Tjson", input])
4795 parsed = json.loads(layout)
4796
4797 @dataclasses.dataclass
4798 class Box:
4799 """
4800 a geometric rectangle, defined by two of its corners
4801 """
4802
4803 llx: float # lower left X coordinate
4804 lly: float # lower left Y coordinate
4805 urx: float # upper right X coordinate
4806 ury: float # upper right Y coordinate
4807
4808 def overlaps(self, other: "Box") -> bool:
4809 """
4810 do we intersect the given box?
4811 """
4812 if self.llx > other.urx:
4813 return False
4814 if self.lly > other.ury:
4815 return False
4816 if self.urx < other.llx:
4817 return False
4818 if self.ury < other.lly:
4819 return False
4820 return True
4821
4822 nodes: list[Box] = []
4823 for obj in parsed["objects"]:
4824 # extract the ellipse drawn for this node
4825 ellipses = [e for e in obj["_draw_"] if e["op"] == "e"]
4826 assert len(ellipses) == 1, "could not find ellipse for node"
4827 center_x, center_y, width, height = ellipses[0]["rect"]
4828
4829 assert center_x >= width, "ellipse extends into negative X space"
4830 assert center_y >= height, "ellipse extends into negative Y space"
4831
4832 node = Box(
4833 center_x - width, center_y - height, center_x + width, center_y + height
4834 )
4835
4836 assert not any(n.overlaps(node) for n in nodes), "nodes overlap"
4837
4838 nodes.append(node)
4839
4840
4841 @pytest.mark.skipif(which("gvpr") is None, reason="GVPR not available")
4842 def test_2577():
4843 """
4844 accessing an uninitialized string should not corrupt GVPR’s state
4845 https://gitlab.com/graphviz/graphviz/-/issues/2577
4846 """
4847
4848 # find our collocated test case
4849 program = Path(__file__).parent / "2577.gvpr"
4850 assert program.exists(), "unexpectedly missing test case"
4851
4852 # run it through GVPR
4853 output = gvpr(program)
4854
4855 # it should have printed an empty string for the uninitialized attribute
4856 assert (
4857 "Before...\n<>\nAfter." in output
4858 ), "incorrect handling of uninitialized attribute in GVPR"
4859
4860
4861 @pytest.mark.skipif(which("gvpr") is None, reason="GVPR not available")
4862 def test_2577_1():
4863 """
4864 a variant of `test_2577` that does not involve attribute access
4865 https://gitlab.com/graphviz/graphviz/-/issues/2577
4866 """
4867
4868 # run GVPR on a simple program
4869 gvprbin = which("gvpr")
4870 output = run(
4871 [gvprbin, 'BEGIN { printf("hello%s world\\n", ""); }'],
4872 stdin=subprocess.DEVNULL,
4873 )
4874
4875 # it should have printed the expected text
4876 assert output == "hello world\n", "gvpr cannot handle empty strings to printf"
4877
4878
4879 @pytest.mark.parametrize(
4880 "program,a_arg,expected",
4881 (
4882 ("BEGIN { print(#ARGV); }", "abc", "1"),
4883 ("BEGIN { print(0 in ARGV); }", "abc", "1"),
4884 (
4885 'BEGIN {string argv[int]; argv[0] = "abc"; print(#argv); print(0 in argv);}',
4886 None,
4887 "1\n1",
4888 ),
4889 ),
4890 )
4891 @pytest.mark.skipif(which("gvpr") is None, reason="GVPR not available")
4892 def test_2582(program: str, a_arg: Optional[str], expected: str):
4893 """
4894 gvpr should treat `ARGV` as an array
4895 https://gitlab.com/graphviz/graphviz/-/issues/2582
4896
4897 Args:
4898 program: Program text to run in gvpr
4899 a_arg: An optional parameter to pass via `-a …` to gvpr
4900 expected: Expected output
4901 """
4902 gvprbin = which("gvpr")
4903 args = [gvprbin]
4904 if a_arg is not None:
4905 args += ["-a", a_arg]
4906 args += [program]
4907
4908 actual = run(args)
4909
4910 assert actual.strip() == expected, "unexpected GVPR program output"
4911
4912
4913 @pytest.mark.parametrize(
4914 "testcase",
4915 (
4916 "2585",
4917 "2585_1",
4918 "2585_2",
4919 "2585_3",
4920 "2585_4",
4921 "2585_5",
4922 "2585_6",
4923 "2585_7",
4924 ),
4925 )
4926 @pytest.mark.skipif(which("gvpr") is None, reason="GVPR not available")
4927 def test_2585(testcase: str):
4928 """
4929 GVPR should reject various invalid uses of `void` types
4930 https://gitlab.com/graphviz/graphviz/-/issues/2585
4931 """
4932
4933 # locate our associated test case in this directory
4934 input = Path(__file__).parent / f"{testcase}.gvpr"
4935 assert input.exists(), "unexpectedly missing test case"
4936
4937 # run the program
4938 gvprbin = which("gvpr")
4939 ret = subprocess.call(
4940 [gvprbin, "-o", os.devnull, "-f", input], stdin=subprocess.DEVNULL
4941 )
4942
4943 assert ret == 1, "GVPR did not reject invalid use of `void`"
4944
4945
4946 @pytest.mark.skipif(which("gml2gv") is None, reason="gml2gv not available")
4947 def test_2586():
4948 """
4949 labels should be preserved in GML→GV translation
4950 https://gitlab.com/graphviz/graphviz/-/issues/2586
4951 """
4952
4953 # locate our associated test case in this directory
4954 input = Path(__file__).parent / "2586.gml"
4955 assert input.exists(), "unexpectedly missing test case"
4956
4957 # translate it
4958 gml2gv = which("gml2gv")
4959 gv = run([gml2gv, input])
4960
4961 assert (
4962 re.search(r'\blabel\s*=\s*"?0"?\b', gv) is not None
4963 ), "labels not preserved in GML→GV translation"
4964
4965
4966 @pytest.mark.skipif(which("gvpr") is None, reason="gvpr not available")
4967 def test_2587():
4968 """
4969 gvpr should have a usable `unsigned` type
4970 https://gitlab.com/graphviz/graphviz/-/issues/2587
4971 """
4972
4973 gvpr_bin = which("gvpr")
4974 output = run(
4975 [gvpr_bin, "BEGIN { unsigned x = 281; print(x); }"],
4976 stdin=subprocess.DEVNULL,
4977 )
4978
4979 assert output == "281\n", "gvpr did not correctly interpret an `unsigned`"
4980
4981
4982 @pytest.mark.skipif(which("gvpr") is None, reason="gvpr not available")
4983 def test_2587_1():
4984 """
4985 gvpr should have a usable `unsigned` type
4986 https://gitlab.com/graphviz/graphviz/-/issues/2587
4987 """
4988
4989 gvpr_bin = which("gvpr")
4990 output = run(
4991 [gvpr_bin, 'BEGIN { unsigned x; sscanf("139", "%u", &x); print(x); }'],
4992 stdin=subprocess.DEVNULL,
4993 )
4994
4995 assert output == "139\n", "gvpr did not correctly interpret an `unsigned`"
4996
4997
4998 @pytest.mark.skipif(which("gvgen") is None, reason="gvgen not available")
4999 def test_2588():
5000 """
5001 `gvgen` should not crash when producing random graphs
5002 https://gitlab.com/graphviz/graphviz/-/issues/2588
5003 """
5004
5005 gvgen = which("gvgen")
5006
5007 # this execution depends on random numbers, so we need to run many times to
5008 # have a chance of provoking the bug
5009 for _ in range(200):
5010 run_raw([gvgen, "-R", "20"], stdout=subprocess.DEVNULL)
5011
5012
5013 @pytest.mark.skipif(which("edgepaint") is None, reason="edgepaint not available")
5014 @pytest.mark.skipif(which("gvgen") is None, reason="gvgen not available")
5015 def test_2591():
5016 """
5017 edgepaint color schemes should do something
5018 https://gitlab.com/graphviz/graphviz/-/issues/2591
5019 """
5020
5021 # make an input graph
5022 gvgen = which("gvgen")
5023 graph = run([gvgen, "-k", "5"])
5024
5025 # run it through neato
5026 laidout = run(["dot", "-Kneato", "-Goverlap=false"], input=graph)
5027
5028 # try two different edgepaint invocations
5029 edgepaint = which("edgepaint")
5030 gray = run([edgepaint, "--angle=89.999", "--color_scheme=gray"], input=laidout)
5031 rgb = run(
5032 [edgepaint, "--angle=89.999", "--color_scheme=#00ff00,#0000ff"],
5033 input=laidout,
5034 )
5035
5036 # process these into an image
5037 gray_svg = run(["dot", "-Kneato", "-n2", "-Tsvg"], input=gray)
5038 rgb_svg = run(["dot", "-Kneato", "-n2", "-Tsvg"], input=rgb)
5039
5040 assert gray_svg != rgb_svg, "edgepaint --color_scheme had no effect"
5041
5042
5043 @pytest.mark.skipif(which("ccomps") is None, reason="ccomps not available")
5044 def test_2593():
5045 """
5046 ccomps should be able to handle this graph in reasonable time
5047 https://gitlab.com/graphviz/graphviz/-/issues/2593
5048 """
5049
5050 # locate our associated test case in this directory
5051 input = Path(__file__).parent / "2593.dot"
5052 assert input.exists(), "unexpectedly missing test case"
5053
5054 # this typically takes 30-45s to run, so give a wide margin of error and require
5055 # that ccomps finishes within that
5056 ccomps = which("ccomps")
5057 proc = subprocess.run(
5058 [ccomps, "-o", os.devnull, input], timeout=60 * 5, check=False
5059 )
5060
5061 assert proc.returncode == 1, "ccomps did not detect graphs have multiple components"
5062
5063
5064 @pytest.mark.skipif(shutil.which("tclsh") is None, reason="tclsh not available")
5065 @pytest.mark.skipif(
5066 platform.system() == "Windows",
5067 reason="pexpect.spawn is not available on Windows "
5068 "(https://pexpect.readthedocs.io/en/stable/overview.html#pexpect-on-windows)",
5069 )
5070 @pytest.mark.xfail(
5071 is_cmake() and is_macos(),
5072 reason="FIXME: 'vgpane' command is unrecognized for unknown reasons",
5073 strict=True,
5074 )
5075 @pytest.mark.xfail(
5076 is_autotools() and is_macos(),
5077 reason="Autotools on macOS does not detect TCL",
5078 strict=True,
5079 )
5080 def test_2596():
5081 """
5082 running Tclpathplan `triangulate` with a malformed callback script should not read
5083 out-of-bounds
5084 https://gitlab.com/graphviz/graphviz/-/issues/2596
5085 """
5086
5087 # if this appears to be an ASan-enabled CI job, teach `tclsh` to load ASan’s
5088 # supporting library because it is otherwise unaware that Tcldot depends on this
5089 # being loaded first
5090 env = os.environ.copy()
5091 dot_exe = which("dot")
5092 if is_asan_instrumented(dot_exe):
5093 cc = os.environ.get("CC", "gcc")
5094 libasan = run([cc, "-print-file-name=libasan.so"]).strip()
5095 print(f"setting LD_PRELOAD={libasan}")
5096 env["LD_PRELOAD"] = libasan
5097
5098 # startup TCL and load the pathplan module
5099 proc = pexpect.spawn("tclsh", timeout=1, env=env)
5100 proc.expect("% ")
5101 proc.sendline("package require Tclpathplan")
5102 proc.expect("% ")
5103
5104 # Create a pane. We assume the first created pane will be index 0, though
5105 # this is not technically required.
5106 proc.sendline("vgpane")
5107 proc.expect("vgpane0")
5108 proc.expect("% ")
5109
5110 # bind the triangulation callback to something ending in a trailing '%'
5111 proc.sendline("vgpane0 bind triangle %")
5112 proc.expect("% ")
5113
5114 # add a triangular polygon
5115 proc.sendline("vgpane0 insert 1 1 2 2 1 2")
5116 proc.expect("1")
5117 proc.expect("% ")
5118
5119 # attempt triangulation on this polygon
5120 proc.sendline("vgpane0 triangulate 1")
5121 proc.expect("% ")
5122
5123 # delete the pane to clean up, to exit ASan-clean
5124 proc.sendline("vgpane0 delete")
5125 proc.expect("% ")
5126
5127
5128 @pytest.mark.skipif(not is_cmake(), reason="only relevant in CMake builds")
5129 @pytest.mark.skipif(shutil.which("cmake") is None, reason="cmake not available")
5130 @pytest.mark.skipif(
5131 re.search(r"\bstatic\b", os.environ.get("CI_JOB_NAME", "")) is not None,
5132 reason="CMake support files are not installed in static builds",
5133 )
5134 def test_2598(tmp_path: Path):
5135 """
5136 Graphviz, as installed by the CMake build system, should be usable with standard
5137 CMake idioms
5138 https://gitlab.com/graphviz/graphviz/-/issues/2598
5139 """
5140
5141 # configure a build directory for our sample applications
5142 src = Path(__file__).parent / "2598"
5143 args = ["cmake", "--debug-find", "-B", tmp_path, "-S", src]
5144 if os.environ.get("CI_JOB_NAME", "").startswith("windows-cmake-Win32"):
5145 args += ["-A", "Win32"]
5146 run_raw(args)
5147
5148 # run compilation
5149 run_raw(["cmake", "--build", tmp_path])
5150
5151
5152 @pytest.mark.skipif(not is_cmake(), reason="only relevant in CMake builds")
5153 @pytest.mark.skipif(shutil.which("cmake") is None, reason="cmake not available")
5154 @pytest.mark.skipif(
5155 re.search(r"\bstatic\b", os.environ.get("CI_JOB_NAME", "")) is not None,
5156 reason="CMake support files are not installed in static builds",
5157 )
5158 def test_2598_1(tmp_path: Path):
5159 """
5160 A variant of test_2598, that does not directly use cdt
5161 https://gitlab.com/graphviz/graphviz/-/issues/2598
5162 """
5163
5164 # configure a build directory for our sample applications
5165 src = Path(__file__).parent / "2598_1"
5166 args = ["cmake", "--debug-find", "-B", tmp_path, "-S", src]
5167 if os.environ.get("CI_JOB_NAME", "").startswith("windows-cmake-Win32"):
5168 args += ["-A", "Win32"]
5169 run_raw(args)
5170
5171 # run compilation
5172 run_raw(["cmake", "--build", tmp_path])
5173
5174
5175 @pytest.mark.skipif(which("gvgen") is None, reason="gvgen not available")
5176 @pytest.mark.skipif(which("mingle") is None, reason="mingle not available")
5177 def test_2599():
5178 """
5179 mingle should not segfault when processing simple graphs
5180 https://gitlab.com/graphviz/graphviz/-/issues/2599
5181 """
5182
5183 # generate a graph
5184 gvgen = which("gvgen")
5185 graph = run([gvgen, "-d", "-k", "5"])
5186
5187 # process it into canonical form
5188 processed = run(["dot"], input=graph)
5189
5190 # pass it through mingle
5191 mingle = which("mingle")
5192 proc = subprocess.run(
5193 [mingle, "-v", "999"], check=False, text=True, input=processed
5194 )
5195
5196 assert proc.returncode in (0, 1), "mingle crashed"
5197
5198
5199 @pytest.mark.skipif(which("acyclic") is None, reason="acyclic not available")
5200 def test_2600():
5201 """
5202 acyclic should produce output
5203 https://gitlab.com/graphviz/graphviz/-/issues/2600
5204 """
5205
5206 # run acyclic on a simple cyclic graph
5207 acyclic = which("acyclic")
5208 ret = subprocess.run(
5209 [acyclic],
5210 input="digraph { A -> B -> C -> D -> E; E -> A }",
5211 stdout=subprocess.PIPE,
5212 check=False,
5213 text=True,
5214 )
5215
5216 assert ret.returncode == 1, "acyclic did not detect a cyclic graph"
5217 assert ret.stdout.strip() != "", "acyclic produced no output"
5218
5219
5220 @pytest.mark.skipif(which("dot_builtins") is None, reason="dot_builtins not available")
5221 def test_2604():
5222 """
5223 dot_builtins should not repeat formats in guidance
5224 https://gitlab.com/graphviz/graphviz/-/issues/2604
5225 """
5226
5227 # a simple graph
5228 input = "digraph { a -> b; }"
5229
5230 # run dot_builtins with an incorrect format
5231 dot_builtins = which("dot_builtins")
5232 proc = subprocess.run(
5233 [dot_builtins, "-o", os.devnull, "-Tpng:"],
5234 stderr=subprocess.PIPE,
5235 input=input,
5236 text=True,
5237 check=False,
5238 )
5239
5240 assert proc.returncode != 0, "dot_builtins accepted malformed format 'png:'"
5241
5242 assert (
5243 len(re.findall(r"\bpng:cairo:cairo\b", proc.stderr)) <= 1
5244 ), "duplicate formats listed in guidance"
5245
5246
5247 @pytest.mark.skipif(which("neato") is None, reason="neato not available")
5248 def test_2609(tmp_path: Path):
5249 """
5250 GIFs should not be blank
5251 https://gitlab.com/graphviz/graphviz/-/issues/2609
5252 """
5253
5254 # locate our associated test case in this directory
5255 input = Path(__file__).parent / "2609.dot"
5256 assert input.exists(), "unexpectedly missing test case"
5257
5258 # run this through Neato and convert to GIF
5259 neato = which("neato")
5260 gif = tmp_path / "2609.gif"
5261 run_raw([neato, "-Tgif", input, "-o", gif])
5262
5263 # load the image and scan its pixels
5264 img = Image.open(gif)
5265 reference = None
5266 for x in range(img.width):
5267 for y in range(img.height):
5268 pixel = img.getpixel((x, y))
5269 if reference is None:
5270 reference = pixel
5271 elif reference != pixel:
5272 # found a different pixel
5273 return
5274
5275 pytest.fail("generated GIF was a solid color")
5276
5277
5278 def test_2613():
5279 """
5280 Graphviz should not fail an assertion when processing this graph
5281 https://gitlab.com/graphviz/graphviz/-/issues/2613
5282 """
5283
5284 # locate our associated test case in this directory
5285 input = Path(__file__).parent / "2613.dot"
5286 assert input.exists(), "unexpectedly missing test case"
5287
5288 # generate it as a PDF
5289 dot("pdf", input)
5290
5291
5292 def test_2614():
5293 """
5294 quotes in strings should be correctly escaped
5295 https://gitlab.com/graphviz/graphviz/-/issues/2614
5296 """
5297
5298 # locate our associated test case in this directory
5299 input = Path(__file__).parent / "2614.dot"
5300 assert input.exists(), "unexpectedly missing test case"
5301
5302 # generate the canonical form of this
5303 canonical = dot("canon", input)
5304
5305 # it should be re-parseable
5306 dot("svg", source=canonical)
5307
5308 # quotes should have been escaped
5309 assert canonical.count('\\"') == 2, "quotes in string were not properly escaped"
5310
5311
5312 def test_2615():
5313 """
5314 cluster→cluster edges should not be duplicated
5315 https://gitlab.com/graphviz/graphviz/-/issues/2615
5316 """
5317
5318 # locate our associated test case in this directory
5319 input = Path(__file__).parent / "2615.dot"
5320 assert input.exists(), "unexpectedly missing test case"
5321
5322 # lay this out
5323 layout = dot("dot", input)
5324
5325 # find an inter-cluster edge
5326 m = re.search(r'\bD\s*->\s*F\s*\[\s*pos\s*=\s*"(?P<position>[^"]*)"', layout)
5327 assert m is not None, "could not locate D->F edge"
5328
5329 edge_count = len(re.findall(r"\be\b", m.group("position")))
5330 assert edge_count == 1, "incorrect number of inter-cluster edges"
5331
5332
5333 @pytest.mark.xfail(
5334 platform.system() == "Windows" and not is_mingw() and not is_ndebug_defined(),
5335 strict=True,
5336 reason="https://gitlab.com/graphviz/graphviz/-/issues/2619",
5337 )
5338 def test_2619():
5339 """
5340 loading a JPEG with initial EXIF stream should be possible
5341 https://gitlab.com/graphviz/graphviz/-/issues/2619
5342 """
5343
5344 # we need to run in our own directory so relative path references work
5345 cwd = Path(__file__).parent
5346
5347 # our test case should be translatable to PDF
5348 run_raw(["dot", "-Tpdf", "-o", os.devnull, "2619.dot"], cwd=cwd)
5349
5350
5351 @pytest.mark.xfail(
5352 platform.system() == "Windows" and not is_mingw() and not is_ndebug_defined(),
5353 strict=True,
5354 reason="https://gitlab.com/graphviz/graphviz/-/issues/2619",
5355 )
5356 @pytest.mark.parametrize("images", ("2619_1", "2619_2"))
5357 @pytest.mark.parametrize("output", ("pdf", "png"))
5358 @pytest.mark.parametrize("source", ("2619_1.dot", "2619_2.dot"))
5359 def test_2619_1(images: str, output: str, source: str, tmp_path: Path):
5360 """
5361 output files for this graph should be non-empty
5362 https://gitlab.com/graphviz/graphviz/-/issues/2619
5363 """
5364
5365 # locate our associated test case in this directory
5366 input = Path(__file__).parent / source
5367 assert input.exists(), "unexpectedly missing test case"
5368
5369 # copy it to a temporary path, replacing image references for our variant
5370 content = input.read_bytes()
5371 specialized = re.sub(
5372 rb"\b2619_(\d)1\.jpg\b", images.encode("utf-8") + rb"_\1.jpg", content
5373 )
5374 destination = tmp_path / "2619.dot"
5375 destination.write_bytes(specialized)
5376
5377 # copy images to the expected directory structure
5378 media = tmp_path / "data/media/media/schoenfeld-liberman.ged"
5379 media.mkdir(parents=True)
5380 for i in (1, 2, 3):
5381 src = Path(__file__).parent / f"{images}_{i}.jpg"
5382 shutil.copy(src, media / f"2619_{i}.jpg")
5383
5384 def sh(args: list[Union[Path, str]], stdin: Optional[bytes] = None) -> bytes:
5385 """run a command, as if via the shell"""
5386 nonlocal tmp_path
5387
5388 # dump the command being run for the user to observe if the test fails
5389 print(
5390 f"+ cd {shlex.quote(str(tmp_path))} && {shlex.join(str(x) for x in args)}"
5391 )
5392
5393 proc = subprocess.run(
5394 args, input=stdin, stdout=subprocess.PIPE, cwd=tmp_path, check=True
5395 )
5396 return proc.stdout
5397
5398 # render this
5399 dot_result = sh(["dot", f"-T{output}", destination])
5400
5401 assert dot_result.strip() != b"", "an empty file was rendered"
5402
5403 # render it with exact position information
5404 positioned = sh(["dot", "-Tdot", destination])
5405
5406 # use this to render with neato
5407 neato = which("neato")
5408 neato_result = sh([neato, "-n2", f"-T{output}"], stdin=positioned)
5409
5410 assert neato_result.strip() != b"", "an empty file was rendered"
5411
5412
5413 @pytest.mark.xfail(
5414 platform.system() == "Windows" and not is_mingw() and not is_ndebug_defined(),
5415 strict=True,
5416 reason="https://gitlab.com/graphviz/graphviz/-/issues/2619",
5417 )
5418 def test_2619_3():
5419 """
5420 loading a JPEG image shall not cause a crash in the GD plugin when the output format is PDF
5421 https://gitlab.com/graphviz/graphviz/-/issues/2619
5422 """
5423
5424 # we need to run in our own directory so relative path references work
5425 cwd = Path(__file__).parent
5426
5427 src = 'digraph {a [image="2619_1_2.jpg"]}'.encode("utf-8")
5428
5429 # our test case shall not cause a crash
5430 run_raw(["dot", "-Tpdf", "-o", os.devnull], cwd=cwd, input=src)
5431
5432
5433 def test_2619_4():
5434 """
5435 processing a node with the 'image' attribute set to a JPEG file shall not yield warnings
5436 https://gitlab.com/graphviz/graphviz/-/issues/2619
5437 """
5438
5439 # we need to run in our own directory so relative path references work
5440 cwd = Path(__file__).parent
5441
5442 src = 'digraph {a [image="2619.jpg"]}'
5443
5444 output = run(
5445 ["dot", "-Tsvg", "-o", os.devnull],
5446 cwd=cwd,
5447 input=src,
5448 stderr=subprocess.STDOUT,
5449 )
5450
5451 assert "Warning:" not in output, f"Warnings issued: {output}"
5452
5453
5454 @pytest.mark.parametrize(
5455 "image",
5456 (
5457 "2619.jpg",
5458 "2619_1_1.jpg",
5459 "2619_1_2.jpg",
5460 "2619_1_3.jpg",
5461 "2619_2_1.jpg",
5462 "2619_2_2.jpg",
5463 "2619_2_3.jpg",
5464 ),
5465 )
5466 def test_2619_5(image: str):
5467 """
5468 a node with the 'image' attribute set to a JPEG file shall render an SVG
5469 containing an 'image' element with the correct width and height
5470 https://gitlab.com/graphviz/graphviz/-/issues/2619
5471 """
5472
5473 # we need to run in our own directory so relative path references work
5474 cwd = Path(__file__).parent
5475
5476 file = cwd / image
5477 width, height = Image.open(file).size
5478
5479 src = f'digraph {{a [image="{image}"]}}'
5480
5481 svg = run(["dot", "-Tsvg"], cwd=cwd, input=src)
5482
5483 # load it as XML
5484 root = ET.fromstring(svg)
5485
5486 # find the `image` element
5487 image_element = root.findall(".//{http://www.w3.org/2000/svg}image")
5488
5489 assert len(image_element) == 1, "could not find an 'image' element in the SVG"
5490
5491 assert image_element[0].get("width") == f"{width}px"
5492 assert image_element[0].get("height") == f"{height}px"
5493
5494
5495 def test_2620():
5496 """
5497 arrows in this graph should not be truncated
5498 https://gitlab.com/graphviz/graphviz/-/issues/2620
5499 """
5500
5501 # locate our associated test case in this directory
5502 input = Path(__file__).parent / "2620.dot"
5503 assert input.exists(), "unexpectedly missing test case"
5504
5505 # render to SVG
5506 svg = dot("svg", input)
5507
5508 # parse the SVG
5509 root = ET.fromstring(svg)
5510
5511 # most of the differences between the “good” and “bad” rendering are small
5512 # (~1pt diff), so discriminate using one that has been observed to be much larger
5513 edge = root.findall(
5514 ".//{http://www.w3.org/2000/svg}g[@id='edge101']/{http://www.w3.org/2000/svg}path"
5515 )
5516 assert len(edge) == 1, "could not find expected edge"
5517
5518 # parse the expected drawing instructions out of this
5519 m = re.match("M(?P<move>.*)C(?P<curve>.*)", edge[0].attrib["d"])
5520 assert m is not None, "drawing command in unexpected format"
5521
5522 # the curve is expected to be composed of two Béziers
5523 points = m.group("curve").split()
5524 assert len(points) == 6, "unexpected number of Bézier curve components"
5525
5526 bezier2 = [pt.split(",") for pt in points[3:]]
5527 assert all(len(pt) == 2 for pt in bezier2), "unexpected Bézier composition"
5528
5529 # compare the end point of the last command against what we expect with a large
5530 # margin of error
5531 expected = -7286.11
5532 assert abs(float(bezier2[2][1]) - expected) < 1000, "incorrect edge construction"
5533
5534
5535 def test_2621():
5536 """
5537 this graph should not trigger an integer overflow in crossing calculation
5538 https://gitlab.com/graphviz/graphviz/-/issues/2621
5539 """
5540
5541 # locate our associated test case in this directory
5542 input = Path(__file__).parent / "2621.dot"
5543 assert input.exists(), "unexpectedly missing test case"
5544
5545 run_raw(["dot", "-Gmclimit=.05", "-Gphase=2", "-Tsvg", "-o", os.devnull, input])
5546
5547
5548 def test_2636_1():
5549 """
5550 `viewBox` in an SVG image should not override `width` and `height`
5551 https://gitlab.com/graphviz/graphviz/-/issues/2636
5552 """
5553
5554 # locate our associated test case in this directory
5555 input = Path(__file__).parent / "2636_1.dot"
5556 assert input.exists(), "unexpectedly missing test case"
5557
5558 # we need to run in our current directory in order to reference the co-located
5559 # 2636_1.svg
5560 cwd = Path(__file__).parent
5561
5562 svg = run(["dot", "-Tsvg", input], cwd=cwd)
5563
5564 # parse the generated SVG
5565 root = ET.fromstring(svg)
5566
5567 # find the included image
5568 imgs = root.findall(".//{http://www.w3.org/2000/svg}image")
5569 assert len(imgs) == 1, "could not find included SVG"
5570 img = imgs[0]
5571
5572 assert img.attrib["height"] == "100px", "image height set incorrectly"
5573 assert img.attrib["width"] == "100px", "image width set incorrectly"
5574
5575
5576 def test_2636_2():
5577 """
5578 `viewBox` parameters in an SVG image should be interpreted correctly
5579 https://gitlab.com/graphviz/graphviz/-/issues/2636
5580 """
5581
5582 # locate our associated test case in this directory
5583 input = Path(__file__).parent / "2636_2.dot"
5584 assert input.exists(), "unexpectedly missing test case"
5585
5586 # we need to run in our current directory in order to reference the co-located
5587 # 2636_2.svg
5588 cwd = Path(__file__).parent
5589
5590 svg = run(["dot", "-Tsvg", input], cwd=cwd)
5591
5592 # parse the generated SVG
5593 root = ET.fromstring(svg)
5594
5595 # find the included image
5596 imgs = root.findall(".//{http://www.w3.org/2000/svg}image")
5597 assert len(imgs) == 1, "could not find included SVG"
5598 img = imgs[0]
5599
5600 assert img.attrib["height"] == "10px", "image height set incorrectly"
5601 assert img.attrib["width"] == "10px", "image width set incorrectly"
5602
5603
5604 @pytest.mark.skipif(which("gvpr") is None, reason="gvpr not available")
5605 def test_2639():
5606 """
5607 in GVPR, setting an attribute on a subgraph should not set it on the root graph
5608 https://gitlab.com/graphviz/graphviz/-/issues/2639
5609 """
5610
5611 # locate our associated supporting files in this directory
5612 input = Path(__file__).parent / "2639.dot"
5613 assert input.exists(), "unexpectedly missing test case"
5614 program = Path(__file__).parent / "2639.gvpr"
5615 assert program.exists(), "unexpectedly missing test case"
5616 checker = Path(__file__).parent / "2639_2.gvpr"
5617 assert checker.exists(), "unexpectedly missing test case"
5618
5619 # process the graph with GVPR
5620 gvpr_bin = which("gvpr")
5621 output = run(
5622 [gvpr_bin, "-c", program.read_text(encoding="utf-8")],
5623 input=input.read_text(encoding="utf-8"),
5624 )
5625
5626 # run this resulting graph through the checker to retrieve one of its root graph’s
5627 # defaults
5628 color = run(
5629 [gvpr_bin, "-c", checker.read_text(encoding="utf-8"), "-o", os.devnull],
5630 input=output,
5631 )
5632
5633 assert (
5634 re.search(r"\bred\b", color) is None
5635 ), "subgraph default was set on root graph"
5636
5637
5638 @pytest.mark.skipif(which("twopi") is None, reason="twopi not available")
5639 def test_2643():
5640 """
5641 twopi should not read/write out of bounds when processing this case’s graph
5642 https://gitlab.com/graphviz/graphviz/-/issues/2643
5643 """
5644
5645 # locate our associated test case in this directory
5646 input = Path(__file__).parent / "2643.dot"
5647 assert input.exists(), "unexpectedly missing test case"
5648
5649 # run this through twopi
5650 twopi = which("twopi")
5651 run_raw([twopi, "-o", os.devnull, input])
5652
5653
5654 @pytest.mark.slow # ~13min
5655 def test_2646():
5656 """
5657 Graphviz should not crash when processing this large graph
5658 https://gitlab.com/graphviz/graphviz/-/issues/2646
5659 """
5660
5661 # locate our associated test case in this directory
5662 input = Path(__file__).parent / "2646.dot"
5663 assert input.exists(), "unexpectedly missing test case"
5664
5665 # run this through Graphviz
5666 dot("pdf", input)
5667
5668
5669 def test_2646_1():
5670 """
5671 It was observed that `test_2646` could crash early on when minor changes subtly
5672 affected the stack depth of functions in lib/common/ns.c. Because `test_2646` is
5673 expensive, this tries to validate the lack of such crashes with something quicker.
5674 https://gitlab.com/graphviz/graphviz/-/issues/2646
5675 """
5676
5677 # locate our associated test case in this directory
5678 input = Path(__file__).parent / "2646.dot"
5679 assert input.exists(), "unexpectedly missing test case"
5680
5681 # Run this through Graphviz. We expect this long running process to timeout, not
5682 # crash.
5683 try:
5684 run(["dot", "-Tpdf", "-o", os.devnull, input], timeout=10)
5685 except subprocess.TimeoutExpired:
5686 pass
5687
5688
5689 def test_2647():
5690 """
5691 `-Tsvg_inline` should allow references to external files in its output
5692 https://gitlab.com/graphviz/graphviz/-/issues/2636#note_2326527219
5693 https://gitlab.com/graphviz/graphviz/-/merge_requests/4208
5694 https://gitlab.com/graphviz/graphviz/-/issues/2647
5695 """
5696
5697 # locate our associated test case in this directory
5698 input = Path(__file__).parent / "2636.dot"
5699 assert input.exists(), "unexpectedly missing test case"
5700
5701 # we need to run in our current directory in order to reference the co-located
5702 # 2636.svg
5703 cwd = Path(__file__).parent
5704
5705 svg = run(["dot", "-Tsvg_inline", input], cwd=cwd)
5706
5707 assert (
5708 re.search(r"\b2636\.svg\b", svg) is not None
5709 ), "`-Tsvg_inline` output did not reference external image"
5710
5711
5712 @pytest.mark.slow # ~10min
5713 def test_MR_2854():
5714 """
5715 this graph should be handled in a reasonable amount of time
5716
5717 The graph used by this test was accelerated by commit
5718 4b736d297bb1599451e89c2fde911d966a1db3cf landing in Merge Request !2857. This test
5719 case checks if performance on this workload has regressed since then.
5720
5721 https://gitlab.com/graphviz/graphviz/-/merge_requests/2854
5722 https://gitlab.com/graphviz/graphviz/-/merge_requests/2857
5723 """
5724
5725 # locate our associated test case in this directory
5726 input = Path(__file__).parent / "2854.dot"
5727 assert input.exists(), "unexpectedly missing test case"
5728
5729 # this typically takes ~10m to run, so give a wide margin of error and require that
5730 # Graphviz finishes within that
5731 run_raw(["dot", "-Tsvg", "-o", os.devnull, input], timeout=60 * 20)
5732
5733
5734 @pytest.mark.skipif(which("gvgen") is None, reason="gvgen not available")
5735 @pytest.mark.parametrize("seed", range(1, 2000))
5736 def test_2640(seed: int):
5737 """
5738 gvgen should not access values out of bounds
5739 https://gitlab.com/graphviz/graphviz/-/issues/2640
5740 """
5741
5742 # the seed 1967 was observed previously to cause crashes on Windows
5743 gvgen = which("gvgen")
5744 run_raw([gvgen, "-R", "20", f"-u{seed}"], stdout=subprocess.DEVNULL)
5745
5746
5747 @pytest.mark.parametrize(
5748 "testcase", ("agattr", "agsafeset", "agset", "agstrbind", "agxset")
5749 )
5750 @pytest.mark.skipif(
5751 is_static_build(),
5752 reason="dynamic libraries are unavailable to link against in static builds",
5753 )
5754 def test_2641(testcase: str):
5755 """
5756 `agattr*` and friends should preserve some measure of backwards compatibility
5757 https://gitlab.com/graphviz/graphviz/-/issues/2641
5758 """
5759
5760 # find co-located test source
5761 c_src = (Path(__file__).parent / f"2641_{testcase}.c").resolve()
5762 assert c_src.exists(), "missing test case"
5763
5764 # run it
5765 run_c(c_src, link=["cgraph"])
5766
5767
5768 def _find_plugin_so(plugin: str) -> Optional[Path]:
5769 """
5770 find the absolute path to the dynamic library for a given Graphviz plugin
5771
5772 Args:
5773 plugin: Name of the plugin being sought
5774
5775 Return:
5776 An absolute path to the corresponding installed dynamic library or `None` if it
5777 could not be found.
5778 """
5779
5780 # figure out the path to installed root based on binaries
5781 dot_bin = which("dot")
5782 root = dot_bin.parents[1]
5783
5784 # extract plugin version
5785 current, revision, age = plugin_version()
5786
5787 for subdir in ("lib", "lib64"):
5788 if is_macos():
5789 candidate = root / subdir / f"graphviz/libgvplugin_{plugin}.dylib"
5790 elif is_mingw():
5791 candidate = root / f"bin/libgvplugin_{plugin}-{current - age}.dll"
5792 elif platform.system() == "Windows":
5793 candidate = root / subdir / f"gvplugin_{plugin}.lib"
5794 else:
5795 candidate = root / subdir / f"graphviz/libgvplugin_{plugin}.so"
5796 print(f"checking {candidate}") # log some useful information
5797 if candidate.exists():
5798 return candidate
5799
5800 if platform.system() == "Linux":
5801 # try it with the version info suffix, which is what some RHEL platforms use
5802 suffix = f".{current - age}.{age}.{revision}"
5803 candidate = root / subdir / f"graphviz/libgvplugin_{plugin}.so{suffix}"
5804 print(f"checking {candidate}") # log some useful information
5805 if candidate.exists():
5806 return candidate
5807
5808 # not found
5809 return None
5810
5811
5812 @pytest.mark.skipif(
5813 is_static_build(),
5814 reason="dynamic libraries are unavailable to link against in static builds",
5815 )
5816 def test_2648(tmp_path: Path):
5817 """
5818 rendering multiple times programmatically should not crash
5819 https://gitlab.com/graphviz/graphviz/-/issues/2648
5820 """
5821
5822 # find co-located test source
5823 c_src = (Path(__file__).parent / "2648.c").resolve()
5824 assert c_src.exists(), "missing test case"
5825
5826 # From here, we essentially want to `run_c(c_src, …)`. However we cannot easily do
5827 # this because we want to directly link against plugins (instead of `dlopen` them),
5828 # libraries that are not in the linker’s search path. So instead we have to take a
5829 # more manual approach.
5830
5831 # find the plugins we need to link against
5832 core = _find_plugin_so("core")
5833 assert core is not None, "core plugin library not found"
5834 dot_layout = _find_plugin_so("dot_layout")
5835 assert dot_layout is not None, "dot layout plugin library not found"
5836
5837 # compile the test code
5838 exe = tmp_path / "a.exe"
5839 compile_c(c_src, link=["cgraph", "gvc", core, dot_layout], dst=exe)
5840
5841 # teach the runtime linker how to find the plugins
5842 env = os.environ.copy()
5843 ld_library_path = f"{core.parent}:{dot_layout.parent}"
5844 prefix = ""
5845 if is_macos():
5846 if "DYLD_LIBRARY_PATH" in env:
5847 env["DYLD_LIBRARY_PATH"] = f"{ld_library_path}:{env['DYLD_LIBRARY_PATH']}"
5848 else:
5849 env["DYLD_LIBRARY_PATH"] = ld_library_path
5850 prefix = f"env DYLD_LIBRARY_PATH={env['DYLD_LIBRARY_PATH']} "
5851 else:
5852 if "LD_LIBRARY_PATH" in env:
5853 env["LD_LIBRARY_PATH"] = f"{ld_library_path}:{env['LD_LIBRARY_PATH']}"
5854 else:
5855 env["LD_LIBRARY_PATH"] = ld_library_path
5856 prefix = f"env LD_LIBRARY_PATH={env['LD_LIBRARY_PATH']} "
5857
5858 # run the test code
5859 print(f"+ {prefix}{shlex.quote(str(exe))}")
5860 subprocess.run([exe], env=env, check=True)
5861
5862
5863 def test_2669():
5864 """
5865 `dpi=…` should scale the SVG `viewBox` as well as the overall size
5866 https://gitlab.com/graphviz/graphviz/-/issues/2669
5867 """
5868
5869 # locate our associated test case in this directory
5870 input = Path(__file__).parent / "2669.dot"
5871 assert input.exists(), "unexpectedly missing test case"
5872
5873 def parse(xml: str) -> tuple[int, int, tuple[float, float]]:
5874 """
5875 parse an SVG
5876
5877 Args:
5878 xml: The text content of an SVG image
5879
5880 Returns:
5881 (width, height, (viewBox width, viewBox height))
5882 """
5883
5884 root = ET.fromstring(xml)
5885
5886 assert root.attrib["width"].endswith("pt")
5887 width = int(root.attrib["width"][:-2])
5888
5889 assert root.attrib["height"].endswith("pt")
5890 height = int(root.attrib["height"][:-2])
5891
5892 viewbox = re.match(
5893 r"\d+(\.\d+)?\s+\d+(\.\d+)?\s+(?P<width>\d+(\.\d+)?)\s+(?P<height>\d+(\.\d+)?)$",
5894 root.attrib["viewBox"],
5895 )
5896 assert viewbox is not None, "unexpected SVG viewBox format"
5897
5898 vb_width = float(viewbox.group("width"))
5899 vb_height = float(viewbox.group("height"))
5900
5901 return width, height, (vb_width, vb_height)
5902
5903 # run this through Graphviz as normal
5904 svg1 = dot("svg", input)
5905
5906 # confirm the width and height roughly match the `viewBox`
5907 width, height, viewbox = parse(svg1)
5908 assert math.isclose(width, viewbox[0], abs_tol=1.0), "mismatched SVG widths"
5909 assert math.isclose(height, viewbox[1], abs_tol=1.0), "mismatched SVG heights"
5910
5911 # run this with a modified DPI
5912 svg2 = run(["dot", "-Tsvg", "-Gdpi=60", input])
5913
5914 # confirm the width and height roughly match the `viewBox`
5915 width, height, viewbox = parse(svg2)
5916 assert math.isclose(width, viewbox[0], abs_tol=1.0), "mismatched SVG widths"
5917 assert math.isclose(height, viewbox[1], abs_tol=1.0), "mismatched SVG heights"
5918
5919
5920 def test_2682():
5921 """
5922 processing a graph with `pack` attributes should not cause a crash
5923 https://gitlab.com/graphviz/graphviz/-/issues/2682
5924 """
5925
5926 # locate our associated test case in this directory
5927 input = Path(__file__).parent / "2682.dot"
5928 assert input.exists(), "unexpectedly missing test case"
5929
5930 # run it through Graphviz
5931 dot("dot", input)
5932
5933
5934 def test_2683():
5935 """
5936 processing a graph with `packmode` attributes should not cause a crash
5937 https://gitlab.com/graphviz/graphviz/-/issues/2683
5938 """
5939
5940 # locate our associated test case in this directory
5941 input = Path(__file__).parent / "2683.dot"
5942 assert input.exists(), "unexpectedly missing test case"
5943
5944 # run it through Graphviz
5945 dot("dot", input)
5946
5947
5948 @pytest.mark.skipif(shutil.which("ps2pdf") is None, reason="ps2pdf not available")
5949 def test_2699():
5950 """
5951 `showboxes` should generate a valid PS file
5952 https://gitlab.com/graphviz/graphviz/-/issues/2699
5953 """
5954
5955 # locate our associated test case in this directory
5956 input = Path(__file__).parent / "2699.dot"
5957 assert input.exists(), "unexpectedly missing test case"
5958
5959 # run it through Graphviz
5960 ps = dot("ps", input)
5961
5962 # run this through `ps2pdf`, an arbitrary PS-consuming program to validate what
5963 # Graphviz gave us
5964 run_raw(["ps2pdf", "-", os.devnull], input=ps)
5965
5966
5967 def test_2705(tmp_path: Path):
5968 """
5969 round tripping a graph through a file should not alter its node defaults
5970 https://gitlab.com/graphviz/graphviz/-/issues/2705
5971 """
5972
5973 # find co-located test source
5974 c_src = (Path(__file__).parent / "2705.c").resolve()
5975 assert c_src.exists(), "missing test case"
5976
5977 from_memory = tmp_path / "memory.dot"
5978 from_file = tmp_path / "file.dot"
5979
5980 # run it
5981 link = ["cgraph"]
5982 if is_static_build():
5983 # in static builds, we also need transitive dependencies
5984 link += ["cdt"]
5985 run_c(c_src, [from_memory, from_file], link=link)
5986
5987 original = from_memory.read_text(encoding="utf-8")
5988 round_tripped = from_file.read_text(encoding="utf-8")
5989 assert (
5990 original == round_tripped
5991 ), "round tripping graph through file was not idempotent"
5992
5993
5994 @pytest.mark.skipif(which("gvpr") is None, reason="gvpr is not available")
5995 def test_2707():
5996 """
5997 gvpr should not perform a double-free while processing this example
5998 https://gitlab.com/graphviz/graphviz/-/issues/2707
5999 """
6000
6001 # find our test sources
6002 program = (Path(__file__).parent / "2707.gvpr").resolve()
6003 assert program.exists(), "missing test case"
6004 graph = (Path(__file__).parent / "share/unix.gv").resolve()
6005 assert graph.exists(), "missing test case"
6006
6007 gvpr_bin = which("gvpr")
6008 run([gvpr_bin, "-f", program, graph])
6009
6010
6011 def test_2712():
6012 """
6013 Graphviz on macOS should not crash while processing this graph
6014 https://gitlab.com/graphviz/graphviz/-/issues/2712
6015 """
6016
6017 source = 'digraph G { abc [URL=" "]; }'
6018
6019 # process this to a JPEG
6020 dot("jpe", source=source)
6021
6022
6023 def test_2716():
6024 """
6025 version components should be exposed that work at compile-time
6026 https://gitlab.com/graphviz/graphviz/-/issues/2716
6027 """
6028
6029 # find co-located test source
6030 c_src = (Path(__file__).parent / "2716.c").resolve()
6031 assert c_src.exists(), "missing test case"
6032
6033 # generate a graph and pass it through dot
6034 compile_c(c_src)
6035
6036
6037 @pytest.mark.skipif(which("fdp") is None, reason="fdp is not available")
6038 @pytest.mark.xfail(
6039 strict=not is_ndebug_defined(),
6040 reason="https://gitlab.com/graphviz/graphviz/-/issues/2717",
6041 )
6042 def test_2717():
6043 """
6044 processing the given graph with fdp should not crash
6045 https://gitlab.com/graphviz/graphviz/-/issues/2717
6046 """
6047
6048 # locate our associated test case in this directory
6049 input = Path(__file__).parent / "2717.dot"
6050 assert input.exists(), "unexpectedly missing test case"
6051
6052 # run it through fdp
6053 fdp = which("fdp")
6054 run([fdp, "-o", os.devnull, input])
6055
6056
6057 @pytest.mark.skipif(which("osage") is None, reason="osage is not available")
6058 def test_2721():
6059 """
6060 osage should not crash when processing this graph
6061 https://gitlab.com/graphviz/graphviz/-/issues/2721
6062 """
6063
6064 # locate our associated test case in this directory
6065 input = Path(__file__).parent / "2721.dot"
6066 assert input.exists(), "unexpectedly missing test case"
6067
6068 # run it through osage
6069 osage = which("osage")
6070 run([osage, "-Tpng", "-o", os.devnull, input])
6071
6072
6073 def test_2722():
6074 """
6075 the `CDT_VERSION` macro should be updated whenever its API changes
6076 https://gitlab.com/graphviz/graphviz/-/issues/2722
6077 """
6078
6079 # The SHA1 digest of ../lib/cdt/cdt.h. This should be updated whenever you update
6080 # ../lib/cdt/cdt.h.
6081 reference = "43c41531381ed1cec4259a08a80dd69b53189100"
6082
6083 # read in the current cdt.h, accounting for Windows vs Unix line ending differences
6084 cdt_h = Path(__file__).absolute().parents[1] / "lib/cdt/cdt.h"
6085 content = cdt_h.read_text(encoding="utf-8")
6086
6087 # hash the content
6088 m = hashlib.sha1()
6089 m.update(content.encode("utf-8"))
6090
6091 # Check they match. The intent here is that this assertion will fail whenever cdt.h
6092 # is updated without taking this test case into account. The failure should prompt
6093 # the developer to update `CDT_VERSION`.
6094 assert (
6095 reference == m.hexdigest()
6096 ), "cdt.h has changed; update test_2722 and remember to update `CDT_VERSION`"
6097
6098
6099 @pytest.mark.xfail(
6100 strict=which("dot") is not None and is_asan_instrumented(which("dot")),
6101 reason="https://gitlab.com/graphviz/graphviz/-/issues/2723",
6102 )
6103 def test_2723():
6104 """
6105 Graphviz should not crash while processing this graph
6106 https://gitlab.com/graphviz/graphviz/-/issues/2723
6107 """
6108
6109 # locate our associated test case in this directory
6110 input = Path(__file__).parent / "2723.dot"
6111 assert input.exists(), "unexpectedly missing test case"
6112
6113 # process this
6114 dot("png", input)
6115
6116
6117 def test_2727():
6118 """
6119 the label “<>” should be accepted
6120 https://gitlab.com/graphviz/graphviz/-/issues/2727
6121 """
6122
6123 # locate our associated test case in this directory
6124 input = Path(__file__).parent / "2727.dot"
6125 assert input.exists(), "unexpectedly missing test case"
6126
6127 # process this
6128 dot("svg", input)
6129
6130
6131 @pytest.mark.skipif(which("gvpr") is None, reason="gvpr is not available")
6132 def test_2731():
6133 """
6134 gvpr should produce output for this example
6135 https://gitlab.com/graphviz/graphviz/-/issues/2731
6136 """
6137
6138 # find our test source
6139 graph = (Path(__file__).parent / "graphs/unix.gv").resolve()
6140
6141 gvpr_bin = which("gvpr")
6142 result = run([gvpr_bin, "-c", 'N{label="\\N";}', graph])
6143
6144 assert result.strip() != "", "gvpr output missing"
6145
6146
6147 @pytest.mark.parametrize(
6148 "fmt",
6149 (
6150 "png",
6151 pytest.param(
6152 "png:cairo:gdk",
6153 marks=pytest.mark.skipif(
6154 is_macos() or platform.system() == "Windows",
6155 reason="GDK plugin not supported",
6156 ),
6157 ),
6158 pytest.param(
6159 "jpg",
6160 marks=pytest.mark.xfail(
6161 is_fedora_43(),
6162 strict=True,
6163 reason="https://gitlab.com/graphviz/graphviz/-/issues/2732",
6164 ),
6165 ),
6166 "jpg:cairo:gd",
6167 ),
6168 )
6169 def test_2732(fmt: str):
6170 """
6171 back ends should not produce empty files
6172 https://gitlab.com/graphviz/graphviz/-/issues/2732
6173
6174 Args:
6175 fmt: Format to pass to dot’s `-T…`.
6176 """
6177
6178 # an arbitrary, trivial graph
6179 source = "graph G { a -- b; }"
6180
6181 # confirm this produces non-empty output
6182 output = dot(fmt, source=source)
6183 assert output != b"", "empty output produced for valid graph"
6184
6185
6186 def test_2734():
6187 """
6188 this graph should not be drawn with sharply angled curves
6189 https://gitlab.com/graphviz/graphviz/-/issues/2734
6190 """
6191
6192 # locate our associated test case in this directory
6193 input = Path(__file__).parent / "2734.dot"
6194 assert input.exists(), "unexpectedly missing test case"
6195
6196 # process this
6197 svg = dot("svg", input)
6198
6199 # parse the SVG
6200 root = ET.fromstring(svg)
6201
6202 # look at each path
6203 for path in root.findall(".//{http://www.w3.org/2000/svg}path"):
6204
6205 # get the definition and make it slightly easier to parse
6206 d = path.get("d")
6207 points_str = d.replace("C", " ").replace("M", " ")
6208
6209 # parse it into a list of points
6210 points = [
6211 (float(x), float(y))
6212 for x, y in [p.split(",") for p in points_str.split(" ") if p]
6213 ]
6214
6215 # examine the angles along the path, looking for an abnormally large one
6216 gradient: Optional[float] = None
6217 last_point: Optional[tuple[float, float]] = None
6218 for p in points:
6219 if last_point is None:
6220 last_point = p
6221 continue
6222 # for simplicity, skip paths with vertical lines because we know the
6223 # problematic one we are scanning for does not have any
6224 if p[0] == last_point[0]:
6225 break
6226 this_gradient = (p[1] - last_point[1]) / (p[0] - last_point[0])
6227 if gradient is not None:
6228 angle = math.atan(
6229 (gradient - this_gradient) / (1 + gradient * this_gradient)
6230 )
6231 assert math.degrees(angle) < 10, "unnecessarily sharp edge generated"
6232 gradient = this_gradient
6233
6234
6235 @pytest.mark.xfail(
6236 reason="https://gitlab.com/graphviz/graphviz/-/issues/2796", strict=True
6237 )
6238 def test_2796():
6239 """
6240 Graphviz should be able to triangulate the points in this graph
6241 https://gitlab.com/graphviz/graphviz/-/issues/2796
6242 """
6243
6244 # locate our associated test case in this directory
6245 input = Path(__file__).parent / "2796.dot"
6246 assert input.exists(), "unexpectedly missing test case"
6247
6248 # process this
6249 p = subprocess.run(
6250 ["dot", "-Tpdf", "-o", os.devnull, input],
6251 stderr=subprocess.PIPE,
6252 check=True,
6253 text=True,
6254 )
6255
6256 assert (
6257 re.search(r"\btrouble in init_rank\b", p.stderr) is None
6258 ), "triangulation failed"
6259
6260
6261 @pytest.mark.skipif(not is_cmake(), reason="only relevant in CMake builds")
6262 @pytest.mark.skipif(is_static_build(), reason="only relevant in shared library builds")
6263 def test_2798(tmp_path: Path):
6264 """
6265 are the CMake exported configs enough to build the examples?
6266 https://gitlab.com/graphviz/graphviz/-/issues/2798
6267 """
6268
6269 # a directory containing a CMake file that describes building the examples
6270 src = Path(__file__).parent / "2798"
6271
6272 # suppress any compiler path tweaks because we do not want to be able to see paths
6273 # in the Graphviz source tree
6274 env = os.environ.copy()
6275 for v in (
6276 "CPATH", # GNU CPP
6277 "C_INCLUDE_PATH", # GNU CPP
6278 "CPLUS_INCLUDE_PATH", # GNU CPP
6279 "OBJC_INCLUDE_PATH", # GNU CPP
6280 "LIBRARY_PATH", # GNU LD
6281 "LD_LIBRARY_PATH", # *nix ld.so
6282 "DYLD_LIBRARY_PATH", # macOS dyld
6283 "INCLUDE", # MSVC
6284 "LIB", # MSVC
6285 "LIBPATH", # MSVC
6286 ):
6287 if v in env:
6288 del env[v]
6289
6290 # configure this
6291 args = ["cmake", "-B", tmp_path, "-S", src]
6292 if platform.system() == "Windows" and not is_mingw():
6293 args += ["-A", os.environ["project_platform"]]
6294 run(args, env=env)
6295
6296 # compile the examples
6297 args = ["cmake", "--build", tmp_path, "--parallel=1", "--verbose"]
6298 if platform.system() == "Windows" and not is_mingw():
6299 # Windows decides which C Run-Time (CRT) library to link based on the
6300 # configuration, which must be the same our dependencies were linked against
6301 args += [f"--config={os.environ['configuration']}"]
6302 run(args, env=env)
6303
6304
6305 def test_2801():
6306 """
6307 `colorscheme` should work correctly
6308 https://gitlab.com/graphviz/graphviz/-/issues/2801
6309 """
6310
6311 # locate our associated test case in this directory
6312 input = Path(__file__).parent / "2801.dot"
6313 assert input.exists(), "unexpectedly missing test case"
6314
6315 # process this
6316 warnings = run(["dot", "-Tpng", "-o", os.devnull, input], stderr=subprocess.STDOUT)
6317
6318 assert "is not a known color" not in warnings, "`colorscheme` not working"
6319
6320
6321 @pytest.mark.parametrize("package", ("Tcldot", "Tclpathplan"))
6322 @pytest.mark.skipif(shutil.which("tclsh") is None, reason="tclsh not available")
6323 @pytest.mark.xfail(
6324 is_autotools() and is_macos(),
6325 reason="Autotools on macOS does not detect TCL",
6326 strict=True,
6327 )
6328 def test_import_tcl_package(package: str):
6329 """
6330 The given TCL package should be loadable
6331 """
6332
6333 # if this appears to be an ASan-enabled CI job, teach `tclsh` to load ASan’s
6334 # supporting library because it is otherwise unaware that Tcldot depends on this
6335 # being loaded first
6336 env = os.environ.copy()
6337 dot_exe = which("dot")
6338 if is_asan_instrumented(dot_exe):
6339 cc = os.environ.get("CC", "gcc")
6340 libasan = run([cc, "-print-file-name=libasan.so"]).strip()
6341 print(f"setting LD_PRELOAD={libasan}")
6342 env["LD_PRELOAD"] = libasan
6343
6344 # ask TCL to import the given package
6345 response = run(
6346 ["tclsh"],
6347 stderr=subprocess.STDOUT,
6348 input=f"package require {package};",
6349 env=env,
6350 )
6351
6352 assert "can't find package" not in response, f"{package} cannot be loaded by TCL"
6353
6354
6355 @pytest.mark.skipif(shutil.which("tclsh") is None, reason="tclsh not available")
6356 @pytest.mark.skipif(
6357 platform.system() == "Windows",
6358 reason="pexpect.spawn is not available on Windows "
6359 "(https://pexpect.readthedocs.io/en/stable/overview.html#pexpect-on-windows)",
6360 )
6361 @pytest.mark.xfail(
6362 is_cmake() and is_macos(),
6363 reason="FIXME: 'vgpane' command is unrecognized for unknown reasons",
6364 strict=True,
6365 )
6366 @pytest.mark.xfail(
6367 is_autotools() and is_macos(),
6368 reason="Autotools on macOS does not detect TCL",
6369 strict=True,
6370 )
6371 def test_triangulation_overflow():
6372 """
6373 running Tclpathplan `triangulate` with a malformed polygon should be rejected
6374 """
6375
6376 # if this appears to be an ASan-enabled CI job, teach `tclsh` to load ASan’s
6377 # supporting library because it is otherwise unaware that Tcldot depends on this
6378 # being loaded first
6379 env = os.environ.copy()
6380 dot_exe = which("dot")
6381 if is_asan_instrumented(dot_exe):
6382 cc = os.environ.get("CC", "gcc")
6383 libasan = run([cc, "-print-file-name=libasan.so"]).strip()
6384 print(f"setting LD_PRELOAD={libasan}")
6385 env["LD_PRELOAD"] = libasan
6386
6387 # startup TCL and load the pathplan module
6388 proc = pexpect.spawn("tclsh", timeout=1, env=env)
6389 proc.expect("% ")
6390 proc.sendline("package require Tclpathplan")
6391 proc.expect("% ")
6392
6393 # Create a pane. We assume the first created pane will be index 0, though
6394 # this is not technically required.
6395 proc.sendline("vgpane")
6396 proc.expect("vgpane0")
6397 proc.expect("% ")
6398
6399 # add a “polygon” with only a single point
6400 proc.sendline("vgpane0 insert 4 5")
6401 proc.expect("1")
6402 proc.expect("% ")
6403
6404 # attempt triangulation on this polygon
6405 proc.sendline("vgpane0 triangulate 1")
6406 proc.expect("cannot be triangulated")
6407 proc.expect("% ")
6408
6409 # delete the pane to clean up, to exit ASan-clean
6410 proc.sendline("vgpane0 delete")
6411 proc.expect("% ")
6412
6413
6414 @pytest.mark.skipif(shutil.which("tclsh") is None, reason="tclsh not available")
6415 @pytest.mark.skipif(
6416 platform.system() == "Windows",
6417 reason="pexpect.spawn is not available on Windows "
6418 "(https://pexpect.readthedocs.io/en/stable/overview.html#pexpect-on-windows)",
6419 )
6420 @pytest.mark.xfail(
6421 is_cmake() and is_macos(),
6422 reason="FIXME: 'vgpane' command is unrecognized for unknown reasons",
6423 strict=True,
6424 )
6425 @pytest.mark.xfail(
6426 is_autotools() and is_macos(),
6427 reason="Autotools on macOS does not detect TCL",
6428 strict=True,
6429 )
6430 def test_vgpane_bad_triangulation():
6431 """
6432 running Tclpathplan `triangulate` with incorrect arguments should be rejected
6433 """
6434
6435 # if this appears to be an ASan-enabled CI job, teach `tclsh` to load ASan’s
6436 # supporting library because it is otherwise unaware that Tcldot depends on this
6437 # being loaded first
6438 env = os.environ.copy()
6439 dot_exe = which("dot")
6440 if is_asan_instrumented(dot_exe):
6441 cc = os.environ.get("CC", "gcc")
6442 libasan = run([cc, "-print-file-name=libasan.so"]).strip()
6443 print(f"setting LD_PRELOAD={libasan}")
6444 env["LD_PRELOAD"] = libasan
6445
6446 # startup TCL and load the pathplan module
6447 proc = pexpect.spawn("tclsh", timeout=1, env=env)
6448 proc.expect("% ")
6449 proc.sendline("package require Tclpathplan")
6450 proc.expect("% ")
6451
6452 # Create a pane. We assume the first created pane will be index 0, though
6453 # this is not technically required.
6454 proc.sendline("vgpane")
6455 proc.expect("vgpane0")
6456 proc.expect("% ")
6457
6458 # bind the triangulation callback to something ending in a trailing '%'
6459 proc.sendline("vgpane0 bind triangle %")
6460 proc.expect("% ")
6461
6462 # run triangulation with no polygon ID, which should be rejected
6463 proc.sendline("vgpane0 triangulate")
6464 proc.expect("wrong # args")
6465
6466 # delete the pane to clean up, to exit ASan-clean
6467 proc.sendline("vgpane0 delete")
6468 proc.expect("% ")
6469
6470
6471 @pytest.mark.skipif(shutil.which("tclsh") is None, reason="tclsh not available")
6472 @pytest.mark.skipif(
6473 platform.system() == "Windows",
6474 reason="pexpect.spawn is not available on Windows "
6475 "(https://pexpect.readthedocs.io/en/stable/overview.html#pexpect-on-windows)",
6476 )
6477 @pytest.mark.xfail(
6478 is_cmake() and is_macos(),
6479 reason="FIXME: 'vgpane' command is unrecognized for unknown reasons",
6480 strict=True,
6481 )
6482 @pytest.mark.xfail(
6483 is_autotools() and is_macos(),
6484 reason="Autotools on macOS does not detect TCL",
6485 strict=True,
6486 )
6487 def test_vgpane_delete():
6488 """
6489 it should be possible to delete an existing `vgpane`
6490 """
6491
6492 # if this appears to be an ASan-enabled CI job, teach `tclsh` to load ASan’s
6493 # supporting library because it is otherwise unaware that Tcldot depends on this
6494 # being loaded first
6495 env = os.environ.copy()
6496 dot_exe = which("dot")
6497 if is_asan_instrumented(dot_exe):
6498 cc = os.environ.get("CC", "gcc")
6499 libasan = run([cc, "-print-file-name=libasan.so"]).strip()
6500 print(f"setting LD_PRELOAD={libasan}")
6501 env["LD_PRELOAD"] = libasan
6502
6503 # startup TCL and load the pathplan module
6504 proc = pexpect.spawn("tclsh", timeout=1, env=env)
6505 proc.expect("% ")
6506 proc.sendline("package require Tclpathplan")
6507 proc.expect("% ")
6508
6509 # Create a pane. We assume the first created pane will be index 0, though
6510 # this is not technically required.
6511 proc.sendline("vgpane")
6512 proc.expect("vgpane0")
6513 proc.expect("% ")
6514
6515 # delete the pane to clean up
6516 proc.sendline("vgpane0 delete")
6517 # `pexpect.expect` returns an index of which given expectation was matched. We
6518 # expect this to return no output (not the invalid handle message) and therefore
6519 # timeout.
6520 is_valid = proc.expect(['Invalid handle: "vgpane0"', pexpect.TIMEOUT]) == 1
6521 assert is_valid, "created vgpane was considered an invalid handle"
6522
6523
6524 def test_changelog_dates():
6525 """
6526 Check the dates of releases in the changelog are correctly formatted
6527 """
6528 changelog = Path(__file__).parent / "../CHANGELOG.md"
6529 with open(changelog, "rt", encoding="utf-8") as f:
6530 for lineno, line in enumerate(f, 1):
6531 m = re.match(r"## \[\d+\.\d+\.\d+\] [-–] (?P<date>.*)$", line)
6532 if m is None:
6533 continue
6534 d = re.match(r"\d{4}-\d{2}-\d{2}", m.group("date"))
6535 assert (
6536 d is not None
6537 ), f"CHANGELOG.md:{lineno}: date in incorrect format: {line}"
6538
6539
6540 @pytest.mark.skipif(which("gvpack") is None, reason="gvpack not available")
6541 def test_duplicate_hard_coded_metrics_warnings():
6542 """
6543 Check “no hard-coded metrics” warnings are not repeated
6544 """
6545
6546 # use the #2239 test case that happens to provoke this
6547 input = Path(__file__).parent / "2239.dot"
6548 assert input.exists(), "unexpectedly missing test case"
6549
6550 # run it through gvpack
6551 gvpack = which("gvpack")
6552 p = subprocess.run(
6553 [gvpack, "-u", "-o", os.devnull, input],
6554 stderr=subprocess.PIPE,
6555 check=False,
6556 text=True,
6557 )
6558
6559 assert (
6560 p.stderr.count("no hard-coded metrics for 'sans'") <= 1
6561 ), "multiple identical “no hard-coded metrics” warnings printed"
6562
6563
6564 @pytest.mark.parametrize("branch", (0, 1, 2, 3))
6565 @pytest.mark.skipif(which("gvpr") is None, reason="gvpr not available")
6566 def test_gvpr_switches(branch: int):
6567 """
6568 confirm the behavior of GVPR switch statements
6569 """
6570
6571 # an input GVPR program with multiple blocks and switches
6572 program = textwrap.dedent(
6573 f"""\
6574 BEGIN {{
6575 switch ({branch}) {{
6576 case 0:
6577 printf("begin 0\\n");
6578 break;
6579 case 1:
6580 printf("begin 1\\n");
6581 break;
6582 case 2:
6583 printf("begin 2\\n");
6584 break;
6585 default:
6586 printf("begin 3\\n");
6587 break;
6588 }}
6589 }}
6590
6591 END {{
6592 switch ({branch}) {{
6593 case 0:
6594 printf("end 0\\n");
6595 break;
6596 case 1:
6597 printf("end 1\\n");
6598 break;
6599 case 2:
6600 printf("end 2\\n");
6601 break;
6602 default:
6603 printf("end 3\\n");
6604 break;
6605 }}
6606 }}
6607 """
6608 )
6609
6610 # run this through GVPR with no input graph
6611 gvpr_bin = which("gvpr")
6612 result = run([gvpr_bin, program], stdin=subprocess.DEVNULL)
6613
6614 # confirm we got the expected output
6615 assert result == f"begin {branch}\nend {branch}\n", "incorrect GVPR switch behavior"
6616
6617
6618 @pytest.mark.parametrize(
6619 "statement,expected",
6620 (
6621 ('printf("%d", 5)', "5"),
6622 ('printf("%d", 0)', "0"),
6623 ('printf("%.0d", 0)', ""),
6624 ('printf("%.0d", 1)', "1"),
6625 ('printf("%.d", 2)', "2"),
6626 ('printf("%d", -1)', "-1"),
6627 ('printf("%.3d", 5)', "005"),
6628 ('printf("%.3d", -5)', "-005"),
6629 ('printf("%5.3d", 5)', " 005"),
6630 ('printf("%-5.3d", -5)', "-005 "),
6631 ('printf("%-d", 5)', "5"),
6632 ('printf("%-+d", 5)', "+5"),
6633 ('printf("%+-d", 5)', "+5"),
6634 ('printf("%+d", -5)', "-5"),
6635 ('printf("% d", 5)', " 5"),
6636 ('printf("% .0d", 0)', " "),
6637 ('printf("%03d", 5)', "005"),
6638 ('printf("%03d", -5)', "-05"),
6639 ('printf("% +d", 5)', "+5"),
6640 ('printf("%-03d", -5)', "-5 "),
6641 ('printf("%o", 5)', "5"),
6642 ('printf("%o", 8)', "10"),
6643 ('printf("%o", 0)', "0"),
6644 ('printf("%.0o", 0)', ""),
6645 ('printf("%.0o", 1)', "1"),
6646 ('printf("%.3o", 5)', "005"),
6647 ('printf("%.3o", 8)', "010"),
6648 ('printf("%5.3o", 5)', " 005"),
6649 ('printf("%u", 5)', "5"),
6650 ('printf("%u", 0)', "0"),
6651 ('printf("%.0u", 0)', ""),
6652 ('printf("%.0u", 1)', "1"),
6653 ('printf("%.3u", 5)', "005"),
6654 ('printf("%5.3u", 5)', " 005"),
6655 ('printf("%u", 5)', "5"),
6656 ('printf("%u", 0)', "0"),
6657 ('printf("%.0u", 0)', ""),
6658 ('printf("%.0u", 1)', "1"),
6659 ('printf("%.3u", 5)', "005"),
6660 ('printf("%5.3u", 5)', " 005"),
6661 ('printf("%-x", 5)', "5"),
6662 ('printf("%03x", 5)', "005"),
6663 ('printf("%-x", 5)', "5"),
6664 ('printf("%03x", 5)', "005"),
6665 ('printf("%-X", 5)', "5"),
6666 ('printf("%03X", 5)', "005"),
6667 ('printf("%.2s", "abc")', "ab"),
6668 ('printf("%.6s", "abc")', "abc"),
6669 ('printf("%5s", "abc")', " abc"),
6670 ('printf("%-5s", "abc")', "abc "),
6671 ('printf("%5.2s", "abc")', " ab"),
6672 ('printf("%%")', "%"),
6673 ),
6674 )
6675 @pytest.mark.skipif(which("gvpr") is None, reason="gvpr not available")
6676 def test_gvpr_printf(statement: str, expected: str):
6677 """
6678 check various behaviors of `printf` in a GVPR program
6679 """
6680
6681 # a program that performs the given `printf`
6682 program = f"BEGIN {{ {statement}; }}"
6683
6684 # run this through GVPR with no input graph
6685 gvpr_bin = which("gvpr")
6686 result = run([gvpr_bin, program], stdin=subprocess.DEVNULL)
6687
6688 # confirm we got the expected output
6689 assert result == expected, "incorrect GVPR printf behavior"
6690
6691
6692 usage_info = """\
6693 Usage: dot [-Vv?] [-(GNEA)name=val] [-(KTlso)<val>] <dot files>
6694 (additional options for neato) [-x] [-n<v>]
6695 (additional options for fdp) [-L(gO)] [-L(nUCT)<val>]
6696 (additional options for config) [-cv]
6697
6698 -V - Print version and exit
6699 -v - Enable verbose mode
6700 -Gname=val - Set graph attribute 'name' to 'val'
6701 -Nname=val - Set node attribute 'name' to 'val'
6702 -Ename=val - Set edge attribute 'name' to 'val'
6703 -Aname=val - Set attribute 'name' to 'val' for graph, node, and edge
6704 -Tv - Set output format to 'v'
6705 -Kv - Set layout engine to 'v' (overrides default based on command name)
6706 -lv - Use external library 'v'
6707 -ofile - Write output to 'file'
6708 -O - Automatically generate an output filename based on the input filename with a .'format' appended. (Causes all -ofile options to be ignored.)
6709 -P - Internally generate a graph of the current plugins.
6710 -q[l] - Set level of message suppression (=1)
6711 -s[v] - Scale input by 'v' (=72)
6712 -y - Invert y coordinate in output
6713
6714 -n[v] - No layout mode 'v' (=1)
6715 -x - Reduce graph
6716
6717 -Lg - Don't use grid
6718 -LO - Use old attractive force
6719 -Ln<i> - Set number of iterations to i
6720 -LU<i> - Set unscaled factor to i
6721 -LC<v> - Set overlap expansion factor to v
6722 -LT[*]<v> - Set temperature (temperature factor) to v
6723
6724 -c - Configure plugins (Writes $prefix/lib/graphviz/config
6725 with available plugin information. Needs write privilege.)
6726 -? - Print usage and exit
6727 """
6728
6729
6730 def test_dot_questionmarkV():
6731 """
6732 test the output from two short options combined
6733 """
6734
6735 out = run(["dot", "-?V"])
6736
6737 assert out == usage_info, "unexpected usage info"
6738
6739
6740 def test_dot_randomV():
6741 """
6742 test the output from a malformed command
6743 """
6744
6745 expected = f"Error: dot: option -r unrecognized\n\n{usage_info}"
6746
6747 proc = subprocess.run(
6748 ["dot", "-randomV"],
6749 stderr=subprocess.PIPE,
6750 text=True,
6751 check=False,
6752 )
6753
6754 assert proc.returncode != 0, "malformed options were accepted"
6755
6756 assert proc.stderr == expected, "unexpected usage info"
6757
6758
6759 def test_dot_V():
6760 """
6761 test the output from `dot -V`
6762 """
6763
6764 proc = subprocess.run(["dot", "-V"], stderr=subprocess.PIPE, text=True, check=True)
6765
6766 c_src = (Path(__file__).parent / "get-package-version.c").resolve()
6767 assert c_src.exists(), "missing test case"
6768 package_version, _ = run_c(c_src)
6769
6770 assert proc.stderr.startswith(
6771 f"dot - graphviz version {package_version.strip()} ("
6772 ), "unexpected -V info"
6773
6774
6775 def test_dot_Vquestionmark():
6776 """
6777 test the output from two short options combined
6778 """
6779
6780 proc = subprocess.run(["dot", "-V?"], stderr=subprocess.PIPE, text=True, check=True)
6781
6782 c_src = (Path(__file__).parent / "get-package-version.c").resolve()
6783 assert c_src.exists(), "missing test case"
6784 package_version, _ = run_c(c_src)
6785
6786 assert proc.stderr.startswith(
6787 f"dot - graphviz version {package_version.strip()} ("
6788 ), "unexpected -V info"
6789
6790
6791 def test_dot_Vrandom():
6792 """
6793 test the output from a short option mixed with long
6794 """
6795
6796 proc = subprocess.run(
6797 ["dot", "-Vrandom"], stderr=subprocess.PIPE, text=True, check=True
6798 )
6799
6800 c_src = (Path(__file__).parent / "get-package-version.c").resolve()
6801 assert c_src.exists(), "missing test case"
6802 package_version, _ = run_c(c_src)
6803
6804 assert proc.stderr.startswith(
6805 f"dot - graphviz version {package_version.strip()} ("
6806 ), "unexpected -V info"
6807
6808
6809 def test_pic_font_size():
6810 """
6811 font size in PIC output format should not be clamped down to 1
6812 related to https://gitlab.com/graphviz/graphviz/-/issues/2487
6813 """
6814
6815 # run a basic graph through PIC generation
6816 src = "graph { a -- b; }"
6817 pic = dot("pic", source=src)
6818
6819 # confirm we got a non-1 font size
6820 m = re.search(r"^\.ps (\d+)", pic, flags=re.MULTILINE)
6821 assert int(m.group(1)) > 1, "font size clamped down to 1"
6822
6823
6824 @pytest.mark.skipif(which("mm2gv") is None, reason="mm2gv not available")
6825 def test_mm_banner_overflow(tmp_path: Path):
6826 """mm2gv should be robust against files with a corrupted banner"""
6827
6828 # construct a file with a corrupted banner > MM_MAX_TOKEN_LENGTH and < MM_MAX_LINE_LENGTH
6829 mm = tmp_path / "matrix.mm"
6830 mm.write_text(f"%{'a' * 10000}", encoding="utf-8")
6831
6832 # run this through mm2gv
6833 ret = subprocess.call(["mm2gv", "-o", os.devnull, mm])
6834
6835 assert ret in (0, 1), "mm2gv crashed when processing malformed input"
6836 assert ret == 1, "mm2gv did not reject malformed input"
6837
6838
6839 def test_control_characters_in_error():
6840 """
6841 malformed input should not result in misleading control data making it to the
6842 output terminal unfiltered
6843 """
6844
6845 # Run something through Graphviz that will trigger an error where the error message
6846 # will contain a color control sequence. This could be used to disrupt the user’s
6847 # terminal in confusing ways.
6848 src = 'graph { a[image="\033[31mfoo"]; }'
6849 ret = subprocess.run(
6850 ["dot", "-Tsvg", "-o", os.devnull],
6851 input=src,
6852 stderr=subprocess.PIPE,
6853 check=False,
6854 text=True,
6855 )
6856
6857 assert "\033" not in ret.stderr, "control character appears in error message"
6858
6859 # Now try something more malicious. Use the backspace character to display a different
6860 # filename in the error message to what was referenced.
6861 src = 'graph { a[image="foo.svg\010\010\010png"]; }'
6862 ret = subprocess.run(
6863 ["dot", "-Tsvg", "-o", os.devnull],
6864 input=src,
6865 stderr=subprocess.PIPE,
6866 check=False,
6867 text=True,
6868 )
6869
6870 assert "\010" not in ret.stderr, "control character appears in error message"
6871
6872
6873 def test_fig_max_colors():
6874 """
6875 using a large number of colors should not crash the FIG renderer
6876 """
6877
6878 # contruct a graph that uses well over 256 colors
6879 buf = io.StringIO()
6880 buf.write("graph {\n")
6881 for red in range(256):
6882 for green in range(10):
6883 buf.write(f' n_{red}_{green}[color="#{red:02x}{green:02x}00"];\n')
6884 buf.write("}\n")
6885
6886 # render this using the FIG renderer
6887 dot("fig", source=buf.getvalue())
6888
6889
6890 @pytest.mark.skipif(which("gvpr") is None, reason="gvpr not available")
6891 def test_gvpr_s2f():
6892 """
6893 casting a string to floating point in GVPR should work
6894 """
6895
6896 # a GVPR program that casts a string to floating point and prints the result
6897 program = 'BEGIN { float x = (float)"1.5"; printf("%0.1f\\n", x); }'
6898
6899 # run this through GVPR with no input graph
6900 gvpr_bin = which("gvpr")
6901 result = run([gvpr_bin, program], stdin=subprocess.DEVNULL)
6902
6903 # confirm we got the expected output
6904 assert result == "1.5\n", "incorrect GVPR float cast behavior"
6905
6906
6907 def test_changelog():
6908 """
6909 sanity checks on ../CHANGELOG.md
6910 """
6911
6912 changelog = Path(__file__).parent / "../CHANGELOG.md"
6913 assert changelog.exists(), "CHANGELOG.md missing"
6914
6915 with open(changelog, "rt", encoding="utf-8") as f:
6916 for lineno, line in enumerate(f, 1):
6917
6918 ignore_h2 = False
6919
6920 # an exception for an old heading
6921 if line == "## [2.42.3] and earlier\n":
6922 ignore_h2 = True
6923
6924 # an exception for unreleased versions
6925 if line.startswith("## ") and "Unreleased" in line:
6926 ignore_h2 = True
6927
6928 if (m := re.match("##(?P<remainder>[^#].*)$", line)) and not ignore_h2:
6929
6930 expected_format = r" \[\d+\.\d+\.\d+\] [\-–] \d{4}-\d{2}-\d{2}$"
6931 assert re.match(expected_format, m.group("remainder")), (
6932 f"CHANGELOG.md:{lineno}: second-level heading did not match "
6933 f'regex r"{expected_format}": {line}'
6934 )
6935
6936 if m := re.match("###(?P<remainder>.*)$", line):
6937 assert m.group("remainder") in (
6938 " Added",
6939 " Changed",
6940 " Fixed",
6941 " Removed",
6942 ), f"CHANGELOG.md:{lineno}: unexpected third-level heading: {line}"
6943
6944 if m := re.match(
6945 r"\[(?P<version>\d+\.\d+\.\d+)\]:(?P<remainder>.*)$", line
6946 ):
6947 prefix = " https://gitlab.com/graphviz/graphviz/compare/"
6948 assert m.group("remainder").startswith(
6949 prefix
6950 ), f"CHANGELOG.md:{lineno}: unexpected finalized history link: {line}"
6951 remainder = m.group("remainder")[len(prefix) :]
6952
6953 assert m.group("remainder").endswith(
6954 f'...{m.group("version")}'
6955 ), f"CHANGELOG.md:{lineno}: history link is for wrong version: {line}"
6956
6957 version_range = re.match(
6958 r"(?P<start_major>\d+)\.(?P<start_minor>\d+)\.(?P<start_patch>\d+)"
6959 r"\.\.\."
6960 r"(?P<end_major>\d+)\.(?P<end_minor>\d+)\.(?P<end_patch>\d+)$",
6961 remainder,
6962 )
6963 assert (
6964 version_range
6965 ), f"CHANGELOG.md:{lineno}: unexpected finalized history link: {line}"
6966
6967 start = tuple(
6968 int(version_range.group(v))
6969 for v in ("start_major", "start_minor", "start_patch")
6970 )
6971 end = tuple(
6972 int(version_range.group(v))
6973 for v in ("end_major", "end_minor", "end_patch")
6974 )
6975 assert (
6976 start < end
6977 ), f"CHANGELOG.md:{lineno}: invalid version range: {line}"
6978
6979
6980 def test_agxbuf_print_nul():
6981 """
6982 `agxbprint` should not account for nor append a NUL byte
6983 """
6984
6985 # find co-located test source
6986 c_src = (Path(__file__).parent / "agxbuf-print-nul.c").resolve()
6987 assert c_src.exists(), "missing test case"
6988
6989 lib = Path(__file__).parents[1] / "lib"
6990 if platform.system() == "Windows" and not is_mingw():
6991 cflags = [f"/I{lib}"]
6992 else:
6993 # gnu17 needed for `strndup`
6994 cflags = ["-std=gnu17", f"-I{lib}"]
6995
6996 run_c(c_src, cflags=cflags)
6997
6998
6999 def test_agxbuf_use_implicit_nul():
7000 """
7001 `agxbuf` should be able to use its entire memory as an inline string
7002 """
7003
7004 # find co-located test source
7005 c_src = (Path(__file__).parent / "agxbuf-use-implicit-nul.c").resolve()
7006 assert c_src.exists(), "missing test case"
7007
7008 lib = Path(__file__).parents[1] / "lib"
7009 if platform.system() == "Windows" and not is_mingw():
7010 cflags = [f"/I{lib}"]
7011 else:
7012 # gnu17 needed for `strndup`
7013 cflags = ["-std=gnu17", f"-I{lib}"]
7014
7015 run_c(c_src, cflags=cflags)
7016
7017
7018 @pytest.mark.skipif(which("edgepaint") is None, reason="edgepaint not available")
7019 def test_edgepaint_error_message():
7020 """
7021 when failing to open its output, edgepaint should not dereference a null
7022 pointer
7023 """
7024
7025 # try to open a non-existent file
7026 edgepaint = which("edgepaint")
7027 proc = subprocess.run(
7028 [edgepaint, "-o", "/a/nonexistent/path"],
7029 stdout=subprocess.DEVNULL,
7030 stderr=subprocess.PIPE,
7031 check=False,
7032 text=True,
7033 )
7034
7035 # edgepaint should name itself in the error message, not “(null)”
7036 assert re.search(
7037 r"\bedgepaint\b", proc.stderr
7038 ), "edgepaint does not know its own name"
7039
7040
7041 @pytest.mark.skipif(which("gvpr") is None, reason="gvpr not available")
7042 def test_lock_graph():
7043 """GVPR’s `lock` should not misinterpret numbers >INT_MAX"""
7044
7045 # find co-located test sources
7046 program1 = Path(__file__).parent / "lock_graph1.gvpr"
7047 assert program1.exists(), "missing test case"
7048 program2 = Path(__file__).parent / "lock_graph2.gvpr"
7049 assert program2.exists(), "missing test case"
7050
7051 # a basic graph
7052 src = "digraph { a -> b; }"
7053
7054 # process this with a conventional locking program
7055 gvpr_bin = which("gvpr")
7056 output = run([gvpr_bin, "-f", program1], input=src)
7057 assert output == "0\n1\n", "locking a graph did not work"
7058
7059 # now try this with a large integer for the locking operation
7060 output = run([gvpr_bin, "-f", program2], input=src)
7061 assert output == "0\n1\n", "locking a graph using a large integer did not work"
7062
7063
7064 def test_duplicate_font_family():
7065 """
7066 SVG output should not contain duplicate `font-family` items
7067 https://gitlab.com/graphviz/graphviz/-/merge_requests/4298
7068 """
7069
7070 # a sample graph to exercise font families
7071 source = textwrap.dedent(
7072 """\
7073 graph G {
7074 graph [fontnames=svg];
7075 N [label="node" fontname="Helvetica"];
7076 }
7077 """
7078 )
7079
7080 # convert this to SVG
7081 svg = dot("svg", source=source)
7082
7083 # extract font families
7084 for ff in re.findall(r'font-family="(?P<families>[^"]*)', svg):
7085 families = [f.strip() for f in ff.split(",")]
7086 assert len(families) == len(set(families)), "duplicate font families listed"
7087
7088
7089 def test_plugin_version_cmake():
7090 """confirm the plugin version defined in CMake matches Autotools"""
7091 autotools_current, autotools_revision, autotools_age = plugin_version()
7092
7093 # the CMake build system assumes the last component is 0 for now
7094 cmake_age = 0
7095
7096 assert (
7097 autotools_age == cmake_age
7098 ), "CMake build system assumes plugin age is 0 and it is not"
7099
7100 # parse the equivalent out of the CMake build system
7101 cmakelists = Path(__file__).resolve().parents[1] / "CMakeLists.txt"
7102 cmake_current: Optional[int] = None
7103 cmake_revision: Optional[int] = None
7104 with open(cmakelists, "rt", encoding="utf-8") as f:
7105 for line in f:
7106 if m := re.match(
7107 r"\s*set\s*\(\s*GVPLUGIN_CURRENT\s+(?P<current>\d+)\s*\)\s*$",
7108 line,
7109 ):
7110 cmake_current = int(m.group("current"))
7111 if cmake_revision is not None:
7112 break
7113 if m := re.match(
7114 r"\s*set\s*\(\s*GVPLUGIN_REVISION\s+(?P<revision>\d+)\s*\)\s*$",
7115 line,
7116 ):
7117 cmake_revision = int(m.group("revision"))
7118 if cmake_current is not None:
7119 break
7120 assert (
7121 cmake_current is not None
7122 ), "failed to parse CMake build system’s plugin current version"
7123 assert (
7124 cmake_revision is not None
7125 ), "failed to parse CMake build system’s plugin revision"
7126
7127 assert (
7128 autotools_current == cmake_current
7129 ), "Autotools and CMake build systems disagree on plugin current version"
7130 assert (
7131 autotools_revision == cmake_revision
7132 ), "Autotools and CMake build systems disagree on plugin revision"
7133
7134
7135 def test_plugin_version_redhat():
7136 """confirm the plugin version defined in Red Hat spec files matches Autotools"""
7137 autotools_current, _, _ = plugin_version()
7138
7139 # parse the equivalent out of the spec file
7140 spec = Path(__file__).resolve().parents[1] / "redhat/graphviz.spec.fedora.in"
7141 rpm_current: Optional[int] = None
7142 with open(spec, "rt", encoding="utf-8") as f:
7143 for line in f:
7144 if m := re.match(
7145 r"\s*%\s*global\s+pluginsver\s+(?P<current>\d+)\s*$",
7146 line,
7147 ):
7148 rpm_current = int(m.group("current"))
7149 break
7150 assert (
7151 rpm_current is not None
7152 ), "failed to parse Red Hat spec file’s plugin current version"
7153
7154 assert (
7155 autotools_current == rpm_current
7156 ), "Autotools and Red Hat spec file disagree on plugin current version"
7157
7158
7159 @pytest.mark.parametrize("lib", ("cdt", "cgraph", "gvc", "gvpr", "pathplan", "xdot"))
7160 def test_library_so_version(lib: str):
7161 """test library SO versions are consistently defined"""
7162
7163 # parse the canonical version out of Autotools
7164 makefile_am = Path(__file__).resolve().parents[1] / "lib" / lib / "Makefile.am"
7165 version: Optional[tuple[int, int, int]] = None
7166 with open(makefile_am, "rt", encoding="utf-8") as f:
7167 for line in f:
7168 if m := re.match(
7169 r"\s*"
7170 + lib.upper()
7171 + r'_VERSION\s*=\s*"(?P<current>\d+):(?P<revision>\d+):(?P<age>\d+)"\s*$',
7172 line,
7173 ):
7174 version = (
7175 int(m.group("current")),
7176 int(m.group("revision")),
7177 int(m.group("age")),
7178 )
7179 break
7180 assert version is not None, "failed to parse library version"
7181
7182 # parse the equivalent out of the CMake build system
7183 cmakelists = Path(__file__).resolve().parents[1] / "lib" / lib / "CMakeLists.txt"
7184 cmake_version: Optional[tuple[int, int, int]] = None
7185 cmake_soversion: Optional[int] = None
7186 with open(cmakelists, "rt", encoding="utf-8") as f:
7187 for line in f:
7188 if m := re.match(
7189 r"\s*VERSION\s+(?P<major>\d+)\.(?P<minor>\d+)\.(?P<patch>\d+)\s*$", line
7190 ):
7191 cmake_version = (
7192 int(m.group("major")),
7193 int(m.group("minor")),
7194 int(m.group("patch")),
7195 )
7196 if cmake_soversion is not None:
7197 break
7198 continue
7199 if m := re.match(r"\s*SOVERSION\s+(?P<major>\d+)\s*$", line):
7200 cmake_soversion = int(m.group("major"))
7201 if cmake_version is not None:
7202 break
7203 continue
7204 assert cmake_version is not None, "failed to parse version from CMake build system"
7205 assert (
7206 cmake_soversion is not None
7207 ), "failed to parse SO version from CMake build system"
7208
7209 assert cmake_version[0] == cmake_soversion, "major version and SO version disagree"
7210
7211 # unconditionally use the mapping rule `major = current - age` even though this is
7212 # platform-dependent, because all the platforms we support use this mapping
7213 assert (
7214 cmake_version[0] == version[0] - version[2]
7215 ), "CMake and Autotools build systems disagree on library major version"
7216
7217 assert (
7218 cmake_version[1] == version[2]
7219 ), "CMake and Autotools build systems disagree on library minor version"
7220
7221 assert (
7222 cmake_version[2] == version[1]
7223 ), "CMake and Autotools build systems disagree on library patch version"
7224
7225 # parse the equivalent out of the Debian rules
7226 rules = Path(__file__).resolve().parents[1] / "debian/rules"
7227 deb_soname: Optional[int] = None
7228 with open(rules, "rt", encoding="utf-8") as f:
7229 for line in f:
7230 if m := re.match(
7231 r"\s*" + lib.upper() + r"_SONAME\s*=\s*(?P<soversion>\d+)\s*$", line
7232 ):
7233 deb_soname = int(m.group("soversion"))
7234 break
7235 assert deb_soname is not None, "failed to parse SONAME from Debian rules"
7236
7237 # again, we use a common mapping rule `major = current - age`
7238 assert (
7239 version[0] - version[2] == deb_soname
7240 ), "Autotools and Debian rules disagree on library version"
7241
7242 # parse the equivalent out of the Debian lintian overrides
7243 overrides = (
7244 Path(__file__).resolve().parents[1] / "debian/libgraphviz4.lintian-overrides"
7245 )
7246 overrides_version1: Optional[int] = None
7247 overrides_version2: Optional[int] = None
7248 with open(overrides, "rt", encoding="utf-8") as f:
7249 for line in f:
7250 if m := re.search(r"\blib" + lib + r"\.so\.(?P<soversion>\d+)\b", line):
7251 overrides_version1 = int(m.group("soversion"))
7252 if overrides_version2 is not None:
7253 break
7254 continue
7255 if m := re.search(r"\blib" + lib + r"(?P<soversion>\d+)\b", line):
7256 overrides_version2 = int(m.group("soversion"))
7257 if overrides_version1 is not None:
7258 break
7259 continue
7260 # libgvpr has no overrides
7261 if lib == "gvpr":
7262 assert overrides_version1 is None
7263 assert overrides_version2 is None
7264 return
7265 assert (
7266 overrides_version1 is not None
7267 ), f"failed to parse lib{lib}.so.* from Debian lintian overrides"
7268 assert (
7269 overrides_version2 is not None
7270 ), f"failed to parse lib{lib}* from Debian lintian overrides"
7271
7272 # again, we use a common mapping rule `major = current - age`
7273 assert (
7274 version[0] - version[2] == overrides_version1
7275 ), "Autotools and Debian lintian overrides disagree on library version"
7276 assert (
7277 version[0] - version[2] == overrides_version2
7278 ), "Autotools and Debian lintian overrides disagree on library version"
7279
7280
7281 def test_negative_dpi():
7282 """can Graphviz deal with an illegal negative `dpi` value?"""
7283
7284 # locate our associated test case in this directory
7285 src = Path(__file__).parent / "negative-dpi.dot"
7286 assert src.exists(), "unexpectedly missing test case"
7287
7288 run(["dot", "-Tpng", "-o", os.devnull, src], timeout=10)