Files
OrcaSlicer/scripts/tests/test_profile_library.py
T
SoftFever 46adf18765 Publish a filament and printer model library for other softwares (#18168)
* Define the profile library format other Orca software reads

Describes the file that will tell OrcaSonar, OrcaCloud and other readers which filament
products exist and which fit each printer model, with its JSON Schema and a shared test
fixture every reader runs, so they all read the file the same way.

* Collect which filaments every printer preset accepts

The rule the AMS tray dialog uses to offer filaments can now be applied to any printer
preset, and a new export gathers, for every system printer preset, the filaments it
accepts with the products, printer models and bundles they name. It is the data behind
the profile library. The dialog itself offers the same filaments as before.

* Let the profile validator export the profile library data

OrcaSlicer_profile_validator --export-library <file> writes, for every system printer
preset, the filaments it accepts, loading the profiles the way the app does so the data
matches what users see. Load problems are reported as warnings; the export fails only
when it cannot load the profiles or write the file.

* Build the profile library file from the validator's export

scripts/profile_library.py turns the validator's export into the published library format,
checks that the file reads back to exactly the filaments each printer and nozzle accepts,
and gives each publish a version newer than the last. Its reader runs the shared fixture,
so the format's reading rules are tested in OrcaSlicer itself.

* Publish the profile library automatically after each main build

After every successful Build all on main, and on demand, a workflow builds the nightly
library from main and the release library from the latest stable release, and publishes
whatever changed to the profile-library release of OrcaSlicer/orcaslicer-profiles. Runs
publish one at a time and never replace newer data with older, and a run that stops part
way is repaired by the next one.

* Make every profile library reader refuse a file with a bad version or channel

The Python reader accepted a file whose version or channel OrcaSonar's
reader refuses, so the two could disagree about the same file. The
shared fixture now carries both cases, and the format doc states the
rule every reader follows.

* Keep the profile library publish run honest when a step fails

A failed run-picking or tooling step could leave the run green with
nothing published, an unreadable current file could stop the very build
that would replace it, and rerunning all jobs could fail on the earlier
attempt's build. A dry run also reported a lower version than a publish
would give after a run that stopped part way.

* Read library versions alike in every reader, and never let the report stop a build

The Python reader accepted a version with a trailing newline or a
non-ASCII digit that the other readers refuse; the shared fixture now
carries both cases. A damaged current file in any form, or a recorded
version with an impossible date, now only marks the build's report as
changed instead of stopping the build that would repair the release.

* Stop a profile library publish clearly on a hand-edited release record

A release description line whose version publish cannot read made the
publish run crash with a traceback, while a dry run quietly ignored it.
Publish now stops before writing anything with a message naming the
line to correct, and a dry run warns that a publish would stop on it.

* Refuse any hand-edited profile library release record before publishing

A record line missing a field was read as no record, so publish could
replace a file with a lower version, and a bad build line crashed the
run with a traceback. Publish now stops before writing anything on a
malformed line, a build commit GitHub can't compare, or a file whose
line is gone, naming what to correct; a dry run warns the same way.

* Refuse a duplicated or build-less profile library release record

A second record line for a channel could lower the version floor, and a
deleted build line let an older build replace newer data unchecked.
Publish now stops on either before writing anything and names what to
correct. A first publish, with nothing recorded yet, is unaffected.

* Warn in a profile library dry run of every record publish would stop on

A dry run reported a clean version for a release description without
its build line, though a publish would refuse it. Both now read the
record through the same checks, so the dry run warns of every stop.

* Check a profile library dry run against the release's asset list

A dry run judged whether a channel's file was on the release by whether
it could download it, while a publish reads the release's asset list, so
an upload that never finished could stop a publish without the dry run
warning. The dry run now reads the same description and asset list.

* List filament products first in the profile library file

Someone opening a library file now meets the filament catalogue right after the channel, instead
of scrolling past the long list of ids that fit every printer first. The data, its hash and the
version are unchanged, so readers and bots see the same library.

* Describe the filaments every printer fits as branded and generic alike

* Call the filaments every printer fits universal_filaments in the profile library

The list of filament products that fit every printer model is now named universal_filaments
instead of everywhere, so someone reading a library file can tell what it holds without the docs.
No library has been published yet, so no reader in use depends on the old name.

* Make the profile library schema refuse values ending in a newline in every validator

A validator that reads the schema's patterns as Python does accepted a version, commit, data hash
or filament id followed by a newline, which every library reader refuses. The schema now refuses
them under either regex dialect.

* Say that a profile bundle that fails to load stops the library export

The export's notes said load errors were only warnings, but a bundle that fails to load stops it,
on purpose: a published file without that bundle would drop all of its printers or filaments. The
comment and the design doc now say so.
2026-12-05 18:32:10 +08:00

773 lines
41 KiB
Python

#!/usr/bin/env python3
"""Tests for scripts/profile_library.py (stdlib unittest, no external deps).
Run from the repo root: python3 -m unittest discover -s scripts/tests -t scripts
"""
import contextlib
import copy
import gzip
import io
import json
import os
import re
import sys
import tempfile
import unittest
sys.path.insert(0, os.path.abspath(os.path.join(os.path.dirname(__file__), "..")))
import profile_library as pl # noqa: E402
FIXTURE = os.path.join(os.path.dirname(__file__), "profile_library_fixture.json")
SCHEMA = os.path.join(os.path.dirname(__file__), "..", "profile_library.schema.json")
COMMIT = "0123456789abcdef0123456789abcdef01234567"
def raw_export():
"""Two models: M1 with a nozzle-limited product, M2 with two presets on one nozzle that accept
different products and that both leave out one generic."""
return {
"bundles": {"V": "1.0.0.0", "OrcaFilamentLibrary": "2.0.0.0"},
"filaments": {
"OFgenAAA": {"vendor": "Generic", "name": "Generic PLA", "type": "PLA"},
"OFgenBBB": {"vendor": "Generic", "name": "Generic PETG", "type": "PETG"},
"OFvnd111": {"vendor": "V", "name": "V PLA", "type": "PLA"},
"OFvnd222": {"vendor": "V", "name": "V PETG", "type": "PETG"},
"OFvndCCC": {"vendor": "V", "name": "V PLA-CF", "type": "PLA-CF"},
},
"universal_filaments": ["OFgenBBB", "OFgenAAA"],
"models": {
"M1": {"vendor": "V", "model_id": "v-m1", "nozzles": ["0.4", "0.6"]},
"M2": {"vendor": "V", "model_id": "v-m2", "nozzles": ["0.4"]},
},
"printers": [
{"preset": "M1 0.4", "model": "M1", "nozzle": "0.4", "filaments": ["OFgenAAA", "OFgenBBB", "OFvnd111"]},
{"preset": "M1 0.6", "model": "M1", "nozzle": "0.6", "filaments": ["OFgenAAA", "OFgenBBB", "OFvnd111", "OFvndCCC"]},
{"preset": "M2 0.4", "model": "M2", "nozzle": "0.4", "filaments": ["OFgenAAA", "OFvnd222"]},
{"preset": "M2 0.4 mirror", "model": "M2", "nozzle": "0.4", "filaments": ["OFgenAAA", "OFvnd111"]},
],
}
def fold(raw=None, channel="nightly", tag=None):
return pl.fold(raw or raw_export(), channel, "2.6.0-dev", COMMIT, tag)
class FoldTest(unittest.TestCase):
def test_own_products_nozzle_limits_and_hidden_generics(self):
models = fold()["printer_models"]
self.assertEqual(models["M1"]["filaments"], ["OFvnd111", "OFvndCCC"])
self.assertEqual(models["M1"]["nozzle_limits"], {"OFvndCCC": ["0.6"]})
self.assertEqual(models["M1"]["hidden"], [])
self.assertEqual(models["M2"]["hidden"], ["OFgenBBB"])
def test_presets_on_one_model_and_nozzle_are_united(self):
m2 = fold()["printer_models"]["M2"]
self.assertEqual(m2["filaments"], ["OFvnd111", "OFvnd222"])
self.assertEqual(m2["nozzle_limits"], {})
def test_the_folded_file_decodes_to_every_answer(self):
doc = fold()
lib = pl.Library(doc, stamped=False)
self.assertEqual(lib.fits_model("M1", "0.4"), {"OFgenAAA", "OFgenBBB", "OFvnd111"})
self.assertEqual(lib.fits_model("M1", "0.6"), {"OFgenAAA", "OFgenBBB", "OFvnd111", "OFvndCCC"})
self.assertEqual(lib.fits_model("M2", "0.4"), {"OFgenAAA", "OFvnd111", "OFvnd222"})
self.assertIsNone(lib.fits_model("M2", "0.6"))
def test_the_round_trip_catches_a_wrong_fold(self):
doc = fold()
doc["printer_models"]["M1"]["nozzle_limits"] = {}
with self.assertRaisesRegex(pl.LibraryError, "round trip failed for M1 at 0.4"):
pl.check_round_trip(doc, pl.answers_by_model(raw_export()))
def test_source_and_contents(self):
doc = fold(channel="release", tag="v2.5.3")
self.assertEqual(doc["schema"], pl.SCHEMA)
self.assertNotIn("version", doc)
self.assertEqual(doc["source"]["tag"], "v2.5.3")
self.assertEqual(doc["source"]["commit"], COMMIT)
self.assertEqual(doc["universal_filaments"], ["OFgenAAA", "OFgenBBB"])
self.assertNotIn("tag", fold()["source"])
def test_a_release_file_needs_a_tag_and_nightly_takes_none(self):
with self.assertRaises(pl.LibraryError):
fold(channel="release")
with self.assertRaises(pl.LibraryError):
fold(tag="v2.5.3")
def test_an_export_naming_an_unknown_filament_is_refused(self):
raw = raw_export()
raw["printers"][0]["filaments"].append("OFmissing")
with self.assertRaisesRegex(pl.LibraryError, "OFmissing"):
fold(raw)
class HashAndOutputTest(unittest.TestCase):
def test_the_same_data_gives_the_same_hash_and_bytes(self):
reordered = raw_export()
reordered["filaments"] = dict(reversed(list(reordered["filaments"].items())))
reordered["printers"].reverse()
a, b = fold(), fold(reordered)
self.assertEqual(a["source"]["data_hash"], b["source"]["data_hash"])
self.assertEqual(pl.dumps(a), pl.dumps(b))
self.assertEqual(pl.gzip_bytes(pl.dumps(a)), pl.gzip_bytes(pl.dumps(b)))
def test_the_hash_leaves_out_version_and_source(self):
doc = fold()
other = copy.deepcopy(doc)
other["version"] = "9.9.9_209901010000"
other["source"]["commit"] = "f" * 40
self.assertEqual(pl.data_hash(doc), pl.data_hash(other))
other["filaments"]["OFvnd111"]["name"] = "Renamed"
self.assertNotEqual(pl.data_hash(doc), pl.data_hash(other))
def test_output_is_ordered_with_one_entry_per_line(self):
text = pl.dumps(fold())
self.assertEqual(json.loads(text), fold())
self.assertIn(' "OFgenAAA": {"name": "Generic PLA", "type": "PLA", "vendor": "Generic"},\n', text)
self.assertEqual(list(json.loads(pl.dumps(pl.stamp(fold(), "", "202612041506")))),
["channel", "filaments", "universal_filaments", "printer_models", "schema", "source", "version"])
def test_gzip_has_a_fixed_header(self):
data = pl.gzip_bytes("{}\n")
self.assertEqual(data[4:8], b"\0\0\0\0") # mtime 0
self.assertEqual(gzip.decompress(data), b"{}\n")
class ChangedTest(unittest.TestCase):
def test_no_current_file_is_a_change(self):
self.assertTrue(pl.changed(fold(), None))
def test_identical_data_is_no_change(self):
self.assertFalse(pl.changed(fold(), fold()))
def test_other_data_is_a_change(self):
raw = raw_export()
raw["filaments"]["OFvnd111"]["name"] = "V PLA+"
self.assertTrue(pl.changed(fold(raw), fold()))
def test_a_current_file_that_is_not_a_document_is_a_change(self):
self.assertTrue(pl.changed(fold(), ["not", "a", "document"]))
def test_a_new_stable_tag_is_a_change_with_the_same_data(self):
old, new = fold(channel="release", tag="v2.5.3"), fold(channel="release", tag="v2.5.4")
self.assertEqual(old["source"]["data_hash"], new["source"]["data_hash"])
self.assertTrue(pl.changed(new, old))
self.assertFalse(pl.changed(new, new))
class StampTest(unittest.TestCase):
def test_the_version_is_the_current_minute(self):
self.assertEqual(pl.next_version("2.6.0-dev", "", "202612041506"), "2.6.0_202612041506")
self.assertEqual(pl.next_version("2.6.0-dev", "2.6.0_202612041400", "202612041506"), "2.6.0_202612041506")
def test_a_same_minute_recorded_stamp_moves_the_version_one_minute_on(self):
self.assertEqual(pl.next_version("2.6.0-dev", "2.6.0_202612041506", "202612041506"), "2.6.0_202612041507")
def test_a_recorded_stamp_ahead_of_the_clock_still_moves_the_version_on(self):
self.assertEqual(pl.next_version("2.6.0", "2.5.3_202612312359", "202612041506"), "2.6.0_202701010000")
def test_stamping_changes_only_the_version(self):
doc = fold()
stamped = pl.stamp(doc, "", "202612041506")
self.assertEqual(stamped["version"], "2.6.0_202612041506")
self.assertEqual({k: v for k, v in stamped.items() if k != "version"}, doc)
self.assertEqual(pl.data_hash(stamped), doc["source"]["data_hash"])
def test_stamping_refuses_a_stale_hash(self):
doc = fold()
doc["filaments"]["OFvnd111"]["name"] = "edited after folding"
with self.assertRaises(pl.LibraryError):
pl.stamp(doc, "", "202612041506")
def test_a_bad_recorded_version_is_refused(self):
with self.assertRaises(pl.LibraryError):
pl.next_version("2.6.0", "2.6.0-202612041506", "202612041506")
class ReportTest(unittest.TestCase):
"""The build's report: what it reads from the release only informs it and never stops it."""
def run_main(self, *argv):
out, self.err = io.StringIO(), io.StringIO()
with contextlib.redirect_stdout(out), contextlib.redirect_stderr(self.err):
code = pl.main(list(argv))
return code, out.getvalue()
def test_an_unreadable_current_file_counts_as_changed(self):
with tempfile.TemporaryDirectory() as d:
raw = os.path.join(d, "raw.json")
with open(raw, "w", encoding="utf-8") as f:
json.dump(raw_export(), f)
whole = pl.gzip_bytes(pl.dumps(pl.stamp(fold(), "", "202612041506")))
corrupt = whole[:20] + bytes(b ^ 0xFF for b in whole[20:40]) + whole[40:]
cases = (("truncated.json.gz", whole[: len(whole) // 2]), ("corrupt.json.gz", corrupt), ("bad.json", b"{not json"),
("source-null.json", b'{"schema": "orca.profile_library.v1", "source": null}'),
("source-list.json", b'{"schema": "orca.profile_library.v1", "source": []}'))
for name, data in cases:
current = os.path.join(d, name)
with open(current, "wb") as f:
f.write(data)
code, out = self.run_main("fold", "--raw", raw, "--channel", "nightly", "--orca-version", "2.6.0-dev",
"--commit", COMMIT, "--current", current, "--out", os.path.join(d, "out.json"))
self.assertEqual(code, 0, name)
self.assertIn("changed=true", out, name)
def recorded(self, d, channel, body, assets=()):
"""`recorded` on a release as `gh release view --json body,assets` prints it."""
path = os.path.join(d, "release.json")
with open(path, "w", encoding="utf-8") as f:
json.dump({"body": body, "assets": [{"name": name, "state": state} for name, state in assets]}, f)
return self.run_main("recorded", "--release", path, "--channel", channel)
def test_the_recorded_version_comes_from_the_description(self):
record = {"build": "a" * 40, "release": None,
"nightly": {"version": "2.6.0_202612050300", "data_hash": "sha256:old", "sha256": "0" * 64}}
with tempfile.TemporaryDirectory() as d:
for text, want, warned in ((pl.render_description(record), "2.6.0_202612050300", False), ("", "", False),
("nightly 2.6.0-bad sha256:x " + "0" * 64, "", True),
("nightly 2.6.0_202613991200 sha256:x " + "0" * 64, "", True)):
self.assertEqual(self.recorded(d, "nightly", text), (0, "version=%s\n" % want))
self.assertEqual("A publish would stop on it" in self.err.getvalue(), warned, text)
self.assertEqual(self.recorded(d, "nightly", "nightly 2.6.0_202612050300 sha256:x\n"), (0, "version=\n"))
self.assertIn("is not a nightly record", self.err.getvalue())
self.assertEqual(self.recorded(d, "release", pl.render_description(dict(record, build=None))), (0, "version=\n"))
self.assertIn("no build line but records or holds nightly", self.err.getvalue())
def test_the_report_checks_the_record_against_the_asset_list_as_publish_does(self):
# A listed file counts whether or not it downloads, such as an upload that never finished.
only_build = pl.render_description({"build": "a" * 40, "nightly": None, "release": None})
with tempfile.TemporaryDirectory() as d:
for state in ("uploaded", "starter"):
self.recorded(d, "nightly", only_build, [(pl.ASSETS["nightly"], state)])
self.assertIn("has profile-library_nightly.json.gz but its description has no nightly line",
self.err.getvalue(), state)
self.assertEqual(self.recorded(d, "nightly", only_build, [(pl.SCHEMA_ASSET, "uploaded")]), (0, "version=\n"))
self.assertEqual(self.err.getvalue(), "")
def test_a_release_that_cant_be_read_reports_no_floor(self):
with tempfile.TemporaryDirectory() as d:
for content in (None, "{not json", "[]"):
path = os.path.join(d, "release.json")
if content is not None:
with open(path, "w", encoding="utf-8") as f:
f.write(content)
self.assertEqual(self.run_main("recorded", "--release", path if content is not None else os.path.join(d, "none"),
"--channel", "nightly"), (0, "version=\n"))
class FixtureTest(unittest.TestCase):
"""The shared fixture's cases, read by this script's reader."""
@classmethod
def setUpClass(cls):
with open(FIXTURE, encoding="utf-8") as f:
cls.fixture = json.load(f)
cls.libs = {name: pl.Library(doc) for name, doc in cls.fixture["libraries"].items()}
def test_the_fixture_hashes_are_the_data_hashes(self):
for name, doc in self.fixture["libraries"].items():
self.assertEqual(doc["source"]["data_hash"], pl.data_hash(doc), name)
def test_filament_lookups(self):
for case in self.fixture["cases"]["filament"]:
self.assertEqual(pl.lookup_filament(self.libs, case["order"], case["id"]), case["expect"], case)
def test_model_lookups(self):
for case in self.fixture["cases"]["model"]:
self.assertEqual(pl.lookup_model(self.libs, case["order"], case["model_id"]), case["expect"], case)
def test_fits(self):
for case in self.fixture["cases"]["fits"]:
got = pl.lookup_fits(self.libs, case["order"], case["model_id"], case["nozzle"])
want = case["expect"]
self.assertEqual({k: v for k, v in got.items() if k != "filaments"},
{k: v for k, v in want.items() if k != "filaments"}, case)
self.assertEqual(set(got.get("filaments", [])), set(want.get("filaments", [])), case)
def test_the_model_list(self):
got = pl.model_list(self.libs["nightly"], self.libs["release"])
self.assertEqual(sorted(map(tuple, got)), sorted(map(tuple, self.fixture["cases"]["models"]["expect"])))
def test_refusals(self):
for case in self.fixture["cases"]["refuse"]:
with self.assertRaises(pl.LibraryError, msg=case["why"]):
pl.Library(case["library"])
class SchemaTest(unittest.TestCase):
"""The published schema's patterns, read with Python's re as Python validators read them."""
def test_every_pattern_refuses_a_trailing_newline(self):
def patterns(node):
if isinstance(node, dict):
for key, value in node.items():
if key == "pattern":
yield value
else:
yield from patterns(value)
elif isinstance(node, list):
for value in node:
yield from patterns(value)
with open(SCHEMA, encoding="utf-8") as f:
found = list(patterns(json.load(f)))
# One valid value per pattern: a version, a commit, a data_hash and a filament_id.
samples = ["2.6.0_202612041506", "0" * 40, "sha256:" + "0" * 64, "OF5CgdDq"]
self.assertEqual(len(found), len(samples))
for pattern in found:
matching = [s for s in samples if re.search(pattern, s)]
self.assertEqual(len(matching), 1, pattern)
self.assertIsNone(re.search(pattern, matching[0] + "\n"), pattern)
VALIDATOR_JOB = "build_linux (aarch64, ubuntu-24.04-arm) / Build Deps / Build OrcaSlicer / Build OrcaSlicer"
SELF_HOSTED_JOB = "build_linux (orca-lnx-server) / Build Deps / Build OrcaSlicer / Build OrcaSlicer"
def build_run(run_id, sha, event="push", branch="main", head_repo=pl.SOURCE_REPO, conclusion="success"):
"""A Build all run as GET /repos/{repo}/actions/runs/{id} returns it (the fields used)."""
return {"id": run_id, "head_sha": sha, "event": event, "head_branch": branch, "conclusion": conclusion,
"repository": {"full_name": pl.SOURCE_REPO}, "head_repository": {"full_name": head_repo}}
def build_jobs(validator="success", name=VALIDATOR_JOB):
jobs = [{"name": "build_linux (aarch64, ubuntu-24.04-arm) / Check Cache", "conclusion": "success"},
{"name": "Slice check (Linux aarch64)", "conclusion": "success"}]
if validator is not None:
jobs.append({"name": name, "conclusion": validator})
return jobs
class FakeApi:
"""Answers GET paths from recorded responses."""
def __init__(self, runs, jobs, artifacts):
self.runs, self.jobs, self.artifacts = runs, jobs, artifacts
def get(self, path, **params):
parts = path.split("/")
if path.endswith("/actions/workflows/build_all.yml/runs"):
return {"workflow_runs": [r for r in self.runs.values() if r["head_branch"] == params["branch"]][::-1]}
if parts[-1] == "jobs":
return {"jobs": self.jobs.get(int(parts[-2]), [])}
if parts[-1] == "artifacts":
return {"artifacts": self.artifacts.get(int(parts[-2]), [])}
return self.runs[int(parts[-1])]
def validator_artifact(sha, expired=False, arch="aarch64"):
return [{"name": "%s-profile-validator-linux-%s" % (sha, arch), "expired": expired}]
class ResolveTest(unittest.TestCase):
def test_only_trusted_builds_of_main_are_eligible(self):
jobs = build_jobs()
self.assertTrue(pl.eligible(build_run(1, "a"), jobs, False)[0])
self.assertTrue(pl.eligible(build_run(1, "a", event="schedule"), jobs, False)[0])
self.assertTrue(pl.eligible(build_run(1, "a", event="workflow_dispatch"), jobs, False)[0], "a manual Build all")
self.assertFalse(pl.eligible(build_run(1, "a", event="pull_request"), jobs, False)[0])
self.assertFalse(pl.eligible(build_run(1, "a", head_repo="someone/OrcaSlicer"), jobs, False)[0])
self.assertFalse(pl.eligible(build_run(1, "a", conclusion="failure"), jobs, False)[0])
self.assertFalse(pl.eligible(build_run(1, "a", branch="release/v2.5.4"), jobs, False)[0])
def test_a_build_deps_only_run_built_no_validator(self):
self.assertFalse(pl.eligible(build_run(1, "a", event="workflow_dispatch"), build_jobs(validator=None), False)[0])
self.assertFalse(pl.eligible(build_run(1, "a"), build_jobs(validator="skipped"), False)[0])
def test_self_hosted_builds_use_the_x86_64_validator(self):
jobs = build_jobs(name=SELF_HOSTED_JOB)
self.assertTrue(pl.eligible(build_run(1, "a"), jobs, True)[0])
self.assertFalse(pl.eligible(build_run(1, "a"), jobs, False)[0])
def test_after_build_all_the_waking_run_is_used(self):
api = FakeApi({7: build_run(7, "old"), 8: build_run(8, "new")}, {7: build_jobs(), 8: build_jobs()},
{7: validator_artifact("old")})
self.assertEqual(pl.resolve(api, "workflow_run", {"id": 7}, False),
{"run_id": 7, "head_sha": "old", "arch": "aarch64", "artifact": "old-profile-validator-linux-aarch64"})
def test_a_waking_run_that_is_not_eligible_stops_quietly(self):
api = FakeApi({7: build_run(7, "a", event="workflow_dispatch")}, {7: build_jobs(validator=None)}, {})
with self.assertRaises(pl.Stop):
pl.resolve(api, "workflow_run", {"id": 7}, False)
def test_by_hand_the_newest_eligible_run_is_used(self):
api = FakeApi({6: build_run(6, "older"), 7: build_run(7, "deps", event="workflow_dispatch"),
8: build_run(8, "fork", head_repo="someone/OrcaSlicer")},
{6: build_jobs(), 7: build_jobs(validator=None), 8: build_jobs()}, {6: validator_artifact("older")})
self.assertEqual(pl.resolve(api, "workflow_dispatch", None, False)["run_id"], 6)
def test_an_eligible_run_whose_validator_expired_asks_for_a_rerun(self):
api = FakeApi({7: build_run(7, "a")}, {7: build_jobs()}, {7: validator_artifact("a", expired=True)})
self.assertTrue(pl.eligible(build_run(7, "a"), build_jobs(), False)[0])
with self.assertRaisesRegex(pl.LibraryError, pl.RERUN):
pl.resolve(api, "workflow_run", {"id": 7}, False)
def test_no_eligible_run_asks_for_a_rerun(self):
api = FakeApi({7: build_run(7, "a", conclusion="failure")}, {7: build_jobs()}, {})
with self.assertRaisesRegex(pl.LibraryError, pl.RERUN):
pl.resolve(api, "workflow_dispatch", None, False)
def test_what_wakes_the_workflow(self):
def woken(event, branch="main", repo=pl.SOURCE_REPO):
return pl.woken_by_trusted_build("workflow_run", {"event": event, "head_branch": branch,
"head_repository": {"full_name": repo}})
self.assertTrue(pl.woken_by_trusted_build("workflow_dispatch", None))
self.assertTrue(woken("push"))
self.assertTrue(woken("schedule"))
self.assertTrue(woken("workflow_dispatch"))
self.assertFalse(woken("pull_request"))
self.assertFalse(woken("push", repo="someone/OrcaSlicer"))
class WorkflowInputsTest(unittest.TestCase):
def test_the_latest_release_must_be_stable(self):
self.assertEqual(pl.stable_tag({"tag_name": "v2.5.3", "draft": False, "prerelease": False}), "v2.5.3")
for bad in ({"tag_name": "nightly-builds", "prerelease": True}, {"tag_name": "v2.6.0", "draft": True}):
with self.assertRaises(pl.LibraryError):
pl.stable_tag(bad)
def test_a_validator_without_the_export_is_refused(self):
self.assertTrue(pl.validator_supports_export(" --export-library arg (=) Write the profile library"))
self.assertFalse(pl.validator_supports_export(" -s [ --slice ] Slice a two-colour cube"))
def test_the_orca_version_comes_from_version_inc(self):
self.assertEqual(pl.orca_version('set(SLIC3R_APP_NAME "OrcaSlicer")\nset(SoftFever_VERSION "2.6.0-dev")\n'), "2.6.0-dev")
with self.assertRaises(pl.LibraryError):
pl.orca_version("set(OTHER 1)\n")
def test_tooling_that_differs_from_main_is_seen(self):
import subprocess
with tempfile.TemporaryDirectory() as repo:
def git(*args):
return subprocess.run(["git", "-C", repo, *args], check=True, capture_output=True, text=True).stdout.strip()
def commit(path, text):
full = os.path.join(repo, path)
os.makedirs(os.path.dirname(full), exist_ok=True)
with open(full, "w", encoding="utf-8") as f:
f.write(text)
git("add", path)
git("-c", "user.name=t", "-c", "user.email=t@t", "commit", "-q", "-m", path)
return git("rev-parse", "HEAD")
git("init", "-q")
base = commit("scripts/profile_library.py", "v1")
other = commit("README.md", "unrelated")
changed_tooling = commit("scripts/profile_library.py", "v2")
git("checkout", "-q", base)
self.assertTrue(pl.tooling_same(repo, other))
self.assertFalse(pl.tooling_same(repo, changed_tooling))
class DecideTest(unittest.TestCase):
"""The publish step's decisions, from the release's state read inside its slot."""
NOW = "202612050200"
def setUp(self):
self.docs = {"nightly": fold(), "release": fold(channel="release", tag="v2.5.3")}
self.contract = {pl.SCHEMA_ASSET: b'{"schema": 1}\n', pl.FIXTURE_ASSET: b'{"fixture": 1}\n'}
self.compared = []
def compare(self, statuses):
def compare(base, head):
self.compared.append((base, head))
return statuses[(base, head)]
return compare
def decide(self, release, head="b" * 40, attempt="1", candidate_attempt="1", latest_tag="v2.5.3",
statuses=None, tooling=True, now=NOW, docs=None):
candidate = {"run_attempt": candidate_attempt, "head_sha": head, "release_tag": "v2.5.3"}
return pl.decide(release, docs or self.docs, self.contract, candidate, latest_tag,
self.compare(statuses or {}), attempt, tooling, now)
@staticmethod
def published(plan, previous=None):
"""The release after `plan` ran to the end."""
assets = {a["name"]: a for a in (previous["assets"] if previous else [])}
for i, item in enumerate(plan["uploads"]):
assets[item["name"]] = {"id": 100 + i, "name": item["name"], "state": "uploaded",
"digest": "sha256:" + pl.hashlib.sha256(item["data"]).hexdigest()}
return {"id": 1, "body": plan["description"], "assets": list(assets.values())}
def uploaded(self, plan):
return sorted(item["name"] for item in plan["uploads"])
def test_a_first_publish_uploads_all_four_files(self):
plan = self.decide(None)
self.assertEqual(self.uploaded(plan), sorted([*pl.ASSETS.values(), pl.SCHEMA_ASSET, pl.FIXTURE_ASSET]))
record = pl.parse_description(plan["description"])
self.assertEqual(record["build"], "b" * 40)
self.assertEqual(record["nightly"]["version"], "2.6.0_" + self.NOW)
self.assertEqual(record["release"]["tag"], "v2.5.3")
self.assertEqual(record["release"]["sha256"],
pl.hashlib.sha256(next(u["data"] for u in plan["uploads"] if u["name"] == pl.ASSETS["release"])).hexdigest())
self.assertEqual(self.compared, [])
def test_the_uploaded_files_are_stamped_and_carry_their_record(self):
plan = self.decide(None)
data = next(u["data"] for u in plan["uploads"] if u["name"] == pl.ASSETS["nightly"])
doc = json.loads(gzip.decompress(data))
self.assertEqual(doc["version"], pl.parse_description(plan["description"])["nightly"]["version"])
self.assertEqual(pl.data_hash(doc), self.docs["nightly"]["source"]["data_hash"])
def test_nothing_changed_uploads_nothing_and_records_the_build(self):
first = self.published(self.decide(None, head="a" * 40))
plan = self.decide(first, head="b" * 40, statuses={("a" * 40, "b" * 40): "ahead"})
self.assertEqual(plan["uploads"], [])
self.assertEqual(pl.parse_description(plan["description"])["build"], "b" * 40)
def test_a_dry_run_reports_the_version_a_publish_gives_after_a_stamp_was_reserved(self):
# A run that recorded a stamp but failed before uploading leaves the description ahead of the
# asset; the dry run's preview reads the same floor publish does.
reserved = "2.6.0_202612050300"
record = {"build": "b" * 40, "release": None,
"nightly": {"version": reserved, "data_hash": "sha256:old", "sha256": "0" * 64}}
release = {"id": 1, "body": pl.render_description(record), "assets": []}
published = pl.parse_description(self.decide(release)["description"])["nightly"]["version"]
with tempfile.TemporaryDirectory() as d:
path = os.path.join(d, "release.json")
with open(path, "w", encoding="utf-8") as f:
json.dump({"body": release["body"], "assets": release["assets"]}, f)
out = io.StringIO()
with contextlib.redirect_stdout(out):
pl.main(["recorded", "--release", path, "--channel", "nightly"])
preview = pl.stamp(self.docs["nightly"], out.getvalue().strip().split("=", 1)[1], self.NOW)["version"]
self.assertEqual(preview, published)
self.assertEqual(published, "2.6.0_202612050301")
def test_a_hand_edited_record_the_stamp_cannot_read_stops_publish_with_its_line_named(self):
for bad in ("2.6.0-bad", "2.6.0_202613991200", "2.6.0_999912312359"):
record = {"build": "b" * 40, "release": None,
"nightly": {"version": bad, "data_hash": "sha256:old", "sha256": "0" * 64}}
release = {"id": 1, "body": pl.render_description(record), "assets": []}
with self.assertRaisesRegex(pl.LibraryError, "description's nightly line records '%s'" % bad):
self.decide(release)
def test_a_record_line_without_a_records_fields_stops_publish_with_its_line_named(self):
good = pl.render_description({"build": "a" * 40, "nightly": None, "release": None})
for line in ("nightly 2.6.0_202612050301 sha256:x", "release 2.5.3_202612050301 sha256:x " + "0" * 64,
"build not-a-commit", "build " + "A" * 40):
with self.assertRaisesRegex(pl.LibraryError, "line %r is not a" % line):
self.decide({"id": 1, "body": good + line + "\n", "assets": []})
def test_a_second_record_line_stops_publish_with_it_named(self):
first = self.published(self.decide(None, head="a" * 40))
older = "nightly 2.6.0_202601010000 sha256:old " + "0" * 64
with self.assertRaisesRegex(pl.LibraryError, "second nightly line, %r" % older):
self.decide(dict(first, body=first["body"] + older + "\n"), head="b" * 40,
statuses={("a" * 40, "b" * 40): "ahead"})
def test_a_release_without_its_build_line_is_not_published_to(self):
first = self.published(self.decide(None, head="a" * 40))
record = pl.parse_description(first["body"])
record["build"] = None
with self.assertRaisesRegex(pl.LibraryError, "no build line but records or holds nightly, release"):
self.decide(dict(first, body=pl.render_description(record)), head="b" * 40)
# Neither records nor files: a first publish, which needs no build line.
self.assertTrue(self.decide({"id": 1, "body": "", "assets": []})["uploads"])
def test_a_file_whose_line_is_gone_is_not_replaced(self):
first = self.published(self.decide(None, head="a" * 40))
record = pl.parse_description(first["body"])
record["nightly"] = None
edited = dict(first, body=pl.render_description(record))
with self.assertRaisesRegex(pl.LibraryError, "has profile-library_nightly.json.gz but its description has no nightly line"):
self.decide(edited, head="b" * 40, statuses={("a" * 40, "b" * 40): "ahead"})
def test_a_build_line_github_cannot_compare_stops_publish_with_it_named(self):
first = self.published(self.decide(None, head="a" * 40))
with self.assertRaisesRegex(pl.LibraryError, "build line names a{40}, which GitHub can't compare"):
self.decide(first, head="b" * 40, statuses={("a" * 40, "b" * 40): None})
def test_a_publish_rerun_alone_on_an_earlier_build_is_refused(self):
with self.assertRaisesRegex(pl.LibraryError, "rerun all jobs"):
self.decide(None, attempt="2", candidate_attempt="1")
def test_tooling_changed_on_main_stops_the_publish(self):
with self.assertRaises(pl.Stop):
self.decide(None, tooling=False)
def test_the_compare_with_the_last_build_decides(self):
first = self.published(self.decide(None, head="a" * 40))
with self.assertRaises(pl.Stop):
self.decide(first, head="0" * 40, statuses={("a" * 40, "0" * 40): "behind"})
with self.assertRaises(pl.LibraryError):
self.decide(first, head="0" * 40, statuses={("a" * 40, "0" * 40): "diverged"})
self.decide(first, head="c" * 40, statuses={("a" * 40, "c" * 40): "ahead"})
self.decide(first, head="d" * 40, statuses={("a" * 40, "d" * 40): "identical"})
self.compared.clear()
self.decide(first, head="a" * 40)
self.assertEqual(self.compared, [], "the same build needs no compare")
def test_a_stable_release_published_since_the_build_skips_the_release_file(self):
plan = self.decide(None, latest_tag="v2.5.4")
self.assertNotIn(pl.ASSETS["release"], self.uploaded(plan))
self.assertIn(pl.ASSETS["nightly"], self.uploaded(plan))
self.assertIsNone(pl.parse_description(plan["description"])["release"])
def test_a_new_stable_tag_republishes_the_release_file_with_the_same_data(self):
first = self.published(self.decide(None, head="a" * 40))
docs = dict(self.docs, release=fold(channel="release", tag="v2.5.4"))
plan = self.decide(first, head="a" * 40, latest_tag="v2.5.4", docs=docs)
self.assertEqual(self.uploaded(plan), [pl.ASSETS["release"]])
def test_a_missing_asset_is_published_again_whatever_the_build_reported(self):
first = self.published(self.decide(None, head="a" * 40))
first["assets"] = [a for a in first["assets"] if a["name"] != pl.ASSETS["nightly"]]
plan = self.decide(first, head="a" * 40)
self.assertEqual(self.uploaded(plan), [pl.ASSETS["nightly"]])
def test_an_old_asset_left_by_a_run_that_stopped_after_its_record_is_replaced(self):
old = self.published(self.decide(None, head="a" * 40))
raw = raw_export()
raw["filaments"]["OFvnd111"]["name"] = "V PLA+"
docs = {"nightly": fold(raw), "release": fold(raw, channel="release", tag="v2.5.3")}
stopped = self.decide(old, head="b" * 40, statuses={("a" * 40, "b" * 40): "ahead"}, docs=docs)
# The description was written, then the run stopped after uploading only nightly.
after = self.published({"description": stopped["description"],
"uploads": [u for u in stopped["uploads"] if u["name"] == pl.ASSETS["nightly"]]}, old)
retry = self.decide(after, head="b" * 40, docs=docs)
self.assertEqual(self.uploaded(retry), [pl.ASSETS["release"]])
def test_an_unfinished_upload_is_deleted_and_replaced(self):
first = self.published(self.decide(None, head="a" * 40))
for asset in first["assets"]:
if asset["name"] in (pl.ASSETS["nightly"], pl.SCHEMA_ASSET):
asset.update(state="starter", digest=None)
plan = self.decide(first, head="a" * 40)
self.assertEqual(self.uploaded(plan), sorted([pl.ASSETS["nightly"], pl.SCHEMA_ASSET]))
ids = {a["name"]: a["id"] for a in first["assets"]}
self.assertEqual({u["name"]: u["delete_id"] for u in plan["uploads"]},
{pl.ASSETS["nightly"]: ids[pl.ASSETS["nightly"]], pl.SCHEMA_ASSET: ids[pl.SCHEMA_ASSET]})
def test_a_finished_upload_without_a_digest_is_left_alone(self):
first = self.published(self.decide(None, head="a" * 40))
for asset in first["assets"]:
if asset["name"] in (pl.ASSETS["nightly"], pl.SCHEMA_ASSET):
asset["digest"] = None
plan = self.decide(first, head="a" * 40)
self.assertEqual(plan["uploads"], [])
self.assertEqual(len([n for n in plan["notes"] if "no digest" in n]), 2)
def test_a_revert_that_uploads_nothing_still_keeps_the_reverted_build_out(self):
a, b, c = "a" * 40, "b" * 40, "c" * 40
published_a = self.published(self.decide(None, head=a))
# C reverts B's change, so C's data equals A's: nothing to upload, but C is recorded.
plan_c = self.decide(published_a, head=c, statuses={(a, c): "ahead"})
self.assertEqual(plan_c["uploads"], [])
after_c = self.published(plan_c, published_a)
raw = raw_export()
raw["filaments"]["OFvnd111"]["name"] = "B's change"
docs_b = {"nightly": fold(raw), "release": fold(raw, channel="release", tag="v2.5.3")}
with self.assertRaises(pl.Stop):
self.decide(after_c, head=b, statuses={(c, b): "behind"}, docs=docs_b)
def test_two_publishes_in_one_minute_get_different_versions(self):
first = self.published(self.decide(None, head="a" * 40))
raw = raw_export()
raw["filaments"]["OFvnd111"]["name"] = "V PLA+"
docs = {"nightly": fold(raw), "release": self.docs["release"]}
second = self.decide(first, head="b" * 40, statuses={("a" * 40, "b" * 40): "ahead"}, docs=docs)
versions = [pl.parse_description(r)["nightly"]["version"] for r in (first["body"], second["description"])]
self.assertEqual(versions, ["2.6.0_202612050200", "2.6.0_202612050201"])
def test_a_retry_after_a_failed_upload_gets_a_newer_version_than_the_one_recorded(self):
stopped = self.decide(None, head="a" * 40, now="202612050200")
# The description is written, then every upload fails after --clobber deleted its asset.
after = {"id": 1, "body": stopped["description"], "assets": []}
retry = self.decide(after, head="a" * 40, now="202612050200")
self.assertEqual(pl.parse_description(retry["description"])["nightly"]["version"], "2.6.0_202612050201")
self.assertEqual(self.uploaded(retry), self.uploaded(stopped))
def test_the_description_round_trips(self):
record = {"build": "a" * 40, "nightly": {"version": "2.6.0_202612050200", "data_hash": "sha256:" + "1" * 64,
"sha256": "2" * 64},
"release": {"version": "2.5.3_202612050200", "data_hash": "sha256:" + "3" * 64, "sha256": "4" * 64,
"tag": "v2.5.3"}}
self.assertEqual(pl.parse_description(pl.render_description(record)), record)
class CommandLineTest(unittest.TestCase):
def run_main(self, argv):
out = io.StringIO()
with contextlib.redirect_stdout(out), contextlib.redirect_stderr(io.StringIO()):
code = pl.main(argv)
return code, dict(line.split("=", 1) for line in out.getvalue().splitlines() if "=" in line)
def test_fold_then_stamp(self):
with tempfile.TemporaryDirectory() as tmp:
raw, folded, gz = (os.path.join(tmp, n) for n in ("raw.json", "folded.json", "lib.json.gz"))
with open(raw, "w", encoding="utf-8") as f:
json.dump(raw_export(), f)
code, out = self.run_main(["fold", "--raw", raw, "--channel", "nightly", "--orca-version", "2.6.0-dev",
"--commit", COMMIT, "--out", folded])
self.assertEqual((code, out["changed"]), (0, "true"))
code, out = self.run_main(["stamp", "--in", folded, "--recorded", "2.6.0_202612041506", "--now",
"202612041506", "--out", gz])
self.assertEqual((code, out["version"]), (0, "2.6.0_202612041507"))
published = pl.read_document(gz)
self.assertEqual(published["version"], "2.6.0_202612041507")
code, out = self.run_main(["fold", "--raw", raw, "--channel", "nightly", "--orca-version", "2.6.0-dev",
"--commit", COMMIT, "--current", gz, "--out", folded])
self.assertEqual((code, out["changed"]), (0, "false"))
def test_a_first_publish_creates_the_release_then_uploads(self):
import urllib.error
from unittest import mock
class Profiles:
def __init__(self):
self.sent = []
def get(self, path, **params):
raise urllib.error.HTTPError(path, 404, "Not Found", {}, None)
def send(self, method, path, body=None):
self.sent.append((method, path, body))
class Source:
def get(self, path, **params):
assert path.endswith("/releases/latest"), path
return {"tag_name": "v2.5.3", "draft": False, "prerelease": False}
profiles = Profiles()
with tempfile.TemporaryDirectory() as tmp:
for channel, doc in (("nightly", fold()), ("release", fold(channel="release", tag="v2.5.3"))):
with open(os.path.join(tmp, channel + ".json"), "w", encoding="utf-8") as f:
f.write(pl.dumps(doc))
for name in (pl.SCHEMA_ASSET, pl.FIXTURE_ASSET):
with open(os.path.join(tmp, name), "w", encoding="utf-8") as f:
f.write("{}\n")
with open(os.path.join(tmp, "meta.json"), "w", encoding="utf-8") as f:
json.dump({"run_attempt": "1", "head_sha": COMMIT, "release_tag": "v2.5.3"}, f)
with mock.patch.object(pl, "github", lambda env: profiles if env == "GH_TOKEN" else Source()), \
mock.patch.object(pl, "tooling_same", lambda *args: True), \
mock.patch("subprocess.run") as run:
code, _ = self.run_main(["publish", "--artifact-dir", tmp, "--attempt", "1", "--now", "202612050200"])
self.assertEqual(code, 0)
self.assertEqual([(m, p) for m, p, _ in profiles.sent], [("POST", "repos/%s/releases" % pl.PROFILES_REPO)])
self.assertIn("build " + COMMIT, profiles.sent[0][2]["body"])
self.assertEqual(profiles.sent[0][2]["make_latest"], "false")
uploads = [c.args[0] for c in run.call_args_list]
self.assertEqual(sorted(os.path.basename(cmd[4]) for cmd in uploads),
sorted([*pl.ASSETS.values(), pl.SCHEMA_ASSET, pl.FIXTURE_ASSET]))
self.assertTrue(all(cmd[:4] == ["gh", "release", "upload", pl.RELEASE_NAME] and "--clobber" in cmd for cmd in uploads))
def test_an_error_exits_non_zero(self):
with tempfile.TemporaryDirectory() as tmp:
raw = os.path.join(tmp, "raw.json")
with open(raw, "w", encoding="utf-8") as f:
json.dump(raw_export(), f)
code, _ = self.run_main(["fold", "--raw", raw, "--channel", "release", "--orca-version", "2.5.3",
"--commit", COMMIT, "--out", os.path.join(tmp, "x.json")])
self.assertEqual(code, 1)
if __name__ == "__main__":
unittest.main()