Implements adjustable slideshow timing and view scope, with manual navigation stopping playback. Adds focused regression tests.
322 lines
14 KiB
Python
322 lines
14 KiB
Python
"""Focused slideshow regressions; run: python3 esphome/tests/slideshow_test.py.
|
|
|
|
Requires PyYAML and g++. Only the configuration itself is read, never secrets.
|
|
The native harness executes the actual YAML lambdas, not Python translations.
|
|
"""
|
|
|
|
from pathlib import Path
|
|
import subprocess
|
|
import tempfile
|
|
import unittest
|
|
|
|
import yaml
|
|
|
|
|
|
class ConfigLoader(yaml.SafeLoader):
|
|
pass
|
|
|
|
|
|
ConfigLoader.add_constructor("!secret", lambda loader, node: "<secret>")
|
|
ConfigLoader.add_constructor("!lambda", lambda loader, node: loader.construct_scalar(node))
|
|
|
|
CONFIG = Path(__file__).resolve().parents[1] / "energymonitor.yaml"
|
|
FIELDS = (
|
|
"page_index", "page_one_gauge_view", "device_usage_view",
|
|
"clock_digital_view", "internet_view", "climate_graph_view",
|
|
)
|
|
# State order follows FIELDS; a view's identity ignores other pages' memories.
|
|
DEFAULT = (0, 1, 0, 0, 0, 0)
|
|
VIEWS = (
|
|
(0, 1), (0, 0), (1, 0), (1, 1), (2, 0), (2, 1),
|
|
(3, 0), (3, 1), (3, 2), (4, 0), (4, 1),
|
|
)
|
|
SUBPAGE_FIELD = (1, 2, 3, 4, 5)
|
|
MANUAL = ("show_previous_page", "toggle_page_mode", "show_next_page")
|
|
|
|
|
|
def by_id(config, section, name):
|
|
return next(item for item in config[section] if item.get("id") == name)
|
|
|
|
|
|
def view(state):
|
|
return state[0], state[SUBPAGE_FIELD[state[0]]]
|
|
|
|
|
|
def state_for(current_view):
|
|
state = list(DEFAULT)
|
|
page, subpage = current_view
|
|
state[0] = page
|
|
state[SUBPAGE_FIELD[page]] = subpage
|
|
return tuple(state)
|
|
|
|
|
|
class SlideshowTest(unittest.TestCase):
|
|
@classmethod
|
|
def setUpClass(cls):
|
|
cls.config = yaml.load(CONFIG.read_text(), Loader=ConfigLoader)
|
|
cls.scripts = {item["id"]: item for item in cls.config["script"]}
|
|
cls.worker = cls.scripts["slideshow_worker"]
|
|
cls.loop = cls.worker["then"][0]["while"]
|
|
cls.interval = by_id(cls.config, "number", "slideshow_interval")
|
|
cls.scope = by_id(cls.config, "select", "slideshow_scope")
|
|
cls.switch = by_id(cls.config, "switch", "slideshow_enabled")
|
|
cls.all_views = cls.scope["initial_option"]
|
|
|
|
temporary = tempfile.TemporaryDirectory(prefix="slideshow-test-")
|
|
cls.addClassCleanup(temporary.cleanup)
|
|
directory = Path(temporary.name)
|
|
cls.binary = directory / "slideshow"
|
|
source = directory / "slideshow.cpp"
|
|
globals_by_id = {item["id"]: item for item in cls.config["globals"]}
|
|
declarations = "\n".join(
|
|
f"{globals_by_id[name]['type']} {name} = "
|
|
f"{globals_by_id[name]['initial_value']};"
|
|
for name in FIELDS
|
|
)
|
|
functions = [
|
|
"void advance_slideshow() {\n"
|
|
+ cls.scripts["advance_slideshow"]["then"][0]["lambda"] + "\n}",
|
|
"uint32_t slideshow_delay() {\n"
|
|
+ cls.loop["then"][0]["delay"] + "\n}",
|
|
]
|
|
for name in MANUAL:
|
|
functions.append(
|
|
f"void {name}() {{\n"
|
|
+ cls.scripts[name]["then"][1]["lambda"] + "\n}"
|
|
)
|
|
source.write_text(
|
|
"#include <cmath>\n#include <cstdint>\n#include <iostream>\n"
|
|
"#include <string>\n#define id(name) name\n"
|
|
+ declarations
|
|
+ "\nstruct { float state; } slideshow_interval;\n"
|
|
+ "struct { std::string option;\n"
|
|
+ " const std::string ¤t_option() const { return option; }\n"
|
|
+ "} slideshow_scope;\n"
|
|
+ "\n".join(functions)
|
|
+ r'''
|
|
void print_state() {
|
|
std::cout << page_index << ' ' << page_one_gauge_view << ' '
|
|
<< device_usage_view << ' ' << clock_digital_view << ' '
|
|
<< internet_view << ' ' << climate_graph_view << '\n';
|
|
}
|
|
int main(int argc, char **argv) {
|
|
if (argc != 4) return 2;
|
|
const std::string action = argv[1];
|
|
const int steps = std::stoi(argv[2]);
|
|
slideshow_scope.option = argv[3];
|
|
if (action == "delay") {
|
|
std::string seconds;
|
|
std::cin >> seconds;
|
|
slideshow_interval.state = std::stof(seconds);
|
|
std::cout << slideshow_delay() << '\n';
|
|
return 0;
|
|
}
|
|
if (action != "defaults") {
|
|
std::cin >> page_index >> page_one_gauge_view >> device_usage_view
|
|
>> clock_digital_view >> internet_view >> climate_graph_view;
|
|
if (!std::cin) return 3;
|
|
}
|
|
for (int i = 0; i < steps; ++i) {
|
|
if (action == "advance") advance_slideshow();
|
|
else if (action == "show_previous_page") show_previous_page();
|
|
else if (action == "toggle_page_mode") toggle_page_mode();
|
|
else if (action == "show_next_page") show_next_page();
|
|
else if (action != "defaults") return 4;
|
|
print_state();
|
|
}
|
|
}
|
|
'''
|
|
)
|
|
result = subprocess.run(
|
|
["g++", "-std=c++17", "-Wall", "-Wextra", "-Werror",
|
|
str(source), "-o", str(cls.binary)],
|
|
capture_output=True, text=True, timeout=30,
|
|
)
|
|
if result.returncode:
|
|
raise RuntimeError("Native harness compilation failed:\n" + result.stderr)
|
|
|
|
def native(self, action, state=DEFAULT, *, steps=1, scope=None):
|
|
result = subprocess.run(
|
|
[str(self.binary), action, str(steps),
|
|
self.all_views if scope is None else scope],
|
|
input=" ".join(map(str, state)), capture_output=True, text=True,
|
|
timeout=5,
|
|
)
|
|
self.assertEqual(result.returncode, 0, result.stderr)
|
|
return [tuple(map(int, line.split())) for line in result.stdout.splitlines()]
|
|
|
|
def delay(self, seconds):
|
|
return self.native("delay", (seconds,))[0][0]
|
|
|
|
def test_default_cycle_has_exactly_eleven_distinct_views(self):
|
|
initial = self.native("defaults")[0]
|
|
self.assertEqual(initial, DEFAULT)
|
|
self.assertEqual(self.all_views, "Alle Ansichten")
|
|
cycle = [initial] + self.native("advance", initial, steps=11)
|
|
self.assertEqual(tuple(map(view, cycle)), VIEWS + (VIEWS[0],))
|
|
self.assertEqual(len(set(map(view, cycle[:-1]))), 11)
|
|
self.assertEqual(view(cycle[-1]), view(initial))
|
|
|
|
def test_full_cycle_from_every_view_wraps_once(self):
|
|
for offset, current in enumerate(VIEWS):
|
|
with self.subTest(start=current):
|
|
initial = state_for(current)
|
|
cycle = [initial] + self.native("advance", initial, steps=11)
|
|
expected = tuple(VIEWS[(offset + step) % 11] for step in range(12))
|
|
self.assertEqual(tuple(map(view, cycle)), expected)
|
|
self.assertEqual(len(set(map(view, cycle[:-1]))), 11)
|
|
self.assertEqual(sum(view(state) == current for state in cycle[1:]), 1)
|
|
self.assertEqual(sum(
|
|
cycle[i][0] == 4 and cycle[i + 1][0] == 0
|
|
for i in range(11)
|
|
), 1)
|
|
|
|
def test_entering_each_main_page_resets_stale_subpage(self):
|
|
# Every remembered page starts on its last subpage, not its first.
|
|
stale = (0, 0, 1, 1, 2, 1)
|
|
first_subpages = (1, 0, 0, 0, 0)
|
|
for destination in range(5):
|
|
with self.subTest(destination=destination):
|
|
initial = list(stale)
|
|
initial[0] = (destination - 1) % 5
|
|
actual = self.native("advance", initial)[0]
|
|
expected = list(initial)
|
|
expected[0] = destination
|
|
expected[SUBPAGE_FIELD[destination]] = first_subpages[destination]
|
|
self.assertEqual(actual, tuple(expected))
|
|
|
|
def test_main_pages_only_wraps_five_and_preserves_all_flags(self):
|
|
for flags in (DEFAULT[1:], (0, 1, 1, 2, 1)):
|
|
for page in range(5):
|
|
with self.subTest(page=page, flags=flags):
|
|
initial = (page,) + flags
|
|
cycle = [initial] + self.native(
|
|
"advance", initial, steps=5, scope="Nur Hauptseiten"
|
|
)
|
|
self.assertEqual([state[0] for state in cycle],
|
|
[(page + step) % 5 for step in range(6)])
|
|
self.assertEqual(len({state[0] for state in cycle[:-1]}), 5)
|
|
self.assertTrue(all(state[1:] == flags for state in cycle))
|
|
self.assertEqual(cycle[-1], initial)
|
|
|
|
def test_current_subpage_continues_without_reset_on_enable(self):
|
|
# Declarative enable/worker tests below prove there is no pre-delay action;
|
|
# these native checks prove the first eventual tick continues each view.
|
|
for index, current in enumerate(VIEWS):
|
|
with self.subTest(current=current):
|
|
initial = state_for(current)
|
|
self.assertEqual(self.delay(self.interval["initial_value"]), 15000)
|
|
actual = self.native("advance", initial)[0]
|
|
self.assertEqual(view(actual), VIEWS[(index + 1) % 11])
|
|
|
|
def test_delay_default_bounds_and_nan_fallback(self):
|
|
for seconds, milliseconds in (
|
|
(self.interval["initial_value"], 15000),
|
|
(-100, 5000), (0, 5000), (4.999, 5000), (5, 5000),
|
|
(42, 42000), (300, 300000), (300.001, 300000), (9999, 300000),
|
|
("nan", 15000), ("inf", 15000), ("-inf", 15000),
|
|
):
|
|
with self.subTest(seconds=seconds):
|
|
self.assertEqual(self.delay(seconds), milliseconds)
|
|
|
|
def test_interval_and_scope_configuration(self):
|
|
for key, expected in {
|
|
"platform": "template", "min_value": 5, "max_value": 300,
|
|
"step": 5, "initial_value": 15, "unit_of_measurement": "s",
|
|
"optimistic": True, "restore_value": True,
|
|
}.items():
|
|
self.assertEqual(self.interval[key], expected, key)
|
|
self.assertEqual(self.scope["options"], ["Alle Ansichten", "Nur Hauptseiten"])
|
|
self.assertEqual(self.scope["initial_option"], "Alle Ansichten")
|
|
self.assertIs(self.scope["optimistic"], True)
|
|
self.assertIs(self.scope["restore_value"], True)
|
|
|
|
def test_switch_is_optimistic_always_off_and_only_starts_or_stops_worker(self):
|
|
self.assertEqual(self.switch["platform"], "template")
|
|
self.assertIs(self.switch["optimistic"], True)
|
|
self.assertEqual(self.switch["restore_mode"], "ALWAYS_OFF")
|
|
self.assertEqual(self.switch["on_turn_on"],
|
|
[{"script.execute": "slideshow_worker"}])
|
|
self.assertEqual(self.switch["on_turn_off"],
|
|
[{"script.stop": "slideshow_worker"}])
|
|
self.assertNotIn("turn_on_action", self.switch)
|
|
self.assertNotIn("turn_off_action", self.switch)
|
|
|
|
def test_worker_restarts_delays_first_then_guards_advance(self):
|
|
self.assertEqual(self.worker["mode"], "restart")
|
|
self.assertEqual(len(self.worker["then"]), 1)
|
|
self.assertEqual(set(self.worker["then"][0]), {"while"})
|
|
self.assertEqual(set(self.loop), {"condition", "then"})
|
|
self.assertEqual(self.loop["condition"], {"switch.is_on": "slideshow_enabled"})
|
|
self.assertEqual(len(self.loop["then"]), 2)
|
|
self.assertEqual(set(self.loop["then"][0]), {"delay"})
|
|
self.assertIsInstance(self.loop["then"][0]["delay"], str)
|
|
self.assertEqual(self.loop["then"][1], {"if": {
|
|
"condition": {"switch.is_on": "slideshow_enabled"},
|
|
"then": [{"script.execute": "advance_slideshow"}],
|
|
}})
|
|
|
|
def test_number_and_select_restart_only_when_running(self):
|
|
for entity in (self.interval, self.scope):
|
|
with self.subTest(entity=entity["id"]):
|
|
self.assertEqual(entity["on_value"], [{"if": {
|
|
"condition": {"switch.is_on": "slideshow_enabled"},
|
|
"then": [{"script.execute": "slideshow_worker"}],
|
|
}}])
|
|
|
|
def test_advancement_refreshes_without_manual_navigation(self):
|
|
actions = self.scripts["advance_slideshow"]["then"]
|
|
self.assertEqual(len(actions), 2)
|
|
self.assertEqual(set(actions[0]), {"lambda"})
|
|
self.assertEqual(actions[1], {"script.execute": "refresh_display"})
|
|
|
|
def test_manual_scripts_stop_first_then_original_action_and_refresh(self):
|
|
for name in MANUAL:
|
|
with self.subTest(script=name):
|
|
actions = self.scripts[name]["then"]
|
|
self.assertEqual(len(actions), 3)
|
|
self.assertEqual(actions[0], {"switch.turn_off": "slideshow_enabled"})
|
|
self.assertEqual(set(actions[1]), {"lambda"})
|
|
self.assertEqual(actions[2], {"script.execute": "refresh_display"})
|
|
for current in VIEWS:
|
|
initial = state_for(current)
|
|
expected = list(initial)
|
|
if name == "show_previous_page":
|
|
expected[0] = (initial[0] - 1) % 5
|
|
elif name == "show_next_page":
|
|
expected[0] = (initial[0] + 1) % 5
|
|
else:
|
|
field = SUBPAGE_FIELD[initial[0]]
|
|
expected[field] = (initial[field] + 1) % (3 if initial[0] == 3 else 2)
|
|
self.assertEqual(self.native(name, initial)[0], tuple(expected), current)
|
|
|
|
def test_hardware_and_home_assistant_buttons_share_manual_scripts(self):
|
|
routes = (
|
|
("button_left", "Zurück", "show_previous_page", "GPIO39"),
|
|
("button_middle", "Modus", "toggle_page_mode", "GPIO38"),
|
|
("button_right", "Weiter", "show_next_page", "GPIO37"),
|
|
)
|
|
for hardware_id, name, script, pin in routes:
|
|
with self.subTest(button=name):
|
|
hardware = by_id(self.config, "binary_sensor", hardware_id)
|
|
ha = next(button for button in self.config["button"] if button["name"] == name)
|
|
expected = [{"script.execute": script}]
|
|
self.assertEqual(hardware["on_press"], expected)
|
|
self.assertEqual(ha["on_press"], expected)
|
|
self.assertEqual(hardware["platform"], "gpio")
|
|
self.assertEqual(hardware["pin"]["number"], pin)
|
|
self.assertEqual(ha["platform"], "template")
|
|
|
|
def test_no_extra_slideshow_button(self):
|
|
self.assertEqual(len(self.config["button"]), 3)
|
|
self.assertEqual({button["name"] for button in self.config["button"]},
|
|
{"Zurück", "Modus", "Weiter"})
|
|
hardware = [item for item in self.config["binary_sensor"]
|
|
if item["platform"] == "gpio"]
|
|
self.assertEqual({item["id"] for item in hardware},
|
|
{"button_left", "button_middle", "button_right"})
|
|
|
|
|
|
if __name__ == "__main__":
|
|
unittest.main(verbosity=2)
|