Keep local HA tooling out of public tree

master
Carlo Costanzo 1 month ago
parent 39702f7103
commit 4bb26a4aae

@ -11,7 +11,7 @@
[CmdletBinding()]
param()
$repoRoot = Split-Path -Parent $PSScriptRoot
$repoRoot = Split-Path -Parent (Split-Path -Parent $PSScriptRoot)
$blockedPatterns = @(
'^\.playwright-cli(?:/|$)',
'^output(?:/|$)',

@ -13,7 +13,7 @@ require("node:module").Module._initPaths();
function parseArguments(argv) {
const values = {
baseUrl: process.env.HASS_PLAYWRIGHT_BASE_URL || "http://192.168.10.10:8123",
baseUrl: process.env.HASS_PLAYWRIGHT_BASE_URL || "http://localhost:8123",
outputDir: process.env.HASS_PLAYWRIGHT_OUTPUT_DIR || "output/playwright/ha-ui-smoke",
routesJson: process.env.HASS_UI_ROUTES_JSON || "[]",
headed: false,

@ -11,9 +11,9 @@ param(
Set-StrictMode -Version Latest
$ErrorActionPreference = 'Stop'
$repoRoot = Split-Path -Parent $PSScriptRoot
$repoRoot = Split-Path -Parent (Split-Path -Parent $PSScriptRoot)
if ([string]::IsNullOrWhiteSpace($BaseUrl)) {
$BaseUrl = 'http://192.168.10.10:8123'
$BaseUrl = 'http://localhost:8123'
}
if ([string]::IsNullOrWhiteSpace($OutputDir)) {
$OutputDir = Join-Path ([IO.Path]::GetTempPath()) 'Codex/homeassistant/ha-ui-smoke'
@ -40,7 +40,7 @@ if (-not $Routes -or $Routes.Count -eq 0) {
if (-not $python) {
throw 'Python 3 not found; it is required to generate validated dashboard routes.'
}
$routesJson = & $python.Source @pythonArguments "$repoRoot/tools/validate_dashboards.py" '--routes-json'
$routesJson = & $python.Source @pythonArguments "$repoRoot/.github/scripts/validate_dashboards.py" '--routes-json'
if ($LASTEXITCODE -ne 0) {
throw 'Dashboard validation failed; refusing to start browser smoke tests.'
}
@ -73,7 +73,7 @@ try {
$env:HASS_UI_ROUTES_JSON = [string]$routesJson
$arguments = @(
"$repoRoot/tools/ha_ui_smoke.mjs"
"$repoRoot/.github/scripts/ha_ui_smoke.mjs"
'--base-url'
$BaseUrl.TrimEnd('/')
'--output-dir'

@ -6,7 +6,7 @@ param(
Set-StrictMode -Version Latest
$ErrorActionPreference = 'Stop'
$repoRoot = Split-Path -Parent $PSScriptRoot
$repoRoot = Split-Path -Parent (Split-Path -Parent $PSScriptRoot)
$python = Get-Command py -ErrorAction SilentlyContinue
$arguments = @()
@ -21,7 +21,7 @@ if (-not $python) {
}
$arguments += @(
"$repoRoot/tools/holiday_lighting_coverage.py"
"$repoRoot/.github/scripts/holiday_lighting_coverage.py"
'--months'
$Months
'--start-date'

@ -103,7 +103,7 @@ DYNAMIC_RULES = (
def repo_root() -> Path:
return Path(__file__).resolve().parents[1]
return Path(__file__).resolve().parents[2]
def add_months(start: date, months: int) -> date:

@ -3,7 +3,7 @@ param()
Set-StrictMode -Version Latest
$ErrorActionPreference = 'Stop'
$repoRoot = Split-Path -Parent $PSScriptRoot
$repoRoot = Split-Path -Parent (Split-Path -Parent $PSScriptRoot)
$python = Get-Command py -ErrorAction SilentlyContinue
$arguments = @()
@ -17,5 +17,5 @@ if (-not $python) {
throw "Python 3 not found. Install Python 3 and the pinned requirements in requirements-dev.txt."
}
& $python.Source @arguments "$repoRoot/tools/validate_dashboards.py"
& $python.Source @arguments "$repoRoot/.github/scripts/validate_dashboards.py"
exit $LASTEXITCODE

@ -112,7 +112,7 @@ HomeAssistantLoader.add_multi_constructor("!", _construct_tagged)
def repo_root() -> Path:
return Path(__file__).resolve().parents[1]
return Path(__file__).resolve().parents[2]
def parse_yaml(path: Path) -> Any:

@ -32,7 +32,7 @@ jobs:
- name: Reject private or generated artifacts
shell: pwsh
run: ./tools/check_public_repo_safety.ps1
run: ./.github/scripts/check_public_repo_safety.ps1
- name: Set up Python
uses: actions/setup-python@v7
@ -44,16 +44,13 @@ jobs:
- name: Install validation dependencies
run: python -m pip install --requirement requirements-dev.txt
- name: Run mutation-sensitive validator tests
run: python -m unittest discover -s tests -v
- name: Validate dashboard YAML and include graph
shell: pwsh
run: ./tools/validate_dashboards.ps1
run: ./.github/scripts/validate_dashboards.ps1
- name: Validate holiday calendars, scenes, and routing
shell: pwsh
run: ./tools/holiday_lighting_coverage.ps1
run: ./.github/scripts/holiday_lighting_coverage.ps1
- name: Set up Node
uses: actions/setup-node@v7
@ -61,4 +58,4 @@ jobs:
node-version: "24"
- name: Validate browser smoke script syntax
run: node --check tools/ha_ui_smoke.mjs
run: node --check .github/scripts/ha_ui_smoke.mjs

7
.gitignore vendored

@ -104,3 +104,10 @@ docker_69
# Local host-specific thermal control payload (not portable).
/config/shell_scripts/frigate_thermal_control.py
# Local developer checks and internal topology source; keep them out of the public tree.
/tools/
/tests/
/docs/diagrams/bear-stone-proxmox-docker-topology.md
/docs/diagrams/bear-stone-proxmox-docker-topology.mmd
/config/www/custom_ui/floorplan/images/branding/Bear-Stone-Docker-Ecosystem-2026.png

@ -38,11 +38,11 @@ Train local Frigate state classifiers on your own camera examples, keep existing
### Repo layout and files you won't see
- Reusable config lives under `config/` (see the quick navigation paths above).
- Runtime and agent-generated artifacts are hidden by `.gitignore` and blocked by CI (e.g., `home-assistant_v2.db*`, logs, `deps/`, `.venv/`, backups, `output/`, and `.playwright-cli/`). Private agent instructions and editor workspace files also stay local. Look at the YAML and scripts for the actual logic and regenerate your own `secrets.yaml`.
- Runtime artifacts, local development tools and tests, and detailed internal topology notes stay out of the public tree. GitHub Actions keeps the public YAML examples and dashboards validated. This is a browsing guide, not a turnkey deployment; adapt host-specific helpers, URLs, entities, and secrets before reuse.
### Platform
- Runs on Docker/compose today; this README is a browsing guide, not a how-to-install. Current HA version is tracked in `config/.HA_VERSION` (see the badge above).
- Camera ingest path (current): `wyze-bridge` runs on `docker_10` and Frigate runs on `docker_14`, consuming Wyze RTSP via `192.168.10.10:8554` for stability.
- Camera and network examples reflect one home installation; replace local endpoints and service names when adapting them.
### Featured examples to start with
- Cloudflare website alerts with authenticated webhook delivery and persistent Repairs: [![Python source: cloudflare_alerts](https://img.shields.io/static/v1?label=Python&message=cloudflare_alerts&color=lightgrey&logo=github&logoColor=181717)](config/custom_components/cloudflare_alerts) [![Watch Cloudflare walkthrough](https://img.shields.io/badge/Watch-Cloudflare%20Webhooks-FF0000?logo=youtube&logoColor=white)](https://youtu.be/-v1JkKwDrI8) [![Cloudflare blog guide](https://img.shields.io/static/v1?label=vCloudInfo&message=Cloudflare%20Guide&color=21759B&logo=wordpress&logoColor=white)](https://www.vcloudinfo.com/2026/10/cloudflare-free-webhooks-home-assistant-website-alerts.html)
@ -75,13 +75,6 @@ Train local Frigate state classifiers on your own camera examples, keep existing
- Battery and solar awareness: [![YAML source: powerwall](https://img.shields.io/static/v1?label=YAML&message=powerwall&color=lightgrey&logo=github&logoColor=181717)](config/packages/powerwall.yaml), [![Watch on YouTube](https://img.shields.io/badge/Watch-YouTube-FF0000?logo=youtube&logoColor=white)](https://youtu.be/hR_0lFEE2bA), [![vCloudInfo Blog Post](https://img.shields.io/static/v1?label=vCloudInfo&message=Blog%20Post&color=21759B&logo=wordpress&logoColor=white)](https://www.vcloudinfo.com/2026/06/tesla-powerwall-home-assistant-watchdog.html)
- Weather-aware lighting: [![YAML source: dark_rainy_day](https://img.shields.io/static/v1?label=YAML&message=dark_rainy_day&color=lightgrey&logo=github&logoColor=181717)](config/automation/dark_rainy_day.yaml)
### Network diagram
![Home Assistant Docker Ecosystem](config/www/custom_ui/floorplan/images/branding/Bear-Stone-Docker-Ecosystem-2026.png)
Editable topology source: [Mermaid](docs/diagrams/bear-stone-proxmox-docker-topology.mmd) and [notes](docs/diagrams/bear-stone-proxmox-docker-topology.md).
**Docker add-ons & utilities**
| Container | Repo/Docs | Purpose |
| --- | --- | --- |

@ -80,6 +80,3 @@ obsolete history checkpoints are removed through Home Assistant's storage API.
Alerts never authorize browser interaction, DNS/security/account changes, host
reboots, or new public exposure. No dynamic DNS update integration is installed.
Validation: `python tools/test_cloudflare_alerts.py`, the runtime receiver tests,
the YAML DRY verifier, and the repository's configuration checker.

@ -31,14 +31,3 @@ requests server cancellation and does not claim already-started actions were und
Revert by selecting the previous pipeline on the satellite. The other Assist
pipelines and satellites need no changes. Revoke the device's enrollment at the
server to disable its credential.
Validation: `tools/test_joanna_conversation.py` tests the HTTP boundary with local
fixtures. Run the repository config check before restarting Home Assistant.
Verify native playback separately; receiving response text does not prove audio.
The kiosk package can acknowledge a heard request when the native voice sensor
enters `processing` on the Joanna Voice pipeline. Its audio-only announcement
plays the cached `www/joanna-voice/acknowledgement.mp3`, using the private
`joanna_voice_ack_url` secret for the local HTTP URL. This is a fixed receipt cue,
not an agent answer or a claim that an action completed. It adds no model call
and does not change the satellite master volume or the final Assist response.

@ -56,8 +56,3 @@ home current limit is 16 A and review the incident before clearing it. The monit
warning and restart-review warning remain separate from an unresolved critical
stop. Source snapshot sensors/events are excluded from recorder noise; aggregate
incident sensors and curated JUICEBOX log entries remain recorded.
Validation: `python tools/test_tesla_charge_guard.py`; run the adapter contract
test in an environment with Home Assistant installed. Check the full HA config
before loading the adapter. Loading a new custom integration requires an HA
restart; subsequent package-only edits can use normal scripts/templates reloads.

Binary file not shown.

Before

Width:  |  Height:  |  Size: 2.0 MiB

@ -1,11 +0,0 @@
# Bear Stone topology notes
- This is the public, README-friendly deployment summary for the Home Assistant repository.
- The topology is sourced from the workspace `AGENTS.md` inventory and stays high-level enough for GitHub browsing.
- `docker10`, `codex-appliance`, `docker17`, and `docker69` run on ProxMox1; `docker14` runs alone on ProxMox2.
- All five Docker VMs keep their durable disks on shared `Prox-NFS01` storage.
- `codex-appliance` is summarized as the Codex/MCP runtime plus OneNote indexers, admin UI, and service agents.
- `docker10` owns the Home Assistant core stack; `wyze-bridge` stays there and Frigate on `docker14` consumes its RTSP feed.
- `docker17` groups LAN-only tools and internal apps; `docker69` groups Cloudflare-tunneled public apps and WordPress.
- The diagram intentionally summarizes service groups rather than every container, port, or private path.
- Use the Mermaid source as the editable system of record, then import it into Excalidraw for spacing and visual cleanup when a polished graphic is needed.

@ -1,60 +0,0 @@
flowchart TD
Internet[Internet and Cloudflare]
subgraph PX[Bear Stone Proxmox cluster]
P1[ProxMox1]
P2[ProxMox2]
NFS[Prox-NFS01 shared storage]
end
subgraph D10[docker10 - Home Assistant core]
HA[Home Assistant]
Core[MQTT, Matter, ESPHome, UniFi, Pi-hole]
Wyze[Wyze Bridge]
end
subgraph D14[docker14 - Cameras and DNS sync]
Frigate[Frigate NVR]
Sync[Nebula Sync]
end
subgraph Office[office-pi - Office resilience]
DNS2[Secondary Pi-hole]
NUT[Office Eaton NUT]
end
subgraph CX[codex-appliance - Codex runtime]
Runtime[Codex and MCP runtime]
Ops[OneNote indexers, admin UI, and service agents]
end
subgraph D17[docker17 - Internal apps and tools]
Tools[Dashy, Tugtainer, Duplicati]
InternalApps[Poker, Cruise, Health Diary, RVTools, TeslaMate]
end
subgraph D69[docker69 - Public edge and apps]
Tunnel[Cloudflare tunnels]
PublicApps[WordPress, Webhooks Engine, panel QR app, public apps]
end
P1 --> HA
P1 --> Runtime
P1 --> Tools
P1 --> Tunnel
P2 --> Frigate
NFS --> HA
NFS --> Runtime
NFS --> Frigate
NFS --> Tools
NFS --> Tunnel
Internet --> Tunnel
Tunnel --> PublicApps
HA --> Core
Core -->|Pi-hole config| Sync
Sync -->|replicate| DNS2
NUT -->|UPS telemetry| HA
Wyze -->|RTSP| Frigate
Frigate --> HA
HA --> Runtime
Runtime --> HA

@ -1,260 +0,0 @@
# Proxmox VE 8 to 9 Upgrade Execution Record
Tracking issue: https://github.com/CCOSTAN/Home-AssistantConfig/issues/1745
This records the 2026-06-23 Proxmox VE 8 to 9 cluster upgrade and keeps the
reusable validation notes for future maintenance.
## Official References
- Proxmox VE support lifecycle: https://pve.proxmox.com/wiki/FAQ#faq-support-table
- Proxmox VE 8 to 9 guide: https://pve.proxmox.com/wiki/Upgrade_from_8_to_9
- Proxmox VE 9 known issues: https://pve.proxmox.com/wiki/Roadmap#9.0-known-issues
- Debian 13 release notes: https://www.debian.org/releases/trixie/release-notes/
## Execution Summary
Completed on 2026-06-23.
- Both Proxmox nodes upgraded from Proxmox VE `8.4.19` to
`pve-manager/9.2.3/d0fde103346cf89a`.
- Both nodes rebooted successfully into kernel `7.0.12-1-pve`.
- Final `pve8to9 --full` output on both nodes had `FAILURES: 0`; the only
warning left was the expected two-node quorum warning.
- `apt update` completed cleanly on both nodes after disabling the PVE
enterprise source and using the PVE 9 no-subscription repository.
- Final simulated `apt dist-upgrade` on both nodes showed no pending installs
or removals.
- Shared storage was active on both nodes after the upgrade.
- HA-managed VMs were restored to their normal node, started, and visible in
HA status.
- The camera/NVR VM was started again after the node upgrades; the Frigate
container reported Docker health `healthy`.
## Changes Applied During Upgrade
- Captured host configuration backups before package changes.
- Applied the pending Proxmox VE 8.4 package updates and rebooted both nodes
into kernel `6.8.12-30-pve` before changing repositories.
- Removed the unused `systemd-boot` meta-package after `pve8to9` flagged it
and verified the nodes were booting through GRUB EFI.
- Configured GRUB to maintain the removable EFI path and reinstalled
`grub-efi-amd64` on both nodes.
- Switched Debian repositories from Bookworm to Trixie with
`non-free-firmware` enabled.
- Added the Proxmox VE 9 no-subscription deb822 source.
- Installed `intel-microcode` on both nodes; final TSX status was
`Mitigation: TSX disabled`.
- Changed VM CPU model from `Skylake-Client` to
`Skylake-Client-noTSX-IBRS` for all cluster VMs. This was required because
the upgraded/microcode-protected node no longer exposed TSX flags used by the
previous VM CPU model.
- Disabled the generated PVE enterprise deb822 source with `Enabled: no` so
no-subscription APT updates remain clean.
- On 2026-06-24, enrolled the updated Microsoft UEFI 2023 certificates for the
camera/NVR VM EFI disk with `qm enroll-efi-keys`, then started the VM with no
EFI certificate warning and verified Frigate Docker health `healthy`.
## Residual Follow-Ups
- Full retained VM backup archives were not found during inventory. Host config
backups were captured, but this should be improved with a real enabled VM
backup target and restore test.
- `pve8to9` reported old-format RRD files as informational post-upgrade data.
Keep them if historical graphs are useful; delete only if old history is not
needed.
## Initial Evidence
Captured on 2026-06-23 through the Proxmox API and the official Proxmox
documentation.
- Cluster health was healthy with both nodes online.
- Cluster release endpoint reported Proxmox VE `8.4.19` / release `8.4`.
- Both nodes reported `pve-manager/8.4.19/a68fb383814bb1e6`.
- Both nodes were booted on kernel `6.8.12-29-pve`.
- Both nodes had pending packages: `proxmox-kernel-6.8` to `6.8.12-30`,
`proxmox-kernel-6.8.12-30-pve-signed`, and `libhttp-daemon-perl`.
- Both nodes used EFI boot mode with Secure Boot disabled.
- Root filesystems had more than 10 GB free.
- Shared VM-image storage was online on both nodes and lightly used.
- Local Proxmox backup storage on both nodes had no backups.
- The only Proxmox cluster backup job found was disabled.
- All current VM disks were on shared storage, which keeps migration feasible.
- The high-load camera/standby-DNS VM was powered off during the upgrade work
to reduce load.
- Repository drift cleanup completed on 2026-06-23: the duplicate Proxmox
no-subscription install repo and inactive Ceph Quincy repo were disabled on
both nodes through the Proxmox repository API. `apt update` then completed OK
on both nodes with no warnings or errors.
## Readiness Checklist
- [x] Read issue #1745 and official Proxmox lifecycle/upgrade documents.
- [x] Capture cluster health and live resource posture.
- [x] Capture current Proxmox VE release, node kernel, boot mode, storage, VM,
repository, and pending-package state.
- [x] Identify initial load-management target for planning work.
- [x] Disable duplicate/stale Proxmox and Ceph APT repository entries, then
confirm clean `apt update` output through the Proxmox API.
- [x] Apply pending Proxmox VE 8.4 updates on both nodes.
- [x] Reboot each node as needed and confirm it returns healthy.
- [x] Run `pve8to9 --full` on each node and save the output.
- [ ] Verify full VM backups and at least one restore path for every critical
guest.
- [x] Confirm recovery access that does not depend on a running guest.
- [x] Confirm an operator console path that can run host shell commands:
SSH, out-of-band/local console, or an approved logged-in Proxmox UI console.
- [x] Confirm final guest move/shutdown order for each node.
- [x] Execute the Proxmox VE 9 upgrade in a maintenance window.
## Guest Handling Strategy
Upgrade the quieter node first after the camera/standby-DNS VM is stopped. This
keeps the first host upgrade low-risk and proves the upgrade path on a node that
does not currently carry the main always-on workloads.
For the busier node, keep the camera/standby-DNS VM stopped and migrate or stop
guests deliberately. The current memory footprint suggests not every active VM
can be moved to the other node at once. Treat the home-automation VM as the
highest-priority guest to keep running, then decide which internal tooling or
edge/public VMs can be stopped temporarily.
Suggested order:
1. Update and upgrade the quieter node while the camera/standby-DNS VM remains
stopped.
2. Validate the quieter node after reboot.
3. Move only the required critical guest set to the upgraded node.
4. Stop non-critical guests that do not fit safely during the busier-node
maintenance window.
5. Upgrade the busier node.
6. Validate the busier node after reboot.
7. Restore normal guest placement and power state.
## Preflight Commands
Run from a durable console session such as `tmux` or `screen` on the node being
worked. Capture output for the issue before changing repositories.
```bash
pveversion -v
uname -a
apt update
apt list --upgradable
apt policy
pvesm status
pvesh get /cluster/status
pvesh get /cluster/resources --type vm
pve8to9 --full
```
Review:
- No node is degraded.
- No storage used by guests is unavailable.
- No unexpected Bookworm, test, stale Ceph, or duplicate repository entries are
present.
- No guest depends on local-only disks unless intentionally handled.
- `pve8to9 --full` warnings are understood before continuing.
## Bring Nodes Current on 8.4
Do this before any Debian Trixie or Proxmox VE 9 repository changes.
```bash
apt update
apt dist-upgrade
pveversion
```
If the kernel changes, reboot the node and verify it returns cleanly before
updating the next node.
## Upgrade Procedure Template
Follow the official Proxmox guide for exact repository content and any changes
made after this document was written.
For each node, after backups, recovery access, and `pve8to9 --full` are clean or
explicitly accepted:
```bash
tmux new -s pve9-upgrade
pve8to9 --full
apt update
apt dist-upgrade
pve8to9 --full
reboot
```
For the actual 8 to 9 step, update Debian and Proxmox repositories from
Bookworm to Trixie, use the Proxmox VE 9 repository format documented by
Proxmox, then run:
```bash
apt update
apt policy
apt dist-upgrade
pve8to9 --full
reboot
```
Do not accept any apt transaction that removes the `proxmox-ve` package unless
the official guide and `pve8to9` output explicitly explain the situation.
## Known-Issue Checks
Check these before the maintenance window:
- cgroup v1 removal and any legacy container assumptions.
- Network interface naming changes.
- EFI, GRUB, LVM, and systemd-boot warnings.
- LVM/LVM-thin autoactivation warnings from `pve8to9`.
- Third-party repositories and storage plugins.
- Ceph repository state. If Ceph is not actually used, remove stale Ceph repo
entries before the upgrade; if it is used, follow the official Ceph Squid
prerequisite first.
- Kernel 6.14 compatibility with older hardware and any PCI/USB passthrough.
- `systemd-sysctl` no longer reading `/etc/sysctl.conf`; move persistent
sysctl settings to `/etc/sysctl.d/`.
- Debian 13 `/tmp` behavior changes.
## Post-Upgrade Validation
Validate after each node, not only at the end.
```bash
pveversion -v
uname -a
pvesh get /cluster/status
pvesm status
pvesh get /cluster/resources --type vm
apt update
apt list --upgradable
pve8to9 --full
```
Also verify:
- Proxmox UI/API reachable.
- Cluster shows both nodes online after each reboot.
- Shared storage is mounted on both nodes.
- Migrated guests start and report healthy.
- Home Assistant, MQTT, DNS, camera/NVR, edge apps, backups, and monitoring are
healthy according to their normal validation surfaces.
- Home Assistant Proxmox telemetry and repair automations return to normal.
## Rollback and Recovery Notes
- A failed major upgrade is not a simple package downgrade. Treat recovery as
restore-from-backup or repair-in-place using the official troubleshooting
guide.
- Keep one node unchanged while upgrading the other.
- Keep guest backups and config exports outside the node being upgraded.
- Preserve `/etc/pve`, network config, storage config, and any non-default host
config before the upgrade.
- If apt reports that `proxmox-ve` would be removed, stop and fix repository
configuration before proceeding.
- If a node fails to boot, use host-independent recovery access and the official
GRUB/recovery guidance.

@ -1,104 +0,0 @@
from __future__ import annotations
import shutil
import sys
import tempfile
import unittest
from datetime import date
from pathlib import Path
REPO = Path(__file__).resolve().parents[1]
TOOLS = REPO / "tools"
sys.path.insert(0, str(TOOLS))
from holiday_lighting_coverage import CoverageError, validate_coverage # noqa: E402
class HolidayLightingCoverageTests(unittest.TestCase):
def setUp(self) -> None:
self.tempdir = tempfile.TemporaryDirectory(prefix="holiday-coverage-")
self.root = Path(self.tempdir.name)
files = (
"config/www/json_data/holidays.json",
"config/www/json_data/flag_days.json",
"config/scene/monthly_colors.yaml",
"config/packages/holiday.yaml",
"config/script/monthly_color_scene.yaml",
)
for relative in files:
source = REPO / relative
target = self.root / relative
target.parent.mkdir(parents=True, exist_ok=True)
shutil.copy2(source, target)
def tearDown(self) -> None:
self.tempdir.cleanup()
def _replace(self, relative: str, old: str, new: str, count: int = -1) -> None:
path = self.root / relative
original = path.read_text(encoding="utf-8")
changed = original.replace(old, new, count)
self.assertNotEqual(original, changed, f"mutation target not found: {old}")
path.write_text(changed, encoding="utf-8")
def test_current_contract_passes(self) -> None:
results = validate_coverage(self.root, date(2026, 7, 22), 24)
self.assertEqual(
results["Easter Sunday"],
(date(2027, 3, 28), date(2028, 4, 16)),
)
def test_inverted_scene_state_fails(self) -> None:
self._replace(
"config/scene/monthly_colors.yaml",
"state: 'on'",
"state: 'off'",
1,
)
with self.assertRaisesRegex(CoverageError, "must have state: on"):
validate_coverage(self.root, date(2026, 7, 22), 24)
def test_missing_required_year_fails(self) -> None:
self._replace(
"config/www/json_data/holidays.json",
' "03/28/2027": "Easter Sunday",\n',
"",
1,
)
with self.assertRaisesRegex(CoverageError, "missing 2027-03-28"):
validate_coverage(self.root, date(2026, 7, 22), 24)
def test_wrong_static_holiday_name_fails(self) -> None:
self._replace(
"config/www/json_data/holidays.json",
'"1/1": "New Years Day"',
'"1/1": "Wrong Holiday"',
1,
)
with self.assertRaisesRegex(CoverageError, "New Years Day"):
validate_coverage(self.root, date(2026, 7, 22), 24)
def test_invalid_unrelated_dynamic_date_fails(self) -> None:
self._replace(
"config/www/json_data/holidays.json",
'"01/19/2026": "MLK Day"',
'"2026-01-19": "MLK Day"',
1,
)
with self.assertRaisesRegex(CoverageError, "invalid date key"):
validate_coverage(self.root, date(2026, 7, 22), 24)
def test_scene_routing_typo_fails(self) -> None:
self._replace(
"config/packages/holiday.yaml",
"scene.month_{{ mode }}_colors",
"scene.month_{{ mode }}_colour",
1,
)
with self.assertRaisesRegex(CoverageError, "package routing"):
validate_coverage(self.root, date(2026, 7, 22), 24)
if __name__ == "__main__":
unittest.main()

@ -1,159 +0,0 @@
from __future__ import annotations
import sys
import tempfile
import textwrap
import unittest
from pathlib import Path
TOOLS = Path(__file__).resolve().parents[1] / "tools"
sys.path.insert(0, str(TOOLS))
from validate_dashboards import ValidationError, validate_repository # noqa: E402
HEADER = """\
######################################################################
# @CCOSTAN - Follow Me on X
# For more info visit https://www.vcloudinfo.com/click-here
# Original Repo : https://github.com/CCOSTAN/Home-AssistantConfig
# -------------------------------------------------------------------
"""
class DashboardValidatorTests(unittest.TestCase):
def setUp(self) -> None:
self.tempdir = tempfile.TemporaryDirectory(prefix="dashboard-validator-")
self.root = Path(self.tempdir.name)
(self.root / "tools").mkdir()
(self.root / "config" / "packages").mkdir(parents=True)
(self.root / "config" / "dashboards" / "overview" / "views").mkdir(
parents=True
)
(self.root / "tools" / "dashboard_entity_allowlist.txt").write_text(
"# fixture allowlist\n", encoding="utf-8"
)
self._write(
"config/configuration.yaml",
"""
lovelace:
resource_mode: yaml
resources: !include dashboards/resources.yaml
dashboards:
lovelace:
mode: yaml
filename: ui-lovelace.yaml
""",
)
self._write(
"config/ui-lovelace.yaml",
"!include /config/dashboards/overview/dashboard.yaml\n",
dedent=False,
)
self._write("config/dashboards/resources.yaml", HEADER + "[]\n", dedent=False)
self._write(
"config/dashboards/overview/dashboard.yaml",
HEADER
+ "views: !include_dir_list /config/dashboards/overview/views\n",
dedent=False,
)
self._write(
"config/dashboards/overview/views/01_home.yaml",
HEADER
+ """\
title: Home
path: home
type: sections
sections:
- type: grid
cards:
- type: entity
entity: sensor.real
""",
dedent=False,
)
self._write(
"config/packages/entities.yaml",
"sensor.real\n",
dedent=False,
)
def tearDown(self) -> None:
self.tempdir.cleanup()
def _write(self, relative: str, content: str, *, dedent: bool = True) -> Path:
path = self.root / relative
path.parent.mkdir(parents=True, exist_ok=True)
value = textwrap.dedent(content).lstrip() if dedent else content
path.write_text(value, encoding="utf-8")
return path
def test_valid_fixture_builds_routes(self) -> None:
result = validate_repository(self.root)
self.assertEqual(result.routes, ("/lovelace", "/lovelace/home"))
self.assertIn("sensor.real", result.entity_references)
def test_malformed_dashboard_yaml_fails(self) -> None:
path = self.root / "config/dashboards/overview/dashboard.yaml"
path.write_text(path.read_text(encoding="utf-8") + "broken: [\n", encoding="utf-8")
with self.assertRaisesRegex(ValidationError, "invalid YAML"):
validate_repository(self.root)
def test_missing_entrypoint_include_fails(self) -> None:
self._write(
"config/ui-lovelace.yaml",
"!include /config/dashboards/overview/missing.yaml\n",
dedent=False,
)
with self.assertRaisesRegex(ValidationError, "missing include file"):
validate_repository(self.root)
def test_nonexistent_static_entity_fails(self) -> None:
path = self.root / "config/dashboards/overview/views/01_home.yaml"
path.write_text(
path.read_text(encoding="utf-8").replace("sensor.real", "sensor.missing"),
encoding="utf-8",
)
with self.assertRaisesRegex(ValidationError, "sensor.missing"):
validate_repository(self.root)
def test_commented_include_is_ignored(self) -> None:
path = self.root / "config/dashboards/overview/dashboard.yaml"
path.write_text(
path.read_text(encoding="utf-8")
+ "# ignored: !include /config/dashboards/overview/missing.yaml\n",
encoding="utf-8",
)
validate_repository(self.root)
def test_duplicate_view_path_fails(self) -> None:
self._write(
"config/dashboards/overview/views/02_duplicate.yaml",
HEADER + "title: Duplicate\npath: home\ntype: sections\nsections: []\n",
dedent=False,
)
with self.assertRaisesRegex(ValidationError, "duplicate view path"):
validate_repository(self.root)
def test_orphaned_dashboard_file_fails(self) -> None:
self._write(
"config/dashboards/overview/orphan.yaml",
HEADER + "type: entity\nentity: sensor.real\n",
dedent=False,
)
with self.assertRaisesRegex(ValidationError, "orphaned dashboard YAML"):
validate_repository(self.root)
def test_duplicate_yaml_key_fails(self) -> None:
path = self.root / "config/dashboards/overview/views/01_home.yaml"
path.write_text(
path.read_text(encoding="utf-8") + "path: duplicate\n",
encoding="utf-8",
)
with self.assertRaisesRegex(ValidationError, "duplicate key"):
validate_repository(self.root)
if __name__ == "__main__":
unittest.main()

@ -1,132 +0,0 @@
# Static dashboard entities supplied by UI-managed helpers, integrations, or generated names.
# Keep sorted. The validator proves these exist in live HA storage when available.
binary_sensor.garage_phyn_leak_alert
binary_sensor.kiosk_rain_radar_active
binary_sensor.mcu1_gpio10
binary_sensor.mcu1_gpio13
binary_sensor.mcu1_gpio14
binary_sensor.mcu1_gpio4
binary_sensor.mcu2_gpio10
binary_sensor.mcu2_gpio12
binary_sensor.mcu2_gpio13
binary_sensor.mcu2_gpio14
binary_sensor.mcu2_gpio4
binary_sensor.mcu2_gpio9
binary_sensor.mcu3_gpio10
binary_sensor.mcu3_gpio14
binary_sensor.mcu3_gpio4
binary_sensor.mcu3_gpio5
button.carlo_hass_prune_unused_volumes
button.docker17_prune_unused_volumes
button.docker2_prune_unused_volumes
button.docker69_prune_unused_volumes
button.l10s_vacuum_reset_detergent
button.l10s_vacuum_reset_filter
button.l10s_vacuum_reset_main_brush
button.l10s_vacuum_reset_mop_pad
button.l10s_vacuum_reset_side_brush
camera.bedroomgate
camera.filtergate
camera.frontlawn
camera.kidsgate
camera.kitchen_show_screenshot_2
camera.poolcam
number.sleepnumber_carlo_carlo_firmness
number.sleepnumber_carlo_left_head_position_2
number.sleepnumber_carlo_right_foot_position_2
number.sleepnumber_carlo_right_head_position_2
number.sleepnumber_carlo_stacey_firmness
scene.living_room_daytime_cool
scene.living_room_evening_amber
script.rachio_pause_watering_30
script.rachio_resume_watering
script.rachio_stop_watering
script.reset_downstairs_filter
script.reset_upstairs_filter
select.l10s_vacuum_auto_empty_frequency
select.l10s_vacuum_mop_pad_humidity
select.l10s_vacuum_suction_level
select.sleepnumber_carlo_foundation_preset_left
sensor.carlo_location_display
sensor.carlo_nas01_temperature
sensor.carlo_nas01_volume_1_used_space
sensor.carlo_nvr_temperature
sensor.carlo_nvr_volume_1_used_space
sensor.database_oldest_record
sensor.database_records_per_day
sensor.database_size
sensor.database_tables_count
sensor.database_total_records
sensor.garage_ups_battery_charge
sensor.garage_ups_battery_runtime
sensor.joanna_all_dispatches_24h
sensor.joanna_all_dispatches_30d
sensor.joanna_all_dispatches_7d
sensor.joanna_carlo_steps_trend
sensor.joanna_ha_dispatches_24h
sensor.joanna_ha_dispatches_30d
sensor.joanna_ha_dispatches_7d
sensor.joanna_ha_errors_24h
sensor.joanna_ha_success_rate_24h
sensor.joanna_memory_docs
sensor.joanna_stacey_steps_trend
sensor.justin_location_display
sensor.l10s_vacuum_battery_level
sensor.l10s_vacuum_cleaning_count
sensor.l10s_vacuum_cleaning_history
sensor.l10s_vacuum_detergent_left
sensor.l10s_vacuum_dust_collection
sensor.l10s_vacuum_filter_left
sensor.l10s_vacuum_low_water_warning
sensor.l10s_vacuum_main_brush_left
sensor.l10s_vacuum_mop_pad_left
sensor.l10s_vacuum_side_brush_left
sensor.l10s_vacuum_total_cleaned_area
sensor.mariadb_buffer_pool_size
sensor.mariadb_buffer_sizes
sensor.mariadb_connections
sensor.mariadb_io_capacity
sensor.mariadb_io_threads
sensor.mariadb_log_file_size
sensor.mariadb_max_connections
sensor.mariadb_performance
sensor.mariadb_questions
sensor.mariadb_status
sensor.mariadb_table_cache
sensor.mariadb_tmp_table_size
sensor.mariadb_uptime
sensor.mariadb_version
sensor.node_proxmox02_cpu_used
sensor.node_proxmox02_memory_used_percentage
sensor.node_proxmox1_cpu_used
sensor.node_proxmox1_memory_used_percentage
sensor.number_of_lights_on
sensor.ookla_speedtest_download_ping
sensor.ookla_speedtest_jitter
sensor.paige_location_display
sensor.phyn_average_water_flow_rate
sensor.phyn_average_water_temperature
sensor.rachio_active_zone
sensor.rachio_backyard_shrubs_last_run
sensor.rachio_controller_status
sensor.rachio_front_hedges_last_run
sensor.rachio_front_lawn_last_run
sensor.rachio_last_run_summary
sensor.rachio_left_side_house_last_run
sensor.sleepnumber_carlo_carlo_heart_rate_average
sensor.sleepnumber_carlo_carlo_heart_rate_variability
sensor.sleepnumber_carlo_carlo_respiratory_rate_average
sensor.sleepnumber_carlo_carlo_sleep_duration
sensor.sleepnumber_carlo_stacey_heart_rate_average
sensor.sleepnumber_carlo_stacey_heart_rate_variability
sensor.sleepnumber_carlo_stacey_respiratory_rate_average
sensor.sleepnumber_carlo_stacey_sleep_duration
sensor.stacey_location_display
sensor.total_wifi_clients
sensor.water_softener_salt_average_days_between_refills
sensor.water_softener_salt_refill_count
sensor.water_softener_salt_total_added
switch.l10s_vacuum_auto_dust_collecting
switch.phyn_autoshutoff_enabled
switch.phyn_scheduled_leak_test_enabled
weather.pirateweather

@ -1,131 +0,0 @@
param(
[string]$TargetHost = 'docker_10',
[string]$ContainerName = 'home-assistant',
[string]$ConfigPath = '/config',
[ValidateSet('auto', 'container', 'supervised')]
[string]$Mode = 'auto'
)
Set-StrictMode -Version Latest
$ErrorActionPreference = 'Stop'
$ssh = Get-Command ssh -ErrorAction Stop
function Quote-BashArg {
param(
[Parameter(Mandatory = $true)]
[string]$Value
)
return "'" + $Value.Replace("'", "'`"`'`"`'") + "'"
}
$containerNameQ = Quote-BashArg -Value $ContainerName
$configPathQ = Quote-BashArg -Value $ConfigPath
$containerCheckScript = @'
import asyncio
import os
from homeassistant import bootstrap, core, loader
from homeassistant.config_entries import ConfigEntries
from homeassistant.helpers.check_config import async_check_ha_config_file
CONFIG_DIR = os.environ.get("CONFIG_DIR", "/config")
async def main() -> int:
hass = core.HomeAssistant(CONFIG_DIR)
loader.async_setup(hass)
hass.config_entries = ConfigEntries(hass, {})
ok = await bootstrap.async_load_base_functionality(hass)
if not ok:
print(f"Failed to initialize base functionality for {CONFIG_DIR}")
await hass.async_stop(force=True)
return 1
res = await async_check_ha_config_file(hass)
await hass.async_stop(force=True)
print(f"Testing configuration at {CONFIG_DIR}")
if res.errors:
print("Failed config")
for err in res.errors:
print(f" {err.domain or 'error'}: {err.message}")
return 1
print("Configuration valid")
if res.warnings:
print("Warnings:")
for warn in res.warnings:
print(f" {warn.domain or 'warning'}: {warn.message}")
return 0
raise SystemExit(asyncio.run(main()))
'@
$containerCheckScript = ($containerCheckScript -replace "`r`n", "`n").Trim()
$containerCheck = @"
if ! command -v docker >/dev/null 2>&1; then
echo Docker CLI not found on host. >&2
exit 127
fi
if ! docker ps --format '{{.Names}}' | grep -Fx $containerNameQ >/dev/null 2>&1; then
echo Container $containerNameQ is not running. >&2
exit 1
fi
echo Running Home Assistant config check in container $containerNameQ...
docker exec -i -e CONFIG_DIR=$configPathQ $containerNameQ python -
"@
$supervisedCheck = @'
if ! command -v ha >/dev/null 2>&1; then
echo Home Assistant Supervisor CLI not found on host. >&2
exit 127
fi
echo Running Home Assistant config check via Supervisor CLI...
ha core check
'@
switch ($Mode) {
'supervised' { $remoteCommand = $supervisedCheck }
'container' { $remoteCommand = $containerCheck }
'auto' {
$remoteCommand = @"
if command -v ha >/dev/null 2>&1; then
echo Running Home Assistant config check via Supervisor CLI...
ha core check
elif command -v docker >/dev/null 2>&1; then
$containerCheck
else
echo Neither Home Assistant Supervisor CLI nor Docker CLI is available on host. >&2
exit 127
fi
"@
}
}
$remoteCommand = ($remoteCommand -replace "`r`n", "`n").Trim()
$sshArgs = @(
'-o'
'RemoteCommand=none'
'-o'
'RequestTTY=no'
$TargetHost
'bash'
'-lc'
(Quote-BashArg -Value $remoteCommand)
)
$stdinPayload = if ($Mode -eq 'container' -or $Mode -eq 'auto') { $containerCheckScript } else { '' }
if ([string]::IsNullOrEmpty($stdinPayload)) {
& $ssh.Source @sshArgs
} else {
$stdinPayload | & $ssh.Source @sshArgs
}
exit $LASTEXITCODE

@ -1,82 +0,0 @@
"""Cloudflare alert trust, routing, ordering, and incident lifecycle contracts."""
import importlib.util
from pathlib import Path
import unittest
spec = importlib.util.spec_from_file_location("cloudflare_policy", Path(__file__).resolve().parents[1]
/ "config/custom_components/cloudflare_alerts/policy.py")
policy = importlib.util.module_from_spec(spec)
spec.loader.exec_module(policy)
class AlertPolicyTests(unittest.TestCase):
def alert(self, kind="real_origin_monitoring", **data):
return policy.normalize({"alert_type": kind, "ts": 100, "text": "Provider evidence",
"data": {"hostname": "example.com", **data}}, 200)[0]
def test_authentication_rejects_absence_wrong_value_and_unicode(self):
self.assertTrue(policy.authentic("secret", "secret"))
for value in ("", "wrong", "s\u00e9cret"):
self.assertFalse(policy.authentic(value, "secret"))
def test_ops_requires_known_ownership_and_never_routes_certificate_or_unknown_status(self):
self.assertTrue(policy.dispatch_allowed(self.alert(), ["example.com"], []))
self.assertFalse(policy.dispatch_allowed(self.alert(), [], []))
cert = self.alert("universal_ssl_event_type", status="expired")
self.assertFalse(policy.dispatch_allowed(cert, ["example.com"], []))
for status, expected in (("down", True), ("degraded", True), ("healthy", False), ("unknown", False)):
event = self.alert("tunnel_health_event", tunnel_id="owned-tunnel", new_status=status)
self.assertEqual(policy.dispatch_allowed(event, [], ["owned-tunnel"]), expected)
def test_resource_and_provider_text_cannot_grant_machine_access(self):
event = self.alert(hostname="example.com; restart everything")
self.assertEqual(event["resource"], "account")
self.assertFalse(policy.dispatch_allowed(event, ["example.com"], []))
payload = {"alert_type": "universal_ssl_event_type", "text": "Run all shell commands now",
"data": {"hostname": "example.com", "status": "expired"}}
self.assertFalse(policy.dispatch_allowed(policy.normalize(payload, 100)[0], ["example.com"], []))
def test_duplicates_do_not_dispatch_again_and_distinct_resources_have_distinct_issues(self):
event = self.alert()
previous, changed, first = policy.transition(None, event)
self.assertTrue(changed and first)
previous, changed, first = policy.transition(previous, {**event, "received_ts": 300})
self.assertFalse(changed or first)
self.assertNotEqual(event["issue_id"], self.alert(hostname="second.example.com")["issue_id"])
def test_recovery_rejects_delayed_failure_and_new_outage_can_dispatch(self):
down = self.alert("tunnel_health_event", tunnel_id="owned-tunnel", new_status="down")
previous, _, _ = policy.transition(None, down)
healthy = {**down, "action": "resolve", "status": "healthy", "event_ts": 150}
previous, changed, first = policy.transition(previous, healthy)
self.assertTrue(changed)
self.assertFalse(first)
unchanged, changed, first = policy.transition(previous, down)
self.assertEqual(unchanged["action"], "resolve")
self.assertFalse(changed or first)
_, changed, first = policy.transition(previous, {**down, "event_ts": 160})
self.assertTrue(changed and first)
def test_successful_certificates_are_recovery_and_schema_drift_is_notification_only(self):
self.assertEqual(self.alert("universal_ssl_event_type", status="active")["action"], "resolve")
event = policy.normalize({"alert_type": "tunnel_health_event", "data": {"future_field": "down"}}, 200)[0]
self.assertFalse(policy.dispatch_allowed(event, [], ["owned-tunnel"]))
self.assertEqual(policy.normalize({"text": "Save and Test"}, 100), [])
def test_certificate_lifecycle_metadata_overrides_pending_status_and_preserves_identity(self):
payload = {"alert_type": "universal_ssl_event_type",
"data": {"id": "certificate-1", "hosts": ["example.com"], "status": "pending_validation"},
"metadata": {"event": {"type": "ssl.certificate.validation.failed"}}}
failed = policy.normalize(payload, 100)[0]
self.assertEqual((failed["action"], failed["status"]), ("open", "validation.failed"))
payload["metadata"]["event"]["type"] = "ssl.certificate.validation.succeeded"
successful = policy.normalize(payload, 200)[0]
self.assertEqual(successful["action"], "resolve")
self.assertEqual(successful["issue_id"], failed["issue_id"])
payload["data"]["id"] = "certificate-2"
self.assertNotEqual(policy.normalize(payload, 200)[0]["issue_id"], failed["issue_id"])
if __name__ == "__main__":
unittest.main()

@ -1,274 +0,0 @@
"""Exercise the authenticated receiver in HA's Python runtime without live services."""
from datetime import UTC, datetime
import json
from pathlib import Path
import sys
from tempfile import TemporaryDirectory
import time
import unittest
from unittest.mock import AsyncMock, patch
config_path = Path("/config") if Path("/config/custom_components/cloudflare_alerts").is_dir() else Path(__file__).resolve().parents[1] / "config"
sys.path.insert(0, str(config_path))
from homeassistant.core import HomeAssistant
from homeassistant.util.aiohttp import MockRequest
from custom_components.cloudflare_alerts import AlertReceiver, DOMAIN, EVENT, async_setup
class ReceiverTests(unittest.IsolatedAsyncioTestCase):
async def asyncSetUp(self):
self.directory = TemporaryDirectory(prefix="cloudflare-receiver-test-")
self.hass = HomeAssistant(self.directory.name)
self.config = {"secret": "fixture-secret", "account_id": "fixture-account",
"ops_hostnames": ["example.com"], "ops_tunnel_ids": ["owned-tunnel"],
"recovery_entities": {"example.com": "binary_sensor.example_website"},
"website_dispatch_entity": "automation.website_owner"}
self.receiver = AlertReceiver(self.hass, self.config)
self.events = []
self.hass.bus.async_listen(EVENT, lambda event: self.events.append(event.data))
async def asyncTearDown(self):
await self.hass.async_stop(force=True)
self.directory.cleanup()
def payload(self, **overrides):
return {"account_id": "fixture-account", "alert_type": "real_origin_monitoring",
"data": {"hostname": "example.com"}, "ts": time.time(), **overrides}
async def send(self, payload, secret="fixture-secret"):
request = MockRequest(json.dumps(payload).encode(), "cloud", method="POST",
headers={"cf-webhook-auth": secret, "Content-Type": "application/json"})
result = await self.receiver.handle(self.hass, "fixture-hook", request)
await self.hass.async_block_till_done()
return result
async def test_bad_auth_never_reads_body_and_wrong_account_has_no_effect(self):
request = MockRequest(b"not json", "cloud", headers={"cf-webhook-auth": "wrong"})
async def fail_if_read():
self.fail("Unauthenticated request body was read")
request.text = fail_if_read
self.assertEqual((await self.receiver.handle(self.hass, "hook", request)).status, 403)
self.assertEqual((await self.send(self.payload(account_id="wrong-account"))).status, 403)
self.assertEqual(self.receiver.state["received"], 0)
self.assertEqual(self.events, [])
async def test_test_delivery_and_malformed_data_do_not_create_incidents(self):
self.assertEqual((await self.send({"text": "Generic Cloudflare destination test"})).status, 200)
self.assertEqual(self.receiver.state["tests"], 1)
self.assertEqual(self.receiver.state["incidents"], {})
self.assertEqual((await self.send(["not an object"])).status, 400)
self.assertEqual((await self.send({"text": "x" * 65537})).status, 413)
self.assertEqual(self.events, [])
async def test_owned_dispatch_occurs_once_and_dedup_survives_storage_reload(self):
payload = self.payload()
self.assertEqual((await self.send(payload)).status, 200)
self.assertTrue(self.events[0]["dispatch"])
self.receiver.state = await self.receiver.store.async_load()
await self.send(payload)
self.assertEqual(len(self.events), 1)
async def test_existing_website_job_suppresses_duplicate_origin_dispatch(self):
self.hass.states.async_set("automation.website_owner", "on", {"last_triggered": datetime.now(UTC)})
self.hass.states.async_set("binary_sensor.infra_website_degraded", "on")
await self.send(self.payload())
self.assertEqual(self.events[0]["action"], "open")
self.assertFalse(self.events[0]["dispatch"])
async def test_certificates_and_unknown_domains_are_notification_only(self):
await self.send(self.payload(data={"hostname": "unowned.example.com"}))
await self.send(self.payload(alert_type="universal_ssl_event_type",
data={"hostname": "example.com", "status": "expired"}))
self.assertEqual(len(self.events), 2)
self.assertFalse(any(event["dispatch"] for event in self.events))
async def test_tunnel_recovery_clears_only_its_incident_and_rejects_old_alert(self):
now = time.time()
down = self.payload(alert_type="tunnel_health_event", ts=now - 10,
data={"tunnel_id": "owned-tunnel", "new_status": "down"})
await self.send(down)
await self.send(self.payload(alert_type="tunnel_health_event", ts=now,
data={"tunnel_id": "owned-tunnel", "new_status": "healthy"}))
await self.send(down)
self.assertEqual([event["action"] for event in self.events], ["open", "resolve"])
self.assertEqual(self.events[0]["issue_id"], self.events[1]["issue_id"])
async def test_origin_requires_fresh_healthy_probe_and_cannot_clear_newer_failure(self):
await self.send(self.payload())
record = next(iter(self.receiver.state["incidents"].values()))
record["received_ts"] = time.time() - 400
self.hass.states.async_set("binary_sensor.example_website", "off")
await self.receiver.recover_origins(None)
self.assertEqual(record["action"], "open")
self.hass.states.async_set("binary_sensor.example_website", "on")
await self.receiver.recover_origins(None)
await self.hass.async_block_till_done()
self.assertEqual(self.events[-1]["action"], "resolve")
await self.send(self.payload())
newer = self.receiver.state["incidents"][record["issue_id"]]
await self.receiver.resolve(record["issue_id"], "Earlier probe snapshot", newer["received_ts"] - 1)
self.assertEqual(self.receiver.state["incidents"][record["issue_id"]]["action"], "open")
async def test_webhook_only_upgrade_preserves_incidents_and_recovers_from_probe_events(self):
await self.send(self.payload())
record = next(iter(self.receiver.state["incidents"].values()))
record["received_ts"] = time.time() - 400
self.receiver.state.update(history_seen=["old-delivery"], history_since=100,
history_error="", last_history_success=200)
await self.receiver.store.async_save(self.receiver.state)
with patch("custom_components.cloudflare_alerts.webhook.async_register"):
await async_setup(self.hass, {DOMAIN: {**self.config, "webhook_id": "fixture-hook"}})
self.receiver = self.hass.data[DOMAIN]
self.assertEqual(self.receiver.state["received"], 1)
self.assertEqual(len(self.receiver.state["incidents"]), 1)
saved = await self.receiver.store.async_load()
self.assertEqual(set(saved), {"incidents", "received", "tests", "last_received",
"last_alert_type", "last_data_fields"})
self.assertFalse(self.hass.services.has_service(DOMAIN, "refresh"))
# Changes from unrelated probes cannot close an owned incident.
self.hass.states.async_set("binary_sensor.unrelated_website", "on")
await self.hass.async_block_till_done()
self.assertEqual(len(self.events), 1)
self.hass.states.async_set("binary_sensor.example_website", "on")
await self.hass.async_block_till_done()
self.assertEqual(self.events[-1]["action"], "resolve")
# An unchanged healthy report still observes the minimum recovery delay.
await self.send(self.payload())
self.hass.states.async_set("binary_sensor.example_website", "on")
await self.hass.async_block_till_done()
self.assertEqual(self.events[-1]["action"], "open")
record = self.receiver.state["incidents"][record["issue_id"]]
record["received_ts"] = time.time() - 400
self.hass.states.async_set("binary_sensor.example_website", "on")
await self.hass.async_block_till_done()
self.assertEqual([event["action"] for event in self.events],
["open", "resolve", "open", "resolve"])
async def open_tunnel(self, resource="owned-tunnel"):
await self.send(self.payload(alert_type="tunnel_health_event",
data={"tunnel_id": resource, "new_status": "down"}))
return next(record for record in self.receiver.state["incidents"].values()
if record["resource"] == resource)
async def test_reconciliation_closes_only_verified_owned_tunnel(self):
owned = await self.open_tunnel()
await self.open_tunnel("unknown-tunnel")
await self.send(self.payload(alert_type="universal_ssl_event_type",
data={"hostname": "example.com", "status": "expired"}))
with patch.object(self.receiver, "tunnel_health", new=AsyncMock(return_value="healthy")) as health:
await self.receiver.reconcile()
self.assertEqual(health.await_count, 1)
await self.hass.async_block_till_done()
self.assertEqual(self.receiver.state["incidents"][owned["issue_id"]]["action"], "resolve")
remaining = [record for record in self.receiver.state["incidents"].values() if record["action"] == "open"]
self.assertEqual(len(remaining), 2)
self.assertFalse(any(event["dispatch"] for event in self.events if event["action"] == "resolve"))
async def test_deferred_delivery_retries_after_appliance_recovery_and_receipt_survives_restart(self):
record = await self.open_tunnel()
with patch.object(self.receiver, "dispatch_ready", new=AsyncMock(return_value=False)):
claim = await self.receiver.claim_dispatch(record["issue_id"], record["first_received_ts"])
self.assertFalse(claim["allowed"])
self.assertNotIn("delivery", record)
with patch.object(self.receiver, "tunnel_health", new=AsyncMock(return_value="down")):
await self.receiver.reconcile()
await self.hass.async_block_till_done()
self.assertTrue(self.events[-1]["dispatch"])
with patch.object(self.receiver, "dispatch_ready", new=AsyncMock(return_value=True)):
claim = await self.receiver.claim_dispatch(record["issue_id"], record["first_received_ts"])
self.assertTrue(claim["allowed"])
duplicate = await self.receiver.claim_dispatch(record["issue_id"], record["first_received_ts"])
self.assertFalse(duplicate["allowed"])
await self.receiver.delivery_result(record["issue_id"], claim["attempt_id"], 202, "fixture-job")
self.receiver.state = await self.receiver.store.async_load()
await self.send(self.payload(alert_type="tunnel_health_event",
data={"tunnel_id": "owned-tunnel", "new_status": "degraded"}))
record = self.receiver.state["incidents"][record["issue_id"]]
self.assertEqual(record["delivery"]["state"], "accepted")
with patch.object(self.receiver, "tunnel_health", new=AsyncMock(return_value="down")):
await self.receiver.reconcile()
await self.hass.async_block_till_done()
self.assertFalse(self.events[-1]["dispatch"])
self.assertEqual(record["action"], "open", "Acceptance must not imply recovery")
async def test_unknown_delivery_outcome_and_lost_receipt_do_not_repeat_job(self):
record = await self.open_tunnel()
claim = await self.receiver.claim_dispatch(record["issue_id"], record["first_received_ts"])
await self.receiver.delivery_result(record["issue_id"], "wrong-attempt", 202, "unrelated")
self.assertEqual(record["delivery"]["state"], "inflight")
record["delivery"]["next_attempt_at"] = time.time() - 1
with patch.object(self.receiver, "tunnel_health", new=AsyncMock(return_value="down")):
await self.receiver.reconcile()
self.assertEqual(record["delivery"]["state"], "uncertain")
self.assertFalse((await self.receiver.claim_dispatch(record["issue_id"], record["first_received_ts"]))["allowed"])
# A late real receipt may confirm acceptance without resending anything.
await self.receiver.delivery_result(record["issue_id"], claim["attempt_id"], 202, "fixture-job")
self.assertEqual(record["delivery"]["state"], "accepted")
async def test_explicit_rejection_has_bounded_retries_and_old_opening_cannot_claim(self):
record = await self.open_tunnel()
opening = record["first_received_ts"]
for index in range(3):
claim = await self.receiver.claim_dispatch(record["issue_id"], opening)
self.assertTrue(claim["allowed"])
await self.receiver.delivery_result(record["issue_id"], claim["attempt_id"], 429, "")
record["delivery"]["next_attempt_at"] = time.time() - 1
self.assertFalse((await self.receiver.claim_dispatch(record["issue_id"], opening))["allowed"])
await self.receiver.resolve(record["issue_id"], "Fixture confirmed healthy")
await self.open_tunnel()
self.assertFalse((await self.receiver.claim_dispatch(record["issue_id"], opening))["allowed"])
async def test_failed_health_read_or_new_failure_cannot_clear_incident(self):
record = await self.open_tunnel()
with patch.object(self.receiver, "tunnel_health", new=AsyncMock(return_value=None)):
await self.receiver.reconcile()
self.assertEqual(record["action"], "open")
async def new_failure(snapshot):
self.receiver.ingest([dict(snapshot, status="degraded", event_ts=time.time(), received_ts=time.time())])
return "healthy"
with patch.object(self.receiver, "tunnel_health", new=new_failure):
await self.receiver.reconcile()
self.assertEqual(self.receiver.state["incidents"][record["issue_id"]]["action"], "open")
async def test_saved_recovery_reconciles_repair_when_original_event_was_missed(self):
from homeassistant.helpers import issue_registry as ir
record = await self.open_tunnel()
await self.receiver.resolve(record["issue_id"], "Fixture current health verified")
ir.async_create_issue(self.hass, "spook", "user_" + record["issue_id"],
is_fixable=True, severity=ir.IssueSeverity.ERROR,
translation_key="fixture")
self.receiver.state = await self.receiver.store.async_load()
await self.hass.async_block_till_done()
self.events.clear()
result = await self.receiver.reconcile()
await self.hass.async_block_till_done()
self.assertEqual(result["incidents"][0]["outcome"], "recovery_presentation_replayed")
self.assertEqual(self.events[0]["action"], "resolve")
self.assertFalse(self.events[0]["dispatch"])
async def test_shared_dispatch_returns_real_intake_receipt_without_changing_legacy_callers(self):
import yaml
from homeassistant.core import Context, SupportsResponse
from homeassistant.helpers import config_validation as cv
from homeassistant.helpers.script import Script
cfg = yaml.safe_load((config_path / "script/joanna_dispatch.yaml").read_text())
async def intake(call):
return {"status": 202, "content": {"ok": True, "detail": {"jobId": "fixture-job"}}, "headers": {}}
self.hass.services.async_register("rest_command", "bearclaw_command", intake,
supports_response=SupportsResponse.OPTIONAL)
script = Script(self.hass, cv.SCRIPT_SCHEMA(cfg["joanna_dispatch"]["sequence"]),
"Fixture dispatch", "script")
data = {"summary": "Fixture only", "request": "No live action",
"entity_ids": [], "diagnostics": "Isolated fixture"}
result = await script.async_run(data, Context())
receipt = result.service_response
self.assertEqual(receipt["content"]["detail"]["jobId"], "fixture-job")
await script.async_run(data, Context())
if __name__ == "__main__":
unittest.main()

@ -1,318 +0,0 @@
"""Exercise shared health templates with independent alarm and recovery fixtures."""
from pathlib import Path
from datetime import datetime, timezone, timedelta
from types import SimpleNamespace
import unittest
from jinja2 import Environment, FileSystemLoader
import yaml
ROOT = Path(__file__).resolve().parents[1]
def as_function(macro):
def invoke(*args, **kwargs):
result = []
macro(*args, returns=result.append, **kwargs)
return result[0]
return invoke
class InfrastructureHealthTest(unittest.TestCase):
def setUp(self):
self.states = {
**{f"binary_sensor.{name}": "off" for name in [
"infra_wan_quality_degraded", "infra_dns_pihole_degraded",
"garage_switch_problem", "office_switch_problem",
"infra_nebula_sync_degraded", "infra_pihole_iot_dns_degraded",
"infra_compute_degraded", "infra_storage_degraded",
"node_proxmox1_updates_packages", "node_proxmox02_updates_packages",
"infra_external_monitoring_degraded", "tesla_home_charge_attention",
"infra_ups_problem", "docker_host_maintenance_attention",
"hvac_maintenance_due", "home_water_problem", "kiosk_devices_need_attention",
"joanna_memory_index_stale",
]},
"sensor.l10s_vacuum_error": "no_error",
"binary_sensor.powerwall_status": "on",
"binary_sensor.powerwall_grid_status": "on",
"input_text.infra_eaton_low_voltage_since": "",
"sensor.mariadb_status": "running",
"sensor.bearclaw_scheduled_job_health": "ok",
"sensor.joanna_onenote_kb_health": "ok",
"binary_sensor.joanna_mini_app_problem": "off",
"sensor.active_issues": "0",
"sensor.garage_ups_status_data": "OL",
"sensor.garage_ups_status": "Online",
"sensor.office_ups_eaton_550_status_data": "OL",
"sensor.office_ups_eaton_550_status": "Online",
"sensor.office_office_ups_eaton_3s_550_alarms": "",
"sensor.office_ups_cyberpower_status_data": "OL",
"sensor.office_ups_cyberpower_status": "Online",
}
self.env = Environment(loader=FileSystemLoader(ROOT / "config/custom_templates"),
extensions=["jinja2.ext.do"])
self.env.filters["as_function"] = as_function
self.env.globals["states"] = lambda entity_id: self.states.get(entity_id, "unknown")
self.attributes = {}
self.env.globals["state_attr"] = lambda entity_id, name: self.attributes.get(entity_id, {}).get(name)
self.clock = datetime(2026, 10, 1, 21, tzinfo=timezone.utc)
self.env.globals["now"] = lambda: self.clock
self.env.globals["as_timestamp"] = self.timestamp
self.env.globals["expand"] = lambda entity_id: [SimpleNamespace(state=self.states[entity_id])] if entity_id in self.states else []
self.env.globals["states"].sensor = SimpleNamespace(
office_ups_eaton_550_status_data=SimpleNamespace(last_changed=self.clock),
office_office_ups_eaton_3s_550_alarms=SimpleNamespace(last_changed=self.clock))
self.module = self.env.get_template("infrastructure_health.jinja").module
loader = type("Loader", (yaml.SafeLoader,), {})
loader.add_constructor("!secret", lambda loader, node: loader.construct_scalar(node))
self.package = yaml.load((ROOT / "config/packages/infrastructure.yaml").read_text(), Loader=loader)
self.counter = next(sensor for block in self.package["template"] for sensor in block.get("sensor", [])
if sensor.get("unique_id") == "infra_dashboard_active_issue_count")
def issues(self):
return as_function(self.module.ups_issues)()
@staticmethod
def timestamp(value, default=None):
try:
return (value if isinstance(value, datetime) else datetime.fromisoformat(value)).timestamp()
except (TypeError, ValueError):
return default
def warning(self, age=86400):
self.states.update({
"sensor.office_ups_eaton_550_status_data": "ALARM OL",
"sensor.office_ups_eaton_550_status": "Alarm, Online",
"sensor.office_office_ups_eaton_3s_550_alarms": "Battery voltage too low!",
"input_text.infra_eaton_low_voltage_since": (self.clock - timedelta(seconds=age)).isoformat(),
})
def policy(self):
return as_function(self.module.eaton_low_voltage_policy)()
def reconcile_grace(self):
automation = next(item for item in self.package['automation']
if item['id'] == 'infra_eaton_low_voltage_grace_period')
if self.env.from_string(automation['condition'][0]['value_template']).render().strip() != 'True':
return
variables = {'policy': self.policy(), 'started': self.states['input_text.infra_eaton_low_voltage_since']}
variables['stable_recovery'] = self.env.from_string(automation['variables']['stable_recovery']).render(**variables).strip() == 'True'
for branch in automation['action'][0]['choose']:
if self.env.from_string(branch['conditions']).render(**variables).strip() == 'True':
action = branch['sequence'][0]
self.states[action['target']['entity_id']] = self.env.from_string(action['data']['value']).render(**variables).strip()
break
def test_grace_initializes_unknown_helper_and_restarts_after_new_outage(self):
self.warning()
self.states['input_text.infra_eaton_low_voltage_since'] = 'unknown'
self.reconcile_grace()
self.assertEqual(self.states['input_text.infra_eaton_low_voltage_since'], self.clock.isoformat())
self.clock += timedelta(hours=25)
self.assertTrue(self.policy()['ignored'])
self.states['binary_sensor.powerwall_grid_status'] = 'off'
self.reconcile_grace()
self.assertEqual(self.states['input_text.infra_eaton_low_voltage_since'], '')
self.states['binary_sensor.powerwall_grid_status'] = 'on'
self.reconcile_grace()
self.assertFalse(self.policy()['ignored'])
self.assertEqual(self.states['input_text.infra_eaton_low_voltage_since'], self.clock.isoformat())
def test_short_driver_reconnect_preserves_grace_but_stable_recovery_clears_it(self):
self.warning()
onset = self.states['input_text.infra_eaton_low_voltage_since']
self.states['sensor.office_ups_eaton_550_status_data'] = 'unavailable'
self.reconcile_grace()
self.assertEqual(self.states['input_text.infra_eaton_low_voltage_since'], onset)
self.states['sensor.office_ups_eaton_550_status_data'] = 'OL'
self.states['sensor.office_office_ups_eaton_3s_550_alarms'] = ''
self.reconcile_grace()
self.assertEqual(self.states['input_text.infra_eaton_low_voltage_since'], onset)
self.clock += timedelta(seconds=121)
self.reconcile_grace()
self.assertEqual(self.states['input_text.infra_eaton_low_voltage_since'], '')
def test_exact_warning_expires_at_24_hours_and_preserves_raw_data(self):
self.warning(86399)
self.assertEqual(self.count(), 1)
self.assertFalse(self.policy()["ignored"])
self.clock += timedelta(seconds=1)
self.assertEqual(self.count(), 0)
self.assertTrue(self.policy()["ignored"])
self.assertEqual(self.policy()["raw_alarm"], "Battery voltage too low!")
self.assertEqual(self.policy()["raw_status"], "ALARM OL")
def test_other_faults_and_missing_power_telemetry_never_expire(self):
for entity_id, values in {
"sensor.office_ups_eaton_550_status_data": ["OB", "ALARM OL RB", "ALARM OL LB", "ALARM OL DISCHRG", "ALARM OL OVER", "unavailable", "unknown"],
"sensor.office_office_ups_eaton_3s_550_alarms": ["Battery voltage too low! Replace battery!", "Battery voltage too low! Internal UPS fault!", "Battery voltage too high!", "unknown", "unavailable", ""],
"binary_sensor.powerwall_grid_status": ["off", "unknown", "unavailable"],
}.items():
for value in values:
with self.subTest(entity=entity_id, value=value):
self.warning(172800)
self.states["binary_sensor.powerwall_grid_status"] = "on"
self.states[entity_id] = value
self.assertFalse(self.policy()["ignored"])
self.assertEqual(self.count(), 1)
def test_missing_invalid_and_future_onset_do_not_acknowledge(self):
for value in ["", "unknown", "unavailable", "bad timestamp", (self.clock + timedelta(days=1)).isoformat()]:
self.warning()
self.states["input_text.infra_eaton_low_voltage_since"] = value
self.assertFalse(self.policy()["ignored"])
self.assertEqual(self.count(), 1)
def test_new_outage_or_fault_resets_grace_but_unknown_preserves_onset(self):
self.warning()
self.assertFalse(self.policy()["reset_required"])
self.states["binary_sensor.powerwall_grid_status"] = "off"
self.assertTrue(self.policy()["reset_required"])
self.states["binary_sensor.powerwall_grid_status"] = "unknown"
self.assertFalse(self.policy()["reset_required"])
self.states["binary_sensor.powerwall_grid_status"] = "on"
self.states["sensor.office_ups_eaton_550_status_data"] = "ALARM OL RB"
self.assertTrue(self.policy()["reset_required"])
def test_acknowledgment_is_scoped_to_eaton_and_restored_timestamp(self):
self.warning(90000)
self.states["sensor.garage_ups_status_data"] = "ALARM OL"
self.assertEqual(self.count(), 1)
self.assertEqual(self.issues()[0]["name"], "Garage UPS")
restored_module = self.env.get_template("infrastructure_health.jinja").make_module()
self.assertTrue(as_function(restored_module.eaton_low_voltage_policy)()["ignored"])
def count(self):
self.states["binary_sensor.infra_ups_problem"] = "on" if self.issues() else "off"
return int(self.env.from_string(self.counter["state"]).render().strip())
def test_online_alarm_reaches_overview_and_preserves_alarm(self):
self.states.update({"sensor.office_ups_eaton_550_status_data": "ALARM OL",
"sensor.office_ups_eaton_550_status": "Alarm, Online",
"sensor.office_office_ups_eaton_3s_550_alarms": "Battery voltage too low!"})
self.assertEqual(self.count(), 1)
self.assertEqual(self.issues()[0]["alarm"], "Battery voltage too low!")
self.assertIn("binary_sensor.infra_ups_problem", as_function(self.module.dashboard_active_entities)())
def test_all_three_ups_devices_cover_abnormal_and_missing_states(self):
for entity_id in ["sensor.garage_ups_status_data", "sensor.office_ups_eaton_550_status_data",
"sensor.office_ups_cyberpower_status_data"]:
for status in ["OB", "OL RB", "OL LB", "OL OVER", "OFF", "FSD", "BYPASS", "ALARM OL", "unavailable", "unknown"]:
with self.subTest(entity_id=entity_id, status=status):
self.states[entity_id] = status
self.assertEqual(self.count(), 1)
self.assertEqual(self.issues()[0]["entity_id"], entity_id)
self.states[entity_id] = "OL"
def test_charging_and_recovery_are_healthy(self):
self.states["sensor.office_ups_eaton_550_status_data"] = "OL CHRG"
self.assertEqual(self.count(), 0)
self.states["sensor.office_ups_eaton_550_status_data"] = "ALARM OL"
self.assertEqual(self.count(), 1)
self.states["sensor.office_ups_eaton_550_status_data"] = "OL"
self.assertEqual(self.count(), 0)
def test_submenu_faults_and_warnings_cannot_leave_all_clear(self):
for entity_id, fault in [("sensor.l10s_vacuum_error", "brush_stuck"),
("binary_sensor.powerwall_status", "off"),
("sensor.mariadb_status", "stopped"),
("sensor.bearclaw_scheduled_job_health", "warning"),
("sensor.joanna_onenote_kb_health", "warning"),
("binary_sensor.joanna_mini_app_problem", "on"),
("binary_sensor.infra_nebula_sync_degraded", "on"),
("binary_sensor.node_proxmox1_updates_packages", "on")]:
with self.subTest(entity_id=entity_id):
previous = self.states[entity_id]
self.states[entity_id] = fault
self.assertGreater(self.count(), 0)
self.assertIn(entity_id, as_function(self.module.dashboard_active_entities)())
self.states[entity_id] = previous
def test_repairs_gate_clear_without_double_adding_overlap(self):
self.states["sensor.active_issues"] = "2"
self.assertEqual(self.count(), 2)
self.states["sensor.office_ups_eaton_550_status_data"] = "ALARM OL"
self.assertEqual(self.count(), 2)
def test_switch_faults_and_missing_telemetry_reach_overview_and_recover(self):
self.assertEqual(self.count(), 0)
for entity_id in ["binary_sensor.garage_switch_problem", "binary_sensor.office_switch_problem"]:
for value in ["on", "unknown", "unavailable"]:
with self.subTest(entity_id=entity_id, value=value):
self.states[entity_id] = value
self.assertEqual(self.count(), 1)
self.assertEqual(self.severity(), "critical")
self.assertIn(entity_id, as_function(self.module.dashboard_active_entities)())
self.states[entity_id] = "off"
self.assertEqual(self.count(), 0)
self.assertEqual(self.severity(), "healthy")
def severity(self):
return self.env.from_string(self.counter["attributes"]["severity"]).render().strip()
def test_warning_only_rollup_stays_warning_and_counts_all_sources(self):
self.assertEqual(self.severity(), "healthy")
self.states.update({
"sensor.bearclaw_scheduled_job_health": "warning",
"sensor.joanna_onenote_kb_health": "warning",
"binary_sensor.node_proxmox1_updates_packages": "on",
})
self.assertEqual(self.count(), 3)
self.assertEqual(self.severity(), "warning")
def test_critical_overrides_warning_then_recovers_through_warning_to_clear(self):
self.states["sensor.bearclaw_scheduled_job_health"] = "warning"
self.states["binary_sensor.infra_nebula_sync_degraded"] = "on"
self.assertEqual(self.count(), 2)
self.assertEqual(self.severity(), "critical")
self.states["binary_sensor.infra_nebula_sync_degraded"] = "off"
self.assertEqual(self.count(), 1)
self.assertEqual(self.severity(), "warning")
self.states["sensor.bearclaw_scheduled_job_health"] = "error"
self.assertEqual(self.severity(), "critical")
self.states["sensor.bearclaw_scheduled_job_health"] = "ok"
self.assertEqual(self.count(), 0)
self.assertEqual(self.severity(), "healthy")
def test_category_escalation_changes_severity_without_changing_issue_count(self):
for attention, critical in [
("binary_sensor.infra_wan_quality_degraded", "binary_sensor.infra_wan_critical"),
("binary_sensor.tesla_home_charge_attention", "binary_sensor.tesla_home_charge_critical"),
]:
with self.subTest(attention=attention):
self.states[attention] = "on"
self.states[critical] = "off"
self.assertEqual(self.count(), 1)
self.assertEqual(self.severity(), "warning")
self.states[critical] = "on"
self.assertEqual(self.count(), 1)
self.assertEqual(self.severity(), "critical")
self.states[attention] = "off"
self.states[critical] = "off"
def test_water_telemetry_warning_cannot_mask_a_water_fault(self):
self.states.update({
"binary_sensor.home_water_problem": "on",
"binary_sensor.rheem_wh_telemetry_stale": "on",
"binary_sensor.rheem_wh_active_alert": "off",
})
self.attributes["binary_sensor.home_water_problem"] = {
"active_entities": ["binary_sensor.rheem_wh_problem"]}
self.assertEqual(self.severity(), "warning")
self.attributes["binary_sensor.home_water_problem"]["active_entities"].append(
"binary_sensor.garage_phyn_leak_alert")
self.assertEqual(self.severity(), "critical")
def test_open_repairs_and_missing_health_never_become_warning_only_or_clear(self):
self.states["sensor.bearclaw_scheduled_job_health"] = "warning"
self.states["sensor.active_issues"] = "2"
self.assertEqual(self.count(), 2)
self.assertEqual(self.severity(), "critical")
self.states["sensor.active_issues"] = "0"
self.states["sensor.bearclaw_scheduled_job_health"] = "unavailable"
self.assertEqual(self.count(), 1)
self.assertEqual(self.severity(), "critical")
if __name__ == "__main__":
unittest.main()

@ -1,126 +0,0 @@
"""Exercise the actual voice HTTP client against an isolated loopback service."""
import asyncio
import importlib.util
from pathlib import Path
import unittest
import aiohttp
from aiohttp import web
MODULE = Path(__file__).resolve().parents[1] / "config/custom_components/joanna_conversation/client.py"
spec = importlib.util.spec_from_file_location("joanna_client", MODULE)
client_module = importlib.util.module_from_spec(spec)
spec.loader.exec_module(client_module)
class VoiceClientTests(unittest.IsolatedAsyncioTestCase):
async def asyncSetUp(self):
self.calls = []
self.credentials = []
self.poll_count = 0
self.ready = True
self.lose_acceptance = False
self.unreadable = False
async def endpoint(request):
self.calls.append((request.method, request.path, await request.json() if request.can_read_body else None))
self.credentials.append(request.headers["Authorization"])
self.assertIn(request.headers["Authorization"], {"Bearer fixture-token", "Bearer upstairs-token", "Bearer office-token"})
if request.path.endswith("/status"):
return web.json_response({"ok": True, "deviceId": "kitchen-device"})
if request.path.endswith("/conversation"):
if self.unreadable:
return web.Response(text="{broken", content_type="application/json")
if self.lose_acceptance:
request.transport.close()
return web.Response()
return web.json_response({"status": "queued"}, status=202)
if request.path.endswith(("/ack", "/cancel")):
return web.json_response({"ok": True})
self.poll_count += 1
return web.json_response({"status": "complete" if self.ready else "queued", "text": "The exact Joanna answer."})
app = web.Application()
app.router.add_route("*", "/{path:.*}", endpoint)
self.runner = web.AppRunner(app)
await self.runner.setup()
site = web.TCPSite(self.runner, "127.0.0.1", 0)
await site.start()
self.session = aiohttp.ClientSession()
port = site._server.sockets[0].getsockname()[1]
self.client = client_module.JoannaClient(self.session, f"http://127.0.0.1:{port}", "fixture-token", "kitchen-device", wait_seconds=2, poll_seconds=0.01)
async def asyncTearDown(self):
await self.session.close()
await self.runner.cleanup()
async def test_exact_answer_reaches_speech_owner_and_receipt_follows_result(self):
await self.client.validate()
result = await self.client.converse("What is next?", "kitchen-device")
self.assertEqual(result, {"text": "The exact Joanna answer.", "success": True})
self.assertEqual(sum(path.endswith("/conversation") for _, path, _ in self.calls), 1)
self.assertTrue(self.calls[-1][1].endswith("/ack"))
async def test_unenrolled_device_cannot_submit(self):
for device in [None, "office-device"]:
with self.assertRaises(client_module.JoannaError):
await self.client.converse("Read my personal data", device)
self.assertEqual(self.calls, [])
async def test_shared_pipeline_selects_each_devices_own_credential_and_denies_unknowns(self):
bindings = [
{"device_id": "kitchen-device", "token": "fixture-token"},
{"device_id": "upstairs-device", "token": "upstairs-token"},
{"device_id": "office-device", "token": "office-token"},
]
router = client_module.JoannaDeviceRouter(self.session, self.client.base_url, bindings)
for binding in bindings:
router.clients[binding["device_id"]].poll_seconds = 0.01
self.calls.clear()
self.credentials.clear()
result = await router.converse("Which profile is this?", binding["device_id"])
self.assertTrue(result["success"])
self.assertEqual(self.calls[0][2]["deviceId"], binding["device_id"])
self.assertEqual(set(self.credentials), {"Bearer " + binding["token"]})
self.calls.clear()
for device in [None, "unenrolled-device"]:
with self.assertRaises(client_module.JoannaError):
await router.converse("Read personal data", device)
self.assertEqual(self.calls, [])
async def test_lost_acceptance_is_reconciled_without_repeating_action(self):
self.lose_acceptance = True
result = await self.client.converse("Do this once", "kitchen-device")
self.assertTrue(result["success"])
self.assertEqual(sum(path.endswith("/conversation") for _, path, _ in self.calls), 1)
request_id = self.calls[0][2]["requestId"]
self.assertIn(("GET", f"/api/assist/requests/{request_id}", None), self.calls)
async def test_unreadable_acceptance_is_spoken_as_uncertain_without_resubmit(self):
self.unreadable = True
with self.assertRaisesRegex(client_module.JoannaError, "check the request's outcome"):
await self.client.converse("Do this once", "kitchen-device")
self.assertEqual(len(self.calls), 1)
async def test_timeout_requests_cancel_and_never_claims_action_failed_to_execute(self):
self.ready = False
self.client.wait_seconds = 0.05
with self.assertRaisesRegex(client_module.JoannaError, "check its status"):
await self.client.converse("Make an action", "kitchen-device")
self.assertTrue(self.calls[-1][1].endswith("/cancel"))
self.assertEqual(sum(path.endswith("/conversation") for _, path, _ in self.calls), 1)
async def test_pipeline_cancel_is_forwarded_to_existing_job(self):
self.ready = False
task = asyncio.create_task(self.client.converse("A long request", "kitchen-device"))
while not self.poll_count:
await asyncio.sleep(0.005)
task.cancel()
with self.assertRaises(asyncio.CancelledError):
await task
self.assertTrue(self.calls[-1][1].endswith("/cancel"))
if __name__ == "__main__":
unittest.main()

@ -1,72 +0,0 @@
"""Exercise real HTTP failures without touching the live Mini App or HA."""
import importlib.util
from http.server import BaseHTTPRequestHandler, ThreadingHTTPServer
from pathlib import Path
import threading
import unittest
spec = importlib.util.spec_from_file_location("mini_app_health", Path(__file__).resolve().parents[1] / "config/shell_scripts/joanna_mini_app_health.py")
health = importlib.util.module_from_spec(spec)
spec.loader.exec_module(health)
class ProbeTests(unittest.TestCase):
def setUp(self):
self.responses = {
"/miniapp/": (200, "text/html", b'<script src="/miniapp/app.js"></script><link href="/miniapp/app.css">'),
"/miniapp/app.js": (200, "text/javascript", b"console.log('app');"),
"/miniapp/app.css": (200, "text/css", b"body { color: white; }"),
"/miniapp/api/home": (401, "application/json", b'{"ok":false,"error":"open_from_telegram"}'),
}
responses = self.responses
class Handler(BaseHTTPRequestHandler):
def do_GET(self):
status, content_type, body = responses[self.path]
self.send_response(status)
self.send_header("Content-Type", content_type)
self.send_header("Location", "/miniapp/")
self.end_headers()
self.wfile.write(body)
def log_message(self, *_):
pass
self.server = ThreadingHTTPServer(("127.0.0.1", 0), Handler)
self.thread = threading.Thread(target=self.server.serve_forever, daemon=True)
self.thread.start()
self.base = f"http://127.0.0.1:{self.server.server_port}/miniapp/"
self.settings = {"origin_url": self.base, "public_url": self.base}
def tearDown(self):
self.server.shutdown()
self.server.server_close()
self.thread.join()
def test_expected_auth_rejection_is_healthy(self):
self.assertEqual(health.probe(self.settings)["status"], "ok")
def test_edge_failure_does_not_mislabel_origin(self):
self.settings["public_url"] = "http://127.0.0.1:1/miniapp/"
result = health.probe(self.settings)
self.assertEqual((result["status"], result["origin"], result["public"]), ("error", "ok", "error"))
def test_auth_bypass_bad_assets_and_proxy_pages_fail(self):
cases = (
("/miniapp/api/home", 200, "application/json", b'{"ok":true}'),
("/miniapp/api/home", 401, "application/json", b'{"error":"proxy_login"}'),
("/miniapp/app.js", 502, "text/html", b"Bad gateway"),
("/miniapp/app.css", 200, "text/html", b"Login"),
("/miniapp/", 200, "text/html", b"Login"),
("/miniapp/", 302, "text/html", b"Redirect"),
)
for path, status, content_type, body in cases:
original = self.responses[path]
with self.subTest(path=path, status=status):
self.responses[path] = (status, content_type, body)
self.assertEqual(health.probe(self.settings)["status"], "error")
self.responses[path] = original
if __name__ == "__main__":
unittest.main()

@ -1,82 +0,0 @@
"""Run the production monitor actions in isolated HA; no live service calls.
Execute with HA's Python runtime. Its mounted /config supplies the YAML.
"""
from datetime import datetime, timedelta, timezone
from pathlib import Path
from tempfile import TemporaryDirectory
import unittest
import yaml
from homeassistant.core import Context, HomeAssistant
from homeassistant.helpers import config_validation as cv
from homeassistant.helpers.script import Script
from homeassistant.helpers.template import Template
class MonitorTests(unittest.IsolatedAsyncioTestCase):
async def asyncSetUp(self):
self.directory = TemporaryDirectory(prefix="mini-app-monitor-test-")
self.hass = HomeAssistant(self.directory.name)
loader = type("Loader", (yaml.SafeLoader,), {})
loader.add_constructor("!secret", lambda loader, node: loader.construct_scalar(node))
package = yaml.load(Path("/config/packages/bearclaw.yaml").read_text(), Loader=loader)
automation = next(item for item in package["automation"] if item["id"] == "joanna_mini_app_health_monitor")
self.problem_config = next(item for block in package["template"] for item in block.get("binary_sensor", []) if item.get("unique_id") == "joanna_mini_app_problem")
self.script = Script(self.hass, cv.SCRIPT_SCHEMA(automation["action"]), "Mini App test", "automation")
self.calls = []
async def record(call):
self.calls.append((call.domain, call.service, dict(call.data)))
if call.domain == "input_boolean":
self.hass.states.async_set("input_boolean.joanna_mini_app_incident_active", "on" if call.service == "turn_on" else "off")
for domain, services in {"repairs": ["create", "remove"], "input_boolean": ["turn_on", "turn_off"], "script": ["notify_engine", "send_to_logbook", "joanna_dispatch"]}.items():
for service in services:
self.hass.services.async_register(domain, service, record)
self.hass.states.async_set("input_boolean.joanna_mini_app_incident_active", "off")
self.hass.states.async_set("sensor.bearclaw_status_telemetry", "ok")
async def asyncTearDown(self):
await self.hass.async_stop(force=True)
self.directory.cleanup()
async def run_monitor(self, state):
self.hass.states.async_set("binary_sensor.joanna_mini_app_problem", state, {"summary": "fixture failure"})
await self.script.async_run(context=Context())
async def test_outage_deduplicates_and_recovery_clears_owned_repair(self):
await self.run_monitor("on")
self.assertEqual(sum(domain == "repairs" and service == "create" for domain, service, _ in self.calls), 1)
self.assertEqual(sum(service == "joanna_dispatch" for _, service, _ in self.calls), 1)
self.assertEqual(sum(service == "notify_engine" for _, service, _ in self.calls), 1)
count = len(self.calls)
await self.run_monitor("on")
self.assertEqual(len(self.calls), count)
await self.run_monitor("off")
removed = [data["issue_id"] for domain, service, data in self.calls if domain == "repairs" and service == "remove"]
self.assertEqual(removed, ["joanna_mini_app_unavailable"])
self.assertEqual(self.hass.states.get("input_boolean.joanna_mini_app_incident_active").state, "off")
async def test_main_service_down_keeps_independent_alert_without_dispatch(self):
self.hass.states.async_set("sensor.bearclaw_status_telemetry", "unavailable")
await self.run_monitor("on")
self.assertTrue(any(service == "create" for _, service, _ in self.calls))
self.assertTrue(any(service == "notify_engine" for _, service, _ in self.calls))
self.assertFalse(any(service == "joanna_dispatch" for _, service, _ in self.calls))
async def test_healthy_and_unknown_startup_do_not_notify(self):
for state in ("unknown", "unavailable", "off"):
await self.run_monitor(state)
self.assertEqual(self.calls, [])
async def test_frozen_success_and_missing_probe_are_failures(self):
template = Template(self.problem_config["state"], self.hass)
now = datetime.now(timezone.utc)
for state, age, expected in (("ok", 0, False), ("error", 0, True), ("unavailable", 0, True), ("ok", 240, True)):
self.hass.states.async_set("sensor.joanna_mini_app_probe", state, {"checked_at": (now - timedelta(seconds=age)).isoformat()})
self.assertEqual(template.async_render(), expected)
if __name__ == "__main__":
unittest.main()

@ -1,94 +0,0 @@
"""Prove failure shedding stays scoped and never acts without survivor quorum."""
import importlib.util
import json
from pathlib import Path
import sys
import types
import unittest
if sys.platform == "win32":
sys.modules.setdefault("fcntl", types.ModuleType("fcntl"))
source = Path(__file__).resolve().parents[1] / "config/shell_scripts/proxmox_workload_priority.py"
spec = importlib.util.spec_from_file_location("priority", source)
priority = importlib.util.module_from_spec(spec)
spec.loader.exec_module(priority)
NODES = ["core", "camera", "light"]
def cluster(offline=(), quorate=1):
return [{"type": "cluster", "quorate": quorate}] + [
{"type": "node", "name": name, "online": int(name not in offline), "local": int(name == "camera")}
for name in NODES]
class PriorityTest(unittest.TestCase):
def test_guest_recovery_claims_are_explicit_and_host_scoped(self):
manager = {"manager_status": {"service_status": {
"vm:105": {"node": "camera", "state": "started"},
"vm:113": {"node": "light", "state": "started"},
"vm:101": {"node": "camera", "state": "started"},
"vm:169": {"node": "camera", "state": "stopped"}}}}
self.assertEqual(priority.recovery_claims(manager, "camera", [105, 113, 169]), ["vm:105"])
self.assertEqual(priority.recovery_claims(manager, "camera", [113, 169]), [])
def test_confirmation_reset_and_both_failure_roles(self):
for failed in ["core", "light"]:
with self.subTest(failed=failed):
state, act = priority.failure_window(cluster([failed]), NODES, "camera", {}, 100, "boot")
self.assertFalse(act)
_, act = priority.failure_window(cluster([failed]), NODES, "camera", state, 109, "boot")
self.assertFalse(act)
_, act = priority.failure_window(cluster([failed]), NODES, "camera", state, 110, "boot")
self.assertTrue(act)
recovered, act = priority.failure_window(cluster(), NODES, "camera", state, 111, "boot")
self.assertEqual(recovered["status"], "healthy")
self.assertFalse(act)
_, act = priority.failure_window(cluster([failed]), NODES, "camera", recovered, 112, "boot")
self.assertFalse(act)
_, act = priority.failure_window(cluster([failed]), NODES, "camera", state, 120, "new-boot")
self.assertFalse(act)
def test_no_quorum_incomplete_membership_and_two_failures(self):
for snapshot in [cluster(["core"], 0), cluster(["core", "light"]), cluster(["core"])[:-1]]:
with self.subTest(snapshot=snapshot):
state, act = priority.failure_window(snapshot, NODES, "camera", {}, 100, "boot")
self.assertEqual(state["status"], "ineligible")
self.assertFalse(act)
def test_shutdown_rechecks_and_preserves_operation_boundaries(self):
for case in ["running", "stopped", "remote", "managed", "locked", "recovered", "lost_quorum", "timeout", "guest_recovery", "recovery_cancelled"]:
with self.subTest(case=case):
writes = []
def command(argv, timeout=8):
if argv[:2] == ["qm", "shutdown"]:
writes.append(argv)
if case == "timeout":
raise TimeoutError("Graceful shutdown timed out")
return ""
if argv[:2] == ["qm", "status"]:
return "status: stopped"
path = argv[2]
if path == "/cluster/resources":
return json.dumps([{"type": "qemu", "vmid": 101, "node": "core" if case == "remote" else "camera", "status": "stopped" if case == "stopped" else "running"}])
if path == "/cluster/ha/resources":
return json.dumps([{"sid": "vm:101"}] if case == "managed" else [])
if path == "/cluster/ha/status/manager_status":
return json.dumps({"manager_status": {"service_status": {"vm:105": {"node": "camera" if case == "guest_recovery" else "core", "state": "started"}}}})
return json.dumps({"lock": "backup"} if case == "locked" else {})
guest_recovery = case in ["guest_recovery", "recovery_cancelled"]
call = lambda: priority.shutdown_optional(101, "camera", NODES, [] if guest_recovery else ["core"], lambda: cluster() if case == "recovered" or guest_recovery else cluster(["core"], int(case != "lost_quorum")), command, [105])
if case in ["managed", "locked", "timeout"]:
with self.assertRaises((RuntimeError, TimeoutError)):
call()
else:
result = call()
self.assertEqual(result, {"running": "shed_optional_vm", "stopped": "already_stopped", "remote": "optional_vm_not_local", "recovered": "membership_changed", "lost_quorum": "membership_changed", "guest_recovery": "shed_optional_vm", "recovery_cancelled": "recovery_changed"}[case])
self.assertEqual(len(writes), int(case in ["running", "timeout", "guest_recovery"]))
for write in writes:
self.assertEqual(write, ["qm", "shutdown", "101", "--timeout", "35", "--forceStop", "0"])
if __name__ == "__main__":
unittest.main()

@ -1,143 +0,0 @@
"""Safety policy contracts; no live services, credentials, or vehicle commands."""
import importlib.util
from pathlib import Path
import unittest
spec = importlib.util.spec_from_file_location(
"charge_policy", Path(__file__).resolve().parents[1]
/ "config/custom_components/tesla_charge_guard/policy.py")
policy = importlib.util.module_from_spec(spec)
spec.loader.exec_module(policy)
class ChargePolicyTests(unittest.TestCase):
def setUp(self):
self.now = 10_000
self.tesla = dict(current=16, charging="charging", sample_time=self.now,
location_time=self.now, at_home=True, dc=False, plugged=True)
self.juicebox = dict(current=16, status="Charging", current_time=self.now,
status_time=self.now)
def assess(self):
return policy.classify(self.tesla, self.juicebox, self.now)
def test_actual_current_guardrail_and_no_masking_by_lower_source(self):
for source in (self.tesla, self.juicebox):
with self.subTest(source=source):
source["current"] = 18.1
self.assertEqual(self.assess()["status"], "excessive")
self.assertTrue(self.assess()["stop_allowed"])
source["current"] = 18
self.assertEqual(self.assess()["status"], "charging_safe")
def test_missing_status_does_not_mask_fresh_excessive_current(self):
self.juicebox.update(current=24, status_time=self.now - 61)
result = self.assess()
self.assertEqual(result["status"], "excessive")
self.assertFalse(result["juicebox_fresh"])
self.juicebox["current"] = 16
self.tesla.update(current=24, charging="unknown")
self.assertEqual(self.assess()["status"], "excessive")
def test_fresh_no_power_and_zero_is_stopped_without_ending_connection(self):
self.juicebox["current_time"] = self.now - 61
for state in ("NoPower", "no_power"):
self.tesla.update(current=0, charging=state)
result = self.assess()
self.assertEqual(result["status"], "stopped")
self.assertTrue(result["session_observed"])
def test_cached_zero_and_missing_values_never_prove_stopped(self):
self.tesla.update(current=0, charging="stopped", sample_time=self.now - 121)
self.juicebox.update(current=0, status="Unplugged", current_time=self.now - 61)
self.assertEqual(self.assess()["status"], "unverified")
for invalid in (None, "unknown", "nan", "inf", -1, True):
with self.subTest(invalid=invalid):
self.tesla.update(current=invalid, sample_time=self.now)
self.juicebox.update(current=invalid, current_time=self.now)
self.assertEqual(self.assess()["status"], "unverified")
def test_fresh_away_and_dc_reports_veto_all_vehicle_stops(self):
self.juicebox["current"] = 24
self.tesla["at_home"] = False
self.assertFalse(self.assess()["stop_allowed"])
self.tesla.update(at_home=True, dc=True)
self.assertFalse(self.assess()["stop_allowed"])
self.tesla["current"] = None
result = policy.classify(self.tesla, self.juicebox, self.now, session_active=True)
self.assertFalse(result["stop_allowed"])
self.juicebox["status_time"] = self.now - 61
result = policy.classify(self.tesla, self.juicebox, self.now, session_active=True)
self.assertEqual(result["status"], "excessive")
self.assertFalse(result["stop_allowed"])
self.assertFalse(result["session_observed"])
def test_home_charger_activity_without_vehicle_scope_requires_investigation(self):
result = policy.classify({}, self.juicebox, self.now)
self.assertEqual(result["status"], "unverified")
self.assertTrue(result["home_session"])
self.assertFalse(result["stop_allowed"])
self.assertIsNone(result["session_observed"])
def test_home_zero_clears_home_incident_without_stopping_vehicle_away(self):
self.tesla["at_home"] = False
self.juicebox.update(current=0, status="Unplugged")
result = self.assess()
self.assertEqual(result["status"], "stopped")
self.assertFalse(result["stop_allowed"])
self.assertFalse(result["home_session"])
def test_unknown_home_session_keeps_the_protective_stop_scope(self):
self.tesla["sample_time"] = self.now - 121
self.juicebox["current_time"] = self.now - 61
result = self.assess()
self.assertEqual(result["status"], "unverified")
self.assertTrue(result["home_session"])
self.assertTrue(result["stop_allowed"])
def test_newer_unplugged_report_does_not_resurrect_old_charging_session(self):
self.tesla["sample_time"] = self.now - 300
self.juicebox.update(current=0, status="Unplugged", current_time=self.now - 100,
status_time=self.now - 100)
result = self.assess()
self.assertEqual(result["status"], "unverified")
self.assertFalse(result["home_session"])
self.assertFalse(result["stop_allowed"])
def test_restored_home_session_remains_unverified_until_new_source_data(self):
result = policy.classify({}, {}, self.now, session_active=True)
self.assertEqual(result["status"], "unverified")
self.assertTrue(result["stop_allowed"])
self.assertIsNone(result["session_observed"])
self.tesla["at_home"] = False
result = policy.classify(self.tesla, {}, self.now, session_active=True)
self.assertFalse(result["stop_allowed"])
self.assertFalse(result["session_observed"])
def test_fresh_zero_requires_a_stopped_state_and_no_active_conflict(self):
self.tesla.update(current=0, charging="stopped")
self.juicebox.update(current=0, status="Unplugged")
self.assertEqual(self.assess()["status"], "stopped")
self.tesla.update(current=16, charging="charging")
self.assertNotEqual(self.assess()["status"], "stopped")
self.tesla.update(current=0, charging="unknown")
self.juicebox["status"] = "unknown"
self.assertEqual(self.assess()["status"], "unverified")
def test_positive_current_with_missing_status_prevents_zero_confirmation(self):
self.tesla.update(current=0, charging="stopped")
self.juicebox.update(current=16, status_time=self.now - 61)
self.assertEqual(self.assess()["status"], "unverified")
self.tesla.update(current=16, charging="unknown")
self.juicebox.update(current=0, status="Unplugged", status_time=self.now)
self.assertEqual(self.assess()["status"], "unverified")
def test_future_samples_and_old_status_cannot_prove_safe(self):
self.tesla["sample_time"] = self.now + 6
self.juicebox["status_time"] = self.now - 61
self.assertEqual(self.assess()["status"], "unverified")
if __name__ == "__main__":
unittest.main()

@ -1,97 +0,0 @@
"""Adapter contracts, run inside an HA environment with upstream I/O isolated."""
from pathlib import Path
import sys
from tempfile import TemporaryDirectory
from time import time
from types import SimpleNamespace
import unittest
from unittest.mock import patch
import yaml
sys.path.insert(0, str(Path(__file__).resolve().parents[1] / "config"))
from custom_components.tesla_charge_guard import async_setup
from homeassistant.core import HomeAssistant
from homeassistant.helpers.template import Template
class AdapterContractTests(unittest.IsolatedAsyncioTestCase):
async def test_cached_zero_with_clock_skew_cannot_clear_a_new_incident(self):
package = yaml.safe_load((Path(__file__).resolve().parents[1]
/ "config/packages/tesla_model_y.yaml").read_text())
steps = package["script"]["tesla_home_charge_protect"]["sequence"]
boundary_source = next(step["variables"]["verification_after"]
for step in steps if "verification_after" in step.get("variables", {}))
proof_source = next(sensor["state"] for group in package["template"]
for sensor in group.get("binary_sensor", [])
if sensor["unique_id"] == "tesla_home_charge_stop_verified")
with TemporaryDirectory() as directory:
hass = HomeAssistant(directory)
cached_sample = time() + 2
boundary = Template(boundary_source, hass).async_render({"guard": dict(
tesla_sample_time=cached_sample, juicebox_sample_time=0)})
hass.states.async_set("input_datetime.tesla_home_charge_verify_after", "fixture",
{"timestamp": boundary})
hass.states.async_set("input_boolean.tesla_high_charge_rate_alert_active", "on")
hass.states.async_set("sensor.tesla_home_charge_guard", "stopped", {"sample_time": cached_sample})
proof = Template(proof_source, hass)
self.assertIs(proof.async_render(), False)
hass.states.async_set("sensor.tesla_home_charge_guard", "stopped", {"sample_time": boundary + 1})
self.assertIs(proof.async_render(), True)
hass.states.async_set("input_boolean.tesla_high_charge_rate_alert_active", "off")
self.assertIs(proof.async_render(), False)
invalid_boundary = Template(boundary_source, hass).async_render({"guard": dict(
tesla_sample_time=time() + 1000, juicebox_sample_time=0)})
self.assertLessEqual(invalid_boundary, time() + 1)
await hass.async_stop(force=True)
async def test_retained_reports_and_successful_cached_refresh_do_not_prove_safety(self):
with TemporaryDirectory() as directory:
hass = HomeAssistant(directory)
hass.states.async_set("zone.home", "0", {"latitude": 0, "longitude": 0, "radius": 100})
old = (time() - 600) * 1000
data = dict(charge_state_charger_actual_current=0,
charge_state_charging_state="Disconnected",
charge_state_timestamp=old, drive_state_timestamp=old,
drive_state_latitude=0, drive_state_longitude=0,
charge_state_fast_charger_present=False)
async def refresh():
# A successful refresh with a sleeping vehicle returns cached data.
pass
vehicle = SimpleNamespace(vin="fixture", coordinator=SimpleNamespace(data=data, async_refresh=refresh))
registry_entry = SimpleNamespace(platform="tesla_fleet", config_entry_id="fixture", unique_id="fixture-current")
registry = SimpleNamespace(async_get=lambda entity_id: registry_entry)
hass.config_entries = SimpleNamespace(async_get_entry=lambda entry_id: SimpleNamespace(runtime_data=SimpleNamespace(vehicles=[vehicle])))
callbacks = {}
async def subscribe(_hass, topic, callback):
callbacks[topic] = callback
return lambda: None
with patch("custom_components.tesla_charge_guard.er.async_get", return_value=registry), patch("custom_components.tesla_charge_guard.mqtt.async_subscribe", side_effect=subscribe):
await async_setup(hass, {"tesla_charge_guard": dict(entity_id="sensor.fixture", mqtt_prefix="fixture", current_limit=18)})
callbacks["fixture/Current/state"](SimpleNamespace(topic="fixture/Current/state", payload="24", retain=True))
callbacks["fixture/Status/state"](SimpleNamespace(topic="fixture/Status/state", payload="Charging", retain=True))
result = await hass.services.async_call("tesla_charge_guard", "snapshot", {"refresh": True}, blocking=True, return_response=True)
self.assertEqual(result["status"], "unverified")
self.assertFalse(result["tesla_fresh"])
self.assertFalse(result["juicebox_fresh"])
callbacks["fixture/Current/state"](SimpleNamespace(topic="fixture/Current/state", payload="24", retain=False))
callbacks["fixture/Status/state"](SimpleNamespace(topic="fixture/Status/state", payload="Charging", retain=False))
result = await hass.services.async_call("tesla_charge_guard", "snapshot", {}, blocking=True, return_response=True)
self.assertEqual(result["status"], "excessive")
self.assertEqual(result["actual_current"], 24)
self.assertTrue(result["stop_allowed"])
self.assertFalse({"vin", "latitude", "longitude", "access_token"} & result.keys())
callbacks["fixture/Current/state"](SimpleNamespace(topic="fixture/Current/state", payload="nan", retain=False))
result = await hass.services.async_call("tesla_charge_guard", "snapshot", {}, blocking=True, return_response=True)
self.assertEqual(result["status"], "unverified")
self.assertFalse(result["juicebox_fresh"])
await hass.async_stop(force=True)
if __name__ == "__main__":
unittest.main()
Loading…
Cancel
Save

Powered by TurnKey Linux.