Commit f48fe62cb1 for bind

commit f48fe62cb119f7e7ccebd5e3f1b6f2b112c5cc41
Author: Nicki Křížek <nicki@isc.org>
Date:   Thu Nov 19 14:31:50 2026 +0000

    Replace digcomp.pl with isctest.tools.digcomp

    A Python script now compares the dig output for the digcomp shell
    function.  More than 100 call sites in 17 test directories use the
    rules of the Perl script, thus the Python script keeps them.  The
    script compares text, because dnspython cannot read all the files.

    One rule is different: the SOA records of a zone transfer get their
    numbers in the same order in the two files.  No test used the
    opposite order.

    A self-test covers the rules.

    Assisted-by: Claude:claude-mythos-5-2

diff --git a/bin/tests/system/conf.sh b/bin/tests/system/conf.sh
index 2f78df6372..9769e7238d 100644
--- a/bin/tests/system/conf.sh
+++ b/bin/tests/system/conf.sh
@@ -79,7 +79,7 @@ cat_d() {

 digcomp() {
   {
-    output=$($PERL $TOP_SRCDIR/bin/tests/system/digcomp.pl "$@")
+    output=$($PYTHON -m isctest.tools.digcomp "$@")
     result=$?
   } || true
   [ -n "$output" ] && {
diff --git a/bin/tests/system/digcomp.pl b/bin/tests/system/digcomp.pl
deleted file mode 100644
index 8024dea5e3..0000000000
--- a/bin/tests/system/digcomp.pl
+++ /dev/null
@@ -1,164 +0,0 @@
-#!/usr/bin/perl
-
-# Copyright (C) Internet Systems Consortium, Inc. ("ISC")
-#
-# SPDX-License-Identifier: MPL-2.0
-#
-# This Source Code Form is subject to the terms of the Mozilla Public
-# License, v. 2.0.  If a copy of the MPL was not distributed with this
-# file, you can obtain one at https://mozilla.org/MPL/2.0/.
-#
-# See the COPYRIGHT file distributed with this work for additional
-# information regarding copyright ownership.
-
-# Compare two files, each with the output from dig, for differences.
-# Ignore "unimportant" differences, like ordering of NS lines, TTL's,
-# etc...
-
-$lc = 0;
-if ($ARGV[0] eq "--lc") {
-	$lc = 1;
-	shift;
-}
-$file1 = $ARGV[0];
-$file2 = $ARGV[1];
-
-$count = 0;
-$firstname = "";
-$status = 0;
-$rcode1 = "none";
-$rcode2 = "none";
-
-open(FILE1, $file1) || die("open: $file1: $!\n");
-while (<FILE1>) {
-	~ s/\r\n//g;
-	~ s/\n//g;
-	if (/^;.+status:\s+(\S+).+$/) {
-		$rcode1 = $1;
-	}
-	next if (/^;/);
-	if (/^(\S+)\s+\S+\s+(\S+)\s+(\S+)\s+(.+)$/) {
-		$name = $1;
-		$class = $2;
-		$type = $3;
-		$value = $4;
-		if ($lc) {
-			$name = lc($name);
-			$value = lc($value);
-		}
-		if ($type eq "SOA") {
-			$firstname = $name if ($firstname eq "");
-			if ($name eq $firstname) {
-				$name = "$name$count";
-				$count++;
-			}
-		}
-		if ($entry{"$name ; $class.$type ; $value"} ne "") {
-			$line = $entry{"$name ; $class.$type ; $value"};
-			print("Duplicate entry in $file1:\n> $_\n< $line\n");
-		} else {
-			$entry{"$name ; $class.$type ; $value"} = $_;
-		}
-	} elsif (/^(\S+)\s+\S+\s+(\S+)\s+(\S+)\s*$/) {
-		$name = $1;
-		$class = $2;
-		$type = $3;
-		$value = "";
-		if ($lc) {
-			$name = lc($name);
-			$value = lc($value);
-		}
-		if ($type eq "SOA") {
-			$firstname = $name if ($firstname eq "");
-			if ($name eq $firstname) {
-				$name = "$name$count";
-				$count++;
-			}
-		}
-		if ($entry{"$name ; $class.$type ; $value"} ne "") {
-			$line = $entry{"$name ; $class.$type ; $value"};
-			print("Duplicate entry in $file1:\n> $_\n< $line\n");
-		} else {
-			$entry{"$name ; $class.$type ; $value"} = $_;
-		}
-	}
-}
-close(FILE1);
-
-$printed = 0;
-
-open(FILE2, $file2) || die("open: $file2: $!\n");
-while (<FILE2>) {
-	~ s/\r\n//g;
-	~ s/\n//g;
-	if (/^;.+status:\s+(\S+).+$/) {
-		$rcode2 = $1;
-	}
-	next if (/^;/);
-	if (/^(\S+)\s+\S+\s+(\S+)\s+(\S+)\s+(.+)$/) {
-		$name = $1;
-		$class = $2;
-		$type = $3;
-		$value = $4;
-		if ($lc) {
-			$name = lc($name);
-			$value = lc($value);
-		}
-		if (($name eq $firstname) && ($type eq "SOA")) {
-			$count--;
-			$name = "$name$count";
-		}
-		if ($entry{"$name ; $class.$type ; $value"} ne "") {
-			$entry{"$name ; $class.$type ; $value"} = "";
-		} else {
-			print("Only in $file2 (missing from $file1):\n")
-			    if ($printed == 0);
-			print("> $_\n");
-			$printed++;
-			$status = 1;
-		}
-	} elsif (/^(\S+)\s+\S+\s+(\S+)\s+(\S+)\s*$/) {
-		$name = $1;
-		$class = $2;
-		$type = $3;
-		$value = "";
-		if ($lc) {
-			$name = lc($name);
-			$value = lc($value);
-		}
-		if (($name eq $firstname) && ($type eq "SOA")) {
-			$count--;
-			$name = "$name$count";
-		}
-		if ($entry{"$name ; $class.$type ; $value"} ne "") {
-			$entry{"$name ; $class.$type ; $value"} = "";
-		} else {
-			print("Only in $file2 (missing from $file1):\n")
-			    if ($printed == 0);
-			print("> $_\n");
-			$printed++;
-			$status = 1;
-		}
-	}
-}
-close(FILE2);
-
-$printed = 0;
-
-foreach $key (keys(%entry)) {
-	if ($entry{$key} ne "") {
-		print("Only in $file1 (missing from $file2):\n")
-		    if ($printed == 0);
-		print("< $entry{$key}\n");
-		$status = 1;
-		$printed++;
-	}
-}
-
-if ($rcode1 ne $rcode2) {
-	print("< status: $rcode1\n");
-	print("> status: $rcode2\n");
-	$status = 1;
-}
-
-exit($status);
diff --git a/bin/tests/system/eddsa/tests.sh b/bin/tests/system/eddsa/tests.sh
index 4967ff2835..212e574998 100644
--- a/bin/tests/system/eddsa/tests.sh
+++ b/bin/tests/system/eddsa/tests.sh
@@ -29,7 +29,7 @@ if [ $ED25519_SUPPORTED = 1 ]; then
   ret=0
   dig_with_opts . @10.53.0.1 soa >dig.out.ns1.test$n || ret=1
   dig_with_opts . @10.53.0.2 soa >dig.out.ns2.test$n || ret=1
-  $PERL ../digcomp.pl dig.out.ns1.test$n dig.out.ns2.test$n || ret=1
+  digcomp dig.out.ns1.test$n dig.out.ns2.test$n || ret=1
   grep "flags:.*ad.*QUERY" dig.out.ns2.test$n >/dev/null || ret=1
   if [ $ret != 0 ]; then echo_i "failed"; fi
   status=$((status + ret))
@@ -57,7 +57,7 @@ if [ $ED448_SUPPORTED = 1 ]; then
   ret=0
   dig_with_opts . @10.53.0.1 soa >dig.out.ns1.test$n || ret=1
   dig_with_opts . @10.53.0.3 soa >dig.out.ns3.test$n || ret=1
-  $PERL ../digcomp.pl dig.out.ns1.test$n dig.out.ns3.test$n || ret=1
+  digcomp dig.out.ns1.test$n dig.out.ns3.test$n || ret=1
   grep "flags:.*ad.*QUERY" dig.out.ns3.test$n >/dev/null || ret=1
   if [ $ret != 0 ]; then echo_i "failed"; fi
   status=$((status + ret))
diff --git a/bin/tests/system/isctest/tests/tests_digcomp.py b/bin/tests/system/isctest/tests/tests_digcomp.py
new file mode 100644
index 0000000000..f1e0d95e4d
--- /dev/null
+++ b/bin/tests/system/isctest/tests/tests_digcomp.py
@@ -0,0 +1,145 @@
+# Copyright (C) Internet Systems Consortium, Inc. ("ISC")
+#
+# SPDX-License-Identifier: MPL-2.0
+#
+# This Source Code Form is subject to the terms of the Mozilla Public
+# License, v. 2.0. If a copy of the MPL was not distributed with this
+# file, you can obtain one at https://mozilla.org/MPL/2.0/.
+#
+# See the COPYRIGHT file distributed with this work for additional
+# information regarding copyright ownership.
+
+"""
+isctest.tools.digcomp self-test
+Pin down the comparison rules legacy tests.sh scripts rely on.
+"""
+
+import pytest
+
+from isctest.tools import digcomp
+
+NOERROR = ";; ->>HEADER<<- opcode: QUERY, status: NOERROR, id: 1\n"
+NXDOMAIN = ";; ->>HEADER<<- opcode: QUERY, status: NXDOMAIN, id: 1\n"
+A = "a.example.\t300\tIN\tA\t10.0.0.1\n"
+NS = "example.\t300\tIN\tNS\tns.example.\n"
+SOA = "example.\t300\tIN\tSOA\tns. hostmaster. 1 0 0 0 0\n"
+
+
+def compare(tmp_path, data1, data2, lowercase=False):
+    (tmp_path / "file1").write_text(data1, encoding="utf-8")
+    (tmp_path / "file2").write_text(data2, encoding="utf-8")
+    same, report = digcomp.compare(
+        str(tmp_path / "file1"), str(tmp_path / "file2"), lowercase
+    )
+    return same, report.replace(f"{tmp_path}/", "")
+
+
+@pytest.mark.parametrize(
+    "data1, data2",
+    [
+        pytest.param(NOERROR + A + NS, NOERROR + NS + A, id="order"),
+        pytest.param(A, A.replace("300", "5"), id="ttl"),
+        pytest.param(NOERROR + A, NOERROR.replace("id: 1", "id: 2") + A, id="id"),
+        pytest.param(
+            A + NS,
+            ";; ANSWER SECTION:\n" + A + "\n" + NS,
+            id="comment-and-blank-lines",
+        ),
+        pytest.param(A, ";a.example.\t\tIN\tA\n" + A, id="question"),
+        pytest.param(A, A.replace("\t", "  "), id="field-separators"),
+        pytest.param(SOA + A + NS + SOA, SOA + NS + A + SOA, id="axfr"),
+        pytest.param("a 300 IN APL\n", "a 5 IN APL\t\n", id="no-value"),
+        pytest.param(A, A + "a.example.\t300\tIN\n\t\t10.0.0.2 )\n", id="other-lines"),
+    ],
+)
+def test_same(tmp_path, data1, data2):
+    assert compare(tmp_path, data1, data2) == (True, "")
+
+
+@pytest.mark.parametrize(
+    "data1, data2, report",
+    [
+        pytest.param(
+            A + NS,
+            A,
+            "Only in file1 (missing from file2):\n< " + NS,
+            id="missing-from-file2",
+        ),
+        pytest.param(
+            A,
+            A + NS,
+            "Only in file2 (missing from file1):\n> " + NS,
+            id="missing-from-file1",
+        ),
+        pytest.param(
+            A,
+            A + A,
+            "Only in file2 (missing from file1):\n> " + A,
+            id="repeated-in-file2",
+        ),
+        pytest.param(
+            A,
+            A.upper(),
+            "Only in file2 (missing from file1):\n> "
+            + A.upper()
+            + "Only in file1 (missing from file2):\n< "
+            + A,
+            id="case",
+        ),
+        pytest.param(
+            'a 300 IN TXT "a "\n',
+            'a 300 IN TXT "a  "\n',
+            'Only in file2 (missing from file1):\n> a 300 IN TXT "a  "\n'
+            'Only in file1 (missing from file2):\n< a 300 IN TXT "a "\n',
+            id="whitespace-in-value",
+        ),
+        pytest.param(
+            SOA + A + SOA,
+            SOA + A,
+            "Only in file1 (missing from file2):\n< " + SOA,
+            id="axfr-one-soa-missing-from-file2",
+        ),
+        pytest.param(
+            SOA + A,
+            SOA + A + SOA,
+            "Only in file2 (missing from file1):\n> " + SOA,
+            id="axfr-one-soa-missing-from-file1",
+        ),
+        pytest.param(
+            NOERROR + A,
+            NXDOMAIN + A,
+            "< status: NOERROR,\n> status: NXDOMAIN,\n",
+            id="status",
+        ),
+        pytest.param(
+            NOERROR + A,
+            A,
+            "< status: NOERROR,\n> status: none\n",
+            id="status-missing",
+        ),
+    ],
+)
+def test_different(tmp_path, data1, data2, report):
+    assert compare(tmp_path, data1, data2) == (False, report)
+
+
+def test_repeated_in_file1(tmp_path):
+    line = A.replace("300", "5")
+    assert compare(tmp_path, A + line, A) == (
+        True,
+        "Duplicate entry in file1:\n> " + line + "< " + A,
+    )
+
+
+def test_lowercase(tmp_path):
+    upper = "A.EXAMPLE.\t300\tIN\tCNAME\tB.EXAMPLE.\n"
+    lower = "a.example.\t300\tIN\tCNAME\tb.example.\n"
+    assert compare(tmp_path, upper, lower, lowercase=True) == (True, "")
+    # The class and the type are compared as they are.
+    assert compare(tmp_path, upper, upper.lower(), lowercase=True) == (
+        False,
+        "Only in file2 (missing from file1):\n> "
+        + upper.lower()
+        + "Only in file1 (missing from file2):\n< "
+        + upper,
+    )
diff --git a/bin/tests/system/isctest/tools/digcomp.py b/bin/tests/system/isctest/tools/digcomp.py
new file mode 100644
index 0000000000..01a07f1d04
--- /dev/null
+++ b/bin/tests/system/isctest/tools/digcomp.py
@@ -0,0 +1,175 @@
+# Copyright (C) Internet Systems Consortium, Inc. ("ISC")
+#
+# SPDX-License-Identifier: MPL-2.0
+#
+# This Source Code Form is subject to the terms of the Mozilla Public
+# License, v. 2.0. If a copy of the MPL was not distributed with this
+# file, you can obtain one at https://mozilla.org/MPL/2.0/.
+#
+# See the COPYRIGHT file distributed with this work for additional
+# information regarding copyright ownership.
+
+"""
+Compare two files holding dig output, ignoring record order and TTLs.
+
+This is a textual comparison, and a deliberately faithful port of the
+Perl digcomp.pl that legacy tests.sh scripts were written against.  The
+behaviour below is relied upon by its callers; do not "fix" it:
+
+- Only two things are compared: the status of the response and the
+  records.  All other lines starting with ';' are skipped, so the
+  records of all sections are pooled and the question and the OPT
+  pseudosection never take part.
+- The status is the token following "status:", trailing comma
+  included.  The last such line wins; a file without one has the
+  status "none".
+- A record is a line of five whitespace-separated fields: name, TTL,
+  class, type and value.  The TTL is ignored, the rest is compared
+  verbatim: names are case-sensitive and whitespace inside the value is
+  significant.  A line with four fields is a record with an empty
+  value.  Any other line is ignored.
+- --lc lowercases the name and the value, not the class and the type.
+- If a record occurs more than one time in the first file, the script
+  reports it, but this is not a failure.  The script keeps only one copy
+  of the record.
+- If a record occurs more than one time in the second file, this is a
+  failure.  Each record in the first file can match only one record in
+  the second file.
+- The two rules above do not apply to the SOA records at the zone apex.
+  A zone transfer starts and ends with the same SOA record.  The script
+  gives a number to each of these records, in the sequence in which
+  they occur in each file.  Thus the two files must contain the same
+  SOA records in the same sequence.  The zone apex is the owner name of
+  the first SOA record in the first file.
+
+Nothing is printed when the files match; legacy callers treat any
+output as a failure report.
+"""
+
+import argparse
+import re
+import sys
+
+STATUS = re.compile(r"^;.+status:\s+(\S+).+$", re.ASCII)
+RECORD = re.compile(r"^(\S+)\s+\S+\s+(\S+)\s+(\S+)\s+(.+)$", re.ASCII)
+RECORD_NO_VALUE = re.compile(r"^(\S+)\s+\S+\s+(\S+)\s+(\S+)\s*$", re.ASCII)
+
+Record = tuple[str, str, str, str]
+
+
+def _parse(path: str, lowercase: bool) -> tuple[str, list[tuple[Record, str]]]:
+    """
+    Return the status and the records of a file, each record paired
+    with the line it comes from.
+    """
+    with open(path, encoding="utf-8") as f:
+        data = f.read()
+
+    status = "none"
+    records = []
+    for line in data.split("\n"):
+        match = STATUS.match(line)
+        if match:
+            status = match.group(1)
+        if line.startswith(";"):
+            continue
+        # The order matters: a four-field line with trailing whitespace
+        # is a five-field record with a whitespace value.
+        match = RECORD.match(line)
+        if match:
+            name, rdclass, rdtype, value = match.groups()
+        else:
+            match = RECORD_NO_VALUE.match(line)
+            if not match:
+                continue
+            name, rdclass, rdtype = match.groups()
+            value = ""
+        if lowercase:
+            name = name.lower()
+            value = value.lower()
+        records.append(((name, rdclass, rdtype, value), line))
+    return status, records
+
+
+def compare(file1: str, file2: str, lowercase: bool = False) -> tuple[bool, str]:
+    """
+    Compare two files with dig output.  Return whether they match and
+    the report of the differences found.
+    """
+    same = True
+    report = []
+    soa_name = None
+
+    status1, records = _parse(file1, lowercase)
+    entries: dict[Record, str] = {}
+    soa_count = 0
+    for (name, rdclass, rdtype, value), line in records:
+        if rdtype == "SOA":
+            if soa_name is None:
+                soa_name = name
+            if name == soa_name:
+                name += str(soa_count)
+                soa_count += 1
+        key = (name, rdclass, rdtype, value)
+        if key in entries:
+            report.append(f"Duplicate entry in {file1}:")
+            report.append(f"> {line}")
+            report.append(f"< {entries[key]}")
+        else:
+            entries[key] = line
+
+    status2, records = _parse(file2, lowercase)
+    only_in_file2 = []
+    soa_count = 0
+    for (name, rdclass, rdtype, value), line in records:
+        if rdtype == "SOA" and name == soa_name:
+            name += str(soa_count)
+            soa_count += 1
+        key = (name, rdclass, rdtype, value)
+        if key in entries:
+            del entries[key]
+        else:
+            only_in_file2.append(f"> {line}")
+    if only_in_file2:
+        same = False
+        report.append(f"Only in {file2} (missing from {file1}):")
+        report.extend(only_in_file2)
+
+    only_in_file1 = [f"< {line}" for line in entries.values()]
+    if only_in_file1:
+        same = False
+        report.append(f"Only in {file1} (missing from {file2}):")
+        report.extend(only_in_file1)
+
+    if status1 != status2:
+        same = False
+        report.append(f"< status: {status1}")
+        report.append(f"> status: {status2}")
+
+    return same, "".join(f"{line}\n" for line in report)
+
+
+def main() -> None:
+    parser = argparse.ArgumentParser(
+        prog="digcomp",
+        description=__doc__,
+        formatter_class=argparse.RawDescriptionHelpFormatter,
+    )
+    parser.add_argument(
+        "--lc", action="store_true", help="lowercase names and values first"
+    )
+    parser.add_argument("file1")
+    parser.add_argument("file2")
+    args = parser.parse_args()
+
+    try:
+        same, report = compare(args.file1, args.file2, args.lc)
+    except OSError as exc:
+        print(f"open: {exc.filename}: {exc.strerror}", file=sys.stderr)
+        sys.exit(exc.errno)
+    sys.stdout.write(report)
+    sys.exit(0 if same else 1)
+
+
+if __name__ == "__main__":
+    main()
diff --git a/bin/tests/system/rpz/tests.sh b/bin/tests/system/rpz/tests.sh
index e2b85d2e59..ab2f7c14c2 100644
--- a/bin/tests/system/rpz/tests.sh
+++ b/bin/tests/system/rpz/tests.sh
@@ -278,7 +278,7 @@ ckresult() {
     setret "'dig $digarg' AD set;"
   fi

-  if $PERL ../digcomp.pl $DIGNM $2 >/dev/null; then
+  if $PYTHON -m isctest.tools.digcomp $DIGNM $2 >/dev/null; then
     grep -q 'Truncated, retrying in TCP' $DIGNM && trunc=1 || trunc=0
     if [ "$tcp" -ne "$trunc" ]; then
       setret "'dig $digarg' wrong; no or unexpected truncation in $DIGNM"
diff --git a/bin/tests/system/views/tests.sh b/bin/tests/system/views/tests.sh
index f8d19281b1..24029035c5 100644
--- a/bin/tests/system/views/tests.sh
+++ b/bin/tests/system/views/tests.sh
@@ -77,7 +77,7 @@ digcomp dig.out.ns2.1 dig.out.ns4.2 || status=1

 echo_i "comparing ns2's initial a.example to one from reconfigured 10.53.0.3"
 echo_i "(should be different)"
-if $PERL ../digcomp.pl dig.out.ns2.1 dig.out.ns3.2 >/dev/null; then
+if $PYTHON -m isctest.tools.digcomp dig.out.ns2.1 dig.out.ns3.2 >/dev/null; then
   echo_i "no differences found.  something's wrong."
   status=1
 fi