diff --git a/.githooks/pre-push b/.githooks/pre-push index e6302a3..4a71768 100755 --- a/.githooks/pre-push +++ b/.githooks/pre-push @@ -3,7 +3,7 @@ # Local SonarQube freshness and BUG/VULNERABILITY ratchet when SONAR_TOKEN is set. # This hook does not run sonar-scanner; run bash scripts/sonar_scan.sh first. # Tier-A stays opt-in (INSTALL_PRE_PUSH=1). Disable Tier-A: rm .githooks/enable-pre-push -# Skip the Sonar checks: SKIP_LOCAL_SONAR=1 git push +# Skip the Sonar checks (and the shell warning): SKIP_LOCAL_SONAR=1 git push # Skip Python coverage: SKIP_PYTHON_COVERAGE=1 git push (CI does not honor that) # Skip types and file sizes: SKIP_QUALITY_CHECKS=1 / SKIP_PYTHON_TYPES=1 (CI honors neither) # Shell coverage runs with the opt-in Tier-A hook below, and always in CI. @@ -47,6 +47,16 @@ if [ "${SKIP_QUALITY_CHECKS:-0}" != "1" ] || [ "${CI:-}" = "true" ]; then "${ROOT}/scripts/check-file-sizes.sh" --strict fi +# SonarCloud analyzes shell and the local Community Build does not. This warns about +# new "[" tests (S7688), the rule SonarCloud reports most. It never blocks a push. +if [ "${SKIP_LOCAL_SONAR:-0}" != "1" ]; then + shell_rc=0 + "${ROOT}/scripts/check-sonar-shell-newcode.sh" || shell_rc=$? + if [ "${shell_rc}" -eq 1 ]; then + echo "pre-push: SonarCloud will likely flag the '[' tests above. The push is not blocked." >&2 + fi +fi + if [ ! -f "${ROOT}/.githooks/enable-pre-push" ]; then exit 0 fi diff --git a/AGENTS.md b/AGENTS.md index 3d5fcce..9a374e3 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -95,6 +95,7 @@ We follow [OpenAI harness engineering](https://openai.com/index/harness-engineer 2. For `lib/` or entrypoint script changes: `./scripts/run-security-scan.sh --ci --with-tests` (or at least `--ci`). 3. Update [docs/SAFETY.md](docs/SAFETY.md) and/or `dev-docs/` if behavior changed ([versioning guide](dev-docs/development/versioning.md)). 4. Confirm [docs/SAFETY.md](docs/SAFETY.md) checklist still passes. +5. Shell findings: local Sonar skips `.sh`. Before a push run `./scripts/check-sonar-shell-newcode.sh`; after it run `python3 scripts/sonarcloud_pr_issues.py --wait 180`. ## Git hooks (local) diff --git a/CHANGELOG.md b/CHANGELOG.md index 64d6c6a..d57606e 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -9,6 +9,8 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0 ### Added +- **Shell findings from SonarCloud, locally:** The local SonarQube Community Build has no Shell analyzer, so `sonar_scan.sh` never reported the shell findings that SonarCloud shows on a PR. `scripts/check-sonar-shell-newcode.sh` approximates the most common one (S7688, use `[[`) on lines added since the merge base, using ShellCheck's `require-double-brackets`. The pre-push hook runs it as a non-blocking warning. `scripts/sonarcloud_pr_issues.py` prints SonarCloud's real new-code issues for the current PR after a push, and `--wait` polls until the analysis matches your HEAD. Both have tests. No runtime behavior changed. +- **Test coverage:** Shell coverage of `lib/*.sh` in Tier-A rises from 16.2% to 26.1% on macOS and from 16.9% to about 26.7% on Ubuntu. Python coverage of `lib/*.py` rises from 31.5% to 99.2%. New Tier-A scripts cover `config-popup-size.sh`, `config-safety.sh`, `time-calculations.sh`, `scheduler-platform.sh` and `resolution-detection.sh`. `tests/test-configure-dialogs-darwin-ui.py` covers every macOS configure-dialog module with fake tkinter widgets and needs no display. Nineteen fast, hermetic scripts moved from Tier-B to Tier-A so the coverage gate counts them. The three `configure.sh` scripts stay in Tier-B. Both coverage floors rise to match. Tests only; runtime behavior is unchanged. The tests found three bugs, which are listed in `dev-docs/TO_DO.md`. - **App icon:** A crescent-moon-and-clock icon (`assets/icon.svg`) heads the README, which also gains status, license, and platform badges. Installers copy `assets/icon-256.png` to `~/.local/lib/sleep-warning/timerwarning-icon.png`. Linux warning popups and pause confirmations pass it to yad or zenity (`--window-icon`) or kdialog (`--icon`) when that tool's help lists the flag, so the taskbar can show it. The first warning in a process spends up to about two seconds on that help check; later warnings in the same process reuse the answer. On macOS the fullscreen tkinter blocker and the configure dialogs set the icon as the Dock icon. The osascript fallback keeps the system icon. `user-docs/MACOS.md` describes that split. A missing icon file leaves the default icon. Buttons and the watchdog are unchanged. Other candidate designs are in `assets/icon-candidates/`. - **Project license:** Source is available under the Apache License 2.0 with the Commons Clause License Condition v1.0. Personal use, modification, redistribution, and a company's own internal use stay allowed when the notices in `LICENSE` stay with the copy. Selling the software, as that condition defines Sell, is not allowed. This is source-available, not an OSI open-source license. Installed behavior is unchanged. - **Gamescope overlay debug flag:** `GAMESCOPE_OVERLAY_DEBUG` (default off) logs one `DEBUG-GAMESCOPE` block per gamescope warning spawn, countdown respawn, and pause notice when the experimental overlay path is active. The environment wins over the config file, including explicit false; a configure save keeps a key that is already in the file and does not write a temporary environment override. The flag does not change geometry, atoms, buttons, auto-close, or the watchdog. Minor capability; do not tag a release for this alone. Pointer behavior is unchanged. @@ -24,6 +26,8 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0 ### Fixed +- **Lock message end time and 24:00 ranges:** The configure lock error printed a blank end time (`Lock ends: today`) because it formatted `HH:MM` values, which `parse_config` and the lock-hour reader return, as bare hours. `calculate_restriction_end_time` and `show_config_locked_error` now share `format_endpoint_12h`, so the message reads `Lock ends: 5:30 AM today`. A range that ends at 24 or 24:00 (for example `16-24`) now reads as ending at 12:00 AM on the next day. It used to read 12:00 PM, and `build_weekly_restricted_intervals` dropped it, so the popup's next-unrestricted time treated that evening as free. `range_endpoint_to_day_minutes` takes an `end` role that accepts 24, as the 16-hour cap code already did. A range that ends at the week boundary (Saturday 24:00) now continues into Sunday in that search. `status.sh` and the configure range summary also print a 24:00 end as 12:00 AM. No restriction, lock, cap, or popup-lifetime check changed: the runtime restricted-time test already handled 24:00. +- **Wayland resolution detection:** `get_display_resolution` tests `A || B && C`, which Bash reads as `(A || B) && C`, so `WAYLAND_DISPLAY` alone never selected Wayland detection. It now does, with or without `XDG_SESSION_TYPE`. - **Pause notice icon:** The Linux "Pause Activated" dialog passes the same yad, zenity, and kdialog icon flags as the warning. A warning that already ran in that process supplies the cached help answer, so the notice does not probe again. The notice watchdog, buttons, and per-day cap are unchanged. - **Icon help probe:** The help check runs the command in its own process group and reads the result from a temporary file after that group is stopped. GNU `timeout` and `gtimeout` are not used: they return when the direct child exits and leave a descendant holding the pipe. A descendant that leaves the process group is not signalled, and it still cannot hold the popup, because the popup reads the file. The check sends SIGTERM after one second and SIGKILL one second later, or SIGKILL immediately if the leader exits sooner. The help file is capped at 2 MiB so a writer that leaves the process group cannot fill the disk. Popup buttons, the watchdog, and the per-day cap are unchanged. - **Greptile review fixes:** Pre-spawn gamescope root-size queries now have a roughly two-second deadline, kill and reap stalled probes, and use fallback dimensions on failure. The test runner preserves its selected Bash interpreter for child tests when PATH points to an older Bash. diff --git a/dev-docs/README.md b/dev-docs/README.md index 2e50d37..2aa7e0d 100644 --- a/dev-docs/README.md +++ b/dev-docs/README.md @@ -38,7 +38,7 @@ See [canonical-vs-archive.md](canonical-vs-archive.md) for what is current vs hi | [`plans/master/`](plans/master/) | [Master implementation plan](plans/master/linux-warning-system-plan.md) | | [`plans/phases/`](plans/phases/) | Phase 1–5 checklists, code-quality plan | | [`plans/`](plans/) | Active feature plans (in progress) | -| [Public repository preparation](plans/plan-public-repo-prep-2026-10-16.md) | Sanitized private staging copy. PayPal removal stays deferred. Next: CI and settings review; public visibility needs a separate approval | +| [Public repository preparation](completed-plans/plan-public-repo-prep-2026-10-16.md) | Complete and archived 2026-10-28. The repository is public. PayPal removal stays deferred | | [`completed-plans/plan-harness-engineering-improvements-2026-06-12.md`](completed-plans/plan-harness-engineering-improvements-2026-06-12.md) | **Complete** — Phases 0–8 (archived 2026-10-25) | | [`completed-plans/`](completed-plans/) | Finished or superseded implementation plans (archive) | @@ -65,4 +65,4 @@ See [canonical-vs-archive.md](canonical-vs-archive.md) for what is current vs hi - **Safety** overrides feature work — read [`docs/SAFETY.md`](../docs/SAFETY.md) before popup, scheduler, or config changes. - **Tests** during restricted hours: use a temp `HOME`; see [`.cursor/rules/config-file-edits.mdc`](../.cursor/rules/config-file-edits.mdc). -**Last updated:** 2026-06-12 (Phase 8 contributor guide; harness Phases 1–7 complete) +**Last updated:** 2026-10-28 (public repository plan archived; test coverage tiers and the SonarCloud shell checks documented) diff --git a/dev-docs/TO_DO.md b/dev-docs/TO_DO.md index 0f8586a..e0d6dce 100644 --- a/dev-docs/TO_DO.md +++ b/dev-docs/TO_DO.md @@ -22,7 +22,7 @@ Doc convention: **`docs/`** = end-users; **`dev-docs/`** = developers and agents - [x] **Linux popup watchdog (code, 2026-05-30)** — `lib/popup-display-linux.sh` uses `popup_compute_watchdog_seconds` + `popup_start_pid_file_watchdog`. Unit tests: `tests/test-popup-safety-linux.sh` (Tier-A on Linux CI, 2026-06-12 harness Phase 7). - [ ] **Linux popup watchdog (integration / display host)** — Optional follow-ups on a Linux machine with DISPLAY: - [x] Tier-A unit tests on `ubuntu-latest` CI (`test-popup-safety-linux.sh` via `./scripts/run-tests.sh --tier a`) - - [ ] `bash tests/test-config-locking.sh` and `bash tests/test-uninstall-lock-hours.sh` on GNU stat host (Tier-B; portable helpers exist) + - [x] `bash tests/test-config-locking.sh` and `bash tests/test-uninstall-lock-hours.sh` on a GNU stat host. Both are Tier-A now and pass on `ubuntu-latest` CI (2026-10-28). They need a non-root user, because they assert a locked directory is not writable. - [ ] `bash tests/test-popup.sh` with yad/zenity/kdialog available - [ ] Add `tests/test-popup-safety-linux-integration.sh` — wedge dialog, assert hard kill within cap (recommended) - [ ] Manual: `POPUP_AUTO_CLOSE=false` + stuck dialog → must terminate within `POPUP_ABSOLUTE_MAX_SECONDS` @@ -37,7 +37,7 @@ Doc convention: **`docs/`** = end-users; **`dev-docs/`** = developers and agents ## Testing (high impact) -- [ ] **Raise line coverage** — Add tests that execute untested `lib/*.py` and `lib/*.sh`, then raise the floors from a new measurement. Current floors: Python 260/826 with a display and 238/826 headless ([python-coverage-baseline.json](../scripts/python-coverage-baseline.json)); shell darwin 2922/18047 and linux 3054/18047 ([shell-coverage-baseline.json](../scripts/shell-coverage-baseline.json)). The configure-dialog UI modules are still unread as code. Do not lower a floor to make a run pass. +- [ ] **Raise line coverage** — Add tests that execute untested `lib/*.py` and `lib/*.sh`, then raise the floors from a new measurement. Current floors: Python 819/826 with or without a display ([python-coverage-baseline.json](../scripts/python-coverage-baseline.json)); shell darwin 4703/18047 and linux 4800/18047 ([shell-coverage-baseline.json](../scripts/shell-coverage-baseline.json)). The interactive shell modules (`configure-ui*.sh`, `configure-input-*.sh`, `configure-dialogs*.sh`, `configure-display-*.sh`) still have little or no coverage. Do not lower a floor to make a run pass. - [ ] **SteamOS Gaming Mode** — Full validation with full-screen games → [STEAMOS_GAMING_MODE.md](STEAMOS_GAMING_MODE.md), [phase 4 plan](plans/phases/plan-phase-4-testing.md) - [x] **2026-10-19 on-device:** popup **displays and stays up** in Gaming Mode (experimental overlay on) - [x] **Click-through + magnification (Phase 1 code):** full `:0` root-width gamescope dialogs + atom/geometry logging → [plan](completed-plans/plan-gamescope-overlay-click-through-2026-10-19.md) @@ -49,7 +49,7 @@ Doc convention: **`docs/`** = end-users; **`dev-docs/`** = developers and agents ## Documentation and release -- [ ] **Public repository preparation — next: private staging checks, then an explicit public-visibility decision** — [Publication plan](plans/plan-public-repo-prep-2026-10-16.md). History sanitization and the TimerWarning installation-name commit are in this repository. PayPal removal stays deferred. Do not make the repository public without a separate approval. +- [x] **Public repository preparation** — `kgrizz-git/TimerWarning` is public (2026-10-26); plan archived 2026-10-28 → [plan](completed-plans/plan-public-repo-prep-2026-10-16.md). Open residue: the install/status/help string check for the public name, and requiring the `security.yml` checks (Static analysis, Tier-A on Ubuntu and macOS) as status checks in the `Mainrules1` ruleset (it requires none today). Donation removal is the deferred item below. - [ ] **Donation cleanup — deferred 2026-10-24** — Leave existing PayPal links in place until the owner reopens this. Do not add donation integrations as part of publication preparation. Spec: [#27](enhancements/enhancement-27-paypal-donation-links.md). - [ ] **SteamOS locale docs** — User guide section (Nix + manual paths); do not automate `locale-gen` in install.sh → [REMAINING_WORK_SUMMARY.md](REMAINING_WORK_SUMMARY.md#documentation-work) @@ -90,4 +90,4 @@ Track detail in [REMAINING_WORK_SUMMARY.md](REMAINING_WORK_SUMMARY.md#mostly-imp **Plans index:** [Master plan](plans/master/linux-warning-system-plan.md) · [Active plans](plans/) · [Completed plans](completed-plans/) -**Last updated:** 2026-10-25 (publication Phase 3 done: stubs removed, completed plans archived, smoke items collected; PayPal removal and public rename deferred) +**Last updated:** 2026-10-28 (public repository plan archived; coverage tests added and 19 Tier-B scripts moved to Tier-A; PayPal removal deferred) diff --git a/dev-docs/plans/plan-public-repo-prep-2026-10-16.md b/dev-docs/completed-plans/plan-public-repo-prep-2026-10-16.md similarity index 92% rename from dev-docs/plans/plan-public-repo-prep-2026-10-16.md rename to dev-docs/completed-plans/plan-public-repo-prep-2026-10-16.md index da64763..5be7dd5 100644 --- a/dev-docs/plans/plan-public-repo-prep-2026-10-16.md +++ b/dev-docs/completed-plans/plan-public-repo-prep-2026-10-16.md @@ -4,7 +4,7 @@ **Revised:** 2026-10-26 -**Status:** Phases 1–4 applied. `kgrizz-git/TimerWarning` is public. On 2026-10-25 its CI was green, the full-history Gitleaks scan was clean, and the tracked file list matched the source. `main` is protected by the active ruleset `Mainrules1`. The classic protection API returns 404 because that protection is a ruleset. The ruleset does not require the Security workflow checks. Phase 5 still includes those required checks and archiving this plan. +**Status:** Complete; archived 2026-10-28. Three items stay open (donation removal, deferred by the owner; a final install/status/help string check; required `security.yml` status checks in the ruleset) and are tracked in `dev-docs/TO_DO.md`. Phases 1–4 applied. `kgrizz-git/TimerWarning` is public. On 2026-10-25 its CI was green, the full-history Gitleaks scan was clean, and the tracked file list matched the source. `main` is protected by the active ruleset `Mainrules1`. The classic protection API returns 404 because that protection is a ruleset. As of 2026-10-28 the ruleset still requires no status checks: none of the `security.yml` jobs (Static analysis, Tier-A on Ubuntu and macOS). Adding them is open and tracked in `dev-docs/TO_DO.md`. **Working branch:** `chore/public-repo-prep-phase-1` for phases 1–4, based on `main` at `86cfc7a`. That name is historical; it is not the branch for later icon work. @@ -258,9 +258,11 @@ changes or forbidden reachable material, reproducible private audit record. in `LICENSE`). `git clone --depth 1 https://github.com/kgrizz-git/TimerWarning.git` succeeded, and `git rev-parse HEAD` in that clone was `a664b8e4a372f23489da24172616c55772691cff`. -7. Archive this plan under `dev-docs/completed-plans/` after final status and - any residual work are recorded. Keep source `LinuxTimerWarning` private - unless separately directed. +7. [x] This plan was archived under `dev-docs/completed-plans/` on 2026-10-28. + The residual work is in `dev-docs/TO_DO.md`: require the `security.yml` checks + (Static analysis, Tier-A on Ubuntu and macOS) on `main`, the install/status/help string check, and donation + removal. + Keep source `LinuxTimerWarning` private unless separately directed. ## Verification and delivery gates @@ -270,7 +272,7 @@ changes or forbidden reachable material, reproducible private audit record. | Phases 1–3 | `./scripts/check-doc-drift.sh --strict`; `./scripts/check-stale-plans.sh --strict`; license/link/donation/branding checks | | Shell or entrypoint changes | Targeted regressions, temp-HOME `CI_HEADLESS=1 ./scripts/run-tests.sh --tier a`, and `./scripts/run-security-scan.sh --ci`; normal hooks intact | | Sanitized export | All preceding checks plus reachable-history privacy scan, `git fsck`, source/export comparison | -| Public release | Destination is public. `Mainrules1` protects `main`. `git clone --depth 1` of the public URL succeeded at `a664b8e`, and the GitHub description is set. Remaining: require the Security workflow checks, then archive this plan | +| Public release | Destination is public. `Mainrules1` protects `main`. `git clone --depth 1` of the public URL succeeded at `a664b8e`, and the GitHub description is set. Remaining: require the `security.yml` checks (Static analysis, Tier-A on Ubuntu and macOS) on `main` (open, tracked in `dev-docs/TO_DO.md`). This plan was archived 2026-10-28 | Follow the operational rules in AGENTS: never unbounded configure menus; timeout, controlled stdin, and bounded output are all required if a menu test is necessary. @@ -281,7 +283,7 @@ CI-green, and merged states separately. Branch cleanup is not release completion **Next action:** `kgrizz-git/TimerWarning` is already public. Phase 5 step 6 is done: `git clone --depth 1` of the public URL succeeded at `a664b8e`, and the -GitHub description is set. Remaining Phase 5 work is to require the Security -workflow checks on `main`, then archive this plan. PayPal removal stays -deferred. Do not rewrite this history again, and do not change the private +GitHub description is set. This plan is archived. The one remaining Phase 5 item +is to require the `security.yml` checks (Static analysis, Tier-A on +Ubuntu and macOS) on `main`, which `dev-docs/TO_DO.md` tracks. PayPal removal stays deferred. Do not rewrite this history again, and do not change the private source repository's history. diff --git a/dev-docs/development/security-scanning.md b/dev-docs/development/security-scanning.md index 441b399..bb7b018 100644 --- a/dev-docs/development/security-scanning.md +++ b/dev-docs/development/security-scanning.md @@ -60,7 +60,7 @@ pip install semgrep Retention policy: [doc-retention.md](doc-retention.md). Skip archive report: `SKIP_ARCHIVE_REPORT=1`. -**pre-push** runs [scripts/check-sonar-freshness.sh](../../scripts/check-sonar-freshness.sh), [scripts/check_sonar_issues.py](../../scripts/check_sonar_issues.py), and [scripts/check-python-coverage.sh](../../scripts/check-python-coverage.sh). The Sonar checks do not start `sonar-scanner`. When `SONAR_TOKEN` is set, the recorded scan in `tmp/sonar-state.json` must match each commit being pushed and the same host; otherwise run [scripts/sonar_scan.sh](../../scripts/sonar_scan.sh) and push again. The issue check fails when a `BUG` or `VULNERABILITY` count rises for the same rule and file. The Python coverage check fails when `lib/*.py` line coverage drops below the display or headless ratio in [scripts/python-coverage-baseline.json](../../scripts/python-coverage-baseline.json). The shell coverage check ([scripts/check-shell-coverage.sh](../../scripts/check-shell-coverage.sh)), which runs with the opt-in Tier-A hook, fails when traced `lib/*.sh` lines drop below [scripts/shell-coverage-baseline.json](../../scripts/shell-coverage-baseline.json). `SKIP_SHELL_COVERAGE=1` or `SKIP_PRE_PUSH_TESTS=1` skips that check locally. CI does not honor it. `localhost`, `[::1]`, and `127.0.0.1` count as the same Sonar host when the scheme and port match. Copy [.env.example](../../.env.example) and `chmod 600 .env`. The token stays in `.env`, which is gitignored. `SKIP_LOCAL_SONAR=1` skips the Sonar checks. `SKIP_PYTHON_COVERAGE=1` skips coverage locally; CI does not honor it. Details: [sonarqube.md](sonarqube.md). Tier-A stays opt-in: `INSTALL_PRE_PUSH=1 ./scripts/install-git-hooks.sh` enables it via [scripts/pre-push-checks.sh](../../scripts/pre-push-checks.sh). Disable Tier-A: `rm .githooks/enable-pre-push`. The local server is separate from the SonarCloud GitHub app. The local Community Build analyzes Python only. +**pre-push** runs [scripts/check-sonar-freshness.sh](../../scripts/check-sonar-freshness.sh), [scripts/check_sonar_issues.py](../../scripts/check_sonar_issues.py), and [scripts/check-python-coverage.sh](../../scripts/check-python-coverage.sh). The Sonar checks do not start `sonar-scanner`. When `SONAR_TOKEN` is set, the recorded scan in `tmp/sonar-state.json` must match each commit being pushed and the same host; otherwise run [scripts/sonar_scan.sh](../../scripts/sonar_scan.sh) and push again. The issue check fails when a `BUG` or `VULNERABILITY` count rises for the same rule and file. The Python coverage check fails when `lib/*.py` line coverage drops below the display or headless ratio in [scripts/python-coverage-baseline.json](../../scripts/python-coverage-baseline.json). The shell coverage check ([scripts/check-shell-coverage.sh](../../scripts/check-shell-coverage.sh)), which runs with the opt-in Tier-A hook, fails when traced `lib/*.sh` lines drop below [scripts/shell-coverage-baseline.json](../../scripts/shell-coverage-baseline.json). `SKIP_SHELL_COVERAGE=1` or `SKIP_PRE_PUSH_TESTS=1` skips that check locally. CI does not honor it. `localhost`, `[::1]`, and `127.0.0.1` count as the same Sonar host when the scheme and port match. Copy [.env.example](../../.env.example) and `chmod 600 .env`. The token stays in `.env`, which is gitignored. `SKIP_LOCAL_SONAR=1` skips the Sonar checks. `SKIP_PYTHON_COVERAGE=1` skips coverage locally; CI does not honor it. Details: [sonarqube.md](sonarqube.md). Tier-A stays opt-in: `INSTALL_PRE_PUSH=1 ./scripts/install-git-hooks.sh` enables it via [scripts/pre-push-checks.sh](../../scripts/pre-push-checks.sh). Disable Tier-A: `rm .githooks/enable-pre-push`. The local server is separate from the SonarCloud GitHub app. The local Community Build analyzes Python only: it has no Shell analyzer, so `sonar_scan.sh` never sees `.sh` files. SonarCloud does analyze them (rules `shell:S7688` use `[[`, `shelldre:S1192` repeated literals, `shelldre:S7679` positional parameters, `shelldre:S131` case without a default, `shelldre:S1066` nested ifs). Two scripts close the gap. [scripts/check-sonar-shell-newcode.sh](../../scripts/check-sonar-shell-newcode.sh) runs ShellCheck's `require-double-brackets` check on lines added since the merge base and approximates S7688. The pre-push hook runs it as a warning. On PR #3 it found all 28 S7688 findings that SonarCloud reported, plus a few extra lines. [scripts/sonarcloud_pr_issues.py](../../scripts/sonarcloud_pr_issues.py) reads SonarCloud's real new-code issues for the pull request after a push. Run `python3 scripts/sonarcloud_pr_issues.py --wait 180` to wait for the analysis of your HEAD. It needs no token because the project is public. **Quality gates** (Ruff, shell complexity, file sizes, types). Install the pinned tools with `pip install -r requirements-dev.txt`. Settings are in `pyproject.toml`. - **Ruff** checks `E`, `F`, and McCabe `C901` (ceiling 19, measured on `lib/` and `scripts/`; tests are exempt from `C901`). Line length is 120. The few diagnostics that existed when the gate was added are recorded as `per-file-ignores` in `pyproject.toml`. Do not add to them. diff --git a/dev-docs/info/GITHUB_SPONSORS_ELIGIBILITY.md b/dev-docs/info/GITHUB_SPONSORS_ELIGIBILITY.md index 8ab2c27..137589e 100644 --- a/dev-docs/info/GITHUB_SPONSORS_ELIGIBILITY.md +++ b/dev-docs/info/GITHUB_SPONSORS_ELIGIBILITY.md @@ -87,7 +87,7 @@ Non-commercial licenses (like License Zero Noncommercial) are **not OSI-approved For the TimerWarning project, as of the 2026-10-24 license decision: - **License**: [`LICENSE`](../../LICENSE) is the Apache License 2.0 with the Commons Clause. That combination is source-available. It is not an OSI open-source license, so this repository does not by itself meet a Sponsors requirement for an open-source license. -- **Publication**: The development repository is still private. A public staging repository is later work in the [publication plan](../plans/plan-public-repo-prep-2026-10-16.md). +- **Publication**: `kgrizz-git/TimerWarning` has been public since 2026-10-26. See the archived [publication plan](../completed-plans/plan-public-repo-prep-2026-10-16.md). - **Donations**: PayPal links stay until the owner reopens removal (deferred 2026-10-24). This note does not add a donation integration. **Conclusion**: Do not treat the current license as satisfying GitHub Sponsors' open-source-license expectation. diff --git a/dev-docs/testing-assessments/test-tiers.md b/dev-docs/testing-assessments/test-tiers.md index 3f61e64..b20808b 100644 --- a/dev-docs/testing-assessments/test-tiers.md +++ b/dev-docs/testing-assessments/test-tiers.md @@ -19,6 +19,14 @@ Fast, headless, no live installed config. Default timeout 300s per script. | `test-popup-safety-darwin.sh` | Watchdog unit tests — **macOS CI only** | | `test-popup-safety-linux.sh` | Watchdog + PID-file kill — **Linux CI only** | | `test-configure-partial-lock.sh` | Tighten-only configure wizard | +| `test-popup-size-config.sh` | Popup size getters, fixed and display-based dimensions, 95% clamp | +| `test-config-safety.sh` | Default hours, runtime cap inputs, runtime cap gate, wizard default fill | +| `test-time-calculations.sh` | Range durations, weekly intervals, next unrestricted time, restriction end time | +| `test-sonar-shell-newcode.sh` | The SonarCloud `[` vs `[[` check on new code, in a throwaway git repo | +| `test-config-locked-message.sh` | Text of the configure lock error: active range, end time, end day | +| `test-scheduler-platform.sh` | systemd and launchd helpers with a stubbed `systemctl` | +| `test-resolution-detection-stubbed.sh` | xrandr, Wayland and gamescope resolution detection with stub tools | +| `test-configure-dialogs-darwin-ui.py` | macOS configure dialogs with fake tkinter widgets (run by the Python coverage gate, not `run-tests.sh`) | | `test-platform-darwin.sh` | Platform detection, plist math — **macOS only** | | `test-darwin-configure-gui.sh` | **macOS only**; **requires GUI** — skipped when `CI_HEADLESS=1` | @@ -37,7 +45,7 @@ Temp-`HOME` and module smokes. Run in batches with `timeout`; see [platform-test ./scripts/run-tests.sh --tier b ``` -Includes configure text-mode, modular refactor checks, lock-hour phases, Darwin grid cache, pause/popup interval tests. +Includes the configure text-mode, modular, blocking, and GUI-split scripts. They call `configure.sh`, so they stay out of Tier-A. The lock-hour phases, Darwin grid cache, and pause and popup interval scripts that used to be here moved to Tier-A on 2026-10-28, because the shell coverage floor only counts Tier-A. ## Tier C — Manual / multi-host diff --git a/lib/configure-core.sh b/lib/configure-core.sh index 5be8ce2..e80dc2f 100644 --- a/lib/configure-core.sh +++ b/lib/configure-core.sh @@ -13,6 +13,7 @@ # - has_gui() - Check if GUI is available # - minutes_to_oncalendar() - Convert minutes to systemd OnCalendar format # - format_hour_12h() - Format hour to 12-hour format with AM/PM +# - format_endpoint_12h() - Format a range endpoint (H, HH:MM, 24:00) to 12-hour format # - get_threshold_warn_description() - Get human-readable warning threshold description # - get_threshold_block_description() - Get human-readable block threshold description # - day_num_to_name_upper() - Convert day number to uppercase day name (for config file) @@ -355,6 +356,34 @@ format_hour_12h() { fi } +# Format a range endpoint as "H:MM AM/PM". +# Accepts a bare hour ("5", "05") or "H:MM" / "HH:MM", the forms parse_config and +# the lock-hour readers return. A bare hour prints ":00", so "5" matches +# format_hour_12h. An end of 24 or 24:00 is midnight and prints "12:00 AM". +# Prints nothing and returns 1 for anything else. +format_endpoint_12h() { + local part="${1//[[:space:]]/}" + local hour minute display ampm + if [[ "${part}" =~ ^([0-9]{1,2})(:([0-9]{2}))?$ ]]; then + hour=$((10#${BASH_REMATCH[1]})) + minute=$((10#${BASH_REMATCH[3]:-0})) + else + return 1 + fi + if [[ "${minute}" -gt 59 || "${hour}" -gt 24 || ( "${hour}" -eq 24 && "${minute}" -ne 0 ) ]]; then + return 1 + fi + ampm="AM" + if [[ "${hour}" -ge 12 && "${hour}" -lt 24 ]]; then + ampm="PM" + fi + display=$((hour % 12)) + if [[ "${display}" -eq 0 ]]; then + display=12 + fi + printf '%d:%02d %s\n' "${display}" "${minute}" "${ampm}" +} + # Get human-readable description of warning threshold # Returns: "X hours/day" format get_threshold_warn_description() { diff --git a/lib/configure-ui-errors.sh b/lib/configure-ui-errors.sh index 5d02a87..103b02b 100644 --- a/lib/configure-ui-errors.sh +++ b/lib/configure-ui-errors.sh @@ -28,7 +28,7 @@ _configure_ui_errors_ensure_deps() { # shellcheck disable=SC1091 [ -f "${_dir}/time-parsing.sh" ] && source "${_dir}/time-parsing.sh" fi - if ! type format_hour_12h >/dev/null 2>&1 || ! type format_ranges_human >/dev/null 2>&1; then + if ! type format_hour_12h >/dev/null 2>&1 || ! type format_endpoint_12h >/dev/null 2>&1 || ! type format_ranges_human >/dev/null 2>&1; then local _dir _dir="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)" # shellcheck disable=SC1091 @@ -439,7 +439,7 @@ show_config_locked_error() { end_part=$(echo "${end_part}" | sed 's/^[[:space:]]*//;s/[[:space:]]*$//') if range_overnight_tail_active_for_hour "${current_hour}" "${start_part}" "${end_part}"; then local end_12h - end_12h=$(format_hour_12h "${end_part}") + end_12h=$(format_endpoint_12h "${end_part}") || continue lock_end="${end_12h}|${day_name}|true" break fi @@ -526,7 +526,7 @@ show_config_locked_error() { end_part=$(echo "${end_part}" | sed 's/^[[:space:]]*//;s/[[:space:]]*$//') if range_overnight_tail_active_for_hour "${current_hour}" "${start_part}" "${end_part}"; then local end_12h - end_12h=$(format_hour_12h "${end_part}") + end_12h=$(format_endpoint_12h "${end_part}") || continue end_info="${end_12h}|${day_name}|true" break fi diff --git a/lib/resolution-detection.sh b/lib/resolution-detection.sh index c215777..8b27fa3 100644 --- a/lib/resolution-detection.sh +++ b/lib/resolution-detection.sh @@ -45,7 +45,7 @@ get_display_resolution() { if [ -n "${DISPLAY}" ]; then # X11 session display_env="x11" - elif [ -n "${WAYLAND_DISPLAY}" ] || [ -n "${XDG_SESSION_TYPE}" ] && [ "${XDG_SESSION_TYPE}" = "wayland" ]; then + elif [[ -n "${WAYLAND_DISPLAY}" || "${XDG_SESSION_TYPE}" == "wayland" ]]; then # Wayland session display_env="wayland" elif pgrep -x gamescope >/dev/null 2>&1; then diff --git a/lib/status-config-display.sh b/lib/status-config-display.sh index 386414d..d1b4d98 100644 --- a/lib/status-config-display.sh +++ b/lib/status-config-display.sh @@ -5,6 +5,33 @@ # Sourced by status.sh (requires print_header, print_status, COLOR_*, CONFIG_FILE) ############################################################################### +# Labels that several status lines repeat. +_STATUS_DISABLED="Disabled" +_STATUS_WARNING="warning" +_STATUS_PAUSE_LABEL="Pause Status" + +# Value of KEY= in the config file: first match, whitespace removed. Empty when absent. +_status_config_value() { + local key="$1" + grep -E "^[[:space:]]*${key}=" "${CONFIG_FILE}" 2>/dev/null | head -n1 | cut -d'=' -f2 | tr -d '[:space:]' +} + +# Same, lowercased. +_status_config_value_lower() { + local key="$1" + _status_config_value "${key}" | tr '[:upper:]' '[:lower:]' +} + +# Format an epoch timestamp with the given date format. GNU date reads "@TS" with -d, +# BSD date reads the epoch with -r. Prints "unknown" when neither works. +_status_format_epoch() { + local timestamp="$1" + local format="$2" + date -d "@${timestamp}" +"${format}" 2>/dev/null \ + || date -r "${timestamp}" +"${format}" 2>/dev/null \ + || echo "unknown" +} + # Format a 24-hour time string "HH[:MM]" to 12-hour format with AM/PM format_hour_12h() { local time_str="$1" @@ -24,17 +51,18 @@ format_hour_12h() { return 0 fi - local display_hour="${hour}" - local ampm="AM" + # Zero-padded input ("08", "09") is not octal: convert once, then use the numbers. + hour=$((10#${hour})) + minute=$((10#${minute})) - if [ "${hour}" -ge 12 ]; then + local ampm="AM" + # 24:00 is midnight at the end of the day, so it stays AM. + if [[ "${hour}" -ge 12 && "${hour}" -lt 24 ]]; then ampm="PM" - if [ "${hour}" -gt 12 ]; then - display_hour=$((hour - 12)) - fi fi - if [ "${display_hour}" -eq 0 ]; then + local display_hour=$((hour % 12)) + if [[ "${display_hour}" -eq 0 ]]; then display_hour=12 fi @@ -44,8 +72,8 @@ format_hour_12h() { # Format a single range to human-readable format format_range_human() { local range="$1" - local day_name="$2" - + # $2 (the day name) is accepted for callers' sake and not used. + local start_raw end_raw start_raw=$(echo "${range}" | cut -d'-' -f1) end_raw=$(echo "${range}" | cut -d'-' -f2) @@ -79,15 +107,10 @@ format_range_human() { if [[ "${shour}" =~ ^[0-9]+$ ]] && [[ "${smin}" =~ ^[0-9]+$ ]] && \ [[ "${ehour}" =~ ^[0-9]+$ ]] && [[ "${emin}" =~ ^[0-9]+$ ]]; then - local shour_p ehour_p smin_p emin_p - printf -v shour_p "%02d" "${shour}" - printf -v ehour_p "%02d" "${ehour}" - printf -v smin_p "%02d" "${smin}" - printf -v emin_p "%02d" "${emin}" - + # HHMM as a number. 10# keeps "08" and "09" out of octal (printf %02d fails on them). local start_total end_total - start_total=$((10#${shour_p}${smin_p})) - end_total=$((10#${ehour_p}${emin_p})) + start_total=$((10#${shour} * 100 + 10#${smin})) + end_total=$((10#${ehour} * 100 + 10#${emin})) if [ "${start_total}" -gt "${end_total}" ]; then overnight="true" @@ -140,9 +163,9 @@ show_configuration() { # Read popup display frequency (Enhancement #30); fallback CHECK_INTERVAL for migration local popup_freq - popup_freq=$(grep -E "^[[:space:]]*POPUP_DISPLAY_FREQUENCY=" "${CONFIG_FILE}" 2>/dev/null | head -n1 | cut -d'=' -f2 | tr -d '[:space:]') + popup_freq=$(_status_config_value POPUP_DISPLAY_FREQUENCY) if [ -z "${popup_freq}" ]; then - popup_freq=$(grep -E "^[[:space:]]*CHECK_INTERVAL=" "${CONFIG_FILE}" 2>/dev/null | head -n1 | cut -d'=' -f2 | tr -d '[:space:]') + popup_freq=$(_status_config_value CHECK_INTERVAL) fi if [ -z "${popup_freq}" ]; then popup_freq="10 (default)" @@ -153,7 +176,7 @@ show_configuration() { # Read popup size local popup_size - popup_size=$(grep -E "^[[:space:]]*POPUP_SIZE=" "${CONFIG_FILE}" 2>/dev/null | head -n1 | cut -d'=' -f2 | tr -d '[:space:]') + popup_size=$(_status_config_value POPUP_SIZE) # Format with dimensions if get_popup_dimensions function is available local display_size @@ -173,7 +196,7 @@ show_configuration() { # Check if it's a custom size - if so, read the custom size value if [ "${popup_size}" = "custom" ]; then local custom_size - custom_size=$(grep -E "^[[:space:]]*POPUP_SIZE_CUSTOM=" "${CONFIG_FILE}" 2>/dev/null | head -n1 | cut -d'=' -f2 | tr -d '[:space:]') + custom_size=$(_status_config_value POPUP_SIZE_CUSTOM) if [ -n "${custom_size}" ]; then # Show custom size value (e.g., "95%x95%") if type get_popup_dimensions >/dev/null 2>&1; then @@ -220,7 +243,7 @@ show_configuration() { # Read popup position local popup_position - popup_position=$(grep -E "^[[:space:]]*POPUP_POSITION=" "${CONFIG_FILE}" 2>/dev/null | head -n1 | cut -d'=' -f2 | tr -d '[:space:]') + popup_position=$(_status_config_value POPUP_POSITION) if [ -z "${popup_position}" ]; then popup_position="center (default)" fi @@ -228,11 +251,11 @@ show_configuration() { # Read minimum display time local min_display_time - min_display_time=$(grep -E "^[[:space:]]*POPUP_MIN_DISPLAY_TIME=" "${CONFIG_FILE}" 2>/dev/null | head -n1 | cut -d'=' -f2 | tr -d '[:space:]') + min_display_time=$(_status_config_value POPUP_MIN_DISPLAY_TIME) if [ -z "${min_display_time}" ]; then min_display_time="30 seconds (default)" elif [ "${min_display_time}" -eq 0 ]; then - min_display_time="Disabled" + min_display_time="${_STATUS_DISABLED}" else min_display_time="${min_display_time} seconds" fi @@ -240,31 +263,31 @@ show_configuration() { # Read popup immovable setting local popup_immovable - popup_immovable=$(grep -E "^[[:space:]]*POPUP_IMMOVABLE=" "${CONFIG_FILE}" 2>/dev/null | head -n1 | cut -d'=' -f2 | tr -d '[:space:]' | tr '[:upper:]' '[:lower:]') + popup_immovable=$(_status_config_value_lower POPUP_IMMOVABLE) if [ -z "${popup_immovable}" ]; then popup_immovable="true (default)" elif [ "${popup_immovable}" = "true" ] || [ "${popup_immovable}" = "1" ] || [ "${popup_immovable}" = "yes" ]; then popup_immovable="Enabled" else - popup_immovable="Disabled" + popup_immovable="${_STATUS_DISABLED}" fi print_status "Prevent Window Movement" "${popup_immovable}" # Read configure block enabled setting (Enhancement #19) local configure_block_enabled - configure_block_enabled=$(grep -E "^[[:space:]]*CONFIGURE_BLOCK_ENABLED=" "${CONFIG_FILE}" 2>/dev/null | head -n1 | cut -d'=' -f2 | tr -d '[:space:]' | tr '[:upper:]' '[:lower:]') + configure_block_enabled=$(_status_config_value_lower CONFIGURE_BLOCK_ENABLED) if [ -z "${configure_block_enabled}" ]; then configure_block_enabled="Disabled (default)" elif [ "${configure_block_enabled}" = "true" ] || [ "${configure_block_enabled}" = "1" ] || [ "${configure_block_enabled}" = "yes" ]; then configure_block_enabled="Enabled" else - configure_block_enabled="Disabled" + configure_block_enabled="${_STATUS_DISABLED}" fi print_status "Block Scripts During Restricted Hours" "${configure_block_enabled}" # Read uninstall protection mode setting (Enhancement #26) local uninstall_protection_mode - uninstall_protection_mode=$(grep -E "^[[:space:]]*UNINSTALL_PROTECTION_MODE=" "${CONFIG_FILE}" 2>/dev/null | head -n1 | cut -d'=' -f2 | tr -d '[:space:]' | tr '[:upper:]' '[:lower:]') + uninstall_protection_mode=$(_status_config_value_lower UNINSTALL_PROTECTION_MODE) if [ -z "${uninstall_protection_mode}" ]; then uninstall_protection_mode="Difficult Uninstall (default)" elif [ "${uninstall_protection_mode}" = "difficult" ]; then @@ -281,14 +304,14 @@ show_configuration() { pause_duration=$(get_pause_duration) pause_cooldown_hours=$(get_pause_cooldown_hours) else - pause_enabled=$(grep -E "^[[:space:]]*PAUSE_ENABLED=" "${CONFIG_FILE}" 2>/dev/null | head -n1 | cut -d'=' -f2 | tr -d '[:space:]' | tr '[:upper:]' '[:lower:]') - pause_duration=$(grep -E "^[[:space:]]*PAUSE_DURATION=" "${CONFIG_FILE}" 2>/dev/null | head -n1 | cut -d'=' -f2 | tr -d '[:space:]') - pause_cooldown_hours=$(grep -E "^[[:space:]]*PAUSE_COOLDOWN_HOURS=" "${CONFIG_FILE}" 2>/dev/null | head -n1 | cut -d'=' -f2 | tr -d '[:space:]') + pause_enabled=$(_status_config_value_lower PAUSE_ENABLED) + pause_duration=$(_status_config_value PAUSE_DURATION) + pause_cooldown_hours=$(_status_config_value PAUSE_COOLDOWN_HOURS) fi if [ -z "${pause_enabled}" ] || [ "${pause_enabled}" = "true" ] || [ "${pause_enabled}" = "1" ] || [ "${pause_enabled}" = "yes" ]; then print_status "Pause Feature" "Enabled" else - print_status "Pause Feature" "Disabled" + print_status "Pause Feature" "${_STATUS_DISABLED}" fi if [ -z "${pause_duration}" ]; then pause_duration="5" @@ -307,13 +330,13 @@ show_configuration() { pause_end_timestamp=$(get_pause_end_timestamp) if [ -n "${pause_end_timestamp}" ]; then local pause_end_time - pause_end_time=$(date -d "@${pause_end_timestamp}" +"%H:%M" 2>/dev/null || date -r "${pause_end_timestamp}" +"%H:%M" 2>/dev/null || echo "unknown") - print_status "Pause Status" "Active until ${pause_end_time}" "good" + pause_end_time=$(_status_format_epoch "${pause_end_timestamp}" "%H:%M") + print_status "${_STATUS_PAUSE_LABEL}" "Active until ${pause_end_time}" "good" else - print_status "Pause Status" "Active (end time unknown)" "warning" + print_status "${_STATUS_PAUSE_LABEL}" "Active (end time unknown)" "${_STATUS_WARNING}" fi elif can_pause_now; then - print_status "Pause Status" "Available" "good" + print_status "${_STATUS_PAUSE_LABEL}" "Available" "good" elif [ "${pause_enabled}" = "true" ] || [ "${pause_enabled}" = "1" ] || [ "${pause_enabled}" = "yes" ] || [ -z "${pause_enabled}" ]; then local next_available_ts next_available_label next_available_ts="" @@ -321,13 +344,13 @@ show_configuration() { next_available_ts=$(get_next_pause_available_timestamp) fi if [ -n "${next_available_ts}" ]; then - next_available_label=$(date -d "@${next_available_ts}" +"%Y-%m-%d %H:%M" 2>/dev/null || date -r "${next_available_ts}" +"%Y-%m-%d %H:%M" 2>/dev/null || echo "unknown") - print_status "Pause Status" "Cooldown until ${next_available_label}" "warning" + next_available_label=$(_status_format_epoch "${next_available_ts}" "%Y-%m-%d %H:%M") + print_status "${_STATUS_PAUSE_LABEL}" "Cooldown until ${next_available_label}" "${_STATUS_WARNING}" else - print_status "Pause Status" "Cooldown (not available yet)" "warning" + print_status "${_STATUS_PAUSE_LABEL}" "Cooldown (not available yet)" "${_STATUS_WARNING}" fi else - print_status "Pause Status" "Disabled" "warning" + print_status "${_STATUS_PAUSE_LABEL}" "${_STATUS_DISABLED}" "${_STATUS_WARNING}" fi local last_pause_date last_pause_timestamp @@ -340,11 +363,11 @@ show_configuration() { fi if [ -n "${last_pause_timestamp}" ]; then local last_pause_time - last_pause_time=$(date -d "@${last_pause_timestamp}" +"%Y-%m-%d %H:%M" 2>/dev/null || date -r "${last_pause_timestamp}" +"%Y-%m-%d %H:%M" 2>/dev/null || echo "unknown") + last_pause_time=$(_status_format_epoch "${last_pause_timestamp}" "%Y-%m-%d %H:%M") print_status "Last Pause Started" "${last_pause_time}" fi else - print_status "Pause Status" "Unable to check (pause-state.sh not available)" "warning" + print_status "${_STATUS_PAUSE_LABEL}" "Unable to check (pause-state.sh not available)" "${_STATUS_WARNING}" fi # Get dialog tool configuration (Enhancement #25) @@ -353,7 +376,7 @@ show_configuration() { configured_dialog_tool=$(get_dialog_tool_config) else # Fallback to manual parsing if function not available - configured_dialog_tool=$(grep -E "^[[:space:]]*DIALOG_TOOL=" "${CONFIG_FILE}" 2>/dev/null | head -n1 | cut -d'=' -f2 | tr -d '[:space:]' | tr '[:upper:]' '[:lower:]') + configured_dialog_tool=$(_status_config_value_lower DIALOG_TOOL) if [ -z "${configured_dialog_tool}" ]; then configured_dialog_tool="auto" fi @@ -373,7 +396,7 @@ show_configuration() { else # Selected tool not installed, will fall back to automatic dialog_tool_display="${configured_dialog_tool} (not installed, will use automatic)" - dialog_tool_status="warning" + dialog_tool_status="${_STATUS_WARNING}" fi else # Use automatic priority system (YAD → Zenity → KDialog) @@ -470,7 +493,7 @@ show_configuration() { local day_name="${day_names[${i}]}" local day_var="${day_vars[${i}]}" local ranges - ranges=$(grep -E "^[[:space:]]*CONFIG_LOCK_HOURS_${day_var}=" "${CONFIG_FILE}" 2>/dev/null | head -n1 | cut -d'=' -f2 | tr -d '[:space:]') + ranges=$(_status_config_value CONFIG_LOCK_HOURS_${day_var}) if [ -n "${ranges}" ]; then has_lock_hours=true @@ -497,7 +520,7 @@ show_configuration() { local day_name="${day_names[${i}]}" local day_var="${day_vars[${i}]}" local ranges - ranges=$(grep -E "^[[:space:]]*UNINSTALL_LOCK_HOURS_${day_var}=" "${CONFIG_FILE}" 2>/dev/null | head -n1 | cut -d'=' -f2 | tr -d '[:space:]') + ranges=$(_status_config_value UNINSTALL_LOCK_HOURS_${day_var}) if [ -n "${ranges}" ]; then has_uninstall_lock_hours=true @@ -517,8 +540,8 @@ show_configuration() { # Check minute precision compatibility (Enhancement 16b); use run interval (Enhancement #30) if type check_minute_precision_compatibility >/dev/null 2>&1 && type get_timer_run_interval >/dev/null 2>&1; then local popup_freq_val run_interval - popup_freq_val=$(grep -E "^[[:space:]]*POPUP_DISPLAY_FREQUENCY=" "${CONFIG_FILE}" 2>/dev/null | head -n1 | cut -d'=' -f2 | tr -d '[:space:]') - [ -z "${popup_freq_val}" ] && popup_freq_val=$(grep -E "^[[:space:]]*CHECK_INTERVAL=" "${CONFIG_FILE}" 2>/dev/null | head -n1 | cut -d'=' -f2 | tr -d '[:space:]') + popup_freq_val=$(_status_config_value POPUP_DISPLAY_FREQUENCY) + [[ -z "${popup_freq_val}" ]] && popup_freq_val=$(_status_config_value CHECK_INTERVAL) if [ -n "${popup_freq_val}" ]; then run_interval=$(get_timer_run_interval "${popup_freq_val}") local config_lines=() diff --git a/lib/time-calculations-append.txt b/lib/time-calculations-append.txt deleted file mode 100644 index 9313d0a..0000000 --- a/lib/time-calculations-append.txt +++ /dev/null @@ -1,175 +0,0 @@ -############################################################################### -# Restriction / lock period end-time calculation (hour-based, configure/runtime UI) -############################################################################### - -_time_calculations_ensure_time_parsing() { - if type range_endpoint_to_day_minutes >/dev/null 2>&1; then - return 0 - fi - local _tp_dir - _tp_dir="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)" - # shellcheck disable=SC1091 - [ -f "${_tp_dir}/time-parsing.sh" ] && source "${_tp_dir}/time-parsing.sh" -} - -_time_calculations_ensure_configure_core() { - if type format_hour_12h >/dev/null 2>&1 && [ -n "${DAY_NAMES[*]:-}" ]; then - return 0 - fi - local _tc_dir - _tc_dir="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)" - # shellcheck disable=SC1091 - [ -f "${_tc_dir}/configure-core.sh" ] && source "${_tc_dir}/configure-core.sh" -} - -_time_calculations_ensure_config() { - if type parse_config >/dev/null 2>&1; then - return 0 - fi - local _tc_dir - _tc_dir="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)" - # shellcheck disable=SC1091 - [ -f "${_tc_dir}/config.sh" ] && source "${_tc_dir}/config.sh" -} - -# Calculate when the current restriction period ends -# This function finds which restriction range the current hour falls into and calculates when it ends -# Handles overnight ranges and multiple ranges per day -# Parameters: -# $1 - current_hour (0-23) -# $2 - current_day (0-6, Sunday=0) -# $3 - restricted_range (optional, comma-separated ranges for current day) -# Returns: "END_HOUR_12H|END_DAY_NAME|IS_OVERNIGHT" or empty string if not in restriction -# Dependencies: configure-core.sh (for format_hour_12h, DAY_NAMES), time-validation.sh (for is_hour_in_single_range), config.sh (for parse_config) -calculate_restriction_end_time() { - local current_hour="$1" - local current_day="$2" - local restricted_range="$3" - - _time_calculations_ensure_time_parsing - _time_calculations_ensure_configure_core || return 1 - _time_calculations_ensure_config || return 1 - - # Check if we're in an overnight range from previous day - local prev_day - if [ "${current_day}" -eq 0 ]; then - prev_day=6 # Sunday -> Saturday - else - prev_day=$((current_day - 1)) - fi - - local prev_day_range - prev_day_range=$(parse_config "${prev_day}" 2>/dev/null || echo "") - - # Check previous day's overnight ranges first - if [ -n "${prev_day_range}" ]; then - local IFS=',' - for range in ${prev_day_range}; do - range=$(echo "${range}" | sed 's/^[[:space:]]*//;s/[[:space:]]*$//') - local start_part end_part - start_part="${range%%-*}" - end_part="${range##*-}" - start_part=$(echo "${start_part}" | sed 's/^[[:space:]]*//;s/[[:space:]]*$//') - end_part=$(echo "${end_part}" | sed 's/^[[:space:]]*//;s/[[:space:]]*$//') - - if range_overnight_tail_active_for_hour "${current_hour}" "${start_part}" "${end_part}"; then - local end_12h - end_12h=$(format_hour_12h "${end_part}") - local current_day_name="${DAY_NAMES[${current_day}]}" - echo "${end_12h}|${current_day_name}|true" - return 0 - fi - done - fi - - # Check current day's ranges - if [ -z "${restricted_range}" ]; then - return 1 - fi - - local IFS=',' - for range in ${restricted_range}; do - range=$(echo "${range}" | sed 's/^[[:space:]]*//;s/[[:space:]]*$//') - - # Check if current hour is in this range - if type is_hour_in_single_range >/dev/null 2>&1; then - if is_hour_in_single_range "${current_hour}" "${range}"; then - local start_part end_part end_12h - start_part="${range%%-*}" - end_part="${range##*-}" - start_part=$(echo "${start_part}" | sed 's/^[[:space:]]*//;s/[[:space:]]*$//') - end_part=$(echo "${end_part}" | sed 's/^[[:space:]]*//;s/[[:space:]]*$//') - - end_12h=$(format_hour_12h "${end_part}") - local current_day_name="${DAY_NAMES[${current_day}]}" - - if range_is_overnight "${start_part}" "${end_part}"; then - local next_day_index=$(( (current_day + 1) % 7 )) - local next_day_name="${DAY_NAMES[${next_day_index}]}" - echo "${end_12h}|${next_day_name}|true" - else - echo "${end_12h}|${current_day_name}|false" - fi - return 0 - fi - else - # Fallback: use minute-aware restricted check when available - if type is_restricted_time >/dev/null 2>&1; then - local current_time_hhmm - current_time_hhmm=$(printf "%02d00" "${current_hour}") - if is_restricted_time "${current_time_hhmm}" "${range}"; then - local start_part end_part end_12h - start_part="${range%%-*}" - end_part="${range##*-}" - start_part=$(echo "${start_part}" | sed 's/^[[:space:]]*//;s/[[:space:]]*$//') - end_part=$(echo "${end_part}" | sed 's/^[[:space:]]*//;s/[[:space:]]*$//') - end_12h=$(format_hour_12h "${end_part}") - local current_day_name="${DAY_NAMES[${current_day}]}" - if range_is_overnight "${start_part}" "${end_part}"; then - local next_day_index=$(( (current_day + 1) % 7 )) - local next_day_name="${DAY_NAMES[${next_day_index}]}" - echo "${end_12h}|${next_day_name}|true" - else - echo "${end_12h}|${current_day_name}|false" - fi - return 0 - fi - else - # Legacy integer-hour fallback - local start_hour end_hour - start_hour=$(echo "${range}" | cut -d'-' -f1) - end_hour=$(echo "${range}" | cut -d'-' -f2) - - local in_range=false - if [ "${start_hour}" -gt "${end_hour}" ]; then - # Overnight range - if [ "${current_hour}" -ge "${start_hour}" ] || [ "${current_hour}" -lt "${end_hour}" ]; then - in_range=true - fi - else - # Normal range - if [ "${current_hour}" -ge "${start_hour}" ] && [ "${current_hour}" -lt "${end_hour}" ]; then - in_range=true - fi - fi - - if [ "${in_range}" = "true" ]; then - local end_12h - end_12h=$(format_hour_12h "${end_hour}") - local current_day_name="${DAY_NAMES[${current_day}]}" - - if [ "${start_hour}" -gt "${end_hour}" ]; then - local next_day_index=$(( (current_day + 1) % 7 )) - local next_day_name="${DAY_NAMES[${next_day_index}]}" - echo "${end_12h}|${next_day_name}|true" - else - echo "${end_12h}|${current_day_name}|false" - fi - return 0 - fi - fi - fi - done - - return 1 # Not in any range -} diff --git a/lib/time-calculations.sh b/lib/time-calculations.sh index 71c7141..ae37531 100644 --- a/lib/time-calculations.sh +++ b/lib/time-calculations.sh @@ -276,6 +276,7 @@ calculate_total_day_duration() { # Convert one range endpoint (HH or HH:MM) to minutes from midnight (0-1439). # Prints minutes on stdout; returns 1 if invalid. +# $2 is "start" (default) or "end". An end of 24 or 24:00 is 1440, the end of the day. _range_part_to_day_minutes() { if ! type range_endpoint_to_day_minutes >/dev/null 2>&1; then local _tc_dir @@ -283,7 +284,9 @@ _range_part_to_day_minutes() { # shellcheck disable=SC1091 [ -f "${_tc_dir}/time-parsing.sh" ] && source "${_tc_dir}/time-parsing.sh" fi - range_endpoint_to_day_minutes "$1" + local part="$1" + local role="${2:-start}" + range_endpoint_to_day_minutes "${part}" "${role}" } build_weekly_restricted_intervals() { @@ -331,7 +334,7 @@ build_weekly_restricted_intervals() { local start_minute end_minute start_minute=$(_range_part_to_day_minutes "${start_part}") || continue - end_minute=$(_range_part_to_day_minutes "${end_part}") || continue + end_minute=$(_range_part_to_day_minutes "${end_part}" end) || continue if [ "${start_minute}" -gt "${end_minute}" ]; then # Overnight range detected (e.g., "23-6" or "23:30-06:00") @@ -588,7 +591,7 @@ get_next_unrestricted_time() { fi # Find the end of the current restricted interval to jump ahead - local interval_end="${minutes_per_week}" # Default: end of week + local interval_end=-1 # Earliest end among the intervals holding search_minute while IFS= read -r interval; do [ -z "${interval}" ] && continue @@ -596,20 +599,19 @@ get_next_unrestricted_time() { local end="${interval##*:}" # Check if search_minute is in this interval - if [ "${search_minute}" -ge "${start}" ] && [ "${search_minute}" -lt "${end}" ]; then - # We're in this interval - the next unrestricted time is at 'end' - # Use the earliest end time (in case of overlapping intervals, though they should be merged) - if [ "${end}" -lt "${interval_end}" ]; then - interval_end="${end}" - fi + # We're in this interval - the next unrestricted time is at 'end'. + # Use the earliest end time (in case of overlapping intervals, though they should be merged). + if [[ "${search_minute}" -ge "${start}" && "${search_minute}" -lt "${end}" \ + && ( "${interval_end}" -lt 0 || "${end}" -lt "${interval_end}" ) ]]; then + interval_end="${end}" fi done <<< "${merged_intervals}" - # Jump to the end of the current restricted interval - if [ "${interval_end}" -lt "${minutes_per_week}" ]; then - # Normal case: end is in current week + # Jump to the end of the current restricted interval. An interval that + # ends at the week boundary (Saturday 24:00) jumps to minute 0 of Sunday. + if [[ "${interval_end}" -gt "${search_minute}" ]]; then local jump_distance=$((interval_end - search_minute)) - search_minute="${interval_end}" + search_minute=$((interval_end % minutes_per_week)) search_count=$((search_count + jump_distance)) else # Shouldn't happen if we found an interval, but fallback: move to next minute @@ -647,7 +649,7 @@ _time_calculations_ensure_time_parsing() { } _time_calculations_ensure_configure_core() { - if type format_hour_12h >/dev/null 2>&1 && [ -n "${DAY_NAMES[*]:-}" ]; then + if type format_endpoint_12h >/dev/null 2>&1 && [[ -n "${DAY_NAMES[*]:-}" ]]; then return 0 fi local _tc_dir @@ -666,6 +668,34 @@ _time_calculations_ensure_config() { [ -f "${_tc_dir}/config.sh" ] && source "${_tc_dir}/config.sh" } +# Print $1 without leading or trailing whitespace. +_time_calculations_trim() { + local value="$1" + value="${value#"${value%%[![:space:]]*}"}" + value="${value%"${value##*[![:space:]]}"}" + printf '%s' "${value}" +} + +# Print "END_12H|DAY_NAME|IS_NEXT_DAY" for a range that is active now. +# The end falls on the next day when the range crosses midnight or ends at 24:00. +# The end may be "H" or "HH:MM", the forms parse_config and the lock-hour readers return. +# Returns 1 when the end is not a valid time. +_restriction_end_info() { + local range="$1" + local current_day="$2" + local start_part end_part end_12h end_minutes + start_part=$(_time_calculations_trim "${range%%-*}") + end_part=$(_time_calculations_trim "${range##*-}") + end_12h=$(format_endpoint_12h "${end_part}") || return 1 + + if { end_minutes=$(range_endpoint_to_day_minutes "${end_part}" end) && [[ "${end_minutes}" -eq 1440 ]]; } \ + || range_is_overnight "${start_part}" "${end_part}"; then + echo "${end_12h}|${DAY_NAMES[$(( (current_day + 1) % 7 ))]}|true" + else + echo "${end_12h}|${DAY_NAMES[${current_day}]}|false" + fi +} + # Calculate when the current restriction period ends # This function finds which restriction range the current hour falls into and calculates when it ends # Handles overnight ranges and multiple ranges per day @@ -674,7 +704,7 @@ _time_calculations_ensure_config() { # $2 - current_day (0-6, Sunday=0) # $3 - restricted_range (optional, comma-separated ranges for current day) # Returns: "END_HOUR_12H|END_DAY_NAME|IS_OVERNIGHT" or empty string if not in restriction -# Dependencies: configure-core.sh (for format_hour_12h, DAY_NAMES), time-validation.sh (for is_hour_in_single_range), config.sh (for parse_config) +# Dependencies: configure-core.sh (for format_endpoint_12h, DAY_NAMES), time-validation.sh (for is_hour_in_single_range), config.sh (for parse_config) calculate_restriction_end_time() { local current_hour="$1" local current_day="$2" @@ -708,9 +738,8 @@ calculate_restriction_end_time() { if range_overnight_tail_active_for_hour "${current_hour}" "${start_part}" "${end_part}"; then local end_12h - end_12h=$(format_hour_12h "${end_part}") - local current_day_name="${DAY_NAMES[${current_day}]}" - echo "${end_12h}|${current_day_name}|true" + end_12h=$(format_endpoint_12h "${end_part}") || return 1 + echo "${end_12h}|${DAY_NAMES[${current_day}]}|true" return 0 fi done @@ -723,85 +752,46 @@ calculate_restriction_end_time() { local IFS=',' for range in ${restricted_range}; do - range=$(echo "${range}" | sed 's/^[[:space:]]*//;s/[[:space:]]*$//') - + range=$(_time_calculations_trim "${range}") + # Check if current hour is in this range if type is_time_in_single_range >/dev/null 2>&1; then if is_time_in_single_range "$(printf '%02d00' "${current_hour}")" "${range}" self; then - local start_part end_part end_12h - start_part="${range%%-*}" - end_part="${range##*-}" - start_part=$(echo "${start_part}" | sed 's/^[[:space:]]*//;s/[[:space:]]*$//') - end_part=$(echo "${end_part}" | sed 's/^[[:space:]]*//;s/[[:space:]]*$//') - - end_12h=$(format_hour_12h "${end_part}") - local current_day_name="${DAY_NAMES[${current_day}]}" - - if range_is_overnight "${start_part}" "${end_part}"; then - local next_day_index=$(( (current_day + 1) % 7 )) - local next_day_name="${DAY_NAMES[${next_day_index}]}" - echo "${end_12h}|${next_day_name}|true" - else - echo "${end_12h}|${current_day_name}|false" - fi + _restriction_end_info "${range}" "${current_day}" || return 1 return 0 fi - else + elif type is_restricted_time >/dev/null 2>&1; then # Fallback: use minute-aware restricted check when available - if type is_restricted_time >/dev/null 2>&1; then - local current_time_hhmm - current_time_hhmm=$(printf "%02d00" "${current_hour}") - if is_restricted_time "${current_time_hhmm}" "${range}" self; then - local start_part end_part end_12h - start_part="${range%%-*}" - end_part="${range##*-}" - start_part=$(echo "${start_part}" | sed 's/^[[:space:]]*//;s/[[:space:]]*$//') - end_part=$(echo "${end_part}" | sed 's/^[[:space:]]*//;s/[[:space:]]*$//') - end_12h=$(format_hour_12h "${end_part}") - local current_day_name="${DAY_NAMES[${current_day}]}" - if range_is_overnight "${start_part}" "${end_part}"; then - local next_day_index=$(( (current_day + 1) % 7 )) - local next_day_name="${DAY_NAMES[${next_day_index}]}" - echo "${end_12h}|${next_day_name}|true" - else - echo "${end_12h}|${current_day_name}|false" - fi - return 0 - fi - else - # Legacy integer-hour fallback - local start_hour end_hour + if is_restricted_time "$(printf '%02d00' "${current_hour}")" "${range}" self; then + _restriction_end_info "${range}" "${current_day}" || return 1 + return 0 + fi + else + # Legacy integer-hour fallback. 10# keeps "08" and "09" out of octal. + local start_hour end_hour in_range=false now_hour start_hour=$(echo "${range}" | cut -d'-' -f1) end_hour=$(echo "${range}" | cut -d'-' -f2) - - local in_range=false - if [ "${start_hour}" -gt "${end_hour}" ]; then + # Plain integers only. A non-numeric value would abort the shell inside $(( )). + if ! [[ "${start_hour}" =~ ^[0-9]+$ && "${end_hour}" =~ ^[0-9]+$ && "${current_hour}" =~ ^[0-9]+$ ]]; then + continue + fi + start_hour=$((10#${start_hour})) + end_hour=$((10#${end_hour})) + now_hour=$((10#${current_hour})) + + if [[ "${start_hour}" -gt "${end_hour}" ]]; then # Overnight range - if [ "${current_hour}" -ge "${start_hour}" ]; then - in_range=true - fi - else - # Normal range - if [ "${current_hour}" -ge "${start_hour}" ] && [ "${current_hour}" -lt "${end_hour}" ]; then + if [[ "${now_hour}" -ge "${start_hour}" ]]; then in_range=true fi + elif [[ "${now_hour}" -ge "${start_hour}" && "${now_hour}" -lt "${end_hour}" ]]; then + in_range=true fi - + if [ "${in_range}" = "true" ]; then - local end_12h - end_12h=$(format_hour_12h "${end_hour}") - local current_day_name="${DAY_NAMES[${current_day}]}" - - if [ "${start_hour}" -gt "${end_hour}" ]; then - local next_day_index=$(( (current_day + 1) % 7 )) - local next_day_name="${DAY_NAMES[${next_day_index}]}" - echo "${end_12h}|${next_day_name}|true" - else - echo "${end_12h}|${current_day_name}|false" - fi + _restriction_end_info "${range}" "${current_day}" || return 1 return 0 fi - fi fi done diff --git a/lib/time-parsing.sh b/lib/time-parsing.sh index 2553755..8eebf1e 100644 --- a/lib/time-parsing.sh +++ b/lib/time-parsing.sh @@ -114,26 +114,23 @@ parse_single_time() { } # Convert 24h to 12h format -# Parameters: hour (0-23), minute (0-59) +# Parameters: hour (0-24), minute (0-59) +# An hour of 24 is midnight at the end of the day, so it prints 12:00am. 24hour_to_12hour() { - local hour="$1" + local hour=$((10#$1)) local minute="$2" - - local h12="${hour}" + local ampm="am" - - if [ "$((10#${hour}))" -ge 12 ]; then + if [[ "${hour}" -ge 12 && "${hour}" -lt 24 ]]; then ampm="pm" - if [ "$((10#${hour}))" -gt 12 ]; then - h12=$((10#${hour} - 12)) - fi fi - if [ "$((10#${h12}))" -eq 0 ]; then + local h12=$((hour % 12)) + if [[ "${h12}" -eq 0 ]]; then h12=12 fi - printf "%d:%02d%s" "$((10#${h12}))" "$((10#${minute}))" "${ampm}" + printf "%d:%02d%s" "${h12}" "$((10#${minute}))" "${ampm}" } # Split "hour minute" output from parse_time_token_to_24h_hm (IFS-safe; use instead of read). @@ -374,15 +371,19 @@ normalize_time_range() { # Convert one range endpoint (HH or HH:MM) to minutes from midnight (0-1439). # Prints minutes on stdout; returns 1 if invalid. +# $2 is the role, "start" (default) or "end". A range may end at 24 or 24:00, +# which is midnight at the end of the day, so the "end" role also accepts it and +# prints 1440. daily-caps.sh reads a 24:00 end the same way. range_endpoint_to_day_minutes() { local part="$1" + local role="${2:-start}" local minutes_per_hour="${MINUTES_PER_HOUR:-60}" + local h m part=$(echo "${part}" | sed 's/^[[:space:]]*//;s/[[:space:]]*$//') [ -z "${part}" ] && return 1 if [[ "${part}" =~ : ]]; then - local h m h=$(echo "${part}" | cut -d: -f1) m=$(echo "${part}" | cut -d: -f2) if ! [[ "${h}" =~ ^[0-9]+$ ]] || ! [[ "${m}" =~ ^[0-9]+$ ]]; then @@ -390,21 +391,22 @@ range_endpoint_to_day_minutes() { fi h=$((10#${h})) m=$((10#${m})) - if [ "${h}" -lt 0 ] || [ "${h}" -gt 23 ] || [ "${m}" -lt 0 ] || [ "${m}" -gt 59 ]; then + else + if ! [[ "${part}" =~ ^[0-9]+$ ]]; then return 1 fi - echo $((h * minutes_per_hour + m)) - return 0 + h=$((10#${part})) + m=0 fi - if ! [[ "${part}" =~ ^[0-9]+$ ]]; then - return 1 + if [[ "${role}" == "end" && "${h}" -eq 24 && "${m}" -eq 0 ]]; then + echo $((24 * minutes_per_hour)) + return 0 fi - local h=$((10#${part})) - if [ "${h}" -lt 0 ] || [ "${h}" -gt 23 ]; then + if [ "${h}" -lt 0 ] || [ "${h}" -gt 23 ] || [ "${m}" -lt 0 ] || [ "${m}" -gt 59 ]; then return 1 fi - echo $((h * minutes_per_hour)) + echo $((h * minutes_per_hour + m)) return 0 } diff --git a/scripts/check-sonar-shell-newcode.sh b/scripts/check-sonar-shell-newcode.sh new file mode 100755 index 0000000..065b463 --- /dev/null +++ b/scripts/check-sonar-shell-newcode.sh @@ -0,0 +1,120 @@ +#!/usr/bin/env bash +# Approximate SonarCloud's shell rule S7688 ("use [[ instead of [") on new code. +# +# The local SonarQube Community Build has no Shell analyzer, so sonar_scan.sh +# never sees .sh files. SonarCloud does analyze them, and S7688 is the rule it +# reports most. ShellCheck's optional check require-double-brackets (SC2292) +# flags the same constructs, once per `[`, as Sonar does. +# +# Only lines added since the merge base are reported, which matches Sonar's +# new-code view. A line that only moved, with the same text as a removed line, is +# skipped, once per removed line: if one line was removed and two identical lines +# were added, the second is still reported. Untracked .sh files count in full. Existing `[ ]` tests stay alone: +# the codebase uses them everywhere. +# +# Checked against SonarCloud on PR #3: it found every S7688 finding Sonar +# reported (28 of 28). It can report a few extra lines, such as a changed line +# whose old version Sonar already tracked as an existing issue. +# +# This does not cover Sonar's other shell rules (S1192 repeated literals, S7679 +# positional parameters, S131 case without a default, S1066 nested ifs). For the +# real result after a push, run scripts/sonarcloud_pr_issues.py. +# +# Usage: ./scripts/check-sonar-shell-newcode.sh [BASE_REF] +# BASE_REF defaults to origin/main, then main. +# Exit: 0 clean, 1 findings, 2 setup problem. + +set -euo pipefail + +if ! command -v shellcheck >/dev/null 2>&1; then + echo "check-sonar-shell-newcode: shellcheck is not installed." >&2 + exit 2 +fi + +ROOT="$(git rev-parse --show-toplevel)" +cd "${ROOT}" + +base_ref="${1:-}" +if [[ -z "${base_ref}" ]]; then + for candidate in origin/main main; do + if git rev-parse --verify --quiet "${candidate}^{commit}" >/dev/null; then + base_ref="${candidate}" + break + fi + done +fi +if [[ -z "${base_ref}" ]] || ! base_sha="$(git merge-base "${base_ref}" HEAD 2>/dev/null)"; then + echo "check-sonar-shell-newcode: no base ref (pass one, e.g. origin/main)." >&2 + exit 2 +fi + +work="$(mktemp -d)" +trap 'rm -rf "${work}"' EXIT + +# Added line numbers of one file since the merge base, one per line. +added_lines() { + local file="$1" + git diff -U0 "${base_sha}" -- "${file}" | awk ' + /^@@/ { + split($3, range, ",") + start = substr(range[1], 2) + 0 + count = (range[2] == "" ? 1 : range[2] + 0) + for (i = 0; i < count; i++) print start + i + }' +} + +# Text of the lines the diff removed, without indentation. An added line with +# the same text is a moved or re-indented line, which Sonar treats as old code. +removed_text() { + local file="$1" + git diff -U0 "${base_sha}" -- "${file}" | grep -E '^-' | grep -vE '^--- ' | sed -E 's/^-[[:space:]]*//' || true +} + +# Changed or new shell files: tracked changes first, then untracked files. +{ + git diff --name-only --diff-filter=AM "${base_sha}" -- '*.sh' + git ls-files --others --exclude-standard -- '*.sh' +} | sort -u | grep -v '^backups/' > "${work}/files" || true + +findings=0 +while IFS= read -r file; do + [[ -f "${file}" ]] || continue + if git ls-files --error-unmatch -- "${file}" >/dev/null 2>&1; then + added_lines "${file}" > "${work}/added" + removed_text "${file}" > "${work}/removed" + else + # NR counts records, so a last line with no trailing newline is included. + awk '{ print NR }' "${file}" > "${work}/added" + : > "${work}/removed" + fi + [[ -s "${work}/added" ]] || continue + shellcheck -o require-double-brackets -S style -f gcc "${file}" 2>/dev/null \ + | awk -F: -v added="${work}/added" -v removed="${work}/removed" -v src="${file}" ' + BEGIN { + while ((getline line < added) > 0) want[line] = 1 + while ((getline line < removed) > 0) gone[line]++ + while ((getline line < src) > 0) { + sub(/^[[:space:]]+/, "", line) + text[++total] = line + } + } + # A removed line excuses at most one added line with the same text. All + # findings on that one line share the decision; the next added line with + # the same text is reported. + /\[SC2292\]/ && ($2 in want) { + if (!($2 in moved)) { + if (gone[text[$2]] > 0) { gone[text[$2]]--; moved[$2] = 1 } else { moved[$2] = 0 } + } + if (!moved[$2]) print + }' > "${work}/hits" || true + if [[ -s "${work}/hits" ]]; then + findings=$((findings + $(wc -l < "${work}/hits"))) + sed 's/: note: Prefer \[\[ \]\] over \[ \] for tests in Bash\/Ksh\/Busybox\. \[SC2292\]/: use [[ ]] instead of [ ]/' "${work}/hits" + fi +done < "${work}/files" + +if [[ "${findings}" -gt 0 ]]; then + echo "check-sonar-shell-newcode: ${findings} added '[' test(s) that SonarCloud flags as S7688." >&2 + exit 1 +fi +echo "check-sonar-shell-newcode: no new '[' tests since ${base_ref}." diff --git a/scripts/python-coverage-baseline.json b/scripts/python-coverage-baseline.json index bcff451..f6e3c2b 100644 --- a/scripts/python-coverage-baseline.json +++ b/scripts/python-coverage-baseline.json @@ -2,12 +2,12 @@ "schema": 2, "scope": "lib/*.py", "display": { - "covered_statements": 260, + "covered_statements": 819, "statements": 826 }, "headless": { - "covered_statements": 238, + "covered_statements": 819, "statements": 826 }, - "note": "Measured 2026-10-26 after tests/test-popup-blocker-darwin.py. A display run covers 260/826 (31.5%). The same suite with the tkinter probe skipped covers 238/826 (28.8%). The popup-blocker tests mock tkinter, so they count in both. Each run is compared with its own ratio." + "note": "Measured 2026-10-28 after tests/test-configure-dialogs-darwin-ui.py, which fakes the tkinter widgets and needs no display. A display run covers 819/826 (99.2%). A run with Tk() unavailable covers the same 819/826, because the new tests do not open a window. The 7 missed statements are the four `if __name__ == \"__main__\"` calls in the configure-dialog scripts and 3 popup-blocker lines. Python 3.11 and 3.12 count the same statements. Each run is compared with its own ratio." } diff --git a/scripts/shell-coverage-baseline.json b/scripts/shell-coverage-baseline.json index 1f0d007..27031b2 100644 --- a/scripts/shell-coverage-baseline.json +++ b/scripts/shell-coverage-baseline.json @@ -2,14 +2,14 @@ "schema": 1, "scope": "lib/*.sh", "darwin": { - "covered_lines": 2922, + "covered_lines": 4703, "statements": 18047, "slack_lines": 30 }, "linux": { - "covered_lines": 3054, + "covered_lines": 4800, "statements": 18047, "slack_lines": 30 }, - "note": "Measured 2026-10-27 from Tier-A under bash xtrace. darwin 2922/18047 (16.2%) on a local macOS run (29 run, 3 skipped); linux 3054/18047 (16.9%) from the Ubuntu CI run. test-popup-notice-deadlines.sh is exempt via SHELL_COVERAGE_OFF. Each OS is checked against its own floor and may fall its slack_lines (30, about 1%) under it to absorb timing noise in the trace. fi and done often never appear in an xtrace. Raising a floor is a new measurement on that OS." + "note": "Measured 2026-10-28 from Tier-A under bash xtrace. darwin 4703/18047 (26.1%) on a local macOS run (54 run, 3 skipped). linux was 4818/18047 (26.7%) in an Ubuntu 24.04 container run as a non-root user (54 run, 3 skipped); the floor is set 18 lines under that until the Ubuntu CI run confirms the number. The jump from 2922 and 3054 comes from new tests for config-popup-size, config-safety, time-calculations, scheduler-platform and resolution-detection, and from moving 19 fast Tier-B scripts into Tier-A. test-popup-notice-deadlines.sh is exempt via SHELL_COVERAGE_OFF. Each OS is checked against its own floor and may fall its slack_lines (30, about 0.2%) under it to absorb timing noise in the trace. fi and done often never appear in an xtrace. Raising a floor is a new measurement on that OS." } diff --git a/scripts/sonar_scan.sh b/scripts/sonar_scan.sh index 6fab84b..6c1726d 100755 --- a/scripts/sonar_scan.sh +++ b/scripts/sonar_scan.sh @@ -16,7 +16,9 @@ # and records the commit in tmp/sonar-state.json. It does not run from the hook. # Scope lives in sonar-project.properties, which Cloud automatic analysis ignores. # This Community Build analyzes Python. It has no Shell language, so a local -# issue count does not cover the Bash sources. +# issue count does not cover the Bash sources. SonarCloud does analyze them: see +# scripts/check-sonar-shell-newcode.sh (before a push) and +# scripts/sonarcloud_pr_issues.py (after a push). set -euo pipefail diff --git a/scripts/sonarcloud_pr_issues.py b/scripts/sonarcloud_pr_issues.py new file mode 100755 index 0000000..1d174ad --- /dev/null +++ b/scripts/sonarcloud_pr_issues.py @@ -0,0 +1,150 @@ +#!/usr/bin/env python3 +"""Print the SonarCloud new-code issues for a pull request, the way the PR sees them. + +The local SonarQube Community Build has no Shell analyzer, so scripts/sonar_scan.sh +cannot report SonarCloud's shell findings (S7688, S1192, S7679, S131, S1066). This +script reads them from SonarCloud's public API after a push. No token is needed +because the project is public. + +SonarCloud analyzes the pull request head within a minute or two of a push. By +default the script reports whatever the last analysis found and says which commit +that was. --wait SECONDS polls until the analysis matches the local HEAD. + +Usage: + python3 scripts/sonarcloud_pr_issues.py # PR of the current branch + python3 scripts/sonarcloud_pr_issues.py 3 --wait 180 + +Exit status: + 0 no new issues. When git returns a local HEAD, the analysis must also be for + it. That comparison runs with or without --wait. Without a HEAD (and + without --wait) the commit is not compared. + 1 new issues, even when the analysis is for another commit + 2 no new issues but the analysis is for another commit, or the PR, the local + HEAD (with --wait), or the API could not be read +""" + +from __future__ import annotations + +import argparse +import json +import subprocess +import sys +import time +import urllib.parse +import urllib.request +from typing import Any + +API = "https://sonarcloud.io/api" +PROJECT = "kgrizz-git_TimerWarning" +PAGE_SIZE = 500 + + +def fetch_json(path: str, params: dict[str, str]) -> dict[str, Any]: + """GET one SonarCloud API path and return the decoded JSON object.""" + url = f"{API}/{path}?{urllib.parse.urlencode(params)}" + with urllib.request.urlopen(url, timeout=30) as response: + return json.load(response) + + +def run_text(command: list[str]) -> str: + """Run a command and return its stripped stdout, or an empty string on failure.""" + try: + result = subprocess.run(command, capture_output=True, text=True, check=False) + except OSError: + return "" + return result.stdout.strip() if result.returncode == 0 else "" + + +def analyzed_commit(pr: str) -> str | None: + """Return the commit SonarCloud last analyzed for this pull request, if any.""" + data = fetch_json("project_pull_requests/list", {"project": PROJECT}) + for pull in data.get("pullRequests", []): + if str(pull.get("key")) == pr: + return pull.get("commit", {}).get("sha") + return None + + +def wait_for_commit(pr: str, sha: str, seconds: int, poll: int = 10) -> bool: + """Poll until the analysis is for *sha*. Return False if *seconds* run out.""" + deadline = time.monotonic() + seconds + while True: + if analyzed_commit(pr) == sha: + return True + if time.monotonic() >= deadline: + return False + time.sleep(poll) + + +def fetch_issues(pr: str) -> list[dict[str, Any]]: + """Return every unresolved new-code issue on the pull request.""" + issues: list[dict[str, Any]] = [] + page = 1 + while True: + data = fetch_json( + "issues/search", + { + "componentKeys": PROJECT, + "pullRequest": pr, + "resolved": "false", + "inNewCodePeriod": "true", + "ps": str(PAGE_SIZE), + "p": str(page), + }, + ) + batch = data.get("issues", []) + issues.extend(batch) + if not batch or len(issues) >= int(data.get("total", 0)): + return issues + page += 1 + + +def format_issue(issue: dict[str, Any]) -> str: + """One line: path:line RULE SEVERITY message.""" + path = str(issue.get("component", "")).split(":", 1)[-1] + line = issue.get("line", "?") + return f"{path}:{line} {issue.get('rule', '?')} {issue.get('severity', '?')} {issue.get('message', '')}" + + +def main(argv: list[str]) -> int: + parser = argparse.ArgumentParser(description=(__doc__ or "").split("\n\n")[0]) + parser.add_argument("pr", nargs="?", help="pull request number (default: the current branch's PR)") + parser.add_argument("--wait", type=int, default=0, metavar="SECONDS", + help="wait up to this long for the analysis of the local HEAD") + args = parser.parse_args(argv) + + pr = args.pr or run_text(["gh", "pr", "view", "--json", "number", "-q", ".number"]) + if not pr: + print("sonarcloud: no PR number given and gh found none for this branch.", file=sys.stderr) + return 2 + head = run_text(["git", "rev-parse", "HEAD"]) + + if args.wait > 0 and not head: + print("sonarcloud: --wait needs the local HEAD commit, but git did not return one.", file=sys.stderr) + return 2 + + try: + if args.wait > 0 and not wait_for_commit(pr, head, args.wait): + print(f"sonarcloud: PR #{pr} was not analyzed at {head[:7]} within {args.wait}s.", file=sys.stderr) + return 2 + analyzed = analyzed_commit(pr) + issues = fetch_issues(pr) + except (OSError, ValueError) as exc: + print(f"sonarcloud: could not read the API: {exc}", file=sys.stderr) + return 2 + + if analyzed is None: + print(f"sonarcloud: PR #{pr} has no analysis yet.", file=sys.stderr) + return 2 + stale = bool(head) and analyzed != head + print(f"sonarcloud: PR #{pr} analyzed at {analyzed[:7]}" + (f" (local HEAD is {head[:7]})" if stale else "")) + + for issue in sorted(issues, key=lambda i: (str(i.get("component")), int(i.get("line") or 0))): + print(format_issue(issue)) + print(f"sonarcloud: {len(issues)} new issue(s).") + if issues: + return 1 + return 2 if stale else 0 + + +if __name__ == "__main__": + sys.exit(main(sys.argv[1:])) diff --git a/tests/test-config-locked-message.sh b/tests/test-config-locked-message.sh new file mode 100644 index 0000000..bd73ebc --- /dev/null +++ b/tests/test-config-locked-message.sh @@ -0,0 +1,115 @@ +#!/bin/bash + +############################################################################### +# Tests the text show_config_locked_error prints when configure is locked: +# the active range, the end time, and which day the lock ends on. Covers +# integer-hour and HH:MM configs, an overnight tail from the previous day, and +# ranges that end at 24 (midnight at the end of the day). +# Runs headless with a temp HOME and a stubbed clock. Text mode only. +############################################################################### + +SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")/.." && pwd)" + +TMP_HOME="$(mktemp -d)" +trap 'rm -rf "${TMP_HOME}"' EXIT +export HOME="${TMP_HOME}" + +# shellcheck disable=SC1091 +source "${SCRIPT_DIR}/lib/configure-core.sh" || exit 1 +# shellcheck disable=SC1091 +source "${SCRIPT_DIR}/lib/config.sh" || exit 1 +# shellcheck disable=SC1091 +source "${SCRIPT_DIR}/lib/time-parsing.sh" || exit 1 +# shellcheck disable=SC1091 +source "${SCRIPT_DIR}/lib/time-validation.sh" || exit 1 +# shellcheck disable=SC1091 +source "${SCRIPT_DIR}/lib/time-calculations.sh" || exit 1 +# shellcheck disable=SC1091 +source "${SCRIPT_DIR}/lib/configure-time.sh" || exit 1 +# shellcheck disable=SC1091 +source "${SCRIPT_DIR}/lib/configure-ui-errors.sh" || exit 1 + +CONFIG_FILE="${TMP_HOME}/sleep-warning.conf" + +FAKE_DOW=1 +FAKE_HOUR=3 +date() { + case "$1" in + +%w) echo "${FAKE_DOW}" ;; + +%H) printf '%02d\n' "${FAKE_HOUR}" ;; + +%H%M) printf '%02d00\n' "${FAKE_HOUR}" ;; + *) command date "$@" ;; + esac +} + +_PASS=0 +_FAIL=0 + +check_line() { + local desc="$1" expected="$2" output="$3" + if printf '%s\n' "${output}" | grep -Fqx -- "${expected}"; then + _PASS=$(( _PASS + 1 )); echo " PASS ${desc} (${expected})" + else + _FAIL=$(( _FAIL + 1 )); echo " FAIL ${desc}: no line '${expected}' in:" + printf '%s\n' "${output}" | sed 's/^/ /' + fi +} + +write_config() { + printf '%s\n' "SUNDAY=" "MONDAY=" "TUESDAY=" "WEDNESDAY=" "THURSDAY=" "FRIDAY=" "SATURDAY=" "$@" > "${CONFIG_FILE}" +} + +# message DAY HOUR: the text-mode error for that clock. +message() { + FAKE_DOW="$1" + FAKE_HOUR="$2" + show_config_locked_error false Configuration 2>&1 +} + +echo "=== same-day restriction ===" +write_config "MONDAY=0-5" +out="$(message 1 3)" +check_line "headline names the restriction" "Error: Configuration is locked during restricted hours." "${out}" +check_line "active range" "Active restriction: 12:00am -> 5:00am" "${out}" +check_line "ends today at 5:00 AM" "Lock ends: 5:00 AM today" "${out}" + +echo "=== HH:MM config ===" +write_config "MONDAY=00:00-05:30" +out="$(message 1 3)" +check_line "end time keeps its minutes" "Lock ends: 5:30 AM today" "${out}" + +echo "=== overnight range, started yesterday ===" +write_config "TUESDAY=22-6" +out="$(message 3 3)" +check_line "the tail is active on Wednesday" "Current time: Wednesday, 3:00 AM" "${out}" +check_line "ends Wednesday morning" "Lock ends: 6:00 AM on Wednesday" "${out}" +write_config "TUESDAY=22:00-06:30" +out="$(message 3 3)" +check_line "the tail with minutes" "Lock ends: 6:30 AM on Wednesday" "${out}" + +echo "=== overnight range, started today ===" +write_config "TUESDAY=22-6" +out="$(message 2 23)" +check_line "ends tomorrow" "Lock ends: 6:00 AM on Wednesday" "${out}" + +echo "=== range ending at 24 ===" +write_config "MONDAY=16-24" +out="$(message 1 17)" +check_line "the range reads as ending at midnight" "Active restriction: 4:00pm -> 12:00am" "${out}" +check_line "the lock ends at midnight, on the next day" "Lock ends: 12:00 AM on Tuesday" "${out}" +write_config "MONDAY=16:00-24:00" +out="$(message 1 23)" +check_line "the HH:MM form agrees" "Lock ends: 12:00 AM on Tuesday" "${out}" +write_config "SATURDAY=16-24" +out="$(message 6 20)" +check_line "Saturday's midnight is Sunday" "Lock ends: 12:00 AM on Sunday" "${out}" + +echo "=== lock hours only ===" +write_config "CONFIG_LOCK_HOURS_MONDAY=1-4" +out="$(message 1 2)" +check_line "headline names the lock hours" "Error: Configuration is locked during configured lock hours." "${out}" +check_line "lock ends today" "Lock ends: 4:00 AM today" "${out}" + +echo "" +echo "Results: ${_PASS} passed, ${_FAIL} failed" +[[ "${_FAIL}" -eq 0 ]] || exit 1 diff --git a/tests/test-config-locking.sh b/tests/test-config-locking.sh index 1fcad00..2dfb257 100644 --- a/tests/test-config-locking.sh +++ b/tests/test-config-locking.sh @@ -17,8 +17,10 @@ # ./tests/test-config-locking.sh # # Notes: -# These tests use the *current* system time (day/hour) and write a config that -# makes the lock active "right now", so no clock mocking is needed. +# The clock is frozen with a `date` stub (Wednesday 14:20), and the config makes +# the lock active at that moment. The library reads the day and hour in several +# separate `date` calls, so a real clock could cross an hour or midnight between +# them. The overnight checks move the frozen clock to 03:00 so they always run. set -euo pipefail @@ -95,6 +97,21 @@ source "${SCRIPT_DIR}/lib/time-parsing.sh" source "${SCRIPT_DIR}/lib/time-validation.sh" source "${SCRIPT_DIR}/lib/config-locking.sh" +# Frozen clock. The library calls `date +%w`, `date +%H`, and `date +%H%M`; every +# other `date` call (timestamps) goes to the real command. +FROZEN_DOW=3 +FROZEN_HOUR=14 +FROZEN_MIN=20 +date() { + case "$*" in + "+%w") echo "${FROZEN_DOW}" ;; + "+%H") printf '%02d\n' "${FROZEN_HOUR}" ;; + "+%M") printf '%02d\n' "${FROZEN_MIN}" ;; + "+%H%M") printf '%02d%02d\n' "${FROZEN_HOUR}" "${FROZEN_MIN}" ;; + *) command date "$@" ;; + esac +} + # config.sh defines CONFIG_DIR but does not create it. Create it here since we run under a temp HOME. mkdir -p "${CONFIG_DIR}" @@ -142,7 +159,7 @@ if [ "$(get_config_lock_enabled)" != "false" ]; then fail "Expected get_config_lock_enabled to fall back to default on invalid value" fi -# Make restrictions cover "right now" +# Make restrictions cover "right now" (the frozen clock) current_day="$(date +%w)" current_hour="$(date +%H)" current_hour="$((10#${current_hour}))" @@ -211,21 +228,24 @@ if is_config_lock_active; then fi echo "Checking is_config_lock_active() for overnight ranges..." -# Test overnight range: previous day 23-6 (11pm to 6am next day) -# If current hour is between 0-5, we should be in the overnight range from previous day -if [ "${current_hour}" -ge 0 ] && [ "${current_hour}" -lt 6 ]; then - cat > "${config_file}" < "${config_file}" < "${CONFIG_FILE}" +} + +echo "=== get_default_hours_for_day ===" +check "Sunday" "1-5" "$(get_default_hours_for_day 0)" +for d in 1 2 3 4 5; do + check "weekday ${d}" "0-5" "$(get_default_hours_for_day "${d}")" +done +check "Saturday" "1-5" "$(get_default_hours_for_day 6)" +get_default_hours_for_day 7 >/dev/null +check "day 7 returns failure" "1" "$?" +get_default_hours_for_day "" >/dev/null +check "empty day returns failure" "1" "$?" + +echo "=== _config_last_assigned_value ===" +rm -f "${CONFIG_FILE}" +_config_last_assigned_value MONDAY >/dev/null +check "missing file returns 1" "1" "$?" +write_config "TUESDAY=1-5" +_config_last_assigned_value MONDAY >/dev/null +check "absent key returns 1" "1" "$?" +write_config "MONDAY=1-2" "MONDAY=3-4" +check "last assignment wins" "3-4" "$(_config_last_assigned_value MONDAY)" +write_config "MONDAY=" +check "present but empty prints nothing" "" "$(_config_last_assigned_value MONDAY)" +_config_last_assigned_value MONDAY >/dev/null +check "present but empty returns 0" "0" "$?" +write_config " MONDAY = 22 - 6 " +check "surrounding whitespace is trimmed" "22 - 6" "$(_config_last_assigned_value MONDAY)" +write_config "MONDAY=a=b" +check "a value keeps later equals signs" "a=b" "$(_config_last_assigned_value MONDAY)" + +echo "=== _config_hours_as_runtime ===" +check "empty stays empty" "" "$(_config_hours_as_runtime "")" +check "whitespace-only stays empty" "" "$(_config_hours_as_runtime " ")" +check "plain hours are normalized" "07:00-23:00" "$(_config_hours_as_runtime "7-23")" +check "spaced overnight is normalized" "22:00-06:00" "$(_config_hours_as_runtime "22 - 6")" +check "mixed 22-06:00 is normalized" "22:00-06:00" "$(_config_hours_as_runtime "22-06:00")" +garbage_out="$(_config_hours_as_runtime "not-a-range")" +if [[ "${garbage_out}" =~ ^[0-9]{2}:[0-9]{2}-[0-9]{2}:[0-9]{2}$ ]]; then + check "garbage never becomes a valid HH:MM range" "not a range" "${garbage_out}" +else + check "garbage never becomes a valid HH:MM range" "not a range" "not a range" +fi + +echo "=== collect_runtime_daily_cap_inputs ===" +write_config \ + "MONDAY=7-23" \ + "TUESDAY=" \ + "CONFIG_LOCK_HOURS_MONDAY=8-12" \ + "UNINSTALL_LOCK_HOURS_FRIDAY=22 - 6" \ + "CONFIGURE_BLOCK_ENABLED=yes" \ + "UNINSTALL_PROTECTION_MODE=none" \ + "CONFIG_LOCK_ENABLED=true" +cfg=() lock=() uninst=() cbe="" upm="" +collect_runtime_daily_cap_inputs cfg lock uninst cbe upm +check "Sunday restriction defaults" "SUNDAY=1-5" "${cfg[0]}" +check "Monday restriction is normalized" "MONDAY=07:00-23:00" "${cfg[1]}" +check "an explicit empty Tuesday stays empty" "TUESDAY=" "${cfg[2]}" +check "Wednesday restriction defaults" "WEDNESDAY=0-5" "${cfg[3]}" +check "Saturday restriction defaults" "SATURDAY=1-5" "${cfg[6]}" +check "Monday configure lock is read" "CONFIG_LOCK_HOURS_MONDAY=08:00-12:00" "${lock[1]}" +check "an omitted configure lock day stays unset" "" "${lock[4]:-}" +check "Friday uninstall lock is normalized" "UNINSTALL_LOCK_HOURS_FRIDAY=22:00-06:00" "${uninst[5]}" +check "configure block flag resolves yes to true" "true" "${cbe}" +check "uninstall protection mode is read" "none" "${upm}" +check "lock enabled is appended after the day lines" "CONFIG_LOCK_ENABLED=true" "${lock[@]: -1}" + +echo "=== runtime_daily_caps_are_safe ===" +rm -f "${CONFIG_FILE}" +runtime_daily_caps_are_safe +check "a missing config file is safe" "0" "$?" +write_config "MONDAY=7-23" +runtime_daily_caps_are_safe +check "16 h is safe" "0" "$?" +write_config "MONDAY=6-23" +runtime_daily_caps_are_safe +check "17 h is unsafe" "1" "$?" +write_config "MONDAY=not-a-range" +runtime_daily_caps_are_safe +check "an unparseable day is unsafe" "1" "$?" +write_config "MONDAY=8-20" "CONFIG_LOCK_HOURS_MONDAY=15-23" "CONFIGURE_BLOCK_ENABLED=yes" +runtime_daily_caps_are_safe +check "restriction plus lock merged to 15 h is safe" "0" "$?" +write_config "MONDAY=6-23" "CONFIGURE_BLOCK_ENABLED=no" +runtime_daily_caps_are_safe +check "the restriction alone still counts with the block off" "1" "$?" + +echo "=== append_missing_restriction_default_lines ===" +missing=() +append_missing_restriction_default_lines missing "MONDAY=7-23" "TUESDAY=" "CONFIG_LOCK_HOURS_WEDNESDAY=1-2" +check "five days are missing" "5" "${#missing[@]}" +check "Sunday gets the Sunday default" "SUNDAY=1-5" "${missing[0]}" +check "Wednesday is still missing despite a lock line" "WEDNESDAY=0-5" "${missing[1]}" +check "Saturday gets the Saturday default" "SATURDAY=1-5" "${missing[4]}" +all_present=() +append_missing_restriction_default_lines all_present SUNDAY=1 MONDAY=1 TUESDAY=1 WEDNESDAY=1 THURSDAY=1 FRIDAY=1 SATURDAY=1 +check "nothing is added when every day is present" "0" "${#all_present[@]}" +none_present=() +append_missing_restriction_default_lines none_present +check "all seven are added from no arguments" "7" "${#none_present[@]}" + +echo "" +echo "Results: ${_PASS} passed, ${_FAIL} failed" +[[ "${_FAIL}" -eq 0 ]] || exit 1 diff --git a/tests/test-configure-dialogs-darwin-ui.py b/tests/test-configure-dialogs-darwin-ui.py new file mode 100644 index 0000000..80e9318 --- /dev/null +++ b/tests/test-configure-dialogs-darwin-ui.py @@ -0,0 +1,862 @@ +#!/usr/bin/env python3 +"""Unit tests for the macOS configure-wizard tkinter dialogs in lib/. + +Covers configure_dialogs_darwin_{window,time_ui,text_ui,list_ui,table_ui}.py, +the one-shot CLIs configure-dialogs-darwin-{time,text,table}.py, and the +dialog daemon configure-dialogs-darwin-daemon.py. + +Nothing here opens a window. Widgets are recorded fakes, and run_modal is a +hook that clicks a button or presses a key instead of blocking. The modules +are imported from lib/ so coverage counts their lines. Importing tkinter does +not need a display, so these tests run the same with or without one. + +Run: + python3 tests/test-configure-dialogs-darwin-ui.py +""" + +from __future__ import annotations + +import importlib +import importlib.util +import io +import json +import sys +import tkinter as tk +import types +import unittest +from contextlib import redirect_stderr, redirect_stdout +from pathlib import Path +from unittest import mock + +REPO_ROOT = Path(__file__).resolve().parents[1] +LIB_DIR = REPO_ROOT / "lib" +sys.path.insert(0, str(LIB_DIR)) + +import configure_dialogs_darwin_list_ui as list_ui # noqa: E402 +import configure_dialogs_darwin_table_ui as table_ui # noqa: E402 +import configure_dialogs_darwin_text_ui as text_ui # noqa: E402 +import configure_dialogs_darwin_time_ui as time_ui # noqa: E402 +import configure_dialogs_darwin_window as cd_window # noqa: E402 + + +def load_script(filename: str, name: str) -> types.ModuleType: + """Import a hyphenated lib/ script without running its __main__ block.""" + spec = importlib.util.spec_from_file_location(name, LIB_DIR / filename) + assert spec is not None and spec.loader is not None, filename + module = importlib.util.module_from_spec(spec) + sys.modules[name] = module + spec.loader.exec_module(module) + return module + + +class FakeWidget: + """A widget that records its constructor arguments and tiny bits of state.""" + + def __init__(self, kind: str, *args, **kwargs): + self.kind = kind + self.args = args + self.kwargs = kwargs + self.command = kwargs.get("command") + self.text = kwargs.get("text") + self.value = None + self.selected: tuple = () + self.inserted: list = [] + self.headings: dict = {} + self.columns: dict = {} + self.handlers: dict = {} + + def bind(self, sequence, func, add=None): + self.handlers[sequence] = func + + def get(self, *_args): + return self.value + + def set(self, value): + self.value = value + + def insert(self, *args, **kwargs): + self.inserted.append((args, kwargs)) + + def heading(self, col, **kwargs): + self.headings[col] = kwargs + + def column(self, col, **kwargs): + self.columns[col] = kwargs + + def selection(self): + return self.selected + + def selection_set(self, item): + self.selected = (item,) + + def curselection(self): + return self.selected + + def __getattr__(self, name): + # pack, grid, configure, bind, focus and the rest are no-ops. + if name.startswith("__"): + raise AttributeError(name) + return mock.MagicMock(name=name) + + +class Harness: + """Fake ttk plus fake tk widgets that remember what a dialog built.""" + + def __init__(self): + self.widgets: list[FakeWidget] = [] + self.ttk = types.SimpleNamespace( + **{ + kind: self._factory(kind) + for kind in ( + "Frame", "LabelFrame", "Label", "Button", "Combobox", "Scrollbar", "Treeview", + ) + } + ) + + def _factory(self, kind): + def make(*args, **kwargs): + widget = FakeWidget(kind, *args, **kwargs) + self.widgets.append(widget) + return widget + + return make + + def make_tk(self, kind): + return self._factory(kind) + + def of(self, kind): + return [w for w in self.widgets if w.kind == kind] + + def button(self, label): + return next(w for w in self.of("Button") if w.text == label) + + +def make_window(): + window = mock.MagicMock(name="window") + window.handlers = {} + + def bind(sequence, func, add=None): + window.handlers[sequence] = func + + window.bind.side_effect = bind + return window + + +def run_dialog(module, show, window, payload, harness, action): + """Run show(window, payload) with run_modal replaced by *action*.""" + fake_cd = mock.MagicMock(name="cd_window") + fake_cd.run_modal.side_effect = lambda _w: action() + patches = [ + mock.patch.object(module, "ttk", harness.ttk), + mock.patch.object(module, "_cd_window", fake_cd), + ] + for p in patches: + p.start() + try: + return show(window, payload), fake_cd + finally: + for p in patches: + p.stop() + + +class WindowHelperTests(unittest.TestCase): + def test_stable_geometry_centers_the_dialog(self): + window = mock.MagicMock() + window.winfo_screenwidth.return_value = 2000 + window.winfo_screenheight.return_value = 1200 + cd_window.set_stable_geometry(window, 500, 300) + window.geometry.assert_called_once_with("500x300+750+300") + + def test_stable_geometry_never_goes_negative(self): + window = mock.MagicMock() + window.winfo_screenwidth.return_value = 100 + window.winfo_screenheight.return_value = 100 + cd_window.set_stable_geometry(window, 500, 300) + window.geometry.assert_called_once_with("500x300+0+0") + + def test_stable_geometry_falls_back_without_a_screen(self): + window = mock.MagicMock() + window.winfo_screenwidth.side_effect = tk.TclError("no display") + cd_window.set_stable_geometry(window, 500, 300) + window.geometry.assert_called_once_with("500x300") + + def test_close_modal_destroys_a_plain_toplevel(self): + window = mock.MagicMock(spec=tk.Toplevel) + cd_window.close_modal(window) + window.destroy.assert_called_once_with() + + def test_close_modal_quits_the_root(self): + window = mock.MagicMock(name="root") + cd_window.close_modal(window) + window.quit.assert_called_once_with() + + def test_close_modal_withdraws_a_reusable_toplevel(self): + window = mock.MagicMock(spec=tk.Toplevel) + window._sw_reusable_modal = True + done = mock.MagicMock() + window._sw_modal_done_var = done + cd_window.close_modal(window) + window.withdraw.assert_called_once_with() + done.set.assert_called_once_with(True) + window.destroy.assert_not_called() + + def test_close_modal_tolerates_tcl_errors_on_a_reusable_toplevel(self): + window = mock.MagicMock(spec=tk.Toplevel) + window._sw_reusable_modal = True + window.withdraw.side_effect = tk.TclError("gone") + done_var = mock.MagicMock() + done_var.set.side_effect = tk.TclError("gone") + window._sw_modal_done_var = done_var + cd_window.close_modal(window) + + def test_run_modal_runs_the_mainloop_for_a_root(self): + window = mock.MagicMock(name="root") + cd_window.run_modal(window) + window.update_idletasks.assert_called_once_with() + window.mainloop.assert_called_once_with() + + def test_run_modal_waits_for_a_plain_toplevel(self): + window = mock.MagicMock(spec=tk.Toplevel) + window.master = mock.MagicMock() + cd_window.run_modal(window) + window.deiconify.assert_called_once_with() + window.grab_set.assert_called_once_with() + window.master.wait_window.assert_called_once_with(window) + window.grab_release.assert_called_once_with() + window.withdraw.assert_not_called() + + def test_run_modal_waits_on_a_variable_for_a_reusable_toplevel(self): + window = mock.MagicMock(spec=tk.Toplevel) + window.master = mock.MagicMock() + window._sw_reusable_modal = True + with mock.patch.object(cd_window.tk, "BooleanVar") as boolean_var: + cd_window.run_modal(window) + window.master.wait_variable.assert_called_once_with(boolean_var.return_value) + window.master.wait_window.assert_not_called() + window.withdraw.assert_called_once_with() + self.assertIsNone(window._sw_modal_done_var) + + def test_run_modal_survives_tcl_errors(self): + window = mock.MagicMock(spec=tk.Toplevel) + window.master = mock.MagicMock() + window._sw_reusable_modal = True + window.deiconify.side_effect = tk.TclError("unmapped") + window.grab_release.side_effect = tk.TclError("gone") + window.withdraw.side_effect = tk.TclError("gone") + with mock.patch.object(cd_window.tk, "BooleanVar"): + cd_window.run_modal(window) + window.master.wait_variable.assert_called_once() + + def test_cleanup_skips_a_destroyed_window(self): + window = mock.MagicMock() + window.winfo_exists.return_value = False + cd_window.cleanup_modal_window(window) + window.winfo_children.assert_not_called() + + def test_cleanup_skips_when_the_interpreter_is_gone(self): + window = mock.MagicMock() + window.winfo_exists.side_effect = tk.TclError("gone") + cd_window.cleanup_modal_window(window) + window.winfo_children.assert_not_called() + + def test_cleanup_destroys_children_of_a_plain_window(self): + window = mock.MagicMock() + window.winfo_exists.return_value = True + children = [mock.MagicMock(), mock.MagicMock()] + window.winfo_children.return_value = children + window._sw_reusable_modal = False + cd_window.cleanup_modal_window(window) + for child in children: + child.destroy.assert_called_once_with() + window.unbind.assert_not_called() + + def test_cleanup_resets_bindings_on_a_reusable_window(self): + window = mock.MagicMock() + window.winfo_exists.return_value = True + window.winfo_children.return_value = [] + window._sw_reusable_modal = True + cd_window.cleanup_modal_window(window) + self.assertEqual( + [c.args[0] for c in window.unbind.call_args_list], + ["", "", "", ""], + ) + window.protocol.assert_called_once_with("WM_DELETE_WINDOW", "") + + def test_cleanup_tolerates_tcl_errors_while_unbinding(self): + window = mock.MagicMock() + window.winfo_exists.return_value = True + window.winfo_children.return_value = [] + window._sw_reusable_modal = True + window.unbind.side_effect = tk.TclError("gone") + window.protocol.side_effect = tk.TclError("gone") + cd_window.cleanup_modal_window(window) + + def test_app_icon_is_set_when_a_file_exists(self): + root = mock.MagicMock() + with mock.patch.object(Path, "is_file", return_value=True), \ + mock.patch.object(cd_window.tk, "PhotoImage") as photo: + cd_window.apply_app_icon(root) + root.iconphoto.assert_called_once_with(True, photo.return_value) + self.assertIs(root._sw_app_icon, photo.return_value) + + def test_app_icon_keeps_the_default_on_a_tk_error(self): + root = mock.MagicMock() + with mock.patch.object(Path, "is_file", return_value=True), \ + mock.patch.object(cd_window.tk, "PhotoImage", side_effect=tk.TclError("bad")): + cd_window.apply_app_icon(root) + root.iconphoto.assert_not_called() + + def test_app_icon_does_nothing_without_a_file(self): + root = mock.MagicMock() + with mock.patch.object(Path, "is_file", return_value=False), \ + mock.patch.object(cd_window.tk, "PhotoImage") as photo: + cd_window.apply_app_icon(root) + photo.assert_not_called() + + def test_frontmost_raises_then_drops_topmost_after_the_grace_period(self): + root = mock.MagicMock() + callbacks = {} + root.bind.side_effect = lambda seq, func, add=None: callbacks.setdefault(seq, func) + cd_window.apply_initial_frontmost(root) + root.lift.assert_called_once_with() + root.focus_force.assert_called_once_with() + root.attributes.assert_called_with("-topmost", True) + grace_ms, end_grace = root.after.call_args_list[0].args + self.assertEqual(grace_ms, cd_window._GRACE_MS) + + root.attributes.reset_mock() + callbacks[""]() + root.attributes.assert_not_called() # still inside the grace period + + end_grace() + callbacks[""]() + root.attributes.assert_called_once_with("-topmost", False) + + # The 50 ms and idle re-asserts run the raise again. + root.lift.reset_mock() + root.after.call_args_list[1].args[1]() + root.after_idle.call_args.args[0]() + self.assertEqual(root.lift.call_count, 2) + + def test_frontmost_tolerates_tcl_errors(self): + root = mock.MagicMock() + root.lift.side_effect = tk.TclError("gone") + root.attributes.side_effect = tk.TclError("gone") + callbacks = {} + root.bind.side_effect = lambda seq, func, add=None: callbacks.setdefault(seq, func) + cd_window.apply_initial_frontmost(root) + root.after.call_args_list[0].args[1]() + callbacks[""]() + + +class TimeDialogTests(unittest.TestCase): + def test_hour_normalisation(self): + cases = {1: "1", 12: "12", 0: "12", -3: "12", 13: "1", 24: "12", "7": "7", "x": "11", None: "11"} + for value, expected in cases.items(): + with self.subTest(value=value): + self.assertEqual(time_ui._norm_hour(value), expected) + + def test_minute_normalisation(self): + cases = { + "00": "00", "15": "15", "45": "45", "7": "00", "8": "15", + "20": "15", "53": "00", "abc": "00", " 30 ": "30", + } + for value, expected in cases.items(): + with self.subTest(value=value): + self.assertEqual(time_ui._norm_minute(value), expected) + + def test_ampm_normalisation(self): + self.assertEqual(time_ui._norm_ampm("pm"), "PM") + self.assertEqual(time_ui._norm_ampm(" PM "), "PM") + self.assertEqual(time_ui._norm_ampm("am"), "AM") + self.assertEqual(time_ui._norm_ampm("junk"), "AM") + + def _show(self, payload, action): + harness = Harness() + window = make_window() + result, fake_cd = run_dialog( + time_ui, time_ui.show_time_dialog, window, payload, harness, + lambda: action(harness, window), + ) + return result, harness, window, fake_cd + + def test_ok_returns_the_start_and_end_as_a_range(self): + payload = { + "start": {"hour": 9, "minute": "30", "ampm": "PM"}, + "end": {"hour": 6, "minute": "00", "ampm": "AM"}, + } + result, _h, _w, fake_cd = self._show(payload, lambda h, w: h.button("OK").command()) + self.assertEqual(result, (True, "9:30PM-6:00AM", 0)) + fake_cd.close_modal.assert_called_once() + + def test_defaults_when_the_payload_has_no_times(self): + result, *_ = self._show({}, lambda h, w: h.button("OK").command()) + self.assertEqual(result, (True, "11:00AM-11:00AM", 0)) + + def test_edited_comboboxes_are_read_back(self): + def action(h, w): + start, end = h.of("Combobox")[:3], h.of("Combobox")[3:] + for widget, value in zip(start + end, ("3", "45", "pm", "14", "07", "am")): + widget.set(value) + h.button("OK").command() + + result, *_ = self._show({}, action) + self.assertEqual(result, (True, "3:45PM-2:00AM", 0)) + + def test_cancel_button_returns_a_cancel(self): + result, *_ = self._show({}, lambda h, w: h.button("Cancel").command()) + self.assertEqual(result, (False, None, 1)) + + def test_return_accepts_and_escape_cancels(self): + result, *_ = self._show({}, lambda h, w: w.handlers[""](None)) + self.assertEqual(result[0:2], (True, "11:00AM-11:00AM")) + result, *_ = self._show({}, lambda h, w: w.handlers[""](None)) + self.assertEqual(result, (False, None, 1)) + + def test_closing_the_window_cancels(self): + def action(h, w): + protocol = next(c for c in w.protocol.call_args_list if c.args[0] == "WM_DELETE_WINDOW") + protocol.args[1]() + + result, *_ = self._show({}, action) + self.assertEqual(result, (False, None, 1)) + + def test_day_and_hint_labels_are_shown_only_when_given(self): + _r, plain, *_ = self._show({}, lambda h, w: h.button("OK").command()) + plain_labels = [w.text for w in plain.of("Label")] + self.assertNotIn("Day: Monday", plain_labels) + _r, rich, *_ = self._show( + {"day_name": " Monday ", "hint_text": "Pick a range", "title": "T", "width": 600, "height": 400}, + lambda h, w: h.button("OK").command(), + ) + labels = [w.text for w in rich.of("Label")] + self.assertIn("Day: Monday", labels) + self.assertIn("Pick a range", labels) + + +class TextDialogTests(unittest.TestCase): + def test_save_action_detection(self): + for label in ("Yes, save", "yes", "Save changes", "SAVE"): + self.assertTrue(text_ui._is_save_action(label), label) + for label in ("No", "Back to Main Menu", "Cancel"): + self.assertFalse(text_ui._is_save_action(label), label) + + def _show(self, payload, action): + harness = Harness() + window = make_window() + text_widget = FakeWidget("Text") + with mock.patch.object(text_ui.tk, "Text", return_value=text_widget): + result, fake_cd = run_dialog( + text_ui, text_ui.show_text_dialog, window, payload, harness, + lambda: action(harness, window), + ) + return result, harness, window, text_widget + + def test_the_text_is_inserted_and_made_read_only(self): + _r, _h, _w, widget = self._show({"text": "hello"}, lambda h, w: h.button("Close").command()) + self.assertEqual(widget.inserted, [(("1.0", "hello"), {})]) + + def test_without_buttons_close_is_the_only_button(self): + result, harness, *_ = self._show({}, lambda h, w: h.button("Close").command()) + self.assertEqual(result, (True, None, 0)) + self.assertEqual([b.text for b in harness.of("Button")], ["Close"]) + + def test_without_buttons_escape_and_window_close_dismiss(self): + result, *_ = self._show({}, lambda h, w: w.handlers[""](None)) + self.assertEqual(result, (True, None, 0)) + + def test_a_save_button_gives_exit_code_zero(self): + payload = {"buttons": ["Yes, save", "No"]} + result, harness, *_ = self._show(payload, lambda h, w: h.button("Yes, save").command()) + self.assertEqual(result, (True, "Yes, save", 0)) + self.assertEqual([b.text for b in harness.of("Button")], ["No", "Yes, save"]) + + def test_a_non_save_button_gives_exit_code_one(self): + payload = {"buttons": ["Yes, save", "No"]} + result, *_ = self._show(payload, lambda h, w: h.button("No").command()) + self.assertEqual(result, (False, "No", 1)) + + def test_return_presses_the_default_button(self): + payload = {"buttons": ["Yes, save", "No"], "default_button": "No"} + result, *_ = self._show(payload, lambda h, w: w.handlers[""](None)) + self.assertEqual(result, (False, "No", 1)) + result, *_ = self._show({"buttons": ["Yes, save", "No"]}, lambda h, w: w.handlers[""](None)) + self.assertEqual(result, (True, "Yes, save", 0)) + + def test_escape_picks_the_last_button(self): + payload = {"buttons": ["Yes, save", "Back to Main Menu"]} + result, *_ = self._show(payload, lambda h, w: w.handlers[""](None)) + self.assertEqual(result, (False, "Back to Main Menu", 1)) + + def test_closing_with_buttons_but_no_choice_is_a_cancel(self): + result, *_ = self._show({"buttons": ["Yes", "No"]}, lambda h, w: None) + self.assertEqual(result, (False, None, 1)) + + def test_a_non_list_buttons_value_is_ignored(self): + result, harness, *_ = self._show({"buttons": "oops"}, lambda h, w: h.button("Close").command()) + self.assertEqual(result, (True, None, 0)) + + +class ListDialogTests(unittest.TestCase): + def _show(self, payload, action, selected=None): + """Run the dialog; *selected* replaces the preselected row before *action*.""" + harness = Harness() + window = make_window() + listbox = FakeWidget("Listbox") + with mock.patch.object(list_ui.tk, "Listbox", return_value=listbox): + result, fake_cd = run_dialog( + list_ui, list_ui.show_list_dialog, window, payload, harness, + lambda: (setattr(listbox, "selected", selected) if selected is not None else None, + action(harness, window, listbox))[1], + ) + return result, harness, window, listbox + + def test_no_items_is_an_error(self): + with self.assertRaises(ValueError): + self._show({"items": []}, lambda h, w, lb: None) + with self.assertRaises(ValueError): + self._show({}, lambda h, w, lb: None) + + def test_items_are_inserted_in_order_as_strings(self): + _r, _h, _w, listbox = self._show( + {"items": ["a", 2, "c"]}, lambda h, w, lb: h.button("Cancel").command() + ) + self.assertEqual([args[1] for args, _ in listbox.inserted], ["a", "2", "c"]) + + def test_ok_returns_the_selected_item(self): + result, *_ = self._show( + {"items": ["a", "b", "c"]}, lambda h, w, lb: h.button("OK").command(), selected=(1,) + ) + self.assertEqual(result, (True, "b", 0, False)) + + def test_ok_with_nothing_selected_keeps_the_dialog_open(self): + calls = [] + + def action(h, w, lb): + h.button("OK").command() + calls.append(lb.selected) + h.button("Cancel").command() + + result, *_ = self._show({"items": ["a"]}, action, selected=()) + self.assertEqual(result, (False, None, 1, False)) + self.assertEqual(calls, [()]) + + def test_double_click_and_return_accept(self): + result, *_ = self._show({"items": ["a", "b"]}, lambda h, w, lb: lb.handlers[""](None), selected=(1,)) + self.assertEqual(result[:2], (True, "b")) + result, *_ = self._show({"items": ["a", "b"]}, lambda h, w, lb: w.handlers[""](None)) + self.assertEqual(result[:2], (True, "a")) + + def test_escape_cancels(self): + result, *_ = self._show({"items": ["a"]}, lambda h, w, lb: w.handlers[""](None)) + self.assertEqual(result, (False, None, 1, False)) + + def test_the_shown_flag_follows_the_map_event(self): + result, *_ = self._show( + {"items": ["a"]}, + lambda h, w, lb: (w.handlers[""](None), h.button("Cancel").command()), + ) + self.assertEqual(result, (False, None, 1, True)) + + def test_the_message_is_shown_only_when_given(self): + _r, plain, *_ = self._show({"items": ["a"]}, lambda h, w, lb: h.button("Cancel").command()) + self.assertEqual(plain.of("Label"), []) + _r, withmsg, *_ = self._show( + {"items": ["a"], "message": "Pick one", "title": "T", "width": 400, "height": 250}, + lambda h, w, lb: h.button("Cancel").command(), + ) + self.assertEqual([w.text for w in withmsg.of("Label")], ["Pick one"]) + + +class TableDialogTests(unittest.TestCase): + ROWS = [["Mon", "7-23"], ["Tue", "8-17"]] + + def _show(self, payload, action, selected=None): + harness = Harness() + window = make_window() + trees = [] + original = harness.ttk.Treeview + + def make_tree(*args, **kwargs): + tree = original(*args, **kwargs) + trees.append(tree) + return tree + + harness.ttk.Treeview = make_tree + result, _cd = run_dialog( + table_ui, table_ui.show_table_dialog, window, payload, harness, + lambda: action(harness, window, trees[0]), + ) + return result, harness, window, trees[0] + + def payload(self, **extra): + return {"columns": ["Day", "Hours"], "rows": self.ROWS, **extra} + + def test_missing_columns_is_an_error(self): + with self.assertRaises(ValueError): + self._show({"rows": []}, lambda h, w, t: None) + + def test_print_column_out_of_range_is_an_error(self): + for bad in (0, 3, -1): + payload = self.payload(print_column=bad) + with self.subTest(print_column=bad), self.assertRaises(ValueError): + self._show(payload, lambda h, w, t: None) + + def test_headings_columns_and_rows_are_built(self): + _r, _h, _w, tree = self._show(self.payload(), lambda h, w, t: h.button("Cancel").command()) + self.assertEqual(tree.headings["c0"], {"text": "Day"}) + self.assertEqual(tree.headings["c1"], {"text": "Hours"}) + self.assertEqual(tree.columns["c0"]["width"], 110) + self.assertEqual(tree.columns["c1"]["width"], 180) + self.assertEqual( + [kw["values"] for _a, kw in tree.inserted], [["Mon", "7-23"], ["Tue", "8-17"]] + ) + + def test_short_rows_are_padded_with_empty_cells(self): + _r, _h, _w, tree = self._show( + {"columns": ["A", "B"], "rows": [["only"]]}, lambda h, w, t: h.button("Cancel").command() + ) + self.assertEqual(tree.inserted[0][1]["values"], ["only", ""]) + + def test_the_first_row_is_preselected_so_ok_returns_it(self): + result, *_ = self._show(self.payload(), lambda h, w, t: h.button("OK").command()) + self.assertEqual(result, (True, "Mon", 0, False)) + + def test_print_column_chooses_which_cell_is_returned(self): + result, *_ = self._show(self.payload(print_column=2), lambda h, w, t: h.button("OK").command()) + self.assertEqual(result[:2], (True, "7-23")) + + def test_a_chosen_row_is_returned(self): + def action(h, w, tree): + tree.selected = ("1",) + h.button("OK").command() + + result, *_ = self._show(self.payload(), action) + self.assertEqual(result[:2], (True, "Tue")) + + def test_ok_with_nothing_selected_keeps_the_dialog_open(self): + def action(h, w, tree): + tree.selected = () + h.button("OK").command() + h.button("Cancel").command() + + result, *_ = self._show(self.payload(), action) + self.assertEqual(result, (False, None, 1, False)) + + def test_double_click_return_and_escape(self): + result, *_ = self._show(self.payload(), lambda h, w, t: t.handlers[""](None)) + self.assertEqual(result[:2], (True, "Mon")) + result, *_ = self._show(self.payload(), lambda h, w, t: w.handlers[""](None)) + self.assertEqual(result[:2], (True, "Mon")) + result, *_ = self._show(self.payload(), lambda h, w, t: w.handlers[""](None)) + self.assertEqual(result[:2], (False, None)) + + def test_an_empty_table_is_not_preselected(self): + result, *_ = self._show( + {"columns": ["A"], "rows": []}, lambda h, w, t: h.button("OK").command() + ) + self.assertEqual(result, (False, None, 1, False)) + + def test_the_shown_flag_follows_the_map_event(self): + result, *_ = self._show( + self.payload(message="Pick", title="T"), + lambda h, w, t: (w.handlers[""](None), h.button("Cancel").command()), + ) + self.assertEqual(result, (False, None, 1, True)) + + +class OneShotCliTests(unittest.TestCase): + def run_cli(self, module, stdin_text): + stdout, stderr = io.StringIO(), io.StringIO() + with mock.patch.object(sys, "stdin", io.StringIO(stdin_text)), \ + redirect_stdout(stdout), redirect_stderr(stderr): + with self.assertRaises(SystemExit) as raised: + module.main() + return raised.exception.code, stdout.getvalue(), stderr.getvalue() + + def check_invalid_json(self, module): + with mock.patch.object(module.tk, "Tk") as tk_root: + code, out, err = self.run_cli(module, "{not json") + self.assertEqual(code, 1) + self.assertEqual(out, "") + self.assertIn("Invalid JSON input", err) + tk_root.assert_not_called() + + def test_time_cli(self): + module = load_script("configure-dialogs-darwin-time.py", "cd_time_cli") + self.check_invalid_json(module) + with mock.patch.object(module.tk, "Tk") as tk_root, \ + mock.patch.object(module._cd_window, "apply_app_icon") as icon, \ + mock.patch.object(module.time_ui, "show_time_dialog", return_value=(True, "9:00AM-5:00PM", 0)): + code, out, _err = self.run_cli(module, "{}") + self.assertEqual((code, out), (0, "9:00AM-5:00PM\n")) + icon.assert_called_once_with(tk_root.return_value) + tk_root.return_value.destroy.assert_called_once_with() + with mock.patch.object(module.tk, "Tk"), \ + mock.patch.object(module._cd_window, "apply_app_icon"), \ + mock.patch.object(module.time_ui, "show_time_dialog", return_value=(False, None, 1)): + code, out, _err = self.run_cli(module, "{}") + self.assertEqual((code, out), (1, "")) + + def test_text_cli(self): + module = load_script("configure-dialogs-darwin-text.py", "cd_text_cli") + self.check_invalid_json(module) + with mock.patch.object(module.tk, "Tk") as tk_root, \ + mock.patch.object(module._cd_window, "apply_app_icon"), \ + mock.patch.object(module.text_ui, "show_text_dialog", return_value=(True, "Yes, save", 0)): + code, out, _err = self.run_cli(module, "{}") + self.assertEqual((code, out), (0, "Yes, save\n")) + tk_root.return_value.destroy.assert_called_once_with() + with mock.patch.object(module.tk, "Tk"), \ + mock.patch.object(module._cd_window, "apply_app_icon"), \ + mock.patch.object(module.text_ui, "show_text_dialog", return_value=(False, None, 1)): + code, out, _err = self.run_cli(module, "{}") + self.assertEqual((code, out), (1, "")) + + def test_table_cli(self): + module = load_script("configure-dialogs-darwin-table.py", "cd_table_cli") + self.check_invalid_json(module) + with mock.patch.object(module.tk, "Tk") as tk_root, \ + mock.patch.object(module._cd_window, "apply_app_icon"), \ + mock.patch.object(module.table_ui, "show_table_dialog", return_value=(True, "Mon", 0, True)): + code, out, _err = self.run_cli(module, "{}") + self.assertEqual((code, out), (0, "Mon\n")) + tk_root.return_value.destroy.assert_called_once_with() + with mock.patch.object(module.tk, "Tk"), \ + mock.patch.object(module._cd_window, "apply_app_icon"), \ + mock.patch.object(module.table_ui, "show_table_dialog", return_value=(False, None, 1, True)): + code, out, _err = self.run_cli(module, "{}") + self.assertEqual((code, out), (1, "")) + + +class DaemonTests(unittest.TestCase): + def setUp(self): + self.daemon = load_script("configure-dialogs-darwin-daemon.py", "cd_daemon") + self.dialog = mock.MagicMock(name="dialog") + self.root = mock.MagicMock(name="root") + self.fake_ui = { + "list_ui": self.fake_module("show_list_dialog", (True, "b", 0, True)), + "table_ui": self.fake_module("show_table_dialog", (True, "Mon", 0, True)), + "text_ui": self.fake_module("show_text_dialog", (True, "Yes", 0)), + "time_ui": self.fake_module("show_time_dialog", (True, "9:00AM-5:00PM", 0)), + } + for name, fake in self.fake_ui.items(): + setattr(self.daemon, name, fake) + + @staticmethod + def fake_module(function: str, result: tuple) -> mock.MagicMock: + module = mock.MagicMock() + getattr(module, function).return_value = result + return module + + def run_op(self, op, **fields): + return self.daemon._run_dialog(self.root, self.dialog, op, {"op": op, **fields}) + + def test_list_table_time_and_text_results(self): + self.assertEqual(self.run_op("list"), {"ok": True, "value": "b", "shown": True}) + self.assertEqual(self.run_op("table"), {"ok": True, "value": "Mon", "shown": True}) + self.assertEqual(self.run_op("time"), {"ok": True, "value": "9:00AM-5:00PM"}) + self.assertEqual(self.run_op("text"), {"ok": True, "value": "Yes", "exit_code": 0}) + + def test_cancelled_results(self): + self.fake_ui["list_ui"].show_list_dialog.return_value = (False, None, 1, False) + self.fake_ui["table_ui"].show_table_dialog.return_value = (False, None, 1, True) + self.fake_ui["time_ui"].show_time_dialog.return_value = (False, None, 1) + self.fake_ui["text_ui"].show_text_dialog.return_value = (False, None, 1) + self.assertEqual(self.run_op("list"), {"ok": False, "cancelled": True, "shown": False}) + self.assertEqual(self.run_op("table"), {"ok": False, "cancelled": True, "shown": True}) + self.assertEqual(self.run_op("time"), {"ok": False, "cancelled": True}) + self.assertEqual(self.run_op("text"), {"ok": False, "cancelled": True}) + + def test_a_text_dialog_dismissed_with_a_label_still_reports_it(self): + self.fake_ui["text_ui"].show_text_dialog.return_value = (False, "No", 1) + self.assertEqual(self.run_op("text"), {"ok": True, "value": "No", "exit_code": 1}) + + def test_unknown_op_is_an_error(self): + self.assertEqual(self.run_op("bogus"), {"ok": False, "error": "unknown op: bogus"}) + + def test_the_dialog_is_released_and_hidden_afterwards(self): + self.dialog.winfo_exists.return_value = True + self.run_op("time") + self.dialog.grab_release.assert_called_once_with() + self.dialog.withdraw.assert_called_once_with() + + def test_a_destroyed_dialog_is_left_alone(self): + self.dialog.winfo_exists.return_value = False + self.run_op("time") + self.dialog.grab_release.assert_not_called() + self.dialog.withdraw.assert_not_called() + + def test_tcl_errors_during_cleanup_are_ignored(self): + self.dialog.winfo_exists.side_effect = tk.TclError("gone") + self.assertTrue(self.run_op("time")["ok"]) + + def test_ui_modules_are_imported_lazily(self): + for name in self.fake_ui: + setattr(self.daemon, name, None) + modules = { + f"configure_dialogs_darwin_{op}_ui": fake + for op, fake in ( + ("list", self.fake_ui["list_ui"]), ("table", self.fake_ui["table_ui"]), + ("text", self.fake_ui["text_ui"]), ("time", self.fake_ui["time_ui"]), + ) + } + with mock.patch.dict(sys.modules, modules): + self.assertTrue(self.run_op("list")["ok"]) + self.assertTrue(self.run_op("table")["ok"]) + self.assertTrue(self.run_op("time")["ok"]) + self.assertTrue(self.run_op("text")["ok"]) + + def test_warm_imports_loads_all_four_modules(self): + for name in self.fake_ui: + setattr(self.daemon, name, None) + self.daemon._warm_imports() + self.assertIs(self.daemon.list_ui, list_ui) + self.assertIs(self.daemon.table_ui, table_ui) + self.assertIs(self.daemon.text_ui, text_ui) + self.assertIs(self.daemon.time_ui, time_ui) + + def run_main(self, lines): + stdout = io.StringIO() + root = mock.MagicMock(name="root") + with mock.patch.object(self.daemon.tk, "Tk", return_value=root), \ + mock.patch.object(self.daemon.tk, "Toplevel"), \ + mock.patch.object(self.daemon, "_warm_imports"), \ + mock.patch.object(cd_window, "apply_app_icon") as icon, \ + mock.patch.object(sys, "stdin", io.StringIO(lines)), \ + redirect_stdout(stdout): + with self.assertRaises(SystemExit) as raised: + self.daemon.main() + responses = [json.loads(line) for line in stdout.getvalue().splitlines()] + return raised.exception.code, responses, root, icon + + def test_main_answers_each_request_and_quits(self): + lines = "\n".join([ + "", + "not json", + json.dumps({"op": "bogus"}), + json.dumps({"op": "time"}), + json.dumps({"op": "quit"}), + json.dumps({"op": "time"}), + ]) + code, responses, root, icon = self.run_main(lines) + self.assertEqual(code, 0) + self.assertEqual(responses[0], {"ok": True, "ready": True}) + self.assertTrue(responses[1]["error"].startswith("invalid json")) + self.assertEqual(responses[2], {"ok": False, "error": "unknown op: bogus"}) + self.assertEqual(responses[3], {"ok": True, "value": "9:00AM-5:00PM"}) + self.assertEqual(responses[4], {"ok": True, "quit": True}) + self.assertEqual(len(responses), 5) # nothing after quit + root.withdraw.assert_called_once_with() + root.destroy.assert_called_once_with() + icon.assert_called_once_with(root) + + def test_main_exits_cleanly_at_end_of_input(self): + code, responses, root, _icon = self.run_main("") + self.assertEqual(code, 0) + self.assertEqual(responses, [{"ok": True, "ready": True}]) + root.destroy.assert_not_called() + + +if __name__ == "__main__": + unittest.main() diff --git a/tests/test-popup-display-source.sh b/tests/test-popup-display-source.sh index f990488..cba4a92 100644 --- a/tests/test-popup-display-source.sh +++ b/tests/test-popup-display-source.sh @@ -3,6 +3,10 @@ set -euo pipefail SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")/.." && pwd)" LIB_DIR="${SCRIPT_DIR}/lib" +# Temp HOME: the config and log directories below must not be created in the real one. +TMP_HOME="$(mktemp -d)" +trap 'rm -rf "${TMP_HOME}"' EXIT +export HOME="${TMP_HOME}" export CONFIG_DIR="${HOME}/.config/sleep-warning" export CONFIG_FILE="${CONFIG_DIR}/config/sleep-warning.conf" mkdir -p "${CONFIG_DIR}/config" "${CONFIG_DIR}/logs" diff --git a/tests/test-popup-size-config.sh b/tests/test-popup-size-config.sh new file mode 100644 index 0000000..a29bdd9 --- /dev/null +++ b/tests/test-popup-size-config.sh @@ -0,0 +1,166 @@ +#!/bin/bash + +############################################################################### +# Tests lib/config-popup-size.sh: size getters, fixed and display-based +# dimensions, custom sizes, and the 95% safe-display clamp. +# Runs headless with a temp HOME and a stubbed get_display_resolution. +############################################################################### + +SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")/.." && pwd)" + +TMP_HOME="$(mktemp -d)" +trap 'rm -rf "${TMP_HOME}"' EXIT +export HOME="${TMP_HOME}" + +# shellcheck disable=SC1091 +source "${SCRIPT_DIR}/lib/config.sh" || exit 1 + +CONFIG_FILE="${TMP_HOME}/sleep-warning.conf" + +# Values that the assertions repeat. +SIZE_DEFAULT="medium" +DIMS_FALLBACK="1280 720" +DIMS_XSMALL="384 216" +DIMS_MEDIUM_DISPLAY="768 432" +SCREEN_2560="2560 1440" +RESOLUTION="${SCREEN_2560}" +get_display_resolution() { + [[ -n "${RESOLUTION}" ]] || return 1 + echo "${RESOLUTION}" +} + +_PASS=0 +_FAIL=0 + +check() { + local desc="$1" expected="$2" actual="$3" + if [[ "${actual}" == "${expected}" ]]; then + _PASS=$(( _PASS + 1 )); echo " PASS ${desc} (${actual})" + else + _FAIL=$(( _FAIL + 1 )); echo " FAIL ${desc}: expected '${expected}', got '${actual}'" + fi +} + +write_config() { + printf '%s\n' "$@" > "${CONFIG_FILE}" +} + +echo "=== get_popup_size ===" +rm -f "${CONFIG_FILE}" +check "missing config file uses the default" "${SIZE_DEFAULT}" "$(get_popup_size)" +write_config "OTHER=1" +check "absent key uses the default" "${SIZE_DEFAULT}" "$(get_popup_size)" +for s in xsmall small medium large xlarge max custom; do + write_config "POPUP_SIZE=${s}" + check "named size ${s}" "${s}" "$(get_popup_size)" +done +write_config "POPUP_SIZE=1000x600" +check "pixel size" "1000x600" "$(get_popup_size)" +write_config "POPUP_SIZE=40%x60%" +check "percent size in range" "40%x60%" "$(get_popup_size)" +write_config "POPUP_SIZE=10%x60%" +check "percent width under 15 falls back" "${SIZE_DEFAULT}" "$(get_popup_size)" +write_config "POPUP_SIZE=60%x96%" +check "percent height over 95 falls back" "${SIZE_DEFAULT}" "$(get_popup_size)" +write_config "POPUP_SIZE=huge" +check "unknown name falls back" "${SIZE_DEFAULT}" "$(get_popup_size)" +write_config " POPUP_SIZE= large " +check "leading space and space after = are tolerated" "large" "$(get_popup_size)" +write_config "POPUP_SIZE=small" "POPUP_SIZE=large" +check "first assignment wins" "small" "$(get_popup_size)" + +echo "=== get_popup_size_mode ===" +rm -f "${CONFIG_FILE}" +check "missing config is fixed" "fixed" "$(get_popup_size_mode)" +write_config "POPUP_SIZE_MODE=display-based" +check "display-based" "display-based" "$(get_popup_size_mode)" +write_config "POPUP_SIZE_MODE=Display-Based" +check "mode is case-insensitive" "display-based" "$(get_popup_size_mode)" +write_config "POPUP_SIZE_MODE=fixed" +check "fixed" "fixed" "$(get_popup_size_mode)" +write_config "POPUP_SIZE_MODE=sideways" +check "unknown mode is fixed" "fixed" "$(get_popup_size_mode)" + +echo "=== get_popup_size_custom and absolute ===" +rm -f "${CONFIG_FILE}" +check "custom default" "50%x50%" "$(get_popup_size_custom)" +check "absolute default" "1280x720" "$(get_popup_size_custom_absolute)" +write_config "POPUP_SIZE_CUSTOM=70%x40%" "POPUP_SIZE_CUSTOM_ABSOLUTE=1600x900" +check "custom is read" "70%x40%" "$(get_popup_size_custom)" +check "absolute is read" "1600x900" "$(get_popup_size_custom_absolute)" +write_config "POPUP_SIZE_CUSTOM=" "POPUP_SIZE_CUSTOM_ABSOLUTE=wide" +check "empty custom uses the default" "50%x50%" "$(get_popup_size_custom)" +check "malformed absolute uses the default" "1280x720" "$(get_popup_size_custom_absolute)" + +echo "=== clamp_popup_dimensions_to_safe_display_max ===" +check "under the limit is unchanged" "1000 500" "$(clamp_popup_dimensions_to_safe_display_max 1000 500 2560 1440)" +check "both axes are clamped to 95%" "2432 1368" "$(clamp_popup_dimensions_to_safe_display_max 5000 5000 2560 1440)" +check "only width is clamped" "950 500" "$(clamp_popup_dimensions_to_safe_display_max 2000 500 1000 1000)" +check "exactly 95% is kept" "950 950" "$(clamp_popup_dimensions_to_safe_display_max 950 950 1000 1000)" + +echo "=== get_popup_dimensions: fixed mode ===" +rm -f "${CONFIG_FILE}" +check "xsmall" "${DIMS_XSMALL}" "$(get_popup_dimensions xsmall)" +check "small" "400 250" "$(get_popup_dimensions small)" +check "${SIZE_DEFAULT}" "800 500" "$(get_popup_dimensions medium)" +check "large" "1230 720" "$(get_popup_dimensions large)" +check "xlarge" "1845 1080" "$(get_popup_dimensions xlarge)" +check "max" "2214 1296" "$(get_popup_dimensions max)" +check "custom with nothing configured" "${DIMS_FALLBACK}" "$(get_popup_dimensions custom)" + +echo "=== get_popup_dimensions: display-based mode ===" +write_config "POPUP_SIZE_MODE=display-based" +check "xsmall is 15%" "${DIMS_XSMALL}" "$(get_popup_dimensions xsmall)" +check "small is 20%" "512 288" "$(get_popup_dimensions small)" +check "medium is 30%" "${DIMS_MEDIUM_DISPLAY}" "$(get_popup_dimensions medium)" +check "large is 50%" "${DIMS_FALLBACK}" "$(get_popup_dimensions large)" +check "xlarge is 75%" "1920 1080" "$(get_popup_dimensions xlarge)" +check "max is 90%" "2304 1296" "$(get_popup_dimensions max)" +check "custom with nothing configured is 50%" "${DIMS_FALLBACK}" "$(get_popup_dimensions custom)" +RESOLUTION="1920 1080" +check "medium scales with the detected resolution" "576 324" "$(get_popup_dimensions medium)" +RESOLUTION="" +check "xsmall falls back to pixels without a resolution" "${DIMS_XSMALL}" "$(get_popup_dimensions xsmall)" +check "small falls back to pixels" "512 288" "$(get_popup_dimensions small)" +check "medium falls back to pixels" "${DIMS_MEDIUM_DISPLAY}" "$(get_popup_dimensions medium)" +check "large falls back to pixels" "1230 720" "$(get_popup_dimensions large)" +check "xlarge falls back to pixels" "1845 1080" "$(get_popup_dimensions xlarge)" +check "max falls back to pixels" "2214 1296" "$(get_popup_dimensions max)" +check "custom falls back to pixels" "${DIMS_FALLBACK}" "$(get_popup_dimensions custom)" +RESOLUTION="${SCREEN_2560}" + +echo "=== get_popup_dimensions: custom ===" +write_config "POPUP_SIZE_CUSTOM=60%x40%" +check "custom percent uses the resolution" "1536 576" "$(get_popup_dimensions custom)" +write_config "POPUP_SIZE_CUSTOM=60%x40%" "POPUP_SIZE_CUSTOM_ABSOLUTE=1000x800" +RESOLUTION="" +check "custom percent without a resolution uses the absolute size" "1000 800" "$(get_popup_dimensions custom)" +RESOLUTION="${SCREEN_2560}" +write_config "POPUP_SIZE_CUSTOM=99%x40%" "POPUP_SIZE_CUSTOM_ABSOLUTE=1000x800" +check "custom percent over 95 uses the absolute size" "1000 800" "$(get_popup_dimensions custom)" +write_config "POPUP_SIZE_CUSTOM=99%x40%" "POPUP_SIZE_CUSTOM_ABSOLUTE=junk" +check "custom percent over 95 with a bad absolute uses 1280x720" "${DIMS_FALLBACK}" "$(get_popup_dimensions custom)" +write_config "POPUP_SIZE_CUSTOM=1500x900" +check "custom pixels" "1500 900" "$(get_popup_dimensions custom)" +write_config "POPUP_SIZE_CUSTOM=9000x9000" +check "custom pixels are clamped to 95% of the display" "2432 1368" "$(get_popup_dimensions custom)" +write_config "POPUP_SIZE_CUSTOM=garbage" "POPUP_SIZE_CUSTOM_ABSOLUTE=900x700" +check "malformed custom uses the absolute size" "900 700" "$(get_popup_dimensions custom)" +write_config "POPUP_SIZE_CUSTOM=garbage" "POPUP_SIZE_CUSTOM_ABSOLUTE=junk" +check "malformed custom and absolute use 1280x720" "${DIMS_FALLBACK}" "$(get_popup_dimensions custom)" + +echo "=== get_popup_dimensions: literal sizes ===" +rm -f "${CONFIG_FILE}" +check "pixel size" "1000 600" "$(get_popup_dimensions 1000x600)" +check "pixel size below the minimum becomes xsmall" "${DIMS_XSMALL}" "$(get_popup_dimensions 300x100)" +check "pixel size is clamped to 95% of the display" "2432 1368" "$(get_popup_dimensions 9000x9000)" +check "percent size uses the resolution" "1024 720" "$(get_popup_dimensions 40%x50%)" +RESOLUTION="" +check "percent size without a resolution assumes 2560x1440" "1024 720" "$(get_popup_dimensions 40%x50%)" +RESOLUTION="${SCREEN_2560}" +check "percent size out of range becomes medium pixels" "${DIMS_MEDIUM_DISPLAY}" "$(get_popup_dimensions 99%x50%)" +check "unknown size becomes medium pixels" "${DIMS_MEDIUM_DISPLAY}" "$(get_popup_dimensions nonsense)" + +echo "" +echo "Results: ${_PASS} passed, ${_FAIL} failed" +[[ "${_FAIL}" -eq 0 ]] || exit 1 diff --git a/tests/test-resolution-detection-stubbed.sh b/tests/test-resolution-detection-stubbed.sh new file mode 100755 index 0000000..58b8f08 --- /dev/null +++ b/tests/test-resolution-detection-stubbed.sh @@ -0,0 +1,122 @@ +#!/bin/bash + +############################################################################### +# Tests lib/resolution-detection.sh: X11 (xrandr), Wayland (wlr-randr, swaymsg, +# wayland-info), the gamescope environment fallback, size validation, and the +# empty-answer failure. Display tools are stub scripts on a private PATH, so the +# result does not depend on the host's real display or installed tools. +############################################################################### + +SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")/.." && pwd)" + +WORK="$(mktemp -d)" +trap '/bin/rm -rf "${WORK}"' EXIT +BIN="${WORK}/bin" +mkdir -p "${BIN}" + +# shellcheck disable=SC1091 +source "${SCRIPT_DIR}/lib/resolution-detection.sh" || exit 1 + +# The private PATH holds only the plain utilities the module needs. Every +# display tool is absent until a test writes a stub for it. +for tool in grep head cut sed uname; do + ln -s "$(command -v "${tool}")" "${BIN}/${tool}" +done +export PATH="${BIN}" + +_PASS=0 +_FAIL=0 + +check() { + local desc="$1" expected="$2" actual="$3" + if [[ "${actual}" == "${expected}" ]]; then + _PASS=$(( _PASS + 1 )); echo " PASS ${desc} (${actual:-})" + else + _FAIL=$(( _FAIL + 1 )); echo " FAIL ${desc}: expected '${expected}', got '${actual}'" + fi +} + +# stub NAME OUTPUT: a tool that prints OUTPUT. +stub() { + local name="$1" + local output="$2" + printf '#!/bin/bash\n/bin/cat <<'"'"'EOF'"'"'\n%s\nEOF\n' "${output}" > "${BIN}/${name}" + /bin/chmod +x "${BIN}/${name}" +} +unstub_all() { + /bin/rm -f "${BIN}/xrandr" "${BIN}/wlr-randr" "${BIN}/swaymsg" "${BIN}/wayland-info" "${BIN}/pgrep" +} +detect() { get_display_resolution; } + +clean_env() { + unset DISPLAY WAYLAND_DISPLAY XDG_SESSION_TYPE GAMESCOPE_WIDTH GAMESCOPE_HEIGHT +} + +echo "=== no detection tool ===" +unstub_all; clean_env +check "nothing available prints nothing" "" "$(detect)" +detect >/dev/null; check "nothing available returns 1" "1" "$?" + +echo "=== X11 (xrandr) ===" +export DISPLAY=":0" +stub xrandr $'Screen 0: minimum 320 x 200, current 2560 x 1440\nDP-1 connected primary 2560x1440+0+0 (normal) 600mm x 340mm\nHDMI-1 connected 1920x1080+2560+0' +check "the primary display wins" "2560 1440" "$(detect)" +stub xrandr $'eDP-1 connected 1920x1080+0+0\nHDMI-1 connected 3840x2160+1920+0' +check "without a primary the first connected display is used" "1920 1080" "$(detect)" +stub xrandr $'DP-1 disconnected\nHDMI-1 disconnected' +detect >/dev/null; check "no connected display fails" "1" "$?" +stub xrandr "DP-1 connected primary 320x240+0+0" +detect >/dev/null; check "a display under 640x480 is rejected" "1" "$?" +stub xrandr "DP-1 connected primary (normal left inverted)" +detect >/dev/null; check "a connected line without a geometry fails" "1" "$?" +stub xrandr "DP-1 connected primary 640x480+0+0" +check "exactly 640x480 is accepted" "640 480" "$(detect)" + +echo "=== Wayland ===" +unstub_all; clean_env +export XDG_SESSION_TYPE="wayland" +stub wlr-randr '[{"name":"DP-1","modes":[{"width": 3840, "height": 2160}]}]' +check "wlr-randr JSON" "3840 2160" "$(detect)" +stub wlr-randr '[{"width": 100, "height": 100}]' +stub swaymsg '[{"name":"eDP-1","current_mode":{"width":2880,"height":1800}}]' +check "a too-small wlr-randr answer falls through to swaymsg" "2880 1800" "$(detect)" +stub swaymsg '' +stub wayland-info 'interface: wl_output mode: 1920x1200 @ 60Hz' +check "an empty swaymsg falls through to wayland-info" "1920 1200" "$(detect)" +unstub_all +export WAYLAND_DISPLAY="wayland-0" +stub wlr-randr '[{"width": 1600, "height": 900}]' +check "a Wayland session with WAYLAND_DISPLAY set" "1600 900" "$(detect)" +unset XDG_SESSION_TYPE +check "WAYLAND_DISPLAY alone selects Wayland detection" "1600 900" "$(detect)" +export XDG_SESSION_TYPE="tty" +check "WAYLAND_DISPLAY wins over a tty session type" "1600 900" "$(detect)" +unset XDG_SESSION_TYPE +stub wlr-randr '[{"width": 100, "height": 100}]' +detect >/dev/null; check "no Wayland tool gives a usable size" "1" "$?" +unset WAYLAND_DISPLAY XDG_SESSION_TYPE +stub wlr-randr '[{"width": 1600, "height": 900}]' +detect >/dev/null; check "without any session hint Wayland tools are not tried" "1" "$?" + +echo "=== gamescope ===" +unstub_all; clean_env +printf '#!/bin/bash\n[ "$1" = "-x" ] && [ "$2" = "gamescope" ]\n' > "${BIN}/pgrep"; /bin/chmod +x "${BIN}/pgrep" +export GAMESCOPE_WIDTH=1280 GAMESCOPE_HEIGHT=800 +check "environment size when gamescope is running" "1280 800" "$(detect)" +export GAMESCOPE_WIDTH=800 GAMESCOPE_HEIGHT=600 +check "800x600 is above the minimum" "800 600" "$(detect)" +export GAMESCOPE_WIDTH=100 GAMESCOPE_HEIGHT=100 +detect >/dev/null; check "a too-small environment size is rejected" "1" "$?" +export GAMESCOPE_WIDTH=wide GAMESCOPE_HEIGHT=tall +detect >/dev/null; check "a non-numeric environment size is rejected" "1" "$?" +unset GAMESCOPE_WIDTH GAMESCOPE_HEIGHT +detect >/dev/null; check "gamescope with no size information fails" "1" "$?" +stub wlr-randr '[{"width": 1280, "height": 800}]' +check "gamescope also tries Wayland tools" "1280 800" "$(detect)" +unstub_all +export GAMESCOPE_WIDTH=1280 GAMESCOPE_HEIGHT=800 +detect >/dev/null; check "the environment size is ignored when gamescope is not running" "1" "$?" + +echo "" +echo "Results: ${_PASS} passed, ${_FAIL} failed" +[[ "${_FAIL}" -eq 0 ]] || exit 1 diff --git a/tests/test-scheduler-platform.sh b/tests/test-scheduler-platform.sh new file mode 100644 index 0000000..fc1f3e0 --- /dev/null +++ b/tests/test-scheduler-platform.sh @@ -0,0 +1,138 @@ +#!/bin/bash + +############################################################################### +# Tests lib/scheduler-platform.sh on the Linux (systemd) path with a stubbed +# systemctl, plus the Darwin branches that touch no external service. +# Runs headless with a temp HOME. Nothing here calls the real systemctl or +# launchctl. +############################################################################### + +SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")/.." && pwd)" + +TMP_HOME="$(mktemp -d)" +trap 'rm -rf "${TMP_HOME}"' EXIT +export HOME="${TMP_HOME}" + +# shellcheck disable=SC1091 +source "${SCRIPT_DIR}/lib/scheduler-platform.sh" || exit 1 + +_PASS=0 +_FAIL=0 + +check() { + local desc="$1" expected="$2" actual="$3" + if [[ "${actual}" == "${expected}" ]]; then + _PASS=$(( _PASS + 1 )); echo " PASS ${desc} (${actual})" + else + _FAIL=$(( _FAIL + 1 )); echo " FAIL ${desc}: expected '${expected}', got '${actual}'" + fi +} + +# Stubs. A function named like a command wins over the real binary. +FAKE_OS="Linux" +uname() { echo "${FAKE_OS}"; } +SYSTEMCTL_LOG="${TMP_HOME}/systemctl.log" +SYSTEMCTL_FAIL="" +SYSTEMCTL_ENABLED="enabled" +SYSTEMCTL_ACTIVE="active" +systemctl() { + local all_args="$*" + local subcommand="${2:-}" # called as: systemctl --user ... + echo "${all_args}" >> "${SYSTEMCTL_LOG}" + case "${all_args}" in + *is-enabled*) echo "${SYSTEMCTL_ENABLED}" ;; + *is-active*) echo "${SYSTEMCTL_ACTIVE}" ;; + *list-timers*) echo "Wed 2026-10-28 13:00:00 EDT 5min left n/a n/a sleep-warning.timer" ;; + *) ;; + esac + case " ${SYSTEMCTL_FAIL} " in + *" ${subcommand} "*) return 1 ;; + *) return 0 ;; + esac +} +calls() { [[ -f "${SYSTEMCTL_LOG}" ]] && paste -sd'|' "${SYSTEMCTL_LOG}"; } +reset_calls() { rm -f "${SYSTEMCTL_LOG}"; SYSTEMCTL_FAIL=""; } + +SYSTEMD_DIR="${HOME}/.config/systemd/user" +BIN="${HOME}/.local/bin/sleep-warning.sh" +make_installed() { + mkdir -p "${SYSTEMD_DIR}" "$(dirname "${BIN}")" + : > "${BIN}" + : > "${SYSTEMD_DIR}/sleep-warning.service" + : > "${SYSTEMD_DIR}/sleep-warning.timer" +} + +echo "=== scheduler_is_darwin and scheduler_plist_path ===" +FAKE_OS="Linux" +scheduler_is_darwin; check "Linux is not Darwin" "1" "$?" +FAKE_OS="Darwin" +scheduler_is_darwin; check "Darwin is Darwin" "0" "$?" +check "plist path is under the user's LaunchAgents" "${HOME}/Library/LaunchAgents/com.sleep-warning.plist" "$(scheduler_plist_path)" + +echo "=== scheduler_stop_and_disable (Linux) ===" +FAKE_OS="Linux"; reset_calls +scheduler_stop_and_disable; check "returns 0 when both calls succeed" "0" "$?" +check "stops, then disables, the timer" "--user stop sleep-warning.timer|--user disable sleep-warning.timer" "$(calls)" +reset_calls; SYSTEMCTL_FAIL="stop" +scheduler_stop_and_disable; check "a failed stop returns 1" "1" "$?" +check "disable is still attempted after a failed stop" "--user stop sleep-warning.timer|--user disable sleep-warning.timer" "$(calls)" +reset_calls; SYSTEMCTL_FAIL="disable" +scheduler_stop_and_disable; check "a failed disable returns 1" "1" "$?" + +echo "=== scheduler_remove_files (Linux) ===" +FAKE_OS="Linux"; make_installed +scheduler_remove_files +check "the service file is removed" "no" "$([[ -e "${SYSTEMD_DIR}/sleep-warning.service" ]] && echo yes || echo no)" +check "the timer file is removed" "no" "$([[ -e "${SYSTEMD_DIR}/sleep-warning.timer" ]] && echo yes || echo no)" +check "the installed script is left alone" "yes" "$([[ -e "${BIN}" ]] && echo yes || echo no)" +scheduler_remove_files; check "removing again is harmless" "0" "$?" + +echo "=== scheduler_reload ===" +FAKE_OS="Linux"; reset_calls +scheduler_reload; check "Linux reload returns 0" "0" "$?" +check "Linux reload runs daemon-reload" "--user daemon-reload" "$(calls)" +FAKE_OS="Darwin"; reset_calls +scheduler_reload; check "Darwin reload returns 0" "0" "$?" +check "Darwin reload calls nothing" "" "$(calls)" + +echo "=== scheduler_is_installed ===" +rm -rf "${HOME}/.local" "${HOME}/.config" "${HOME}/Library" +FAKE_OS="Linux" +scheduler_is_installed; check "nothing installed" "1" "$?" +make_installed +scheduler_is_installed; check "script, service and timer present" "0" "$?" +rm -f "${SYSTEMD_DIR}/sleep-warning.timer" +scheduler_is_installed; check "a missing timer file is not installed" "1" "$?" +make_installed; rm -f "${BIN}" +scheduler_is_installed; check "a missing script is not installed" "1" "$?" +FAKE_OS="Darwin"; make_installed +scheduler_is_installed; check "Darwin needs the plist, not the systemd files" "1" "$?" +mkdir -p "$(dirname "$(scheduler_plist_path)")"; : > "$(scheduler_plist_path)" +scheduler_is_installed; check "Darwin installed with script and plist" "0" "$?" +rm -f "${BIN}" +scheduler_is_installed; check "Darwin without the script is not installed" "1" "$?" + +echo "=== scheduler_status_lines (Linux) ===" +FAKE_OS="Linux"; reset_calls +SYSTEMCTL_ENABLED="enabled"; SYSTEMCTL_ACTIVE="active" +out="$(scheduler_status_lines | paste -sd'|' -)" +check "active timer shows platform, state and the first five timer fields" \ + "Platform: Linux (systemd)|Enabled: enabled|Active: active|Next trigger: Wed 2026-10-28 13:00:00 EDT 5min" "${out}" +SYSTEMCTL_ENABLED="disabled"; SYSTEMCTL_ACTIVE="inactive" +out="$(scheduler_status_lines | paste -sd'|' -)" +check "an inactive timer has no next trigger" "Platform: Linux (systemd)|Enabled: disabled|Active: inactive" "${out}" +SYSTEMCTL_ENABLED=""; SYSTEMCTL_ACTIVE="" +out="$(scheduler_status_lines | paste -sd'|' -)" +check "empty systemctl answers read as unknown" "Platform: Linux (systemd)|Enabled: unknown|Active: unknown" "${out}" + +echo "=== scheduler_enable_start (Linux) ===" +FAKE_OS="Linux"; reset_calls +scheduler_enable_start; check "returns 0 when every call succeeds" "0" "$?" +check "reloads, enables, then starts the timer" \ + "--user daemon-reload|--user enable sleep-warning.timer|--user start sleep-warning.timer" "$(calls)" +reset_calls; SYSTEMCTL_FAIL="start" +scheduler_enable_start; check "the exit status is the start call's" "1" "$?" + +echo "" +echo "Results: ${_PASS} passed, ${_FAIL} failed" +[[ "${_FAIL}" -eq 0 ]] || exit 1 diff --git a/tests/test-sonar-shell-newcode.sh b/tests/test-sonar-shell-newcode.sh new file mode 100755 index 0000000..37e29b7 --- /dev/null +++ b/tests/test-sonar-shell-newcode.sh @@ -0,0 +1,154 @@ +#!/bin/bash + +############################################################################### +# Tests scripts/check-sonar-shell-newcode.sh in a throwaway git repository: +# it reports `[` tests added since the merge base, and only those. Existing +# tests, moved or re-indented lines, deletions, and `[[ ]]` stay quiet. Untracked +# files count in full. +# Skips when shellcheck is not installed. Runs with a temp HOME and temp repo. +############################################################################### + +SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")/.." && pwd)" +CHECK="${SCRIPT_DIR}/scripts/check-sonar-shell-newcode.sh" + +if ! command -v shellcheck >/dev/null 2>&1; then + echo "SKIP: shellcheck is not installed" + exit 0 +fi + +WORK="$(mktemp -d)" +trap 'rm -rf "${WORK}"' EXIT +export HOME="${WORK}/home" +mkdir -p "${HOME}" + +_PASS=0 +_FAIL=0 + +check() { + local desc="$1" expected="$2" actual="$3" + if [[ "${actual}" == "${expected}" ]]; then + _PASS=$(( _PASS + 1 )); echo " PASS ${desc} (${actual})" + else + _FAIL=$(( _FAIL + 1 )); echo " FAIL ${desc}: expected '${expected}', got '${actual}'" + fi +} + +REPO="${WORK}/repo" +git_in_repo() { + git -C "${REPO}" -c user.name=test -c user.email=test@example.com -c commit.gpgsign=false "$@" +} + +new_repo() { + rm -rf "${REPO}" + mkdir -p "${REPO}" + git_in_repo init -q -b main +} + +# run_check: prints "rc|lines" where lines are the reported file:line pairs. +run_check() { + local out rc + out="$(cd "${REPO}" && "${CHECK}" "$@" 2>/dev/null)" + rc=$? + printf '%s|%s' "${rc}" "$(printf '%s\n' "${out}" | grep -E '^[^ ]+:[0-9]+:[0-9]+:' | cut -d: -f1,2 | sort -u | paste -sd' ' -)" +} + +commit_all() { + local message="$1" + git_in_repo add -A + git_in_repo commit -q -m "${message}" +} + +# The base file has two old `[ ]` tests that must never be reported. +write_base() { + cat > "${REPO}/a.sh" <<'BASE' +#!/bin/bash +old_one() { + if [ -n "$1" ]; then + echo one + fi +} +old_two() { + [ -e /tmp ] && echo two +} +BASE +} + +echo "=== a new '[' test is reported, old ones are not ===" +new_repo; write_base; commit_all base +git_in_repo checkout -q -b feature +printf 'added() {\n if [ -z "$1" ]; then echo none; fi\n}\n' >> "${REPO}/a.sh" +commit_all change +check "only the added line is reported" "1|a.sh:11" "$(run_check main)" + +echo "=== '[[ ]]' is clean ===" +new_repo; write_base; commit_all base +git_in_repo checkout -q -b feature +printf 'added() {\n if [[ -z "$1" ]]; then echo none; fi\n}\n' >> "${REPO}/a.sh" +commit_all change +check "a double-bracket test passes" "0|" "$(run_check main)" + +echo "=== several '[' on one line are each counted ===" +new_repo; write_base; commit_all base +git_in_repo checkout -q -b feature +printf 'added() {\n if [ -z "$1" ] || [ -z "$2" ]; then echo none; fi\n}\n' >> "${REPO}/a.sh" +commit_all change +out="$(cd "${REPO}" && "${CHECK}" main 2>&1)" +check "the summary counts both" "2" "$(printf '%s\n' "${out}" | sed -n "s/.*: \([0-9]*\) added '\[' test.*/\1/p")" + +echo "=== a re-indented old line is not new ===" +new_repo; write_base; commit_all base +git_in_repo checkout -q -b feature +sed -i.bak 's/^ \[ -e \/tmp \] \&\& echo two/ [ -e \/tmp ] \&\& echo two/' "${REPO}/a.sh" && rm -f "${REPO}/a.sh.bak" +commit_all reindent +check "re-indenting keeps the line old" "0|" "$(run_check main)" + +echo "=== one removed line excuses only one added copy ===" +new_repo; write_base; commit_all base +git_in_repo checkout -q -b feature +# Replace the one old `[ -e /tmp ]` line with two re-indented copies of it (lines 8 and 9). +printf '%s\n' '#!/bin/bash' 'old_one() {' ' if [ -n "$1" ]; then' ' echo one' ' fi' '}' \ + 'old_two() {' ' [ -e /tmp ] && echo two' ' [ -e /tmp ] && echo two' '}' > "${REPO}/a.sh" +commit_all duplicate +check "the extra copy is reported, the moved one is not" "1|a.sh:9" "$(run_check main)" + +echo "=== a deletion is clean ===" +new_repo; write_base; commit_all base +git_in_repo checkout -q -b feature +printf '#!/bin/bash\n' > "${REPO}/a.sh" +commit_all delete +check "removing tests reports nothing" "0|" "$(run_check main)" + +echo "=== uncommitted changes count ===" +new_repo; write_base; commit_all base +git_in_repo checkout -q -b feature +printf 'added() {\n [ -z "$1" ] && echo none\n}\n' >> "${REPO}/a.sh" +check "a working-tree edit is reported" "1|a.sh:11" "$(run_check main)" + +echo "=== untracked files count in full ===" +new_repo; write_base; commit_all base +git_in_repo checkout -q -b feature +printf '#!/bin/bash\nif [ -n "$1" ]; then echo x; fi\n' > "${REPO}/new.sh" +check "an untracked file is reported" "1|new.sh:2" "$(run_check main)" + +echo "=== untracked file without a trailing newline ===" +new_repo; write_base; commit_all base +git_in_repo checkout -q -b feature +printf '#!/bin/bash\nif [ -n "$1" ]; then echo x; fi' > "${REPO}/no-newline.sh" +check "the last line is counted" "1|no-newline.sh:2" "$(run_check main)" +printf '[ -n "$1" ] && echo x' > "${REPO}/one-line.sh" +check "a single line with no newline is counted" "1|no-newline.sh:2 one-line.sh:1" "$(run_check main)" + +echo "=== other files are ignored ===" +new_repo; write_base; commit_all base +git_in_repo checkout -q -b feature +printf 'if [ -n "$1" ]; then echo x; fi\n' > "${REPO}/notes.txt" +commit_all text +check "non-shell files are skipped" "0|" "$(run_check main)" + +echo "=== setup problems ===" +new_repo; write_base; commit_all base +check "an unknown base ref exits 2" "2|" "$(run_check no-such-ref)" + +echo "" +echo "Results: ${_PASS} passed, ${_FAIL} failed" +[[ "${_FAIL}" -eq 0 ]] || exit 1 diff --git a/tests/test-sonarcloud-pr-issues.py b/tests/test-sonarcloud-pr-issues.py new file mode 100644 index 0000000..33ea85d --- /dev/null +++ b/tests/test-sonarcloud-pr-issues.py @@ -0,0 +1,225 @@ +#!/usr/bin/env python3 +"""Unit tests for scripts/sonarcloud_pr_issues.py. + +The SonarCloud API and the gh and git calls are mocked, so nothing here touches the +network. Run: python3 tests/test-sonarcloud-pr-issues.py +""" + +from __future__ import annotations + +import io +import sys +import unittest +import urllib.error +from contextlib import redirect_stderr, redirect_stdout +from pathlib import Path +from typing import Any +from unittest import mock + +SCRIPTS_DIR = Path(__file__).resolve().parents[1] / "scripts" +sys.path.insert(0, str(SCRIPTS_DIR)) + +import sonarcloud_pr_issues as sc # noqa: E402 + +HEAD = "e21e27272667f1f10751139c88461d70ed004a65" +OLD = "34d6ca52f8a978c7c018efb9bdc98562eb9241d7" + + +def issue(path: str, line: int, rule: str = "shell:S7688", severity: str = "MAJOR") -> dict[str, Any]: + return { + "component": f"kgrizz-git_TimerWarning:{path}", + "line": line, + "rule": rule, + "severity": severity, + "message": "Use '[[' instead of '['.", + } + + +def pulls(sha: str | None, key: str = "3") -> dict[str, Any]: + pull: dict[str, Any] = {"key": key} + if sha is not None: + pull["commit"] = {"sha": sha} + return {"pullRequests": [pull]} + + +class FormatTests(unittest.TestCase): + def test_format_strips_the_project_key(self): + text = sc.format_issue(issue("lib/a.sh", 12, "shelldre:S131", "CRITICAL")) + self.assertEqual(text, "lib/a.sh:12 shelldre:S131 CRITICAL Use '[[' instead of '['.") + + def test_format_tolerates_missing_fields(self): + self.assertEqual(sc.format_issue({}), ":? ? ? ") + + +class FetchIssuesTests(unittest.TestCase): + def test_one_page(self): + data = {"total": 2, "issues": [issue("a.sh", 1), issue("b.sh", 2)]} + with mock.patch.object(sc, "fetch_json", return_value=data) as fetch: + self.assertEqual(len(sc.fetch_issues("3")), 2) + params = fetch.call_args.args[1] + self.assertEqual(params["pullRequest"], "3") + self.assertEqual(params["inNewCodePeriod"], "true") + self.assertEqual(params["resolved"], "false") + + def test_pages_until_the_total_is_reached(self): + pages = [ + {"total": 3, "issues": [issue("a.sh", 1), issue("a.sh", 2)]}, + {"total": 3, "issues": [issue("a.sh", 3)]}, + ] + with mock.patch.object(sc, "fetch_json", side_effect=pages) as fetch: + self.assertEqual(len(sc.fetch_issues("3")), 3) + self.assertEqual([c.args[1]["p"] for c in fetch.call_args_list], ["1", "2"]) + + def test_an_empty_page_stops_the_loop(self): + with mock.patch.object(sc, "fetch_json", return_value={"total": 5, "issues": []}) as fetch: + self.assertEqual(sc.fetch_issues("3"), []) + self.assertEqual(fetch.call_count, 1) + + +class AnalyzedCommitTests(unittest.TestCase): + def test_finds_the_pull_request(self): + with mock.patch.object(sc, "fetch_json", return_value=pulls(HEAD)): + self.assertEqual(sc.analyzed_commit("3"), HEAD) + + def test_other_pull_requests_are_ignored(self): + with mock.patch.object(sc, "fetch_json", return_value=pulls(HEAD, key="9")): + self.assertIsNone(sc.analyzed_commit("3")) + + def test_a_pull_request_without_a_commit(self): + with mock.patch.object(sc, "fetch_json", return_value=pulls(None)): + self.assertIsNone(sc.analyzed_commit("3")) + + +class WaitTests(unittest.TestCase): + def test_returns_at_once_when_the_commit_matches(self): + with mock.patch.object(sc, "analyzed_commit", return_value=HEAD), \ + mock.patch.object(sc.time, "sleep") as sleep: + self.assertTrue(sc.wait_for_commit("3", HEAD, 60)) + sleep.assert_not_called() + + def test_polls_until_the_commit_matches(self): + with mock.patch.object(sc, "analyzed_commit", side_effect=[OLD, OLD, HEAD]), \ + mock.patch.object(sc.time, "sleep") as sleep: + self.assertTrue(sc.wait_for_commit("3", HEAD, 60, poll=5)) + self.assertEqual(sleep.call_count, 2) + + def test_gives_up_after_the_deadline(self): + clock = iter([0.0, 5.0, 11.0]) + with mock.patch.object(sc, "analyzed_commit", return_value=OLD), \ + mock.patch.object(sc.time, "sleep"), \ + mock.patch.object(sc.time, "monotonic", side_effect=lambda: next(clock)): + self.assertFalse(sc.wait_for_commit("3", HEAD, 10, poll=5)) + + +class MainTests(unittest.TestCase): + def run_main(self, argv: list[str], *, head: str = HEAD, analyzed: str | None = HEAD, + issues: list[dict[str, Any]] | None = None, pr: str = "3") -> tuple[int, str, str]: + def fake_run_text(command: list[str]) -> str: + return pr if command[0] == "gh" else head + + out, err = io.StringIO(), io.StringIO() + with mock.patch.object(sc, "run_text", side_effect=fake_run_text), \ + mock.patch.object(sc, "analyzed_commit", return_value=analyzed), \ + mock.patch.object(sc, "fetch_issues", return_value=issues or []), \ + redirect_stdout(out), redirect_stderr(err): + code = sc.main(argv) + return code, out.getvalue(), err.getvalue() + + def test_clean_pull_request(self): + code, out, _err = self.run_main([]) + self.assertEqual(code, 0) + self.assertIn("analyzed at e21e272", out) + self.assertIn("0 new issue(s)", out) + + def test_issues_exit_one_and_are_sorted(self): + found = [issue("tests/b.sh", 9), issue("lib/a.sh", 30), issue("lib/a.sh", 4)] + code, out, _err = self.run_main([], issues=found) + self.assertEqual(code, 1) + lines = [line for line in out.splitlines() if "S7688" in line] + self.assertEqual([line.split()[0] for line in lines], ["lib/a.sh:4", "lib/a.sh:30", "tests/b.sh:9"]) + self.assertIn("3 new issue(s)", out) + + def test_a_clean_but_stale_analysis_is_not_a_pass(self): + code, out, _err = self.run_main([], analyzed=OLD) + self.assertEqual(code, 2) + self.assertIn("local HEAD is e21e272", out) + + def test_issues_win_over_staleness(self): + code, _out, _err = self.run_main([], analyzed=OLD, issues=[issue("a.sh", 1)]) + self.assertEqual(code, 1) + + def test_no_analysis_yet(self): + code, _out, err = self.run_main([], analyzed=None) + self.assertEqual(code, 2) + self.assertIn("no analysis yet", err) + + def test_no_pull_request_found(self): + code, _out, err = self.run_main([], pr="") + self.assertEqual(code, 2) + self.assertIn("no PR number", err) + + def test_an_explicit_pr_number_skips_gh(self): + with mock.patch.object(sc, "run_text", return_value=HEAD) as run_text, \ + mock.patch.object(sc, "analyzed_commit", return_value=HEAD), \ + mock.patch.object(sc, "fetch_issues", return_value=[]), \ + redirect_stdout(io.StringIO()): + self.assertEqual(sc.main(["7"]), 0) + self.assertEqual([c.args[0][0] for c in run_text.call_args_list], ["git"]) + + def test_wait_timeout_exits_two(self): + out, err = io.StringIO(), io.StringIO() + with mock.patch.object(sc, "run_text", return_value=HEAD), \ + mock.patch.object(sc, "wait_for_commit", return_value=False) as wait, \ + redirect_stdout(out), redirect_stderr(err): + code = sc.main(["3", "--wait", "30"]) + self.assertEqual(code, 2) + wait.assert_called_once_with("3", HEAD, 30) + self.assertIn("not analyzed at e21e272", err.getvalue()) + + def test_wait_without_a_local_head_exits_two_and_never_polls(self): + err = io.StringIO() + with mock.patch.object(sc, "run_text", return_value=""), \ + mock.patch.object(sc, "wait_for_commit") as wait, \ + mock.patch.object(sc, "analyzed_commit") as analyzed, \ + redirect_stdout(io.StringIO()), redirect_stderr(err): + code = sc.main(["3", "--wait", "30"]) + self.assertEqual(code, 2) + wait.assert_not_called() + analyzed.assert_not_called() + self.assertIn("needs the local HEAD", err.getvalue()) + + def test_no_head_without_wait_still_reports(self): + with mock.patch.object(sc, "run_text", return_value=""), \ + mock.patch.object(sc, "analyzed_commit", return_value=HEAD), \ + mock.patch.object(sc, "fetch_issues", return_value=[]), \ + redirect_stdout(io.StringIO()): + self.assertEqual(sc.main(["3"]), 0) + + def test_api_errors_exit_two(self): + err = io.StringIO() + with mock.patch.object(sc, "run_text", return_value=HEAD), \ + mock.patch.object(sc, "analyzed_commit", side_effect=urllib.error.URLError("offline")), \ + redirect_stdout(io.StringIO()), redirect_stderr(err): + code = sc.main(["3"]) + self.assertEqual(code, 2) + self.assertIn("could not read the API", err.getvalue()) + + +class RunTextTests(unittest.TestCase): + def test_returns_stdout_on_success(self): + done = mock.Mock(returncode=0, stdout="abc\n") + with mock.patch.object(sc.subprocess, "run", return_value=done): + self.assertEqual(sc.run_text(["git", "rev-parse", "HEAD"]), "abc") + + def test_returns_empty_on_failure(self): + done = mock.Mock(returncode=1, stdout="boom\n") + with mock.patch.object(sc.subprocess, "run", return_value=done): + self.assertEqual(sc.run_text(["gh", "pr", "view"]), "") + + def test_returns_empty_when_the_command_is_missing(self): + with mock.patch.object(sc.subprocess, "run", side_effect=FileNotFoundError): + self.assertEqual(sc.run_text(["gh"]), "") + + +if __name__ == "__main__": + unittest.main() diff --git a/tests/test-status-display.sh b/tests/test-status-display.sh index 1c78cba..fbbdce4 100755 --- a/tests/test-status-display.sh +++ b/tests/test-status-display.sh @@ -89,6 +89,50 @@ else pass=$((pass + 1)) fi +assert_equals() { + local label="$1" + local expected="$2" + local actual="$3" + if [[ "${actual}" == "${expected}" ]]; then + echo "PASS: ${label}" + pass=$((pass + 1)) + else + echo "FAIL: ${label} (expected '${expected}', got '${actual}')" + fail=$((fail + 1)) + fi +} + +# format_hour_12h in this module takes "HH[:MM]". 24:00 is midnight at the end +# of the day, so it must read as AM, not noon. +assert_equals "format_hour_12h midnight" "12:00 AM" "$(format_hour_12h 0)" +assert_equals "format_hour_12h 5:30" "5:30 AM" "$(format_hour_12h 05:30)" +assert_equals "format_hour_12h noon" "12:00 PM" "$(format_hour_12h 12)" +assert_equals "format_hour_12h 4 PM" "4:00 PM" "$(format_hour_12h 16:00)" +assert_equals "format_hour_12h 23:59" "11:59 PM" "$(format_hour_12h 23:59)" +assert_equals "format_hour_12h 24:00 is midnight" "12:00 AM" "$(format_hour_12h 24:00)" +assert_equals "format_hour_12h 24 is midnight" "12:00 AM" "$(format_hour_12h 24)" +assert_equals "format_hour_12h leaves a non-numeric value alone" "soon" "$(format_hour_12h soon)" + +# Zero-padded 08 and 09 are decimal, not invalid octal. stderr must stay empty. +assert_equals "format_hour_12h 08:00" "8:00 AM" "$(format_hour_12h 08:00)" +assert_equals "format_hour_12h 09" "9:00 AM" "$(format_hour_12h 09)" +assert_equals "format_hour_12h minute 08" "7:08 AM" "$(format_hour_12h 07:08)" +assert_equals "format_hour_12h minute 09 in the afternoon" "1:09 PM" "$(format_hour_12h 13:09)" +assert_equals "format_hour_12h 08:00 writes nothing to stderr" "" "$(format_hour_12h 08:00 2>&1 >/dev/null)" +assert_equals "format_hour_12h 09 writes nothing to stderr" "" "$(format_hour_12h 09 2>&1 >/dev/null)" +assert_equals "format_hour_12h 07:08 writes nothing to stderr" "" "$(format_hour_12h 07:08 2>&1 >/dev/null)" +assert_equals "format_range_human range ending at 24:00 is not overnight" \ + "4:00 PM → 12:00 AM" "$(format_range_human "16:00-24:00" Monday)" +# The same zero-padded values reach format_range_human through the overnight check. +assert_equals "format_range_human overnight range with 08:00" \ + "8:00 AM → 6:00 AM (overnight)" "$(format_range_human "08:00-06:00" Monday)" +assert_equals "format_range_human same-day range with minute 09" \ + "7:09 AM → 10:00 PM" "$(format_range_human "07:09-22:00" Monday)" +assert_equals "format_range_human 08:00-06:00 writes nothing to stderr" "" \ + "$(format_range_human "08:00-06:00" Monday 2>&1 >/dev/null)" +assert_equals "format_range_human overnight range" \ + "10:00 PM → 6:00 AM (overnight)" "$(format_range_human "22:00-06:00" Monday)" + echo "" echo "Results: ${pass} passed, ${fail} failed" [ "${fail}" -eq 0 ] diff --git a/tests/test-time-calculations.sh b/tests/test-time-calculations.sh new file mode 100644 index 0000000..a2ccca0 --- /dev/null +++ b/tests/test-time-calculations.sh @@ -0,0 +1,258 @@ +#!/bin/bash + +############################################################################### +# Tests lib/time-calculations.sh: range durations, interval merging, weekly +# restricted intervals, minute offsets, time formatting, the next unrestricted +# time, and the restriction end-time lookup. +# Runs headless with a temp HOME. `date` is stubbed where the clock matters. +############################################################################### + +SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")/.." && pwd)" + +TMP_HOME="$(mktemp -d)" +trap 'rm -rf "${TMP_HOME}"' EXIT +export HOME="${TMP_HOME}" + +# shellcheck disable=SC1091 +source "${SCRIPT_DIR}/lib/configure-core.sh" || exit 1 +# shellcheck disable=SC1091 +source "${SCRIPT_DIR}/lib/config.sh" || exit 1 +# shellcheck disable=SC1091 +source "${SCRIPT_DIR}/lib/time-parsing.sh" || exit 1 +# shellcheck disable=SC1091 +source "${SCRIPT_DIR}/lib/configure-validation.sh" || exit 1 +# shellcheck disable=SC1091 +source "${SCRIPT_DIR}/lib/time-validation.sh" || exit 1 +# shellcheck disable=SC1091 +source "${SCRIPT_DIR}/lib/time-calculations.sh" || exit 1 + +CONFIG_FILE="${TMP_HOME}/sleep-warning.conf" + +_PASS=0 +_FAIL=0 + +check() { + local desc="$1" expected="$2" actual="$3" + if [[ "${actual}" == "${expected}" ]]; then + _PASS=$(( _PASS + 1 )); echo " PASS ${desc} (${actual})" + else + _FAIL=$(( _FAIL + 1 )); echo " FAIL ${desc}: expected '${expected}', got '${actual}'" + fi +} + +# An empty config: every day is configured, none restricted. +all_days_empty() { + printf '%s\n' "SUNDAY=" "MONDAY=" "TUESDAY=" "WEDNESDAY=" "THURSDAY=" "FRIDAY=" "SATURDAY=" "$@" > "${CONFIG_FILE}" +} + +echo "=== calculate_range_duration ===" +check "0-5 is 5 h" "5" "$(calculate_range_duration "0-5")" +check "23-6 spans midnight for 7 h" "7" "$(calculate_range_duration "23-6")" +check "0-12 is 12 h" "12" "$(calculate_range_duration "0-12")" +check "0-13 is 13 h" "13" "$(calculate_range_duration "0-13")" +check "HH:MM endpoints" "5" "$(calculate_range_duration "00:00-05:00")" +check "overnight HH:MM endpoints" "7" "$(calculate_range_duration "23:00-06:00")" +check "mixed HH and HH:MM" "6" "$(calculate_range_duration "0-06:00")" +check "surrounding whitespace is trimmed" "5" "$(calculate_range_duration " 0-5 ")" +check "a zero-length range is 0 h" "0" "$(calculate_range_duration "5-5")" +check "a 90-minute range truncates to 1 h" "1" "$(calculate_range_duration "00:00-01:30")" + +echo "=== merge_hour_intervals ===" +check "no input prints nothing" "" "$(merge_hour_intervals)" +check "one interval is unchanged" "0:5" "$(merge_hour_intervals "0:5")" +check "overlapping intervals merge" "0:10" "$(merge_hour_intervals "0:5" "4:10")" +check "adjacent intervals merge" "0:10" "$(merge_hour_intervals "0:5" "5:10")" +check "disjoint intervals stay apart" "0:3|5:8" "$(merge_hour_intervals "5:8" "0:3" | paste -sd'|' -)" +check "a contained interval is absorbed" "0:10" "$(merge_hour_intervals "0:10" "2:4")" + +echo "=== calculate_total_day_duration ===" +rm -f "${CONFIG_FILE}" +all_days_empty +check "plain day with no overnight from yesterday" "5" "$(calculate_total_day_duration 1 "0-5")" +check "empty ranges are 0 h" "0" "$(calculate_total_day_duration 1 "")" +check "two ranges add up" "7" "$(calculate_total_day_duration 1 "0-5,22-24")" +check "overlapping ranges are merged, not double counted" "8" "$(calculate_total_day_duration 1 "0-5,3-8")" +check "an overnight range counts only today's portion" "3" "$(calculate_total_day_duration 1 "21-5")" +all_days_empty "SUNDAY=23-5" +check "yesterday's overnight tail is added (Mon 0-5 overlaps Sun 23-5)" "5" "$(calculate_total_day_duration 1 "0-5")" +check "tail plus today's overnight start" "6" "$(calculate_total_day_duration 1 "23-5")" +all_days_empty "SATURDAY=22-6" +check "Sunday looks back at Saturday" "6" "$(calculate_total_day_duration 0 "")" +check "partial hours round up" "2" "$(calculate_total_day_duration 1 "00:00-01:30")" + +echo "=== range_endpoint_to_day_minutes ===" +check "start role: plain hour" "300" "$(range_endpoint_to_day_minutes 5)" +check "start role: HH:MM" "330" "$(range_endpoint_to_day_minutes 05:30)" +range_endpoint_to_day_minutes 24 >/dev/null; check "start role rejects 24" "1" "$?" +range_endpoint_to_day_minutes 24:00 start >/dev/null; check "start role rejects 24:00" "1" "$?" +check "end role accepts 24" "1440" "$(range_endpoint_to_day_minutes 24 end)" +check "end role accepts 24:00" "1440" "$(range_endpoint_to_day_minutes 24:00 end)" +range_endpoint_to_day_minutes 24:30 end >/dev/null; check "end role rejects 24:30" "1" "$?" +range_endpoint_to_day_minutes 25 end >/dev/null; check "end role rejects 25" "1" "$?" +check "end role still reads ordinary times" "1380" "$(range_endpoint_to_day_minutes 23 end)" +range_endpoint_to_day_minutes "" >/dev/null; check "empty is invalid" "1" "$?" +range_endpoint_to_day_minutes 7:75 >/dev/null; check "minutes over 59 are invalid" "1" "$?" + +echo "=== build_weekly_restricted_intervals ===" +all_days_empty +check "no restrictions prints a single blank line" "" "$(build_weekly_restricted_intervals)" +all_days_empty "MONDAY=0-5" +check "Monday 0-5" "1440:1740" "$(build_weekly_restricted_intervals)" +all_days_empty "MONDAY=9-17,20-22" +check "two ranges on one day" "1980:2460|2640:2760" "$(build_weekly_restricted_intervals | paste -sd'|' -)" +all_days_empty "MONDAY=23-6" +check "an overnight range splits at midnight" "2820:2880|2880:3240" "$(build_weekly_restricted_intervals | paste -sd'|' -)" +all_days_empty "SATURDAY=23-6" +check "Saturday overnight wraps to Sunday" "10020:10080|0:360" "$(build_weekly_restricted_intervals | paste -sd'|' -)" +all_days_empty "MONDAY=07:30-08:45" +check "HH:MM endpoints" "1890:1965" "$(build_weekly_restricted_intervals)" +all_days_empty "MONDAY=bogus-range" +check "an unparseable range is skipped" "" "$(build_weekly_restricted_intervals)" +all_days_empty "TUESDAY=16-24" +check "a range ending at 24 runs to the end of the day" "3840:4320" "$(build_weekly_restricted_intervals)" +all_days_empty "TUESDAY=16:00-24:00" +check "a range ending at 24:00 runs to the end of the day" "3840:4320" "$(build_weekly_restricted_intervals)" +all_days_empty "TUESDAY=0-24" +check "0-24 covers the whole day" "2880:4320" "$(build_weekly_restricted_intervals)" +all_days_empty "SATURDAY=16-24" +check "Saturday 16-24 ends at the end of the week" "9600:10080" "$(build_weekly_restricted_intervals)" +all_days_empty "TUESDAY=24-5" +check "24 is not a valid start" "" "$(build_weekly_restricted_intervals)" + +echo "=== get_current_minute_offset ===" +date() { + case "$1" in + +%w) echo "${FAKE_DOW}" ;; + +%H) echo "${FAKE_HOUR}" ;; + +%M) echo "${FAKE_MIN}" ;; + *) command date "$@" ;; + esac +} +FAKE_DOW=0 FAKE_HOUR=00 FAKE_MIN=00 +check "Sunday midnight is minute 0" "0" "$(get_current_minute_offset)" +FAKE_DOW=1 FAKE_HOUR=08 FAKE_MIN=09 +check "leading zeros are not read as octal" "1929" "$(get_current_minute_offset)" +FAKE_DOW=6 FAKE_HOUR=23 FAKE_MIN=59 +check "Saturday 23:59 is the last minute of the week" "10079" "$(get_current_minute_offset)" + +echo "=== is_minute_restricted ===" +intervals=$'100:200\n500:600' +is_minute_restricted 100 "${intervals}"; check "start is restricted" "0" "$?" +is_minute_restricted 199 "${intervals}"; check "last minute inside is restricted" "0" "$?" +is_minute_restricted 200 "${intervals}"; check "end is not restricted (half-open)" "1" "$?" +is_minute_restricted 550 "${intervals}"; check "second interval" "0" "$?" +is_minute_restricted 300 "${intervals}"; check "a gap is unrestricted" "1" "$?" +is_minute_restricted 100 ""; check "no intervals means unrestricted" "1" "$?" + +echo "=== format_minute_offset_to_time ===" +# Current time: Monday 12:00 (1440 + 720 = 2160) +now=2160 +check "1 minute away" "in 1 minute" "$(format_minute_offset_to_time 2161 "${now}")" +check "45 minutes away" "in 45 minutes" "$(format_minute_offset_to_time 2205 "${now}")" +check "later today, PM" "at 5:00 PM" "$(format_minute_offset_to_time $((1440 + 17 * 60)) "${now}")" +check "later today, 12:30 PM" "at 12:30 PM" "$(format_minute_offset_to_time $((1440 + 750)) $((1440 + 540)))" +check "midday is PM, not 0 PM" "at 12:00 PM" "$(format_minute_offset_to_time $((1440 + 720)) $((1440 + 540)))" +check "tomorrow morning" "Tomorrow at 6:05 AM" "$(format_minute_offset_to_time $((2880 + 6 * 60 + 5)) "${now}")" +check "tomorrow just after midnight" "Tomorrow at 12:00 AM" "$(format_minute_offset_to_time 2880 "${now}")" +check "two days out uses the day name" "Wednesday at 9:00 AM" "$(format_minute_offset_to_time $((3 * 1440 + 540)) "${now}")" +check "Saturday rolls over to Sunday as tomorrow" "Tomorrow at 7:00 AM" "$(format_minute_offset_to_time 420 $((6 * 1440 + 600)))" +check "an earlier offset wraps into next week" "in 30 minutes" "$(format_minute_offset_to_time 10 $((7 * 1440 - 20)))" + +echo "=== get_next_unrestricted_time ===" +all_days_empty +check "no restrictions" "now (no restrictions configured)" "$(get_next_unrestricted_time)" +all_days_empty "MONDAY=0-5" +get_current_minute_offset() { echo "${FAKE_OFFSET}"; } +FAKE_OFFSET=$((1440 + 2 * 60)) +check "inside Monday 0-5 the end is 5:00 AM today" "at 5:00 AM" "$(get_next_unrestricted_time)" +FAKE_OFFSET=$((1440 + 4 * 60 + 30)) +check "30 minutes before the end" "in 30 minutes" "$(get_next_unrestricted_time)" +FAKE_OFFSET=$((1440 + 6 * 60)) +check "already unrestricted gives the current minute" "in 0 minutes" "$(get_next_unrestricted_time)" +all_days_empty "MONDAY=22-6" +FAKE_OFFSET=$((1440 + 23 * 60)) +check "an overnight restriction ends tomorrow" "Tomorrow at 6:00 AM" "$(get_next_unrestricted_time)" +all_days_empty "MONDAY=16-24" +FAKE_OFFSET=$((1440 + 17 * 60)) +check "a range ending at 24 ends at midnight, tomorrow" "Tomorrow at 12:00 AM" "$(get_next_unrestricted_time)" +all_days_empty "MONDAY=16-24" "TUESDAY=0-5" +check "back-to-back ranges across midnight are one block" "Tomorrow at 5:00 AM" "$(get_next_unrestricted_time)" +all_days_empty "SATURDAY=16-24" "SUNDAY=0-6" +FAKE_OFFSET=$((6 * 1440 + 20 * 60)) +check "a range ending at the week boundary continues into Sunday" "Tomorrow at 6:00 AM" "$(get_next_unrestricted_time)" +all_days_empty "SATURDAY=22-6" +FAKE_OFFSET=$((6 * 1440 + 23 * 60 + 30)) +check "a Saturday overnight range wraps to Sunday morning" "Tomorrow at 6:00 AM" "$(get_next_unrestricted_time)" +full_day="00:00-23:59,23:59-00:00" +all_days_empty "SUNDAY=${full_day}" "MONDAY=${full_day}" "TUESDAY=${full_day}" "WEDNESDAY=${full_day}" "THURSDAY=${full_day}" "FRIDAY=${full_day}" "SATURDAY=${full_day}" +FAKE_OFFSET=100 +check "24/7 restrictions never end" "No unrestricted time scheduled (24/7 restrictions active)" "$(get_next_unrestricted_time)" + +echo "=== format_endpoint_12h ===" +check "bare hour matches format_hour_12h" "5:00 AM" "$(format_endpoint_12h 5)" +check "zero-padded hour" "5:00 AM" "$(format_endpoint_12h 05)" +check "HH:MM keeps its minutes" "5:30 AM" "$(format_endpoint_12h 05:30)" +check "midnight" "12:00 AM" "$(format_endpoint_12h 0)" +check "noon" "12:00 PM" "$(format_endpoint_12h 12)" +check "12:15 PM" "12:15 PM" "$(format_endpoint_12h 12:15)" +check "afternoon" "4:45 PM" "$(format_endpoint_12h 16:45)" +check "23:59" "11:59 PM" "$(format_endpoint_12h 23:59)" +check "24 is midnight at the end of the day" "12:00 AM" "$(format_endpoint_12h 24)" +check "24:00 is midnight at the end of the day" "12:00 AM" "$(format_endpoint_12h 24:00)" +check "whitespace is ignored" "6:00 AM" "$(format_endpoint_12h " 06:00 ")" +for bad in 25 24:30 7:60 abc "" 5:5 -1; do + out="$(format_endpoint_12h "${bad}")"; rc=$? + check "invalid endpoint '${bad}' returns 1 and prints nothing" "1|" "${rc}|${out}" +done + +echo "=== calculate_restriction_end_time ===" +all_days_empty "MONDAY=0-5" "TUESDAY=22-6" +check "inside a same-day range" "5:00 AM|Monday|false" "$(calculate_restriction_end_time 2 1 "0-5")" +check "the last restricted hour" "5:00 AM|Monday|false" "$(calculate_restriction_end_time 4 1 "0-5")" +check "HH:MM range, as parse_config returns it" "5:00 AM|Monday|false" "$(calculate_restriction_end_time 2 1 "$(parse_config 1)")" +check "HH:MM end with minutes" "5:30 AM|Monday|false" "$(calculate_restriction_end_time 2 1 "00:00-05:30")" +check "outside every range" "" "$(calculate_restriction_end_time 12 1 "0-5")" +calculate_restriction_end_time 12 1 "0-5" >/dev/null +check "outside every range returns failure" "1" "$?" +calculate_restriction_end_time 12 3 "" >/dev/null +check "no ranges for today returns failure" "1" "$?" +check "inside an overnight range, ends tomorrow" "6:00 AM|Wednesday|true" "$(calculate_restriction_end_time 23 2 "22-6")" +check "inside an overnight HH:MM range" "6:00 AM|Wednesday|true" "$(calculate_restriction_end_time 23 2 "$(parse_config 2)")" +check "the second of two ranges" "11:00 PM|Monday|false" "$(calculate_restriction_end_time 21 1 "0-5,20-23")" +check "Saturday overnight ends on Sunday" "6:00 AM|Sunday|true" "$(calculate_restriction_end_time 23 6 "22-6")" +check "a range ending at 24 ends at midnight on the next day" "12:00 AM|Tuesday|true" "$(calculate_restriction_end_time 17 1 "16-24")" +check "the same range as HH:MM" "12:00 AM|Tuesday|true" "$(calculate_restriction_end_time 17 1 "16:00-24:00")" +check "Saturday 16-24 ends on Sunday" "12:00 AM|Sunday|true" "$(calculate_restriction_end_time 17 6 "16-24")" +all_days_empty "MONDAY=22-6" +check "yesterday's overnight tail ends today" "6:00 AM|Tuesday|true" "$(calculate_restriction_end_time 3 2 "")" +all_days_empty "SATURDAY=22:00-06:30" +check "Sunday looks back at Saturday's tail, with minutes" "6:30 AM|Sunday|true" "$(calculate_restriction_end_time 3 0 "")" +all_days_empty "MONDAY=22-6" "TUESDAY=0-3" +check "the tail wins over today's own ranges" "6:00 AM|Tuesday|true" "$(calculate_restriction_end_time 1 2 "0-3")" + +echo "=== calculate_restriction_end_time: legacy integer-hour fallback ===" +# With neither time-validation helper loaded the function falls back to plain +# integer hours. Zero-padded hours ("08", "09") must stay decimal, not octal. +legacy() { + ( + unset -f is_time_in_single_range is_restricted_time + calculate_restriction_end_time "$@" 2>"${TMP_HOME}/legacy.err" + ) +} +all_days_empty +check "padded same-day range" "5:00 PM|Monday|false" "$(legacy 09 1 "08-17")" +check "padded range, no stderr" "" "$(cat "${TMP_HOME}/legacy.err")" +check "padded hour before the range" "" "$(legacy 07 1 "08-17")" +check "padded overnight range" "6:00 AM|Tuesday|true" "$(legacy 23 1 "22-06")" +check "padded start and end 09" "9:00 AM|Monday|false" "$(legacy 08 1 "07-09")" +check "padded range, still no stderr" "" "$(cat "${TMP_HOME}/legacy.err")" +legacy 12 1 "08-17" >/dev/null +check "unpadded hour inside a padded range" "0" "$?" +# A value that is not a plain integer is skipped. It must not abort the shell. +out="$( (unset -f is_time_in_single_range is_restricted_time + calculate_restriction_end_time 9 1 "8am-17" 2>/dev/null; echo "rc=$?; reached the next line") )" +check "a non-numeric legacy range returns 1 and the shell keeps going" "rc=1; reached the next line" "${out}" + +echo "" +echo "Results: ${_PASS} passed, ${_FAIL} failed" +[[ "${_FAIL}" -eq 0 ]] || exit 1 diff --git a/tests/test-uninstall-lock-hours.sh b/tests/test-uninstall-lock-hours.sh index 4862f60..6ba04f3 100755 --- a/tests/test-uninstall-lock-hours.sh +++ b/tests/test-uninstall-lock-hours.sh @@ -16,8 +16,9 @@ # ./tests/test-uninstall-lock-hours.sh # # Notes: -# These tests use the *current* system time (day/hour) and write a config that -# makes the lock active "right now", so no clock mocking is needed. +# The clock is frozen with a `date` stub (Wednesday 14:20), and the config makes +# the lock active at that moment. The library reads the day and hour in separate +# `date` calls, so a real clock could cross an hour or midnight between them. # This test does NOT actually run uninstall.sh (which would affect systemd), # but instead tests the restore_config_permissions() function logic. @@ -117,7 +118,22 @@ source "${SCRIPT_DIR}/lib/config-locking.sh" # Create config directory structure mkdir -p "${CONFIG_DIR}/config" -# Get current time +# Frozen clock. The library calls `date +%w`, `date +%H`, and `date +%H%M`; every +# other `date` call (timestamps) goes to the real command. +FROZEN_DOW=3 +FROZEN_HOUR=14 +FROZEN_MIN=20 +date() { + case "$*" in + "+%w") echo "${FROZEN_DOW}" ;; + "+%H") printf '%02d\n' "${FROZEN_HOUR}" ;; + "+%M") printf '%02d\n' "${FROZEN_MIN}" ;; + "+%H%M") printf '%02d%02d\n' "${FROZEN_HOUR}" "${FROZEN_MIN}" ;; + *) command date "$@" ;; + esac +} + +# Get current time (the frozen clock) current_day="$(date +%w)" current_hour="$(date +%H)" current_hour="$((10#${current_hour}))" diff --git a/tests/tiers.yaml b/tests/tiers.yaml index 0364d6f..8107e09 100644 --- a/tests/tiers.yaml +++ b/tests/tiers.yaml @@ -49,27 +49,20 @@ tier_a: - test-prune-backups.sh - test-prune-dev-docs-archive.sh - test-prune-completed-plans.sh - - name: test-platform-darwin.sh - platform: darwin - - name: test-darwin-configure-gui.sh - platform: darwin - requires_gui: true - -tier_b: - description: Temp-HOME / module smokes; optional PR, recommended pre-release - scripts: + - test-popup-size-config.sh + - test-config-safety.sh + - test-time-calculations.sh + - test-config-locked-message.sh + - test-sonar-shell-newcode.sh + - test-scheduler-platform.sh + - test-resolution-detection-stubbed.sh - test-atomic-write.sh - test-write-config-override-flags.sh - - test-config-locking.sh - test-popup-display-source.sh - test-status-display.sh - test-install-linux-source.sh - test-install-license-notice.sh - - test-configure-text-mode.sh - - test-configure-modular.sh - test-modular-refactor.sh - - test-configure-blocking.sh - - test-configure-gui-split.sh - test-lock-hours-phase2.sh - test-uninstall-lock-hours.sh - test-uninstall-lock-hours-phase2.sh @@ -81,6 +74,20 @@ tier_b: - test-darwin-table-json.sh - test-popup-interval-message.sh - test-pause-feature.sh + - test-config-locking.sh + - name: test-platform-darwin.sh + platform: darwin + - name: test-darwin-configure-gui.sh + platform: darwin + requires_gui: true + +tier_b: + description: Temp-HOME / module smokes; optional PR, recommended pre-release + scripts: + - test-configure-text-mode.sh + - test-configure-modular.sh + - test-configure-blocking.sh + - test-configure-gui-split.sh tier_c: description: Manual, GUI-heavy, or multi-host; document only