diff --git a/scripts/course/course.toml b/scripts/course/course.toml index 85e75ad7..c43ea0b4 100644 --- a/scripts/course/course.toml +++ b/scripts/course/course.toml @@ -105,6 +105,12 @@ label = "1.3" slug = "routings" title = "Routings — the path a material takes" one_line = "The ordered operations that make a material, each on a named machine." +outcomes = [ + "Say what a routing is: operations in sequence, each on a named machine, for one material.", + "Read a plant's routings in Admin, and the cost center each step bills to, read from its machine's line.", + "Define a routing in the form, and say the two things it refuses: no operation, and a code in use.", +] +scene = "scripts/scenes/course/02-03-routings.toml" [[module.lesson]] order = 4 diff --git a/scripts/record-scene.py b/scripts/record-scene.py index 726f03e9..23854350 100644 --- a/scripts/record-scene.py +++ b/scripts/record-scene.py @@ -4,8 +4,8 @@ python scripts/record-scene.py --base http://127.0.0.1:8110 --out /tmp/take python scripts/record-scene.py --course # course.json and the tree's README only -A scene file is a list of steps — `goto`, `click`, `wait_for`, `say`, `hold`, -`mark`, `slide` — against a plant that is already running. This file drives a browser +A scene file is a list of steps — `goto`, `click`, `fill`, `choose`, +`wait_for`, `say`, `hold`, `mark`, `slide` — against a plant that is already running. This file drives a browser through them, burns the overlay into the picture, and writes, into one folder: * `.gif`, the published loop, under the budget the scene states and @@ -70,7 +70,8 @@ narrator is drawn there afterwards, and nothing a viewer must read may sit under it. The take is checked for that as it is filmed. It also hides the floating Assistant and Design buttons, which are the product's and sit in that -corner. +corner, and lifts the product's toast above the caption bar, which would +otherwise cover it. It is a developer tool. It is not in the wheel, not in CI, and not asked to run on Windows. It needs `ffmpeg`, and a Python with Playwright and its @@ -102,14 +103,18 @@ HERE = Path(__file__).resolve().parent REPO = HERE.parent -# The seven words a step can be. An eighth is a newer scene file than this +# The nine words a step can be. A tenth is a newer scene file than this # script, and guessing what it meant is how a recording comes out missing the -# thing it was made to show. -VERBS = ("goto", "click", "wait_for", "say", "hold", "mark", "slide") +# thing it was made to show. `fill` types into a field, a key at a time so the +# viewer sees it typed, and `choose` picks an option of a ``) and the option's `value`") if verb == "say": if not step.get("line"): raise SystemExit(f"{where}: a `say` needs a `line` — it is the sentence on screen") @@ -391,6 +406,8 @@ def planned_seconds(scene: dict) -> float: total += SCROLL_SECONDS if step["do"] == "goto": total += float(step["settle"]) + elif step["do"] == "fill": + total += len(step["text"]) * TYPE_DELAY_SECONDS + SMALL_STEP_SECONDS elif step["do"] == "say": total += float(step["hold"]) elif step["do"] == "hold": @@ -426,6 +443,10 @@ def play(scene: dict, stage) -> None: stage.goto(step["url"], float(step["settle"])) elif verb == "click": stage.click(step["selector"]) + elif verb == "fill": + stage.fill(step["selector"], step["text"]) + elif verb == "choose": + stage.choose(step["selector"], step["value"]) elif verb == "wait_for": stage.wait_for(step, float(step["timeout"])) elif verb == "say": @@ -483,6 +504,10 @@ def overlay_script(badge: str, captions: bool = True) -> str: "padding:0 18px!important;border-radius:8px!important;white-space:nowrap!important;" "box-shadow:0 2px 10px rgba(0,0,0,.5)!important}" ".assist-launch,.design-launch{display:none!important}" + # The product's message after a save sits 22 px off the bottom, under + # the caption bar; it is lifted above the bar's two lines, where the + # viewer can read it, and is otherwise drawn as the product draws it. + f".toast{{bottom:{TOAST_LIFT}px!important}}" ) return f""" (() => {{ @@ -603,6 +628,7 @@ def click(self, selector: str) -> None: # above. When the clicked thing is gone after the click (a button that # takes itself away, a link that leaves the page) the press is all # there is, and the mark says so. + self.clear_of_caption(selector) heard = len(self.presses) # The same element `page.click` will press: the first that matches. clicked = self.page.locator(selector).first.element_handle() @@ -623,6 +649,52 @@ def click(self, selector: str) -> None: print(f" at {mark['x']},{mark['y']} press {mark.get('press')}" + (f" ({mark['settled']})" if "settled" in mark else ""), flush=True) + def fill(self, selector: str, text: str) -> None: + # Emptied first, then typed a key at a time, so the frames show the + # words arriving rather than a field that was blank and then full. + self.clear_of_caption(selector) + field = self.page.locator(selector).first + field.fill("") + if text: + field.press_sequentially(text, delay=int(TYPE_DELAY_SECONDS * 1000)) + self.note(f"fill {selector}: {text!r}", "fill", text=text) + self.page.wait_for_timeout(int(SMALL_STEP_SECONDS * 1000)) + + def choose(self, selector: str, value: str) -> None: + # The option is picked, not the list opened: an open ``. Neither writes; the click on +the form's button does, and that still needs `allow_writes`. The product's +message after a save is lifted above the caption bar, which otherwise covers +it. No plant and no browser here. +""" + +from __future__ import annotations + +import importlib.util +from pathlib import Path + +import pytest + +REPO = Path(__file__).resolve().parents[1] +RUNNER = REPO / "scripts" / "record-scene.py" + + +@pytest.fixture(scope="module") +def runner(): + spec = importlib.util.spec_from_file_location("record_scene_fill_choose", RUNNER) + module = importlib.util.module_from_spec(spec) + spec.loader.exec_module(module) + return module + + +def write_scene(tmp_path: Path, steps: str) -> Path: + path = tmp_path / "scene.toml" + path.write_text('name = "form"\nbase = "http://127.0.0.1:8040"\n' + steps, encoding="utf-8") + return path + + +def test_fill_and_choose_are_words_a_step_can_be(runner): + assert "fill" in runner.VERBS and "choose" in runner.VERBS + + +def test_the_stage_is_handed_the_field_and_its_text_and_the_list_and_its_option(runner, tmp_path): + scene = runner.load_scene(write_scene(tmp_path, ''' +[[step]] +do = "fill" +selector = "#code" +text = "RT-PALLET" + +[[step]] +do = "choose" +selector = "#material" +value = "PALLET" +''')) + handed = [] + + class Stage: + def fill(self, selector, text): + handed.append(("fill", selector, text)) + + def choose(self, selector, value): + handed.append(("choose", selector, value)) + + runner.play(scene, Stage()) + + assert handed == [("fill", "#code", "RT-PALLET"), ("choose", "#material", "PALLET")] + + +def test_a_fill_without_its_text_or_a_choose_without_its_option_is_refused_before_filming(runner, tmp_path): + with pytest.raises(SystemExit, match="needs a `selector` and the `text`"): + runner.load_scene(write_scene(tmp_path, '[[step]]\ndo = "fill"\nselector = "#code"\n')) + with pytest.raises(SystemExit, match="the option's `value`"): + runner.load_scene(write_scene(tmp_path, '[[step]]\ndo = "choose"\nselector = "#material"\n')) + + +def test_typing_takes_time_in_the_plan_by_the_length_of_what_is_typed(runner, tmp_path): + fill = '[[step]]\ndo = "fill"\nselector = "#a"\ntext = "{}"\n' + short = runner.load_scene(write_scene(tmp_path, fill.format("RT"))) + long = runner.load_scene(write_scene(tmp_path, fill.format("RT-PALLET-LINE-ONE"))) + + assert runner.planned_seconds(long) - runner.planned_seconds(short) == pytest.approx( + 16 * runner.TYPE_DELAY_SECONDS) + + +def test_the_products_message_after_a_save_is_drawn_above_the_caption_bar(runner): + overlay = runner.overlay_script("badge") + + assert f".toast{{bottom:{runner.TOAST_LIFT}px!important}}" in overlay + # Above two lines of caption: 18 px padding, two lines of 25 px at 1.3, the border. + assert runner.TOAST_LIFT > 18 * 2 + 2 * 25 * 1.3 + 2 diff --git a/tests/test_class_1_3_defines_a_routing_whose_steps_bring_their_cost_centers.py b/tests/test_class_1_3_defines_a_routing_whose_steps_bring_their_cost_centers.py new file mode 100644 index 00000000..09735bf2 --- /dev/null +++ b/tests/test_class_1_3_defines_a_routing_whose_steps_bring_their_cost_centers.py @@ -0,0 +1,226 @@ +"""Class 1.3 defines a routing whose steps bring their machines' cost centers, on a scratch cutlery plant. + +*Routings — the path a material takes* is the first class of the core: a +fork's road in words, the three words a routing is made of, the plant's +routings table, a new pallet routing typed into the Admin form with each +step's cost center read from its machine's line, and the two things the form +refuses. This file holds the scene file to what the outline asks of it. No +plant and no browser: the scene is loaded and walked the way the recorder +walks it. +""" + +from __future__ import annotations + +import importlib.util +import json +import re +from pathlib import Path +from urllib.parse import urlparse + +import pytest + +from fsmes import modules + +REPO = Path(__file__).resolve().parents[1] +RUNNER = REPO / "scripts" / "record-scene.py" +SCENE = REPO / "scripts" / "scenes" / "course" / "02-03-routings.toml" +PACK = REPO / "labs" / "cutlery" / "masterdata" + +# The lab fleet, the public demo and the stock demo ports: a class is never +# filmed on a plant somebody else is looking at. +NOT_OURS = {8090, 8110, 8120, 8140, 9030, 5433, 5434, 4944, 4945} + +# What no caption, card or note may carry: a calendar date, a year, a month's +# name. The class is about any plant on any day. +A_DATE = re.compile( + r"\b(19|20)\d\d\b|\b\d{1,2}/\d{1,2}/\d{2,4}\b|" + r"\b(January|February|March|April|May|June|July|August|September|October|November|December)\b" +) + + +@pytest.fixture(scope="module") +def runner(): + """`scripts/record-scene.py`, imported by path because of the hyphen.""" + spec = importlib.util.spec_from_file_location("record_scene_class_1_3", RUNNER) + module = importlib.util.module_from_spec(spec) + spec.loader.exec_module(module) + return module + + +@pytest.fixture(scope="module") +def scene(runner): + return runner.load_scene(SCENE) + + +def pack(kind: str) -> list[dict]: + return json.loads((PACK / f"{kind}.json").read_text(encoding="utf-8")) + + +def everything_written(scene: dict) -> list[str]: + """Every sentence a viewer or a reader of the folder will see.""" + written = [scene["title"], scene["what_is_written"], *scene["notes"], *scene["honesty"]] + for step in scene["step"]: + if step["do"] == "say": + written.append(step["line"]) + if step["do"] == "slide": + written += [step["title"], *step["lines"]] + if step["do"] == "fill": + written.append(step["text"]) + return written + + +def typed(scene: dict, part: str) -> list[str]: + return [step["text"] for step in scene["step"] if step["part"] == part and step["do"] == "fill"] + + +def chosen(scene: dict, part: str) -> list[str]: + return [step["value"] for step in scene["step"] if step["part"] == part and step["do"] == "choose"] + + +def test_the_scene_is_a_full_take_of_class_1_3_named_by_its_label_that_runs_four_to_six_minutes(runner, scene): + assert scene["lesson"] == "1.3" and scene["take_is"] == "lesson" + assert (scene["width"], scene["height"]) == (1280, 720) + planned = runner.planned_seconds(scene) + # Page loads and waits add to the plan; the finished take is measured. + assert 240 <= planned <= scene["budget_seconds"] <= 360, planned + print(f"planned {planned} s against a {scene['budget_seconds']} s budget") + + +def test_it_films_into_the_routings_folder_of_the_core(runner, scene): + course = runner.load_course(REPO / "scripts" / "course" / "course.toml") + _, lesson = runner.find_lesson(course, scene["lesson"]) + + assert lesson["path"] == "02-the-core/03-routings" + assert lesson["scene"] == SCENE.relative_to(REPO).as_posix() + + +def test_the_scene_walks_the_five_parts_in_order(runner, scene): + order = [] + for step in scene["step"]: + if not order or order[-1] != step["part"]: + order.append(step["part"]) + + assert order == list(runner.PARTS) + + +def test_the_hook_is_a_card_of_a_forks_road_then_its_line_and_is_short_enough_for_the_teaser(runner, scene): + hook = [step for step in scene["step"] if step["part"] == "hook"] + + assert hook[0]["do"] == "slide" and hook[0]["name"] == "a-forks-road" + machines = [op["equipment"] for op in next(r for r in pack("routings") if r["code"] == "RT-FORK1")["operations"]] + assert [line.rsplit(" ", 1)[-1] for line in hook[0]["lines"] if "_" in line] == machines + assert [step["url"] for step in hook if step["do"] == "goto"] == ["/dashboard?line=FORK1LINE"] + assert runner.planned_seconds(dict(scene, step=hook)) - scene["gif_skip_seconds"] <= 30 + + +def test_the_idea_cards_name_operation_sequence_and_routing_and_the_recipe_of_steps(scene): + cards = {step["name"]: step for step in scene["step"] if step["do"] == "slide" and step["part"] == "idea"} + + assert [line.split(":")[0] for line in cards["three-words"]["lines"]] == ["Operation", "Sequence", "Routing"] + assert cards["steps-not-ingredients"]["title"] == "The recipe of steps, not of ingredients" + + +def test_the_routing_typed_in_is_not_in_the_pack_and_every_code_in_it_is_the_plants_own(scene): + codes = {r["code"] for r in pack("routings")} + materials = {m["code"] for m in pack("materials")} + machines = {e["code"]: e for e in pack("equipment")} + screen_typed, screen_chosen = typed(scene, "screen"), chosen(scene, "screen") + + assert "RT-PALLET" in screen_typed and "RT-PALLET" not in codes + assert screen_chosen == ["PALLET", "PAL1_Palletizer", "PAL1_StretchWrap"] + assert screen_chosen[0] in materials + assert all(code in machines for code in screen_chosen[1:]) + # The cost center the class says filled itself is the machines' line's, and + # neither machine carries one of its own. + assert {machines[machines[code]["parent"]]["cost_center"] for code in screen_chosen[1:]} == {"CC-PAL01"} + assert not any(machines[code].get("cost_center") for code in screen_chosen[1:]) + assert "CC-PAL01" not in screen_typed + + +def test_the_routing_is_created_by_the_forms_own_button_and_seen_in_the_table_afterwards(scene): + screen = [step for step in scene["step"] if step["part"] == "screen"] + create = next(i for i, step in enumerate(screen) if step["do"] == "click" and "routing-create" in step["selector"]) + + assert screen[create + 1]["do"] == "wait_for" and "RT-PALLET created" in screen[create + 1]["text"] + assert any(step["do"] == "wait_for" and step.get("text") == "RT-PALLET" for step in screen[create:]) + + +def test_what_it_refuses_is_a_routing_with_no_operation_and_a_code_already_used(scene): + refuses = [step for step in scene["step"] if step["part"] == "refuses"] + waits = [step["text"] for step in refuses if step["do"] == "wait_for"] + said = " ".join(step["line"] for step in refuses if step["do"] == "say") + + assert waits == ["A routing needs at least one operation.", "already exists"] + assert sum(1 for step in refuses if step["do"] == "click") == 2 + assert "machine that does not exist" in said and "list with no blank" in said + + +def test_the_you_now_know_card_says_the_classs_own_outcomes_word_for_word(runner, scene): + course = runner.load_course(REPO / "scripts" / "course" / "course.toml") + _, lesson = runner.find_lesson(course, scene["lesson"]) + know = [step for step in scene["step"] if step["part"] == "know" and step["do"] == "slide"] + + assert len(lesson["outcomes"]) == 3 + assert len(know) == 1 and know[0]["lines"] == lesson["outcomes"] + + +def test_every_page_it_visits_is_a_screen_the_app_serves(scene): + served = [page.path for module in modules.REGISTRY for page in module.pages] + patterns = [re.compile("^" + re.sub(r"\{[^}]+\}", "[^/]+", path) + "$") for path in served] + visited = {urlparse(step["url"]).path for step in scene["step"] if step["do"] == "goto"} + + unserved = sorted(path for path in visited if not any(p.match(path) for p in patterns)) + assert unserved == [], f"{len(unserved)} of {len(visited)} pages are not served: {unserved}" + + +def test_every_frame_carries_the_pre_alpha_simulated_plant_badge(scene): + assert scene["badge"] == "pre-alpha · simulated plant · v{version}" + + +def test_no_caption_card_note_or_typed_word_carries_a_date(scene): + dated = [line for line in everything_written(scene) if A_DATE.search(line)] + + assert dated == [], f"{len(dated)} lines carry a date: {dated}" + + +def test_it_is_filmed_on_a_scratch_cutlery_plant_on_loopback_and_never_on_one_somebody_else_runs(runner, scene): + base = urlparse(scene["base"]) + + assert scene["plant"]["pack"] == "labs/cutlery" + assert base.hostname == "127.0.0.1" + assert base.port not in NOT_OURS + # It writes, so it must be refused anywhere but loopback. + assert scene["allow_writes"] + runner.refuse_to_write_off_this_box(scene) + with pytest.raises(SystemExit): + runner.refuse_to_write_off_this_box(dict(scene, base="http://100.64.0.1:8040")) + + +def test_the_existing_pallet_routing_the_lists_and_the_replay_are_owned_up_to(scene): + honesty = " ".join(scene["honesty"]).lower() + + assert "rt-pal1" in honesty + assert "no blank" in honesty + assert "ten times" in honesty + + +def test_admin_is_opened_at_its_routings_and_no_screen_of_people_is_filmed(scene): + urls = [step["url"] for step in scene["step"] if step["do"] == "goto"] + + assert not [url for url in urls if "people" in url] + assert [url for url in urls if "/admin" in url] == ["/dashboard/admin#routings"] + + +def test_the_recorder_plays_every_step_of_it(runner, scene): + handed: list[str] = [] + + class Stage: + def __getattr__(self, verb): + return lambda *args: handed.append(verb) + + runner.play(scene, Stage()) + + for verb in ("goto", "click", "fill", "choose"): + assert handed.count(verb) == sum(1 for step in scene["step"] if step["do"] == verb), verb + assert handed.count("scroll_to") == sum(1 for step in scene["step"] if step.get("scroll_to")) + assert handed.count("slide") == 4 and "terminal" not in handed