mirror of
https://github.com/ChuckBuilds/LEDMatrix.git
synced 2026-10-04 22:35:08 +00:00
* fix(sports): share the ESPN rejected-range memo with the background service BackgroundDataService always sent a season range first and, on a 400, fell back to chunks without recording the rejection, so every background season fetch spent a doomed request and live scoreboards learned nothing from it (or it from them). The worker now consults and sets the same 6-hour memo fetch_espn_scoreboard() uses: a known rejection goes straight to month/day chunks, and if every chunk fails the range is asked once for a real error without re-spending the chunks. Co-Authored-By: Claude Opus 5 <noreply@anthropic.com> * fix(web): keep plugin asset and action routes inside their directories POST /plugins/assets/upload, GET /plugins/assets/list and POST /plugins/assets/delete joined the request's plugin_id onto assets/plugins unchecked, so '../../config' created, wrote, listed and deleted outside it. #561 guarded only the route that serves the files. All three now go through path_safety.resolve_under and answer 400 for anything but a plain name, and delete only unlinks a metadata path that resolves into that plugin's uploads directory. PluginManager.get_plugin_directory refuses ids that are not one plain path segment, so /plugins/action (which runs a manifest script from the returned directory) and every other caller get the guard; the action route also rejects such ids up front, covering its no-manager fallback. Co-Authored-By: Claude Opus 5 <noreply@anthropic.com> * fix(web): report a no-op plugin update as already up to date update_plugin() returns True both for a real update and for "nothing to do" (a ZIP-installed monorepo plugin already at the registry version, a bundled plugin). With no git commit to compare, POST /plugins/update called every such success "updated successfully", so Check & Update All counted most official plugins as updated on every run. The route now reads what changed off the plugin itself (commit, else manifest version, else last_updated) and returns data.update_status (updated / up_to_date / local_only). The update-all toast is summarised by PluginInstallManager.summarizeUpdateResults from that status, falling back to the message for older servers. Co-Authored-By: Claude Opus 5 <noreply@anthropic.com> * fix(sports): scoreboard scroll speed no longer follows target_fps sports_scroll computed the crisp speed ladder against the global target_fps whenever limit_refresh_rate_hz was the 100 Hz default. Since frame-locked presentation (#545) the helper steps a fixed number of whole pixels per presented frame and the panel presents at its real refresh, so the General tab's "Scroll Frame Rate" became a speed multiplier: 60 ran a 50 px/s scoreboard at 100 px/s, 200 ran it at 25 px/s. The ladder now uses the display manager's refresh_hz, then display.hardware.limit_refresh_rate_hz, then the default. target_fps is not consulted. Docstrings now say scroll_delay is ignored for pacing (no behaviour change there) and describe the fixed-step model. Tests: replace the tests that pinned target_fps as the ladder refresh and described time-based stepping; assert speed independence from target_fps (unit and end-to-end presented px/s against the real helper), that the fixed per-frame step is applied, and that scroll_delay does not change speed. Co-Authored-By: Claude Opus 5 <noreply@anthropic.com> * fix(web): escape registry and upload values in plugin manager inline handlers The store, saved-repository and custom-registry buttons built onclick='...(${JSON.stringify(id)})...'. JSON.stringify leaves ' alone, so a custom registry entry whose id contained ' closed the attribute and added its own handler. One helper, jsStringAttr(), now HTML-escapes the JSON literal for every one of those handlers, and the store View button opens only http(s) repo links. The live window.updateImageList (plugins_manager.js loads last, so its copy wins over the file-upload widget's) wrote the uploaded file's original name, path and ids into markup raw; they are escaped now. Co-Authored-By: Claude Opus 5 <noreply@anthropic.com> * docs(changelog): note plugin asset, action and inline handler guards Co-Authored-By: Claude Opus 5 <noreply@anthropic.com> * fix(update): let the root pip wrapper install web_interface/requirements.txt Update Code, the automatic update's health check and Install Base Requirements install web_interface/requirements.txt through safe_pip_install.sh, which only allowed the root requirements.txt. The first commit changing that file would fail its dependency install, and the automatic updater rolls back any update whose dependencies did not install -- on every device, for every newer commit. The wrapper now lists both core requirement files. Only their folders are resolved, so a requirements.txt symlinked out of the project is compared by its target and refused (previously the root file's own symlink target was what got allowed). The updater's file list is a named constant, and a test runs the real wrapper (pip stubbed) on every file Update Code and the rollback install. Co-Authored-By: Claude Opus 5 <noreply@anthropic.com> * fix(web): do not retry plugin requests that got an HTTP answer PluginAPI.request wrapped everything that was not a structured error as NETWORK_ERROR: a proxy's 502 HTML page (response.json() throws) and a JSON error without error_code included. Check & Update All retries NETWORK_ERROR, so those updates were re-sent five more times with backoff, contrary to the #587 contract that an HTTP error response is the server's answer. NETWORK_ERROR now means only that fetch() rejected. Any HTTP response without an error_code, or with a body that is not JSON, is API_ERROR with the HTTP status attached. Tested against the shipped api_client.js. Co-Authored-By: Claude Opus 5 <noreply@anthropic.com> * fix(scroll): restart the stats window when an idle gap is dropped by size #582 dropped an idle gap from the frame stats two ways: the reset_scroll() sentinel, which also restarts the 5s window timer, and a size guard for scrollers that never call reset_scroll(), which did not. On that path the first real frame after the gap found the boundary overdue and logged a stats line for a one-frame window. Both paths now share one seeding helper. Co-Authored-By: Claude Opus 5 <noreply@anthropic.com> * fix(update): leave plugins alone when update_core's own rollback fails update_core returns rollback_failed directly when a partial pull or an update whose health check never started cannot be rolled back. run() only held plugins back for 'verifying', so those devices still got new plugin versions and a display restart on top of a core in an unknown state -- the opposite of what the health-check path does, and of the 3.4.0 changelog (plugins are left alone if the rollback fails). Co-Authored-By: Claude Opus 5 <noreply@anthropic.com> * docs(api): make the REST reference match the api_v3 package Every documented request body, query parameter and response shape was re-checked against the handlers in web_interface/blueprints/api_v3/. Fixes calls that failed as documented (repo_url, action_id/params, files/image_id, font_file+font_family, ?font=, cache key, auto_enable_ap_mode, plugin limit keys), removes the font-override endpoints dropped in #566, corrects response shapes (plugins/config, plugins/schema, health, metrics, operation history, github-status, fonts/catalog, cache/list, logs, wifi, on-demand, SSE streams), and adds the 26 routes it omitted (backup, system auto-update/git, wifi radio, starlark editor, MQTT bridge, status endpoints, skins). Documents the merge semantics of partial JSON saves to /config/main and /plugins/config and the dim-schedule POST accepting GET's days shape, which land in the same change set. Replaces app.py line numbers and the removed api_v3.py path with file and function names. Co-Authored-By: Claude Opus 5 <noreply@anthropic.com> * fix(web): remove the General-tab plugin system toggles that did nothing plugin_system.auto_discover, auto_load_enabled and development_mode had General-tab toggles whose help tips promised dormant plugins and verbose logging, but nothing reads them: every enabled plugin is discovered and loaded regardless. Remove the three toggles. The keys stay tolerated in stored configs. The save handler now stores a flag only when a client sends it; treating a missing key as an unchecked box would otherwise rewrite all three to false on every General-tab save, which still posts plugins_directory. Co-Authored-By: Claude Opus 5 <noreply@anthropic.com> * refactor(scroll): remove dead code left by #523/#570 - Drop the optional scipy.ndimage import and HAS_SCIPY; nothing read them since the numpy blend replaced the scipy path. - Drop ScrollHelper._last_integer_position and frame_time_target, which were written but never read. - Keep target_fps and set_target_fps() but document them as informational: nothing paces off them, yet ledmatrix-elections' test_scroll_pacing.py reads helper.target_fps back and third-party plugins may call the setter. - Fix stale comments: fixed_pixels_per_frame's "use scroll_delay to throttle", set_sub_pixel_scrolling's "default: True", and set_frame_based_scrolling's claim that it steps. The plugins monorepo was grepped for every removed name; none is used. Co-Authored-By: Claude Opus 5 <noreply@anthropic.com> * docs(fonts): point plugins at plugin_manager.font_manager; drop removed overrides UI FONT_MANAGER.md told plugins to read display_manager.font_manager, which does not exist, so a plugin following it failed to load with AttributeError. The shared FontManager lives on the PluginManager and BasePlugin._get_font_manager() returns it (with a fallback for harnesses). Also removes the Fonts-tab override workflow and element-override panels that #566 deleted, from FONT_MANAGER.md and WEB_INTERFACE_GUIDE.md. Co-Authored-By: Claude Opus 5 <noreply@anthropic.com> * docs(store): search via /plugins/store/list?query=; send Content-Type on registry curls /plugins/store/search does not exist (404) and the list endpoint reads query, not q. The registry guide's curl examples omitted the JSON Content-Type, so the handlers saw an empty body and answered 400. Co-Authored-By: Claude Opus 5 <noreply@anthropic.com> * fix(config): use the shared core-key list in the last three private copies StartupValidator warned "Plugin 'auto_update' is enabled but not found" on every display start with auto-update or a dim schedule on; the reserved plugin-id check missed auto_update, sync, location and the rest; and ConfigManager's (uncalled) orphan cleanup would have deleted display, schedule and auto_update. All three now read src/core_config_keys.py, which also gains CORE_SECRETS_KEYS for the github/youtube secrets sections. Co-Authored-By: Claude Opus 5 <noreply@anthropic.com> * fix(web): partial JSON saves to /config/main change only what they send A JSON body with one field reset every checkbox in the sections it touched: the MQTT bridge's brightness slider turned off disable_hardware_pulsing, inverse_colors, show_refresh_rate and use_short_date_format, and a timezone-only save turned off web-UI autostart and weekly auto-updates. Missing-means-unchecked now applies only to form posts: form-encoded bodies and the v3 forms, which mark themselves with a hidden __form_section input. Also on the config routes: - vegas_min/max_cycle_duration no longer match the generic *_duration rule, so they stop landing in display_durations and a blank one no longer rejects the whole Display save; - saving from the Raw JSON editor calls start_setup_if_needed like the General form, so enabling auto-update there finishes its setup; - the schedule and dim-schedule POSTs accept the per-day days.<day> shape their GETs return, as well as the flat form keys. Co-Authored-By: Claude Opus 5 <noreply@anthropic.com> * fix(scripts): install plugin dependencies from the configured plugins directory install_plugin_dependencies.sh scanned only plugins/, but the Plugin Store installs into plugin_system.plugins_directory (default plugin-repos), so the documented "Recommended" fix found 0 plugins on every store install. It now reads plugins_directory from config/config.json (relative to the project root or absolute, default plugin-repos) and also scans plugins/ for dev symlinks, installing a plugin reached through both only once. With set -e alone, `pip ... | tee` took tee's exit status, so a failed pip install was reported as success; set -o pipefail. Co-Authored-By: Claude Opus 5 <noreply@anthropic.com> * docs: replace stale API names, line numbers and the api_v3.py path - ADVANCED_FEATURES: StreamManager methods that exist (get_next_segment, take_next_group, refresh, advance_cycle, ...), and the real on-demand status envelope ({status, data: {state, service}}) - app.py:199 / :144 / :607-619 line citations and web_interface/blueprints/api_v3.py (now a package) replaced with file and function names in ADVANCED_FEATURES, CONFIG_DEBUGGING, PLUGIN_ARCHITECTURE_SPEC, PLUGIN_QUICK_REFERENCE, PLUGIN_CONFIGURATION_TABS, TROUBLESHOOTING and web_interface/README - CONFIG_DEBUGGING: partial /config/main saves change only sent keys; use /config/raw/main to replace the file; describe where validation runs - TROUBLESHOOTING: clear_cache.py needs --clear-all (no args only prints usage) Co-Authored-By: Claude Opus 5 <noreply@anthropic.com> * fix(scripts): verify the web interface that actually ships, on port 5000 verify_installation.sh failed every healthy install: it required the long-removed web_interface_v2.py and looked for a listener on port 5001, while the web interface binds 5000 (web_interface/start.py). It now checks the files ledmatrix-web.service runs (start_web_conditionally.py, web_interface/start.py, app.py) and port 5000. verify_web_ui.sh had the same 5001 port in its listen check, HTTP probe and printed URLs. Port matches are anchored so :50001 no longer counts as :5000. Co-Authored-By: Claude Opus 5 <noreply@anthropic.com> * docs(plugins): one display-size contract: display_manager.width/height CLAUDE.md (#580) says to read display_manager.width/height because matrix is None when hardware init fails; the development guide, the safety-harness doc and two DisplayManager docstrings still recommended matrix.width/height. The bundled starlark-apps plugin read matrix.width unguarded, so its magnify recommendation and frame scaling raised in fallback mode (e.g. after the Pi 5 hardware refusal). Co-Authored-By: Claude Opus 5 <noreply@anthropic.com> * fix(install): make install_service.sh --help print usage instead of installing install_service.sh parsed no arguments, so `sudo ./scripts/install/ install_service.sh --help` (presented as harmless in MIGRATION_GUIDE.md) rewrote ledmatrix.service, ledmatrix-web.service and both update-verify units and enabled/started them. It now handles -h/--help (usage, exit 0, no changes) and rejects any other argument with exit 2 before doing anything. Running it with no arguments, as first_time_install.sh does, is unchanged. Co-Authored-By: Claude Opus 5 <noreply@anthropic.com> * docs(scroll): describe the fixed-step model and document frame_hold Since #545 a crisp speed from scroll_config.configure() makes the helper advance a fixed whole-pixel step per presented frame with no clock, and the display manager's frame hold is part of the speed. The docs still described the removed wall-clock model: - scroll_config's module and configure() docstrings said speed is applied in time-based mode and that omitting the hold "falls back to fractional pixels"; omitting it actually runs the scroll frame_hold times too fast. - SCROLL_PERFORMANCE.md said ScrollHelper accumulates elapsed time in both modes, and read a 20 ms stats median as missed refreshes although that is a healthy 50 px/s (hold 2) scroll. It now explains the fixed step, the hold-dependent healthy median, that target_fps plays no part, and that a hand-added scroll_pixels_per_second loses to a schema-default pair. - PLUGIN_API_REFERENCE.md documented set_scrolling_state(is_scrolling) without frame_hold; it now documents the parameter (core 3.4.0) with a configure() + set_scrolling_state example. - update_scroll_position/set_scroll_speed and set_scrolling_state docstrings say the same. Co-Authored-By: Claude Opus 5 <noreply@anthropic.com> * docs(config): mark target_fps legacy; describe what Vegas scroll_delay does - General tab "Scroll Frame Rate" (target_fps) is labelled legacy: after the sports_scroll fix nothing in core scrolling reads it. The field and its API validation stay so saved configs and plugins that read global_config['target_fps'] keep working. CONFIG_REFERENCE says the same. - Vegas frame_based_scrolling/scroll_delay were described as frame-count stepping at ~50 FPS. Neither steps nor sets a frame rate: frame-based mode converts the speed to px per scroll_delay, clamps it to 0.1-5, and still advances by elapsed time, so the applied speed is clamp(scroll_speed * scroll_delay, 0.1, 5) / scroll_delay px/s. The config comments, render_pipeline comment and CONFIG_REFERENCE rows now say so. No behaviour change. Co-Authored-By: Claude Opus 5 <noreply@anthropic.com> * docs(deps): describe how plugin dependencies are really installed The guides said the web service runs as root, that installs pick --user from os.geteuid(), and quoted a warning and a PluginManager._install_plugin_dependencies() method that don't exist. The web unit runs as the installing user; store installs go through install_requirements_file() and sudo safe_pip_install.sh (root), with a user-level fallback that says so, and load-time installs run in the display service's own (root) interpreter. Manual paths now use the configured plugins directory (plugin-repos/ by default) instead of plugins/, which store installs no longer use, and install_plugin_dependencies.sh is described as scanning that directory. Co-Authored-By: Claude Opus 5 <noreply@anthropic.com> * fix(update): count local changes one way for the preflight and the pull The automatic update's preflight ignored mode-only changes and anything whose status line contained plugins/ or plugin-repos/, then promised "Automatic updates will not stash your changes". perform_core_update used plain git status (modes count) and ignored only 'plugins/', then ran 'git stash push -- :!plugins', which nothing ever pops. So an edit to a bundled plugin under plugin-repos/, or the installer's chmods on tracked scripts, passed the preflight and was stashed away for good. - auto_update.local_changes() is the one predicate both use: core.fileMode=false, porcelain -z, and plugins/ and plugin-repos/ excluded by leading folder rather than substring (a core file under web_interface/static/v3/js/plugins/ now counts). - Update Code's explicit stash leaves out both plugin folders; the pull's --autostash carries their edits and mode changes across and reapplies them. - The automatic updater calls perform_core_update(stash_local_changes= False), which refuses instead of stashing edits that appeared after the preflight; update_core reports that as 'blocked'. Co-Authored-By: Claude Opus 5 <noreply@anthropic.com> * fix(scripts): diagnostics follow the web autostart default and api_v3 package #556 made a missing web_display_autostart mean "start" (only an explicit false/off keeps the web interface down), but the diagnostics still said otherwise: diagnose_web_ui.sh reported a missing key as "defaults to false", diagnose_web_interface.sh said the web interface "will not start unless this is set to true" and recommended enabling it, and debug_web_manual.py printed False. Troubleshooting a down web UI pointed users at a non-cause. Both shell scripts now evaluate the setting with the launcher's own autostart_enabled() (inline fallback if it cannot be imported) and report on / off / not set (on) / unparseable config; debug_web_manual.py uses the same function. They also check web_interface/blueprints/api_v3/ __init__.py: api_v3.py became a package in #553, so every healthy checkout was reported as missing a file. Co-Authored-By: Claude Opus 5 <noreply@anthropic.com> * docs(install): what install_service.sh installs; verify script port; no sudo for --help install_service.sh installs and starts ledmatrix, ledmatrix-web and the update-verify units, not only ledmatrix.service (systemd/README.md, README.md). MIGRATION_GUIDE presented 'sudo install_service.sh --help' as a harmless check; it now shows --help without sudo and warns what a real run does. SSH_UNAVAILABLE_AFTER_INSTALL: verify_installation.sh checks the web interface on port 5000. Co-Authored-By: Claude Opus 5 <noreply@anthropic.com> * docs(changelog): note update-all, plugin system settings and script fixes Co-Authored-By: Claude Opus 5 <noreply@anthropic.com> * fix(display): size the preview after orientation and pixel mappers display_geometry.physical_size claimed to give DisplayManager's answer but only computed cols*chain x rows*parallel. RGBMatrix.width/height are measured after the library's pixel mappers, so a Rotate:90 / orientation 90 chain previewed 128x32 for a 32x128 panel and a U-mapper chain of four 256x32 for 128x64. Model the built-in mappers' size effect as the pinned lib/pixel-mapper.cc does (Rotate, U-mapper, V-mapper, StackToRow, Remap; Mirror and unknown names leave it alone), and move the orientation composition here so DisplayManager and the preview share it. The module docstring no longer claims the sync handshake uses it; that imports only DEFAULT_CHAIN_LENGTH. Audit finding F18. Co-Authored-By: Claude Opus 5 <noreply@anthropic.com> * fix(display): refuse settings the rgbmatrix library aborts on, on every board The library answers several settings with a NULL matrix or abort() rather than an error, so the display service crash-looped (Restart=on-failure) instead of reaching fallback mode: rows above 64, chain_length above 255 (uint8_t binding setter, documented as "no upper limit"), a misspelled hardware_mapping, and parallel 2-3 on a single-output mapping, reachable from the Display form on the default adafruit-hat(-pwm) mapping. #586 only guarded the Pi 5 subset. - src/matrix_support.py holds the rules for every board (Options::Validate ranges, binding integer types, mapping names and outputs from lib/hardware-mapping.c) plus the Pi 5 ones, and is the one source of the API's numeric ranges. - DisplayManager checks them before building options and raises MatrixSettingsRefused, so a hand-edited config falls back with a logged, reported reason. Emulator mode only warns. - The config API refuses them with a 400 naming the setting; combinations are checked against stored values but reported only when the request sets a field involved. - The hardware status file gains "cause" (settings/library/forced). The fallback log and Display banner give the Pi 5 rebuild hint only for a library failure instead of rebuild + gpio_slowdown advice for every failure; one Pi 5 slowdown recommendation (1-3, start at 1). - The Display form offers classic/classic-pi1 and orientation 90/270 and renders any other stored mapping selected with a warning, so an unrelated save no longer rewrites them; the API accepts 90/270. Audit findings F03, F16, F19, F21. Co-Authored-By: Claude Opus 5 <noreply@anthropic.com> * docs(display): library limits, template defaults and Pi 5 slowdown - rows 8-64, chain_length 1-255, parallel limited by the mapping's outputs, classic/classic-pi1 mappings and orientation 90/270 documented. - Defaults are the config.template.json values: config migration adds missing keys from the template, so the listed "code defaults" never applied. - One Raspberry Pi 5 gpio_slowdown recommendation: 1-3 in PIO mode, starting at 1. - Troubleshooting describes the refused-settings fallback, and CHANGELOG corrects the Unreleased "no upper limit" entry. Audit findings F19, F20, F21. Co-Authored-By: Claude Opus 5 <noreply@anthropic.com> * fix(scripts): scroll_speeds.py opens the panel with the service's options --measure and --demo built RGBMatrixOptions from a private copy of the display service's builder that had drifted: gpio_slowdown came from display.hardware (default 2) instead of display.runtime (default 3), and rp1_rio, panel_type, disable_hardware_pulsing, inverse_colors, pixel_mapper_config and orientation were skipped, with different defaults (hardware_mapping "regular", pwm_bits 11). A panel needing a high slowdown was measured -- or garbled -- in a setup the service never drives. The option filling in DisplayManager._setup_matrix moves, unchanged, into DisplayManager.apply_matrix_options(options, config), which _setup_matrix calls and the script reuses (overriding only limit_refresh_rate_hz for --measure). The script now loads the whole config rather than the hardware block. Tests pin the script's options to the service's attribute for attribute. Co-Authored-By: Claude Opus 5 <noreply@anthropic.com> * fix(scripts): scroll_speeds.py recommends keys the resolver honours The ladder ended by telling users to set display_options.scroll_pixels_per_second. scroll_config ranks that key below the scroll_speed + scroll_delay pair, deliberately, and several plugin schemas default the pair into config, so the advised key was silently ignored (a schema-default 1/0.02 pair plus an advised 66 still resolved to 50 px/s). The advice is now the pair that selects the crisp speed exactly (pixels_per_frame every frame_hold/refresh seconds), explains that the pair outranks scroll_pixels_per_second, and gives the scoreboards' per-league scroll_settings.scroll_speed (px/s) form. Tests resolve the printed pair over a schema-default pair and check it lands on the advertised speed and hold. Co-Authored-By: Claude Opus 5 <noreply@anthropic.com> * docs: withdraw the target_fps claim for sports_scroll; fix the Vegas speed formula - SPORTS_UNIFICATION.md still presented honouring global target_fps as sports_scroll's added behaviour and its one user-visible gain; note that it was withdrawn because it had become a speed multiplier. - ADVANCED_FEATURES.md gave Vegas scrolling as (scroll_speed / target_fps) * elapsed; the real rule is scroll_speed px/s by elapsed time, through a 0.1-5 px per scroll_delay clamp when frame_based_scrolling is on. Co-Authored-By: Claude Opus 5 <noreply@anthropic.com> * docs(changelog): scroll model fixes Co-Authored-By: Claude Opus 5 <noreply@anthropic.com> * fix(dev): link-github links plugins from the ledmatrix-plugins monorepo link-github <name> cloned https://github.com/ChuckBuilds/ledmatrix-<name>.git, and those per-plugin repositories no longer exist: official plugins are directories in the ledmatrix-plugins monorepo. It now clones (or pulls) the monorepo once into the dev directory, finds plugins/<name>, plugins/ledmatrix-<name> or the plugin whose manifest id is <name>, and links it under its manifest id. With an explicit repo URL it still links a single-repository plugin as before. dev_plugins.json: github_user is honoured again (monorepo owner, e.g. a fork), plus plugins_repo and plugins_branch; github_pattern, which was documented but never read, is dropped and warned about. Ships dev_plugins.json.example and git-ignores dev_plugins.json, both of which the guide promised. Reading JSON falls back to python3 when jq is missing (get_plugin_id silently returned nothing without jq). update/status/list find the git checkout above a monorepo plugin directory (its .git is not in the plugin dir), and update pulls a shared checkout once. status no longer exits 1 when nothing is broken. Docs: PLUGIN_DEVELOPMENT_GUIDE (quick start, link-github, configuration, workflow, store integration, hello-world link, submission), and the nonexistent scripts/git-hooks/pre-push-plugin-version and scripts/bump_plugin_version.py replaced with the real rule: bump the manifest version and run update_registry.py. scripts/dev/README.md and CLAUDE.md updated to match. Co-Authored-By: Claude Opus 5 <noreply@anthropic.com> * docs(scripts): monorepo workspace layout; fix_perms and install READMEs MULTI_ROOT_WORKSPACE_SETUP described one sibling repository per plugin; setup_plugin_repos.py links ../ledmatrix-plugins/plugins/* into plugin-repos/ and update_plugin_repos.py pulls only the monorepo, and the workspace file opens LEDMatrix plus ../ledmatrix-plugins. scripts/fix_perms/README.md listed cache directories fix_cache_permissions.sh never touches and a 'ledmatrix' service user that doesn't exist (also in scripts/install/README.md); adds safe_pip_install.sh. install/README: install_service.sh installs the web and update-verify units too. Co-Authored-By: Claude Opus 5 <noreply@anthropic.com> * fix(update): keep the rollback's pip retries inside the unit time limit The health check reinstalled the previous requirements by trying the next bash path after any failure, including a 600 s pip timeout. Two files, two paths: up to 40 minutes of pip alone, while systemd stops ledmatrix-update-verify.service at TimeoutStartSec=30min -- killing the rollback half-way and leaving the update 'verifying' until the web UI calls it lost. - Like permission_utils.install_requirements_file, only a sudo refusal moves on to the next bash; a pip that ran and failed or timed out is not repeated. The refusal wording is one list (permission_utils.SUDO_REFUSAL_PHRASES), mirrored in the stdlib-only verifier and pinned equal by a test. - All reinstalls in one rollback share a 600 s budget. - WORST_CASE_SECONDS adds up every timeout on the longest path (27.5 min); a test holds it under the unit's TimeoutStartSec and that under the web UI's VERIFY_LOST_SECONDS. Co-Authored-By: Claude Opus 5 <noreply@anthropic.com> * fix(plugins): prepare plugin configs one way for load, saves, GET, hot reload and dev tools Plugin config was prepared differently depending on how it arrived: - JSON POST /plugins/config built a partial body on schema defaults, so {"enabled": true} reset every other setting of the plugin. It now merges onto the stored section first, as the form path already did. - Legacy-boolean normalization (#588) ran only at load: GET /plugins/config returned the raw boolean, posting it back failed validation, and hot reload handed plugins the raw section (a legacy dynamic_duration: true came back as a boolean). schema_manager.prepare_plugin_config (normalize, then defaults) is now used by PluginManager.load_plugin, both save paths, GET, the save notifications and DisplayController's hot-reload callback. - The JSON save's filter kept only enabled/display_duration/live_priority and dropped a submitted skin, skin_options or vegas_* tuning key. There is now one core-owned per-plugin list, schema_manager.CORE_PLUGIN_PROPERTIES, used by validation and by the save filter; PluginManager's CORE_OWNED_CONFIG_KEYS is its vegas subset. - Plugin sections posted to /config/main were stored verbatim, including values /plugins/config rejects. They now go through the same preparation (_prepare_plugin_config_for_save, extracted from save_plugin_config), and a failing section rejects the whole save before anything is written. - dev_server read only top-level defaults and let a schema enabled:false win; build_full_config shallow-merged overrides, dropping sibling defaults; the harness extracted defaults differently from the device. loading.build_config now uses the device's extraction and preparation, and dev_server, check_plugin, render_plugin and the harness all use it. Co-Authored-By: Claude Opus 5 <noreply@anthropic.com> * docs(mqtt-bridge): brightness changes apply live and touch nothing else The display service's hot reload applies a saved brightness within a few seconds, and /config/main no longer resets other display settings on a brightness-only JSON body. Co-Authored-By: Claude Opus 5 <noreply@anthropic.com> * docs(changelog): automatic update hardening Co-Authored-By: Claude Opus 5 <noreply@anthropic.com> * docs(config): rewrite PLUGIN_CONFIG_ARCHITECTURE for the v3 web UI It described web_interface_v2.py and index_v2.html (both gone), client-side form generation, one POST per field with {key, value}, and 'no nested objects'. The v3 UI renders plugin forms server-side from the schema (pages_v3 partial + plugin_config.html macros, nested sections and x-widgets), posts the whole form once, and save_plugin_config() merges onto the stored section, validates, splits x-secret fields and notifies the plugin. Co-Authored-By: Claude Opus 5 <noreply@anthropic.com> * docs(mqtt): brightness saves apply via hot reload and leave other settings alone The bridge README said brightness is applied on the display's next restart; the display controller's config hot reload applies it within seconds. It also now states that the bridge's partial JSON save changes only brightness (the /config/main merge fix in this change set). Co-Authored-By: Claude Opus 5 <noreply@anthropic.com> * fix(update): don't log pip's output from the health check's reinstall pip can echo a private index URL with embedded credentials; permission_utils redacts it, the stdlib-only verifier cannot, so it logs the exit code only. Co-Authored-By: Claude Opus 5 <noreply@anthropic.com> * docs(config): mark the plugin_system toggles as unused legacy keys auto_discover, auto_load_enabled and development_mode are read by nothing and leave the General tab in this change set (F40). CONFIG_REFERENCE said they were read by the plugin loader; PLUGIN_CONFIGURATION_GUIDE and the REST reference listed them as live settings. Co-Authored-By: Claude Opus 5 <noreply@anthropic.com> * docs(changelog): docs and developer tools group Co-Authored-By: Claude Opus 5 <noreply@anthropic.com> * fix(web): legacy plugin-system toggles no longer count as a General save auto_discover, auto_load_enabled and development_mode have left the General form, so a post carrying only one of them is not a general-settings save and must not treat web_display_autostart and auto_update as unchecked. The plugin_system block itself is left as on main for the branch that reworks it. Co-Authored-By: Claude Opus 5 <noreply@anthropic.com> * docs(changelog): config-save and plugin-config preparation fixes Co-Authored-By: Claude Opus 5 <noreply@anthropic.com> * docs(claude): re-check matrix_support.py rules when the library submodule is bumped Co-Authored-By: Claude Opus 5 <noreply@anthropic.com> * fix: address Codacy findings on the core audit PR - plugin_manager.prepare_plugin_config: when the fallback legacy-boolean pass also fails, log a warning instead of a bare except/pass. - api_client.js: request() refuses any endpoint that is not a plain path under /api/v3 ("//host", backslashes, ".." or "." segments, whitespace, control characters) with INVALID_ENDPOINT before calling fetch(), and plugin ids are URL-encoded wherever they are put into a URL (also in the app-shell batch load). - test_update_all.js: pins both against the shipped client. Co-Authored-By: Claude Opus 5 <noreply@anthropic.com> * fix(web): check endpoint control characters without a control-character regex Codacy (ESLint no-control-regex, Biome noControlCharactersInRegex) flags the \x00-\x1f range in checkEndpoint's regex. Test the char codes instead; the endpoints refused are unchanged. Co-Authored-By: Claude Opus 5 <noreply@anthropic.com> * test(auto-update): make the seed script executable on disk, not only in the index On Linux Repo.publish() commits with -a, which recorded scripts/run.sh as 100644 upstream because the seed file was never chmod +x. The pull then brought in the same mode the installer chmod had made locally, so installer_chmod saw no mode change left to check. The updater was fine: with the upstream commit at 100755 the --autostash carries the device's chmod across. Verified under Linux (WSL, git 2.43): the old helper fails exactly as CI did, the fixed one passes all 63 tests in the file. Co-Authored-By: Claude Opus 5 <noreply@anthropic.com> --------- Co-authored-by: Claude Opus 5 <noreply@anthropic.com>
855 lines
38 KiB
Python
855 lines
38 KiB
Python
"""Weekly automatic updates (web_interface/auto_update.py).
|
|
|
|
The updater pulls code and restarts services unattended. These pin down that
|
|
it runs only when asked and due, refuses to touch a checkout it could damage,
|
|
never leaves new code running without a health check, and reports every
|
|
failure instead of logging it and moving on.
|
|
|
|
Git runs for real against a throwaway origin/device clone pair; systemd, sudo
|
|
and the health check service are faked.
|
|
"""
|
|
import json
|
|
import shutil
|
|
import subprocess
|
|
import sys
|
|
from datetime import datetime, timezone
|
|
from pathlib import Path
|
|
from unittest.mock import MagicMock, patch
|
|
|
|
import pytest
|
|
|
|
ROOT = Path(__file__).resolve().parent.parent
|
|
sys.path.insert(0, str(ROOT))
|
|
|
|
from web_interface import auto_update as au # noqa: E402
|
|
|
|
# Local time is pinned to UTC below, so 03:00 is inside the quiet hours.
|
|
NIGHT = datetime(2026, 9, 14, 3, 0, tzinfo=timezone.utc).timestamp()
|
|
NOON = datetime(2026, 9, 14, 12, 0, tzinfo=timezone.utc).timestamp()
|
|
ON = {'auto_update': {'enabled': True}}
|
|
OFF = {'auto_update': {'enabled': False}}
|
|
|
|
needs_git = pytest.mark.skipif(shutil.which('git') is None, reason='git not installed')
|
|
|
|
|
|
@pytest.fixture(autouse=True)
|
|
def local_is_utc(monkeypatch):
|
|
"""Pin 'local time' so quiet-hours checks don't depend on the host zone."""
|
|
monkeypatch.setattr(au, '_zone', lambda name: timezone.utc)
|
|
|
|
|
|
def git(cwd, *args):
|
|
result = subprocess.run(['git', '-c', 'user.name=t', '-c', 'user.email=t@example.com', *args],
|
|
cwd=str(cwd), capture_output=True, text=True)
|
|
assert result.returncode == 0, result.stderr
|
|
return result.stdout.strip()
|
|
|
|
|
|
class Repo:
|
|
"""An origin, a checkout that publishes to it, and the device's clone."""
|
|
|
|
def __init__(self, tmp):
|
|
self.seed = tmp / 'seed'
|
|
self.seed.mkdir()
|
|
git(self.seed, 'init', '-q', '-b', 'main')
|
|
(self.seed / 'app.py').write_text('v = 1\n')
|
|
git(self.seed, 'add', '.')
|
|
git(self.seed, 'commit', '-qm', 'one')
|
|
self.origin = tmp / 'origin.git'
|
|
git(tmp, 'clone', '-q', '--bare', str(self.seed), str(self.origin))
|
|
git(self.seed, 'remote', 'add', 'origin', str(self.origin))
|
|
self.device = tmp / 'device'
|
|
git(tmp, 'clone', '-q', str(self.origin), str(self.device))
|
|
|
|
def head(self):
|
|
return git(self.device, 'rev-parse', 'HEAD')
|
|
|
|
def publish(self, text='v = 2\n'):
|
|
(self.seed / 'app.py').write_text(text)
|
|
git(self.seed, 'commit', '-qam', 'next')
|
|
git(self.seed, 'push', '-q', 'origin', 'main')
|
|
return git(self.seed, 'rev-parse', 'HEAD')
|
|
|
|
|
|
def real_pull(device, **extra):
|
|
def core_update(**kwargs):
|
|
before = git(device, 'rev-parse', 'HEAD')
|
|
r = subprocess.run(['git', 'pull', '-q', '--rebase', '--autostash'],
|
|
cwd=str(device), capture_output=True, text=True)
|
|
after = git(device, 'rev-parse', 'HEAD')
|
|
result = {'status': 'success' if r.returncode == 0 else 'error',
|
|
'message': 'Code updated successfully.' if r.returncode == 0 else r.stderr,
|
|
'restart_required': before != after, 'dependency_failures': []}
|
|
result.update(extra)
|
|
return result
|
|
return core_update
|
|
|
|
|
|
class FakeStore:
|
|
def __init__(self, plugins_dir, versions, bump=(), fail=()):
|
|
self.plugins_dir = str(plugins_dir)
|
|
self.bump, self.fail = set(bump), set(fail)
|
|
for pid, version in versions.items():
|
|
d = Path(plugins_dir) / pid
|
|
d.mkdir(parents=True)
|
|
(d / 'manifest.json').write_text(json.dumps({'id': pid, 'version': version}))
|
|
self.updated_calls = []
|
|
|
|
def list_installed_plugins(self):
|
|
return [p.name for p in Path(self.plugins_dir).iterdir()]
|
|
|
|
def _get_local_git_info(self, path):
|
|
return None
|
|
|
|
def update_plugin(self, pid):
|
|
self.updated_calls.append(pid)
|
|
if pid in self.fail:
|
|
return False
|
|
if pid in self.bump:
|
|
path = Path(self.plugins_dir) / pid / 'manifest.json'
|
|
m = json.loads(path.read_text())
|
|
m['version'] = '9.9.9'
|
|
path.write_text(json.dumps(m))
|
|
return True
|
|
|
|
|
|
class Harness:
|
|
"""An AutoUpdater on a real clone.
|
|
|
|
``helper`` is whether the health check's path unit is active; ``pickup``
|
|
whether the health check actually starts when asked. Starting it is
|
|
simulated the way systemd does it: the request file is consumed
|
|
(ExecStartPre) and the verifier marks the pending update "verifying".
|
|
"""
|
|
|
|
def __init__(self, tmp, repo, *, helper=True, pickup=True, core_update=None, store=None,
|
|
disk_free=10 ** 12, display_active=True, enabled=True, clock=NIGHT):
|
|
self.sudo, self.restarts, self.now = [], [], clock
|
|
self.state_at_handoff = None
|
|
|
|
def run(args, **kwargs):
|
|
if args[0] == 'sudo':
|
|
self.sudo.append(list(args))
|
|
return subprocess.CompletedProcess(args, 0, stdout='', stderr='')
|
|
return subprocess.run(args, **kwargs)
|
|
|
|
def sleep(seconds):
|
|
updater = self.updater
|
|
if self.state_at_handoff is None:
|
|
self.state_at_handoff = au.load_state(updater.state_file)
|
|
if pickup and updater.request_file.exists():
|
|
updater.request_file.unlink()
|
|
pending = au._read_json(updater.pending_file)
|
|
pending['status'] = 'verifying'
|
|
au._write_json(updater.pending_file, pending)
|
|
|
|
self.config = {'auto_update': {'enabled': enabled}, 'timezone': 'UTC'}
|
|
cm = MagicMock()
|
|
cm.load_config.return_value = self.config
|
|
self.updater = au.AutoUpdater(
|
|
config_manager=cm, core_update=core_update or real_pull(repo.device),
|
|
store_manager=store, project_root=repo.device, clock=lambda: self.now,
|
|
restart=self.restarts.append, run=run,
|
|
service_active=lambda unit: display_active, helper_ready=lambda: helper,
|
|
disk_free=lambda path: disk_free, sleep=sleep)
|
|
|
|
@property
|
|
def state(self):
|
|
return au.load_state(self.updater.state_file)
|
|
|
|
@property
|
|
def pending(self):
|
|
return au._read_json(self.updater.pending_file)
|
|
|
|
def write_pending(self, **fields):
|
|
au._write_json(self.updater.pending_file, fields)
|
|
|
|
|
|
def stub_updater(tmp_path, outcome='up_to_date', message='ok', store=None, enabled=True, clock=NIGHT):
|
|
"""For scheduling and plugin tests: the core update is stubbed out."""
|
|
cm = MagicMock()
|
|
cm.load_config.return_value = {'auto_update': {'enabled': enabled}, 'timezone': 'UTC'}
|
|
restarts = []
|
|
updater = au.AutoUpdater(config_manager=cm, core_update=MagicMock(), store_manager=store,
|
|
project_root=tmp_path, clock=lambda: clock,
|
|
restart=restarts.append)
|
|
updater.update_core = MagicMock(return_value={'outcome': outcome, 'message': message})
|
|
return updater, restarts
|
|
|
|
|
|
# -- scheduling ---------------------------------------------------------------
|
|
|
|
class TestIsDue:
|
|
def test_not_before_next_due(self):
|
|
assert not au.is_due(100, 200, 3)
|
|
|
|
def test_in_quiet_hours_once_due(self):
|
|
assert au.is_due(200, 200, 3)
|
|
|
|
def test_waits_for_quiet_hours(self):
|
|
assert not au.is_due(200, 100, 12)
|
|
|
|
def test_gives_up_waiting_after_grace(self):
|
|
assert au.is_due(100 + au.QUIET_HOURS_GRACE_SECONDS, 100, 12)
|
|
|
|
|
|
class TestTick:
|
|
def test_disabled_never_runs(self, tmp_path):
|
|
updater, _ = stub_updater(tmp_path, enabled=False)
|
|
assert updater.tick() is False
|
|
updater.update_core.assert_not_called()
|
|
|
|
def test_enabling_at_noon_waits_for_the_night(self, tmp_path):
|
|
updater, _ = stub_updater(tmp_path, clock=NOON)
|
|
assert updater.tick() is False
|
|
updater.update_core.assert_not_called()
|
|
assert au.load_state(updater.state_file)['next_due'] == NOON
|
|
|
|
def test_runs_when_due_and_schedules_a_week_out(self, tmp_path):
|
|
updater, _ = stub_updater(tmp_path)
|
|
assert updater.tick() is True
|
|
state = au.load_state(updater.state_file)
|
|
assert state['next_due'] == NIGHT + au.UPDATE_INTERVAL_SECONDS
|
|
assert updater.tick() is False, "ran twice in one night"
|
|
|
|
def test_transient_error_retries_next_day(self, tmp_path):
|
|
updater, _ = stub_updater(tmp_path, outcome='error', message='no network')
|
|
updater.tick()
|
|
state = au.load_state(updater.state_file)
|
|
assert state['next_due'] == NIGHT + au.RETRY_AFTER_FAILURE_SECONDS
|
|
assert state['alert']['message'] == 'no network'
|
|
|
|
def test_blocked_keeps_weekly_cadence_but_alerts(self, tmp_path):
|
|
updater, _ = stub_updater(tmp_path, outcome='blocked', message='local edits')
|
|
updater.tick()
|
|
state = au.load_state(updater.state_file)
|
|
assert state['next_due'] == NIGHT + au.UPDATE_INTERVAL_SECONDS
|
|
assert 'local edits' in state['alert']['message']
|
|
|
|
|
|
# -- checks before touching the checkout ---------------------------------------
|
|
|
|
@needs_git
|
|
class TestPreflightRefuses:
|
|
def test_nothing_new_is_up_to_date(self, tmp_path):
|
|
repo = Repo(tmp_path)
|
|
h = Harness(tmp_path, repo)
|
|
result = h.updater.run()
|
|
assert result['core_outcome'] == 'up_to_date'
|
|
assert result['status'] == 'success'
|
|
assert h.sudo == [] and 'alert' not in h.state
|
|
|
|
def test_without_the_health_check_code_is_not_touched(self, tmp_path):
|
|
repo = Repo(tmp_path)
|
|
old = repo.head()
|
|
repo.publish()
|
|
h = Harness(tmp_path, repo, helper=False)
|
|
result = h.updater.run()
|
|
assert result['core_outcome'] == 'blocked'
|
|
assert repo.head() == old
|
|
assert 'health check is set up' in result['core_message']
|
|
assert h.state['alert']
|
|
|
|
def test_local_edits_are_never_stashed(self, tmp_path):
|
|
repo = Repo(tmp_path)
|
|
old = repo.head()
|
|
repo.publish()
|
|
(repo.device / 'app.py').write_text('mine\n')
|
|
h = Harness(tmp_path, repo)
|
|
result = h.updater.run()
|
|
assert result['core_outcome'] == 'blocked'
|
|
assert 'app.py' in result['core_message']
|
|
assert repo.head() == old
|
|
assert (repo.device / 'app.py').read_text() == 'mine\n'
|
|
assert git(repo.device, 'stash', 'list') == ''
|
|
|
|
def test_local_commits_block(self, tmp_path):
|
|
repo = Repo(tmp_path)
|
|
repo.publish()
|
|
(repo.device / 'extra.txt').write_text('x\n')
|
|
git(repo.device, 'add', 'extra.txt')
|
|
git(repo.device, 'commit', '-qm', 'local')
|
|
mine = repo.head()
|
|
h = Harness(tmp_path, repo)
|
|
result = h.updater.run()
|
|
assert result['core_outcome'] == 'blocked'
|
|
assert 'local commit' in result['core_message']
|
|
assert repo.head() == mine
|
|
|
|
def test_a_rebase_really_in_progress_blocks(self, tmp_path):
|
|
repo = Repo(tmp_path)
|
|
repo.publish('v = 2\n')
|
|
(repo.device / 'app.py').write_text('v = mine\n')
|
|
git(repo.device, 'commit', '-qam', 'local')
|
|
git(repo.device, 'fetch', '-q')
|
|
stopped = subprocess.run(['git', '-c', 'user.name=t', '-c', 'user.email=t@example.com',
|
|
'rebase', 'origin/main'], cwd=str(repo.device), capture_output=True, text=True)
|
|
assert stopped.returncode != 0, "the rebase should stop on the conflict"
|
|
result = Harness(tmp_path, repo).updater.run()
|
|
assert result['core_outcome'] == 'blocked'
|
|
assert 'rebase is in progress' in result['core_message']
|
|
assert (repo.device / '.git' / 'rebase-merge').exists(), "a live rebase must be left alone"
|
|
|
|
def test_an_abandoned_rebase_is_cleared_and_the_update_runs(self, tmp_path):
|
|
"""Found on a real device: a pull stopped mid-rebase a week earlier,
|
|
HEAD was later checked out to a branch, and the leftover rebase
|
|
directory would have blocked every automatic update forever."""
|
|
repo = Repo(tmp_path)
|
|
leftover = repo.device / '.git' / 'rebase-merge'
|
|
leftover.mkdir()
|
|
(leftover / 'head-name').write_text('refs/heads/main\n')
|
|
new = repo.publish()
|
|
result = Harness(tmp_path, repo).updater.run()
|
|
assert not leftover.exists()
|
|
assert result['core_outcome'] == 'verifying'
|
|
assert repo.head() == new
|
|
|
|
def test_a_merge_in_progress_blocks(self, tmp_path):
|
|
repo = Repo(tmp_path)
|
|
repo.publish()
|
|
(repo.device / '.git' / 'MERGE_HEAD').write_text(repo.head() + '\n')
|
|
result = Harness(tmp_path, repo).updater.run()
|
|
assert result['core_outcome'] == 'blocked'
|
|
assert 'merge is in progress' in result['core_message']
|
|
|
|
def test_low_disk_blocks(self, tmp_path):
|
|
repo = Repo(tmp_path)
|
|
repo.publish()
|
|
result = Harness(tmp_path, repo, disk_free=10 * 1024 * 1024).updater.run()
|
|
assert result['core_outcome'] == 'blocked'
|
|
assert 'disk space' in result['core_message']
|
|
|
|
def test_unreachable_origin_retries_tomorrow(self, tmp_path):
|
|
repo = Repo(tmp_path)
|
|
git(repo.device, 'remote', 'set-url', 'origin', str(tmp_path / 'nowhere'))
|
|
h = Harness(tmp_path, repo)
|
|
result = h.updater.run()
|
|
assert result['core_outcome'] == 'error'
|
|
assert h.state['next_due'] == NIGHT + au.RETRY_AFTER_FAILURE_SECONDS
|
|
|
|
def test_version_already_rolled_back_is_not_retried(self, tmp_path):
|
|
repo = Repo(tmp_path)
|
|
old = repo.head()
|
|
bad = repo.publish()
|
|
h = Harness(tmp_path, repo)
|
|
au.save_state({'rolled_back_head': bad}, h.updater.state_file)
|
|
result = h.updater.run()
|
|
assert result['core_outcome'] == 'up_to_date'
|
|
assert 'rolled back before' in result['core_message']
|
|
assert repo.head() == old and h.sudo == []
|
|
|
|
|
|
# -- what counts as a local change ---------------------------------------------
|
|
|
|
def _device_with_plugin_and_script(tmp_path):
|
|
"""A clone carrying a bundled plugin and an executable script, as LEDMatrix does."""
|
|
repo = Repo(tmp_path)
|
|
for rel, text in (('plugin-repos/web-ui-info/manager.py', 'x = 1\n'),
|
|
('web_interface/static/v3/js/plugins/store.js', 'var a;\n'),
|
|
('scripts/run.sh', 'echo hi\n')):
|
|
(repo.seed / rel).parent.mkdir(parents=True, exist_ok=True)
|
|
(repo.seed / rel).write_text(text)
|
|
# Executable on disk too, not only in the index: Repo.publish() commits
|
|
# with -a, which on Linux would otherwise record run.sh as 100644 upstream
|
|
# and hide the device's own mode change behind the pull.
|
|
import os
|
|
os.chmod(repo.seed / 'scripts' / 'run.sh', 0o755)
|
|
git(repo.seed, 'add', '.')
|
|
git(repo.seed, 'update-index', '--chmod=+x', 'scripts/run.sh')
|
|
git(repo.seed, 'commit', '-qm', 'layout')
|
|
git(repo.seed, 'push', '-q', 'origin', 'main')
|
|
git(repo.device, 'pull', '-q')
|
|
return repo
|
|
|
|
|
|
def _chmod_like_the_installer(device):
|
|
"""first_time_install.sh sets tracked 100755 files to 644: a mode-only change.
|
|
|
|
Windows has no exec bit, so there core.fileMode=true alone shows it."""
|
|
import os
|
|
git(device, 'config', 'core.fileMode', 'true')
|
|
os.chmod(device / 'scripts' / 'run.sh', 0o644)
|
|
assert 'mode change 100755 => 100644 scripts/run.sh' in git(device, 'diff', '--summary')
|
|
|
|
|
|
@needs_git
|
|
class TestLocalChangesAreCountedOnce:
|
|
"""The preflight promises the pull will not stash. That holds only if both
|
|
count local changes the same way (auto_update.local_changes)."""
|
|
|
|
def test_mode_changes_and_plugin_folders_do_not_count(self, tmp_path):
|
|
repo = _device_with_plugin_and_script(tmp_path)
|
|
_chmod_like_the_installer(repo.device)
|
|
(repo.device / 'plugin-repos/web-ui-info/manager.py').write_text('x = 2 # store update\n')
|
|
assert au.local_changes(repo.device) == []
|
|
|
|
def test_a_core_folder_named_plugins_still_counts(self, tmp_path):
|
|
"""The old filter matched 'plugins/' anywhere in the line."""
|
|
repo = _device_with_plugin_and_script(tmp_path)
|
|
(repo.device / 'web_interface/static/v3/js/plugins/store.js').write_text('var mine;\n')
|
|
assert au.local_changes(repo.device) == ['web_interface/static/v3/js/plugins/store.js']
|
|
|
|
def test_a_staged_rename_is_reported_by_its_new_name(self, tmp_path):
|
|
repo = Repo(tmp_path)
|
|
git(repo.device, 'mv', 'app.py', 'main.py')
|
|
assert au.local_changes(repo.device) == ['main.py']
|
|
|
|
def test_the_preflight_refuses_a_core_edit_under_a_plugins_folder(self, tmp_path):
|
|
repo = _device_with_plugin_and_script(tmp_path)
|
|
old = repo.head()
|
|
repo.publish()
|
|
(repo.device / 'web_interface/static/v3/js/plugins/store.js').write_text('var mine;\n')
|
|
result = Harness(tmp_path, repo).updater.run()
|
|
assert result['core_outcome'] == 'blocked'
|
|
assert 'store.js' in result['core_message']
|
|
assert repo.head() == old
|
|
|
|
@pytest.fixture
|
|
def core_update(self, monkeypatch):
|
|
"""The real perform_core_update, pointed at a test clone."""
|
|
from web_interface.blueprints import api_v3 as pkg
|
|
from web_interface.blueprints.api_v3 import system
|
|
|
|
def point_at(device):
|
|
monkeypatch.setattr(system, 'PROJECT_ROOT', device)
|
|
monkeypatch.setattr(pkg.api_v3, 'plugin_store_manager', None, raising=False)
|
|
monkeypatch.setattr(system, '_pip_install_requirements',
|
|
lambda *a, **k: pytest.fail('no requirements changed'))
|
|
return system.perform_core_update
|
|
return point_at
|
|
|
|
@pytest.mark.parametrize('change', [
|
|
'bundled_plugin_edit',
|
|
pytest.param('installer_chmod', marks=pytest.mark.skipif(
|
|
sys.platform == 'win32',
|
|
reason='no exec bit: the reset inside --autostash cannot clear a mode change, '
|
|
'so git will not reapply it (on Linux it reapplies cleanly)')),
|
|
])
|
|
def test_an_update_that_passed_the_preflight_leaves_no_stash(self, tmp_path, core_update, change):
|
|
"""Found by audit: a bundled-plugin edit or the installer's chmods
|
|
passed the preflight, then perform_core_update stashed them for good.
|
|
Now --autostash carries them across the pull and puts them back."""
|
|
repo = _device_with_plugin_and_script(tmp_path)
|
|
new = repo.publish()
|
|
if change == 'installer_chmod':
|
|
_chmod_like_the_installer(repo.device)
|
|
else:
|
|
(repo.device / 'plugin-repos/web-ui-info/manager.py').write_text('x = 2 # store update\n')
|
|
h = Harness(tmp_path, repo, core_update=core_update(repo.device))
|
|
assert h.updater.preflight({})[0] == 'ready'
|
|
|
|
result = h.updater.run()
|
|
assert result['core_outcome'] == 'verifying', result['core_message']
|
|
assert repo.head() == new
|
|
assert git(repo.device, 'stash', 'list') == ''
|
|
if change == 'installer_chmod':
|
|
assert 'mode change 100755 => 100644 scripts/run.sh' in git(repo.device, 'diff', '--summary')
|
|
else:
|
|
assert 'store update' in (repo.device / 'plugin-repos/web-ui-info/manager.py').read_text()
|
|
|
|
def test_edits_made_after_the_preflight_are_refused_not_stashed(self, tmp_path, core_update):
|
|
repo = Repo(tmp_path)
|
|
old = repo.head()
|
|
repo.publish()
|
|
perform = core_update(repo.device)
|
|
|
|
def edit_then_update(**kwargs):
|
|
(repo.device / 'app.py').write_text('mine\n')
|
|
return perform(**kwargs)
|
|
result = Harness(tmp_path, repo, core_update=edit_then_update).updater.run()
|
|
assert result['core_outcome'] == 'blocked'
|
|
assert 'app.py' in result['core_message'] and 'will not stash' in result['core_message']
|
|
assert repo.head() == old
|
|
assert git(repo.device, 'stash', 'list') == ''
|
|
assert (repo.device / 'app.py').read_text() == 'mine\n'
|
|
|
|
def test_update_code_still_stashes_core_edits_but_not_plugin_folders(self, tmp_path, core_update):
|
|
repo = _device_with_plugin_and_script(tmp_path)
|
|
new = repo.publish()
|
|
(repo.device / 'scripts/run.sh').write_text('echo mine\n')
|
|
(repo.device / 'plugin-repos/web-ui-info/manager.py').write_text('x = 2 # store update\n')
|
|
payload = core_update(repo.device)()
|
|
assert payload['status'] == 'success', payload['message']
|
|
assert 'stashed' in payload['message']
|
|
assert repo.head() == new
|
|
assert 'LEDMatrix auto-stash before update' in git(repo.device, 'stash', 'list')
|
|
stashed = git(repo.device, 'stash', 'show', '--name-only', 'stash@{0}')
|
|
assert stashed.split() == ['scripts/run.sh']
|
|
assert 'store update' in (repo.device / 'plugin-repos/web-ui-info/manager.py').read_text()
|
|
|
|
|
|
# -- the update and its hand-off to the health check ---------------------------
|
|
|
|
@needs_git
|
|
class TestUpdateIsVerified:
|
|
def test_pull_hands_off_to_the_health_check(self, tmp_path):
|
|
repo = Repo(tmp_path)
|
|
old = repo.head()
|
|
new = repo.publish()
|
|
store = FakeStore(tmp_path / 'plugins', {'weather': '1.0.0'}, bump={'weather'})
|
|
h = Harness(tmp_path, repo, store=store)
|
|
result = h.updater.run()
|
|
|
|
assert result['core_outcome'] == 'verifying' and result['status'] == 'pending'
|
|
assert repo.head() == new
|
|
assert h.pending == {**h.pending, 'status': 'verifying', 'old_head': old, 'new_head': new,
|
|
'display_was_active': True, 'dependency_failures': []}
|
|
assert not h.updater.request_file.exists(), "the request is consumed when the check starts"
|
|
assert h.sudo == [], "triggering the health check needs no privilege"
|
|
assert h.restarts == [], "restarts belong to the health check, not the web process"
|
|
assert store.updated_calls == [], "plugins must wait until the new code is verified"
|
|
assert h.state['plugins_pending'] is True
|
|
assert h.updater.verifier_copy.read_text() == au.VERIFIER_SOURCE.read_text()
|
|
|
|
def test_state_is_saved_before_the_health_check_restarts_this_process(self, tmp_path):
|
|
repo = Repo(tmp_path)
|
|
repo.publish()
|
|
h = Harness(tmp_path, repo)
|
|
h.updater.run()
|
|
assert h.state_at_handoff['last_result']['core_outcome'] == 'verifying'
|
|
assert h.state_at_handoff['plugins_pending'] is True
|
|
|
|
def test_dependency_failures_reach_the_health_check(self, tmp_path):
|
|
repo = Repo(tmp_path)
|
|
repo.publish()
|
|
h = Harness(tmp_path, repo,
|
|
core_update=real_pull(repo.device, dependency_failures=['requirements.txt']))
|
|
h.updater.run()
|
|
assert h.pending['dependency_failures'] == ['requirements.txt']
|
|
|
|
def test_a_health_check_that_never_starts_means_the_update_is_undone(self, tmp_path):
|
|
repo = Repo(tmp_path)
|
|
old = repo.head()
|
|
repo.publish()
|
|
h = Harness(tmp_path, repo, pickup=False)
|
|
result = h.updater.run()
|
|
assert repo.head() == old
|
|
assert result['core_outcome'] == 'blocked'
|
|
assert 'did not start' in result['core_message']
|
|
assert h.pending is None and not h.updater.request_file.exists()
|
|
assert h.state['alert']
|
|
|
|
def test_failed_pull_retries_tomorrow(self, tmp_path):
|
|
repo = Repo(tmp_path)
|
|
old = repo.head()
|
|
repo.publish()
|
|
h = Harness(tmp_path, repo,
|
|
core_update=lambda **kw: {'status': 'error', 'message': 'Update failed: network'})
|
|
result = h.updater.run()
|
|
assert result['core_outcome'] == 'error'
|
|
assert repo.head() == old
|
|
assert h.state['next_due'] == NIGHT + au.RETRY_AFTER_FAILURE_SECONDS
|
|
|
|
def test_failed_pull_that_moved_head_is_rolled_back(self, tmp_path):
|
|
repo = Repo(tmp_path)
|
|
old = repo.head()
|
|
repo.publish()
|
|
pull = real_pull(repo.device)
|
|
|
|
def half_failed(**kwargs):
|
|
pull()
|
|
return {'status': 'error', 'message': 'Update failed: interrupted'}
|
|
result = Harness(tmp_path, repo, core_update=half_failed).updater.run()
|
|
assert repo.head() == old
|
|
assert 'rolled back' in result['core_message']
|
|
|
|
@pytest.mark.parametrize('how', ['partial_pull', 'check_never_started'])
|
|
def test_a_failed_rollback_leaves_plugins_and_the_display_alone(self, tmp_path, how):
|
|
"""update_core returns rollback_failed itself on two paths. The device
|
|
is then in an unknown state, exactly as when the health check reports
|
|
rollback_failed, so no plugin updates and no restart may follow."""
|
|
repo = Repo(tmp_path)
|
|
repo.publish()
|
|
store = FakeStore(tmp_path / 'plugins', {'clock': '1.0.0'}, bump={'clock'})
|
|
pull = real_pull(repo.device)
|
|
|
|
def half_failed(**kwargs):
|
|
pull()
|
|
return {'status': 'error', 'message': 'Update failed: interrupted'}
|
|
h = Harness(tmp_path, repo, store=store, pickup=how != 'check_never_started',
|
|
core_update=half_failed if how == 'partial_pull' else None)
|
|
real_run = h.updater.run_command
|
|
|
|
def reset_fails(args, **kwargs):
|
|
if args[:3] == ['git', 'reset', '--hard']:
|
|
return subprocess.CompletedProcess(args, 1, stdout='', stderr='index.lock exists')
|
|
return real_run(args, **kwargs)
|
|
h.updater.run_command = reset_fails
|
|
|
|
result = h.updater.run()
|
|
assert result['core_outcome'] == 'rollback_failed'
|
|
assert store.updated_calls == [], "plugins must not pile onto a core in an unknown state"
|
|
assert h.restarts == []
|
|
assert h.state['plugins_pending'] is False and result['plugins_deferred'] is False
|
|
assert h.state['alert']
|
|
|
|
|
|
# -- reporting the health check's outcome --------------------------------------
|
|
|
|
@needs_git
|
|
class TestHealthCheckOutcome:
|
|
def _after_update(self, tmp_path, **pending):
|
|
repo = Repo(tmp_path)
|
|
store = FakeStore(tmp_path / 'plugins', {'weather': '1.0.0'}, bump={'weather'})
|
|
h = Harness(tmp_path, repo, store=store)
|
|
au.save_state({'plugins_pending': True, 'next_due': NIGHT + au.UPDATE_INTERVAL_SECONDS,
|
|
'last_result': {'core_outcome': 'verifying', 'status': 'pending',
|
|
'plugins_deferred': True}}, h.updater.state_file)
|
|
h.write_pending(old_head='a' * 40, new_head='b' * 40, created_at=NIGHT, **pending)
|
|
return h, store
|
|
|
|
def test_waits_while_the_check_runs(self, tmp_path):
|
|
h, store = self._after_update(tmp_path, status='verifying')
|
|
h.now = NIGHT + 60
|
|
assert h.updater.tick() is False
|
|
assert store.updated_calls == [] and h.pending
|
|
|
|
def test_success_then_runs_the_deferred_plugins(self, tmp_path):
|
|
h, store = self._after_update(tmp_path, status='success')
|
|
assert h.updater.tick() is True
|
|
result = h.state['last_result']
|
|
assert result['core_outcome'] == 'updated' and result['status'] == 'success'
|
|
assert result['plugins_updated'] == ['weather']
|
|
assert h.restarts == ['ledmatrix']
|
|
assert 'alert' not in h.state and h.pending is None
|
|
|
|
def test_rollback_alerts_and_remembers_the_bad_commit(self, tmp_path):
|
|
h, store = self._after_update(tmp_path, status='rolled_back',
|
|
reason='the web interface did not respond')
|
|
h.updater.tick()
|
|
assert 'rolled back' in h.state['alert']['message']
|
|
assert 'the web interface did not respond' in h.state['alert']['message']
|
|
assert h.state['rolled_back_head'] == 'b' * 40
|
|
assert store.updated_calls == ['weather'], "the old code is healthy; plugins may update"
|
|
|
|
def test_failed_rollback_alerts_and_skips_plugins(self, tmp_path):
|
|
h, store = self._after_update(tmp_path, status='rollback_failed',
|
|
reason='display down', detail='reset failed')
|
|
h.updater.tick()
|
|
assert f'git reset --hard {"a" * 40}' in h.state['alert']['message']
|
|
assert store.updated_calls == []
|
|
assert h.state['plugins_pending'] is False
|
|
|
|
def test_a_check_that_never_reports_back_alerts(self, tmp_path):
|
|
h, _ = self._after_update(tmp_path, status='verifying')
|
|
h.now = NIGHT + au.VERIFY_LOST_SECONDS + 1
|
|
h.updater.tick()
|
|
assert h.state['last_result']['core_outcome'] == 'lost'
|
|
assert 'never reported back' in h.state['alert']['message']
|
|
|
|
def test_dismissed_alert_stays_hidden_until_a_new_one(self, tmp_path):
|
|
h, _ = self._after_update(tmp_path, status='rolled_back', reason='x')
|
|
h.updater.tick()
|
|
alert_id = h.state['alert']['id']
|
|
|
|
def status():
|
|
return au.describe_status(h.config, state_file=h.updater.state_file,
|
|
pending_file=h.updater.pending_file,
|
|
setup_file=tmp_path / 'no-setup.json', helper=lambda: True)
|
|
assert status()['alert_id'] == alert_id
|
|
au.dismiss_alert(alert_id, h.updater.state_file)
|
|
assert status()['alert'] is None
|
|
state = h.state
|
|
state['alert'] = {'id': 'newer', 'message': 'again'}
|
|
au.save_state(state, h.updater.state_file)
|
|
assert status()['alert'] == 'again'
|
|
|
|
|
|
def test_describe_status_reports_setup(tmp_path):
|
|
setup = tmp_path / 'setup.json'
|
|
setup.write_text(json.dumps({'status': 'failed', 'message': 'not root'}))
|
|
kwargs = dict(state={}, state_file=tmp_path / 's.json', pending_file=tmp_path / 'p.json',
|
|
setup_file=setup)
|
|
on = au.describe_status(ON, helper=lambda: False, **kwargs)
|
|
assert on['verifier_installed'] is False
|
|
assert (on['setup_status'], on['setup_message']) == ('failed', 'not root')
|
|
|
|
def never(): raise AssertionError("systemctl asked while updates are off")
|
|
assert au.describe_status(OFF, helper=never, **kwargs)['verifier_installed'] is None
|
|
|
|
|
|
# -- setting it up from the web UI ----------------------------------------------
|
|
|
|
class TestSetupFromTheWebUI:
|
|
def _host(self, monkeypatch, ready=False, active=True, restart_ok=True):
|
|
restarts = []
|
|
monkeypatch.setattr(au, 'helper_ready', lambda: ready)
|
|
monkeypatch.setattr(au, '_service_active', lambda unit: active)
|
|
monkeypatch.setattr(au, 'restart_service', lambda unit: restarts.append(unit) or restart_ok)
|
|
return restarts
|
|
|
|
def test_switching_on_restarts_the_display_to_finish_setup(self, monkeypatch):
|
|
restarts = self._host(monkeypatch)
|
|
note = au.start_setup_if_needed(False, ON)
|
|
assert restarts == ['ledmatrix']
|
|
assert 'display is restarting' in note
|
|
|
|
@pytest.mark.parametrize('was_enabled, config, ready', [
|
|
(True, ON, False), # already on: an unrelated save must not restart the display
|
|
(False, OFF, False), # still off
|
|
(False, ON, True), # already set up
|
|
])
|
|
def test_nothing_to_do(self, monkeypatch, was_enabled, config, ready):
|
|
restarts = self._host(monkeypatch, ready=ready)
|
|
assert au.start_setup_if_needed(was_enabled, config) is None
|
|
assert restarts == []
|
|
|
|
def test_a_stopped_display_is_not_started(self, monkeypatch):
|
|
restarts = self._host(monkeypatch, active=False)
|
|
assert 'next time the display service starts' in au.start_setup_if_needed(False, ON)
|
|
assert restarts == []
|
|
|
|
def test_a_failed_restart_says_so(self, monkeypatch):
|
|
self._host(monkeypatch, restart_ok=False)
|
|
assert 'Could not restart' in au.start_setup_if_needed(False, ON)
|
|
|
|
|
|
# -- plugins --------------------------------------------------------------------
|
|
|
|
class TestPlugins:
|
|
def test_nothing_changed_restarts_nothing(self, tmp_path):
|
|
store = FakeStore(tmp_path / 'plugins', {'clock': '1.0.0'})
|
|
updater, restarts = stub_updater(tmp_path, store=store)
|
|
updater.run()
|
|
assert store.updated_calls == ['clock']
|
|
assert restarts == []
|
|
|
|
def test_plugin_update_restarts_display_only(self, tmp_path):
|
|
store = FakeStore(tmp_path / 'plugins', {'clock': '1.0.0', 'weather': '1.0.0'},
|
|
bump={'weather'})
|
|
updater, restarts = stub_updater(tmp_path, store=store)
|
|
result = updater.run()
|
|
assert result['plugins_updated'] == ['weather']
|
|
assert restarts == ['ledmatrix']
|
|
|
|
def test_plugin_failure_alerts_but_keeps_weekly_cadence(self, tmp_path):
|
|
store = FakeStore(tmp_path / 'plugins', {'zip-only': '1.0.0'}, fail={'zip-only'})
|
|
updater, _ = stub_updater(tmp_path, store=store)
|
|
result = updater.run()
|
|
assert result['plugins_failed'] == ['zip-only'] and result['status'] == 'error'
|
|
state = au.load_state(updater.state_file)
|
|
assert 'zip-only' in state['alert']['message']
|
|
assert state['next_due'] == NIGHT + au.UPDATE_INTERVAL_SECONDS
|
|
|
|
def test_local_only_plugins_are_left_alone(self, tmp_path):
|
|
store = FakeStore(tmp_path / 'plugins', {'mine': '1.0.0'})
|
|
path = tmp_path / 'plugins' / 'mine' / 'manifest.json'
|
|
path.write_text(json.dumps({'id': 'mine', 'version': '1.0.0', 'local_only': True}))
|
|
updater, _ = stub_updater(tmp_path, store=store)
|
|
updater.run()
|
|
assert store.updated_calls == []
|
|
|
|
|
|
def test_restart_service_skips_a_stopped_unit(monkeypatch):
|
|
calls = []
|
|
|
|
def run(args, **kwargs):
|
|
calls.append(args)
|
|
return MagicMock(stdout='inactive\n', returncode=3, stderr='')
|
|
monkeypatch.setattr(au.subprocess, 'run', run)
|
|
assert au.restart_service('ledmatrix') is False
|
|
assert calls == [['systemctl', 'is-active', 'ledmatrix']], (
|
|
"a display the user stopped must not be started by an update")
|
|
|
|
|
|
def test_core_update_names_the_requirement_files_that_failed():
|
|
"""The health check refuses code whose dependencies did not install, so
|
|
the failure has to arrive as data, not only as a sentence in the message."""
|
|
from web_interface.blueprints import api_v3 as pkg
|
|
from web_interface.blueprints.api_v3 import system
|
|
|
|
heads = iter(['aaa111\n', 'bbb222\n'])
|
|
|
|
def run(args, **kwargs):
|
|
if args[:2] == ['git', 'rev-parse'] and args[-1] == 'HEAD':
|
|
out = next(heads, 'bbb222\n')
|
|
elif args[:2] == ['git', 'diff']:
|
|
out = 'requirements.txt\n'
|
|
elif '@{u}' in args:
|
|
out = 'origin/main\n'
|
|
else:
|
|
out = ''
|
|
return subprocess.CompletedProcess(args, 0, stdout=out, stderr='')
|
|
|
|
pkg.api_v3.plugin_store_manager = None
|
|
failed_install = subprocess.CompletedProcess([], 1, stdout='', stderr='boom')
|
|
with patch.object(pkg.subprocess, 'run', run), \
|
|
patch.object(system, '_pip_install_requirements', return_value=failed_install):
|
|
result = system.perform_core_update()
|
|
assert result['status'] == 'success'
|
|
assert result['dependency_failures'] == ['requirements.txt']
|
|
|
|
|
|
# -- web routes -------------------------------------------------------------------
|
|
|
|
@pytest.fixture
|
|
def api_client(monkeypatch):
|
|
from flask import Flask
|
|
from web_interface.blueprints.api_v3 import api_v3
|
|
app = Flask(__name__)
|
|
app.register_blueprint(api_v3, url_prefix='/api/v3')
|
|
cm = MagicMock()
|
|
cm.load_config.return_value = {'timezone': 'UTC', 'auto_update': {'enabled': True}}
|
|
cm.get_raw_file_content.return_value = {}
|
|
cm.save_config_atomic.return_value = MagicMock(status=MagicMock(value='success'), message=None)
|
|
api_v3.config_manager = cm
|
|
api_v3.plugin_manager = MagicMock(plugins={})
|
|
# Never restart a real display from a test run.
|
|
setup_calls = []
|
|
monkeypatch.setattr(au, 'start_setup_if_needed',
|
|
lambda was_enabled, config: setup_calls.append(was_enabled) or None)
|
|
return app.test_client(), cm, setup_calls
|
|
|
|
|
|
class TestStatusRoutes:
|
|
def test_status_carries_the_alert(self, api_client, monkeypatch):
|
|
client, _, _ = api_client
|
|
monkeypatch.setattr(au, 'describe_status', lambda config: {'alert': 'rolled back', 'alert_id': '7'})
|
|
data = client.get('/api/v3/system/auto-update').get_json()['data']
|
|
assert data == {'alert': 'rolled back', 'alert_id': '7'}
|
|
|
|
@pytest.mark.parametrize('body', [{}, [1], 'x', 5])
|
|
def test_dismiss_needs_an_id_in_a_json_object(self, api_client, body):
|
|
client, _, _ = api_client
|
|
assert client.post('/api/v3/system/auto-update/dismiss', json=body).status_code == 400
|
|
|
|
def test_dismiss(self, api_client, monkeypatch):
|
|
client, _, _ = api_client
|
|
calls = []
|
|
monkeypatch.setattr(au, 'dismiss_alert', calls.append)
|
|
assert client.post('/api/v3/system/auto-update/dismiss', json={'alert_id': '7'}).status_code == 200
|
|
assert calls == ['7']
|
|
|
|
|
|
class TestSettingsSave:
|
|
def _saved(self, cm):
|
|
return cm.save_config_atomic.call_args[0][0]
|
|
|
|
def test_checked_toggle_saves_enabled(self, api_client):
|
|
client, cm, setup_calls = api_client
|
|
cm.load_config.return_value = {'timezone': 'UTC'}
|
|
resp = client.post('/api/v3/config/main', json={'timezone': 'UTC', 'auto_update_enabled': 'true'})
|
|
assert resp.status_code == 200
|
|
saved = self._saved(cm)
|
|
assert saved['auto_update'] == {'enabled': True}
|
|
assert 'auto_update_enabled' not in saved, "the form field must not leak into config.json"
|
|
assert setup_calls == [False], "setup is told the toggle was previously off"
|
|
|
|
def test_unchecked_toggle_on_general_save_disables(self, api_client):
|
|
client, cm, setup_calls = api_client
|
|
# The General form marks its posts; an unchecked box is then absent.
|
|
resp = client.post('/api/v3/config/main',
|
|
json={'__form_section': 'general', 'timezone': 'UTC'})
|
|
assert resp.status_code == 200
|
|
assert self._saved(cm)['auto_update'] == {'enabled': False}
|
|
assert setup_calls == [True]
|
|
|
|
def test_setup_note_reaches_the_user(self, api_client, monkeypatch):
|
|
client, cm, _ = api_client
|
|
cm.load_config.return_value = {'timezone': 'UTC'}
|
|
monkeypatch.setattr(au, 'start_setup_if_needed',
|
|
lambda was_enabled, config: 'Finishing automatic update setup: the display is restarting.')
|
|
body = client.post('/api/v3/config/main',
|
|
json={'timezone': 'UTC', 'auto_update_enabled': 'true'}).get_json()
|
|
assert 'the display is restarting' in body['message']
|