#!/usr/bin/env python3 """Tests for the model_id half of scripts/orca_profile_tool.py: the mint, the check and the generate-id pass (stdlib unittest, no external deps). Run from the repo root: python -m unittest discover -s scripts/tests -v """ import contextlib import io import json import os import re import shutil import sys import tempfile import unittest sys.path.insert(0, os.path.abspath(os.path.join(os.path.dirname(__file__), ".."))) import orca_profile_tool as apt # noqa: E402 REPO_ROOT = os.path.abspath(os.path.join(os.path.dirname(__file__), "..", "..")) REAL_PROFILES = os.path.join(REPO_ROOT, "resources", "profiles") MODEL_ID_FORMAT = re.compile(r"[a-z0-9]+(?:[.-][a-z0-9]+)*") class ModelTree: """A throwaway resources/profiles-shaped directory of printer models.""" def __init__(self): self.dir = tempfile.mkdtemp(prefix="model_id_test_") self.profiles = os.path.join(self.dir, "profiles") os.makedirs(self.profiles) def cleanup(self): shutil.rmtree(self.dir, ignore_errors=True) def index_path(self, vendor): return os.path.join(self.profiles, vendor + ".json") def add_vendor(self, vendor): for sub in apt.PROFILE_SUBDIRS: os.makedirs(os.path.join(self.profiles, vendor, sub), exist_ok=True) if not os.path.exists(self.index_path(vendor)): self._write_index(vendor, {"name": vendor, "version": "01.00.00.00", "machine_model_list": []}) def _write_index(self, vendor, index): with open(self.index_path(vendor), "w", encoding="utf-8", newline="\n") as f: json.dump(index, f, indent=4) f.write("\n") def path(self, vendor, name): return os.path.join(self.profiles, vendor, "machine", name + ".json") def model(self, vendor, name, model_id=None): """A machine_model file named after the model; returns its path.""" data = {"type": "machine_model", "name": name} if model_id is not None: data["model_id"] = model_id data["nozzle_diameter"] = "0.4" return self.raw(vendor, name, json.dumps(data, indent="\t") + "\n") def raw(self, vendor, name, text): """A machine_model file with exactly these bytes; returns its path.""" self.add_vendor(vendor) path = self.path(vendor, name) with open(path, "w", encoding="utf-8", newline="") as f: f.write(text) return path def read(self, vendor, name): with open(self.path(vendor, name), encoding="utf-8", newline="") as f: return f.read() class ModelTreeCase(unittest.TestCase): def setUp(self): self.t = ModelTree() self.addCleanup(self.t.cleanup) def check(self): buf = io.StringIO() with contextlib.redirect_stdout(buf): errors = apt.check_machine_model_ids(self.t.profiles) return errors, buf.getvalue() def generate(self, vendors=None, dry_run=False): buf = io.StringIO() with contextlib.redirect_stdout(buf): changed, errors = apt.generate_model_ids(self.t.profiles, vendors, dry_run) return changed, errors, buf.getvalue() def run_command(self, *argv): buf = io.StringIO() with contextlib.redirect_stdout(buf): rc = apt.main([*argv, "--profiles", self.t.profiles]) return rc, buf.getvalue() class TestModelIdMint(unittest.TestCase): EXAMPLES = ( ("Prusa", "Prusa MK4S", "prusa-prusa-mk4s"), ("Voron", "Voron 2.4 350", "voron-voron-2.4-350"), ("UltiMaker", "UltiMaker 2+", "ultimaker-ultimaker-2-plus"), ("FELIX Printers", "FELIX Pro L 3.0", "felix-printers-felix-pro-l-3.0"), ("Afinia", "Afinia H+1(HS)", "afinia-afinia-h-plus-1-hs"), ("Vivedino", "Troodon 2.0 - Klipper", "vivedino-troodon-2.0-klipper"), ("WEMAKE3D", "WEMAKE3D TinyBotV1", "wemake3d-wemake3d-tinybotv1"), ) def test_examples(self): for vendor, name, expected in self.EXAMPLES: self.assertEqual(apt.generate_model_id(vendor, name), expected) def test_every_mint_is_lower_case_words_joined_by_hyphens(self): for vendor, name, _expected in self.EXAMPLES: self.assertRegex(apt.generate_model_id(vendor, name), MODEL_ID_FORMAT) def test_a_plus_keeps_two_names_apart(self): # "UltiMaker 2" and "UltiMaker 2+" ship side by side. self.assertNotEqual(apt.generate_model_id("U", "UltiMaker 2"), apt.generate_model_id("U", "UltiMaker 2+")) def test_a_dot_is_kept_only_between_digits(self): self.assertEqual(apt.generate_model_id("V", "Model v.2"), "v-model-v-2") self.assertEqual(apt.generate_model_id("V", "Mk3.5."), "v-mk3.5") self.assertNotEqual(apt.generate_model_id("V", "X 2.4"), apt.generate_model_id("V", "X 24")) def test_accents_fold_to_ascii(self): self.assertEqual(apt.generate_model_id("Vé", "Modèle Ü"), "ve-modele-u") def test_a_name_with_no_letters_or_digits_mints_nothing(self): self.assertEqual(apt.generate_model_id("V", "+-!"), "v-plus") self.assertEqual(apt.generate_model_id("V", "!!!"), "") def test_the_bundle_is_part_of_the_identity(self): self.assertNotEqual(apt.generate_model_id("Creality", "K1"), apt.generate_model_id("Elegoo", "K1")) class TestCheck(ModelTreeCase): def test_minted_ids_and_bambu_codes_pass(self): self.t.model("V", "V One", "v-v-one") self.t.model("W", "W Two+", "w-w-two-plus") self.t.model("BBL", "Bambu Lab A1 mini", "N1") errors, out = self.check() self.assertEqual(errors, 0, out) def test_a_hand_written_id_is_rejected(self): # A valid-looking id that is not what the bundle and name give is exactly # what a duplicate check alone lets through. self.t.model("WEMAKE3D", "WEMAKE3D TinyBotV1", "v1") errors, out = self.check() self.assertEqual(errors, 1, out) self.assertIn('has the model_id "v1" but its bundle and name give ' '"wemake3d-wemake3d-tinybotv1"', out) self.assertIn('"python scripts/orca_profile_tool.py generate-id --model-id" or ' 'paste it', out) def test_a_missing_or_blank_id_is_rejected(self): self.t.model("Cubicon", "Cubicon xCeler-I") self.t.model("Cubicon", "Cubicon xCeler-Mini", " ") errors, out = self.check() self.assertEqual(errors, 2, out) for name in ("xceler-i", "xceler-mini"): self.assertIn(f'needs the model_id "cubicon-cubicon-{name}", which its bundle ' f"and name give", out) def test_a_mismatch_explains_what_a_rename_costs(self): # A rename is the legitimate way to reach this error; the contributor and the # reviewer reading the PR comment both need to know it orphans added printers. self.t.model("V", "V One Pro", "v-v-one") errors, out = self.check() self.assertEqual(errors, 1, out) self.assertIn("If you renamed the model, the new id is expected: printers users " "added with the old id must be added again", out) def test_a_non_string_id_is_rejected(self): self.t.model("V", "V One", 797581801) errors, out = self.check() self.assertEqual(errors, 1, out) self.assertIn('has the model_id 797581801 but its bundle and name give "v-v-one"', out) def test_a_copied_id_is_rejected(self): self.t.model("V", "V Artisan", "v-v-artisan") self.t.model("V", "V U1", "v-v-artisan") errors, out = self.check() self.assertEqual(errors, 1, out) self.assertIn('machine_model "V U1" has the model_id "v-v-artisan" but its bundle ' 'and name give "v-v-u1"', out) def test_bambu_keeps_its_codes_but_needs_one(self): self.t.model("BBL", "Bambu Lab A1", "N2S") self.t.model("BBL", "Bambu Lab X1", "") errors, out = self.check() self.assertEqual(errors, 1, out) self.assertIn('machine_model "Bambu Lab X1" has no model_id', out) def test_two_names_minting_one_id_clash(self): self.t.model("V", "Foo X", "v-foo-x") self.t.model("V", "Foo-X", "v-foo-x") errors, out = self.check() self.assertEqual(errors, 1, out) self.assertIn('model_id "v-foo-x" is shared by 2 machine models', out) self.assertIn("V/machine/Foo X.json", out) self.assertIn("V/machine/Foo-X.json", out) def test_ids_that_differ_only_by_case_clash(self): self.t.model("BBL", "Bambu One", "N1") self.t.model("BBL", "Bambu Two", "n1") errors, out = self.check() self.assertEqual(errors, 1, out) self.assertIn('model_id "N1 / n1" is shared by 2 machine models', out) def test_a_name_that_mints_nothing_is_reported(self): self.t.model("V", "!!!", "v") errors, out = self.check() self.assertEqual(errors, 1, out) self.assertIn("has a name that gives no model_id", out) def test_the_check_command_fails_on_a_copied_id(self): # Through the CI entry point, so the check is wired into `check`. self.t.model("V", "V Artisan", "v-v-artisan") self.t.model("V", "V U1", "v-v-u1") rc, out = self.run_command("update-index") self.assertEqual(rc, 0, out) rc, out = self.run_command("check") self.assertEqual(rc, 0, out) self.t.model("V", "V U1", "v-v-artisan") rc, out = self.run_command("check") self.assertEqual(rc, 1, out) self.assertIn('has the model_id "v-v-artisan" but its bundle and name give ' '"v-v-u1"', out) class TestGenerate(ModelTreeCase): def test_a_missing_id_is_inserted_after_the_identifying_keys(self): self.t.raw("V", "V One", '{\n\t"type": "machine_model",\n\t"name": "V One",\n' '\t"from": "system",\n\t"nozzle_diameter": "0.4"\n}\n') changed, errors, out = self.generate() self.assertEqual((changed, errors), (1, 0), out) self.assertEqual(self.t.read("V", "V One"), '{\n\t"type": "machine_model",\n\t"name": "V One",\n' '\t"from": "system",\n\t"model_id": "v-v-one",\n' '\t"nozzle_diameter": "0.4"\n}\n') def test_a_wrong_id_is_replaced_in_place(self): # CRLF endings and four-space indentation survive: only the value changes. before = ('{\r\n "type": "machine_model",\r\n "name": "V One",\r\n' ' "model_id": "v1",\r\n "nozzle_diameter": "0.4"\r\n}\r\n') self.t.raw("V", "V One", before) changed, errors, out = self.generate() self.assertEqual((changed, errors), (1, 0), out) self.assertEqual(self.t.read("V", "V One"), before.replace('"v1"', '"v-v-one"')) def test_idempotent(self): self.t.model("V", "V One") self.generate() changed, errors, out = self.generate() self.assertEqual((changed, errors), (0, 0), out) def test_bambu_is_left_alone(self): self.t.model("BBL", "Bambu Lab A1", "N2S") self.t.model("BBL", "Bambu Lab X1") before = (self.t.read("BBL", "Bambu Lab A1"), self.t.read("BBL", "Bambu Lab X1")) changed, errors, out = self.generate() self.assertEqual((changed, errors), (0, 0), out) self.assertEqual((self.t.read("BBL", "Bambu Lab A1"), self.t.read("BBL", "Bambu Lab X1")), before) def test_dry_run_writes_nothing(self): self.t.model("V", "V One", "v1") before = self.t.read("V", "V One") changed, errors, out = self.generate(dry_run=True) self.assertEqual((changed, errors), (1, 0), out) self.assertIn('would update V/machine/V One.json: model_id "v1" -> "v-v-one"', out) self.assertEqual(self.t.read("V", "V One"), before) def test_vendor_narrowing(self): self.t.model("V", "V One") self.t.model("W", "W One") changed, errors, out = self.generate(vendors=["V"]) self.assertEqual((changed, errors), (1, 0), out) self.assertIn('"model_id": "v-v-one"', self.t.read("V", "V One")) self.assertNotIn("model_id", self.t.read("W", "W One")) def test_the_model_id_flag_writes_model_ids_only(self): self.t.model("V", "V One") filament = os.path.join(self.t.profiles, "V", "filament", "F.json") with open(filament, "w", encoding="utf-8", newline="\n") as f: json.dump({"type": "filament", "name": "F", "instantiation": "true"}, f) rc, out = self.run_command("generate-id", "--model-id") self.assertEqual(rc, 0, out) self.assertIn('"model_id": "v-v-one"', self.t.read("V", "V One")) with open(filament, encoding="utf-8") as f: self.assertNotIn("setting_id", f.read()) class TestRealTree(unittest.TestCase): def test_every_shipped_model_carries_its_id(self): buf = io.StringIO() with contextlib.redirect_stdout(buf): errors = apt.check_machine_model_ids(REAL_PROFILES) self.assertEqual(errors, 0, buf.getvalue()) if __name__ == "__main__": unittest.main()