Files
OrcaSlicer/scripts/tests/test_gcode_fingerprint.py
T
Hanif Koh 5fd70d3301 Add a Script That Fingerprints Sweep G-code and Compares Two Sweeps
OrcaSlicer_profile_validator -s -o saves one G-code file per shipped
printer preset. gcode_fingerprint.py hashes each file without the lines
that differ between two runs of the same sources (the timestamp, the
config block and the object ids taken from a process-wide counter), and
reports which slices changed between two sweeps.

A slice whose output cannot repeat yet (fuzzy skin, random infill
rotation) is listed as not compared. A slice present in one sweep only
is listed and does not count as changed.
2026-11-28 22:08:47 +08:00

329 lines
14 KiB
Python

#!/usr/bin/env python3
"""Tests for scripts/gcode_fingerprint.py (stdlib unittest, no external deps).
Run from the repo root: python3 -m unittest discover -s scripts/tests -t scripts
"""
import os
import subprocess
import sys
import tempfile
import unittest
sys.path.insert(0, os.path.abspath(os.path.join(os.path.dirname(__file__), "..")))
import gcode_fingerprint as gf # noqa: E402
SCRIPT = os.path.join(os.path.dirname(__file__), "..", "gcode_fingerprint.py")
CONFIG_BLOCK = (
"; CONFIG_BLOCK_START\n"
"; fuzzy_skin = {fuzzy}\n"
"; layer_height = 0.2\n"
"; sparse_infill_rotate_template = {rotate}\n"
"; CONFIG_BLOCK_END\n"
)
MOTION = (
"G1 X10 Y10 E1.5\n"
"; object ids of layer 1 start: {label},16\n"
"M624 AwAAAAAAAAA=\n"
"; start printing object, unique label id: {label}\n"
"G1 X20 Y10 E3 ; perimeter\n"
"; stop printing object, unique label id: {label}\n"
"; object ids of this layer1 end: {label},16\n"
"M625\n"
)
def gcode(date="2026-11-26 at 10:00:00", label=15, fuzzy="none", rotate="", motion=MOTION, block_first=True):
"""A small file with every line shape the script strips, and motion it must keep."""
header = (
"; HEADER_BLOCK_START\n"
f"; generated by OrcaSlicer 2.6.0-dev on {date}\n"
f"; model label id: {label}\n"
"; HEADER_BLOCK_END\n"
)
block = CONFIG_BLOCK.format(fuzzy=fuzzy, rotate=rotate)
body = motion.format(label=label)
return (header + block + body if block_first else header + body + block).encode()
class NormaliseTest(unittest.TestCase):
def test_drops_only_the_lines_that_vary_between_runs(self):
self.assertEqual(
gf.normalise(gcode()),
b"; HEADER_BLOCK_START\n; HEADER_BLOCK_END\n"
b"G1 X10 Y10 E1.5\nM624 AwAAAAAAAAA=\nG1 X20 Y10 E3 ; perimeter\nM625\n",
)
def test_config_block_is_dropped_wherever_it_sits(self):
self.assertEqual(gf.normalise(gcode(block_first=True)), gf.normalise(gcode(block_first=False)))
def test_keeps_a_file_that_has_none_of_those_lines(self):
plain = b"G28\nG1 X5 Y5\n; note\n"
self.assertEqual(gf.normalise(plain), plain)
def test_a_config_block_that_never_closes_is_an_error(self):
broken = gcode().replace(b"; CONFIG_BLOCK_END\n", b"")
with self.assertRaisesRegex(ValueError, "CONFIG_BLOCK_END"):
gf.normalise(broken)
def test_a_config_block_that_closes_before_it_opens_is_an_error(self):
with self.assertRaisesRegex(ValueError, "CONFIG_BLOCK_START"):
gf.normalise(b"G28\n; CONFIG_BLOCK_END\n")
class DigestTest(unittest.TestCase):
def test_timestamp_label_ids_and_config_do_not_change_the_digest(self):
first = gcode(date="2026-11-26 at 10:00:00", label=15)
second = gcode(date="2027-01-02 at 03:04:05", label=3210).replace(b"layer_height = 0.2", b"layer_height = 0.2\n; new_option = 1")
self.assertEqual(gf.digest(first), gf.digest(second))
def test_one_changed_coordinate_changes_the_digest(self):
moved = MOTION.replace("X20", "X20.001")
self.assertNotEqual(gf.digest(gcode()), gf.digest(gcode(motion=moved)))
class UnstableReasonTest(unittest.TestCase):
def test_fuzzy_skin_on_is_not_reproducible(self):
self.assertEqual(gf.unstable_reason(gcode(fuzzy="allwalls")), "fuzzy skin")
def test_fuzzy_skin_off_is_reproducible(self):
for off in ("none", "disabled_fuzzy"):
with self.subTest(value=off):
self.assertEqual(gf.unstable_reason(gcode(fuzzy=off)), "")
def test_random_infill_rotation_is_not_reproducible(self):
for template in ("0~45", "45^3"):
with self.subTest(template=template):
self.assertEqual(gf.unstable_reason(gcode(rotate=template)), "random infill rotation")
def test_a_fixed_infill_rotation_is_reproducible(self):
self.assertEqual(gf.unstable_reason(gcode(rotate="45,135")), "")
def test_a_config_block_without_those_options_is_reproducible(self):
self.assertEqual(gf.unstable_reason(b"; CONFIG_BLOCK_START\n; layer_height = 0.2\n; CONFIG_BLOCK_END\nG28\n"), "")
def test_a_file_without_a_config_block_cannot_be_checked(self):
self.assertEqual(gf.unstable_reason(b"G28\n; fuzzy_skin = allwalls\n"), "no config block")
class FingerprintDirTest(unittest.TestCase):
def setUp(self):
self.tmp = tempfile.TemporaryDirectory()
self.addCleanup(self.tmp.cleanup)
def write(self, name, data):
with open(os.path.join(self.tmp.name, name), "wb") as f:
f.write(data)
def test_one_row_per_gcode_file_sorted_by_name(self):
self.write("Voron__Voron 2.4 0.4 nozzle.gcode", gcode())
self.write("Bambulab__Bambu Lab A1 0.4 nozzle.gcode", gcode())
self.write("M3D__Enabler__Fuzzy Skin @M3D.gcode", gcode(fuzzy="allwalls"))
self.write("notes.txt", b"not g-code")
rows = gf.fingerprint_dir(self.tmp.name)
self.assertEqual([row[0] for row in rows],
["Bambulab__Bambu Lab A1 0.4 nozzle", "M3D__Enabler__Fuzzy Skin @M3D", "Voron__Voron 2.4 0.4 nozzle"])
self.assertEqual(rows[0][1], gf.digest(gcode()))
self.assertEqual(rows[0][2], "")
self.assertEqual(rows[1][1:], ("-", "fuzzy skin"))
def test_a_file_name_that_would_break_the_file_format_is_an_error(self):
self.write("A__one\rtwo.gcode", gcode())
with self.assertRaisesRegex(ValueError, "tab or a line break"):
gf.fingerprint_dir(self.tmp.name)
def test_a_directory_without_gcode_is_an_error(self):
self.write("notes.txt", b"not g-code")
with self.assertRaisesRegex(ValueError, "no .gcode files"):
gf.fingerprint_dir(self.tmp.name)
def test_rows_survive_a_round_trip_through_the_file_format(self):
self.write("A__one.gcode", gcode())
self.write("A__two.gcode", gcode(fuzzy="allwalls"))
rows = gf.fingerprint_dir(self.tmp.name)
path = os.path.join(self.tmp.name, "fingerprints.tsv")
with open(path, "w", encoding="utf-8", newline="\n") as f:
gf.write_fingerprints(rows, f)
self.assertEqual(gf.read_fingerprints(path), {row[0]: (row[1], row[2]) for row in rows})
def test_windows_line_ends_read_the_same(self):
path = os.path.join(self.tmp.name, "crlf.tsv")
with open(path, "wb") as f:
f.write(b"A__one\tabc123\t\r\nA__two\t-\tfuzzy skin\r\n")
self.assertEqual(gf.read_fingerprints(path), {"A__one": ("abc123", ""), "A__two": ("-", "fuzzy skin")})
def test_a_row_needs_either_a_digest_or_a_reason(self):
for row in ("A__one\t-\t\n", "A__one\tabc123\tfuzzy skin\n"):
with self.subTest(row=row):
path = os.path.join(self.tmp.name, "bad.tsv")
with open(path, "w", encoding="utf-8", newline="\n") as f:
f.write(row)
with self.assertRaisesRegex(ValueError, "either a digest or a reason"):
gf.read_fingerprints(path)
def test_a_malformed_fingerprint_line_is_an_error(self):
path = os.path.join(self.tmp.name, "bad.tsv")
with open(path, "w", encoding="utf-8") as f:
f.write("only-a-name\n")
with self.assertRaisesRegex(ValueError, "line 1"):
gf.read_fingerprints(path)
class CompareTest(unittest.TestCase):
BASE = {
"Bambulab__A1": ("aaa", ""),
"Bambulab__P1S": ("bbb", ""),
"Voron__V0": ("ccc", ""),
"Voron__Gone": ("ddd", ""),
"M3D__Fuzzy": ("-", "fuzzy skin"),
}
HEAD = {
"Bambulab__A1": ("aaa", ""),
"Bambulab__P1S": ("XXX", ""),
"Voron__V0": ("ccc", ""),
"Voron__New": ("eee", ""),
"M3D__Fuzzy": ("-", "fuzzy skin"),
}
def test_each_slice_lands_in_exactly_one_list(self):
report = gf.compare(self.BASE, self.HEAD)
self.assertEqual(report.changed, ["Bambulab__P1S"])
self.assertEqual(report.only_base, ["Voron__Gone"])
self.assertEqual(report.only_head, ["Voron__New"])
self.assertEqual(report.not_compared, [("M3D__Fuzzy", "fuzzy skin")])
self.assertEqual(report.same_count, 2)
def test_a_slice_unstable_on_one_side_only_is_not_compared(self):
report = gf.compare({"A__x": ("aaa", "")}, {"A__x": ("-", "fuzzy skin")})
self.assertEqual(report.changed, [])
self.assertEqual(report.not_compared, [("A__x", "fuzzy skin")])
def test_report_names_every_slice_grouped_by_vendor(self):
text = gf.format_report(gf.compare(self.BASE, self.HEAD), limit=20)
self.assertIn("G-code changed for 1 of 3 compared slices", text)
self.assertIn("Bambulab (1)", text)
self.assertIn("P1S", text)
self.assertIn("Only in base (1)", text)
self.assertIn("Gone", text)
self.assertIn("Only in head (1)", text)
self.assertIn("New", text)
self.assertIn("Not compared (1)", text)
self.assertIn("fuzzy skin", text)
def test_report_says_so_when_nothing_changed(self):
same = {"A__x": ("aaa", ""), "A__y": ("bbb", "")}
self.assertIn("G-code is the same for all 2 compared slices", gf.format_report(gf.compare(same, same), limit=20))
def test_long_groups_are_cut_at_the_limit(self):
base = {f"V__p{i:02d}": ("a", "") for i in range(5)}
head = {name: ("b", "") for name in base}
text = gf.format_report(gf.compare(base, head), limit=2)
self.assertIn("p00", text)
self.assertIn("p01", text)
self.assertNotIn("p02", text)
self.assertIn("and 3 more", text)
class CommandLineTest(unittest.TestCase):
def setUp(self):
self.tmp = tempfile.TemporaryDirectory()
self.addCleanup(self.tmp.cleanup)
def run_script(self, *args):
return subprocess.run([sys.executable, SCRIPT, *args], capture_output=True, text=True, check=False)
def sweep(self, name, files):
folder = os.path.join(self.tmp.name, name)
os.mkdir(folder)
for file_name, data in files.items():
with open(os.path.join(folder, file_name), "wb") as f:
f.write(data)
out = os.path.join(self.tmp.name, name + ".tsv")
result = self.run_script("fingerprint", folder, "-o", out)
self.assertEqual(result.returncode, 0, result.stderr)
return out
def test_identical_sweeps_exit_zero(self):
base = self.sweep("base", {"A__x.gcode": gcode(label=1)})
head = self.sweep("head", {"A__x.gcode": gcode(label=900, date="2030-01-01 at 00:00:00")})
result = self.run_script("compare", base, head)
self.assertEqual(result.returncode, 0, result.stdout + result.stderr)
self.assertIn("G-code is the same for all 1 compared slices", result.stdout)
def test_a_changed_slice_exits_one(self):
base = self.sweep("base", {"A__x.gcode": gcode()})
head = self.sweep("head", {"A__x.gcode": gcode(motion=MOTION.replace("X20", "X21"))})
result = self.run_script("compare", base, head)
self.assertEqual(result.returncode, 1, result.stdout + result.stderr)
self.assertIn("G-code changed for 1 of 1 compared slices", result.stdout)
def test_added_and_removed_slices_alone_exit_zero(self):
base = self.sweep("base", {"A__x.gcode": gcode(), "A__old.gcode": gcode()})
head = self.sweep("head", {"A__x.gcode": gcode(), "A__new.gcode": gcode()})
result = self.run_script("compare", base, head)
self.assertEqual(result.returncode, 0, result.stdout + result.stderr)
self.assertIn("Only in base (1)", result.stdout)
self.assertIn("Only in head (1)", result.stdout)
def test_sweeps_with_no_slice_in_common_exit_two(self):
base = self.sweep("base", {"A__x.gcode": gcode()})
head = self.sweep("head", {"B__y.gcode": gcode()})
result = self.run_script("compare", base, head)
self.assertEqual(result.returncode, 2)
self.assertIn("no slice in common", result.stderr)
def test_an_empty_fingerprint_file_exits_two(self):
base = self.sweep("base", {"A__x.gcode": gcode()})
empty = os.path.join(self.tmp.name, "empty.tsv")
open(empty, "w", encoding="utf-8").close()
result = self.run_script("compare", base, empty)
self.assertEqual(result.returncode, 2)
self.assertIn("no slice in common", result.stderr)
def test_a_limit_below_one_exits_two(self):
base = self.sweep("base", {"A__x.gcode": gcode()})
for limit in ("0", "-1", "abc"):
with self.subTest(limit=limit):
result = self.run_script("compare", base, base, "--limit", limit)
self.assertEqual(result.returncode, 2)
self.assertIn("must be a whole number, at least 1", result.stderr)
def test_a_missing_input_exits_two(self):
base = self.sweep("base", {"A__x.gcode": gcode()})
result = self.run_script("compare", base, os.path.join(self.tmp.name, "absent.tsv"))
self.assertEqual(result.returncode, 2)
self.assertIn("absent.tsv", result.stderr)
def test_an_empty_sweep_folder_exits_two(self):
folder = os.path.join(self.tmp.name, "empty")
os.mkdir(folder)
result = self.run_script("fingerprint", folder)
self.assertEqual(result.returncode, 2)
self.assertIn("no .gcode files", result.stderr)
def test_standard_output_gets_the_same_bytes_as_an_output_file(self):
folder = os.path.join(self.tmp.name, "one")
os.mkdir(folder)
with open(os.path.join(folder, "A__x.gcode"), "wb") as f:
f.write(gcode())
out = os.path.join(self.tmp.name, "one.tsv")
self.assertEqual(self.run_script("fingerprint", folder, "-o", out).returncode, 0)
printed = subprocess.run([sys.executable, SCRIPT, "fingerprint", folder], capture_output=True, check=True)
with open(out, "rb") as f:
self.assertEqual(printed.stdout, f.read())
def test_fingerprint_prints_to_stdout_without_an_output_file(self):
folder = os.path.join(self.tmp.name, "one")
os.mkdir(folder)
with open(os.path.join(folder, "A__x.gcode"), "wb") as f:
f.write(gcode())
result = self.run_script("fingerprint", folder)
self.assertEqual(result.returncode, 0, result.stderr)
self.assertEqual(result.stdout, f"A__x\t{gf.digest(gcode())}\t\n")
if __name__ == "__main__":
unittest.main()