diff --git a/.claude/skills/bump-pyhive/SKILL.md b/.claude/skills/bump-pyhive/SKILL.md new file mode 100644 index 0000000..f4c5da0 --- /dev/null +++ b/.claude/skills/bump-pyhive/SKILL.md @@ -0,0 +1,71 @@ +--- +name: bump-pyhive +description: Update the pyhive-integration (apyhiveapi) requirement in the Hive custom component's manifest.json, review what changed in the library, and verify the component against it. Use when a pyhive bump PR is open, a new pyhive release or beta is out, before cutting a component beta, or the user wants to test a pyhive beta/dev build. +--- + +# Bump pyhive-integration + +`pyhive-integration` (imported as `apyhiveapi`) is pinned in `custom_components/hive/manifest.json` `requirements`. Dependabot can't bump it, so `.github/workflows/pyhive_bump.yml` opens `deps/pyhive-integration-` PRs instead. + +Read the principles in `CLAUDE.md` first. In short: +- This repo may pin a **newer** `pyhive-integration` than core hive does, including pre-releases. That's intended. +- Keep the pin exact (`==`). Don't switch to `>=` to quiet hassfest; `.github/scripts/hassfest.py` already treats that difference as a warning. +- A pre-release pin can only ship in a component **beta**. A stable component release needs a stable pin. + +## 1. Pick the target +```bash +jq -r '.requirements[]' custom_components/hive/manifest.json # current pin +curl -fsS https://pypi.org/pypi/pyhive-integration/json | jq -r '.info.version' # latest stable +# newest version overall, pre-releases included (sorted as versions, not by upload date) +curl -fsS https://pypi.org/pypi/pyhive-integration/json | jq -r '.releases | keys[]' \ + | .venv/bin/python -c 'import sys; from packaging.version import Version; print(max(sys.stdin.read().split(), key=Version))' +gh pr list --search "pyhive-integration in:title" --state open # existing PR? +``` +- For a beta (or when the user asks for "latest"), the target is the newest version overall. +- For a stable release, the target is the latest stable. +- Also note core's pin, from `.venv/lib/python*/site-packages/homeassistant/components/hive/manifest.json`. Core's re-exported platforms are written against it, so a big gap needs a closer look. + +If there's already an open PR for the target, work on that branch (`gh pr checkout `) instead of making a new change. + +## 2. Review what changed +`uv pip download` doesn't exist, so fetch the wheels from PyPI's JSON API into the scratchpad and unpack them there: +```bash +S=/pyhive +for v in ; do + url=$(curl -fsS "https://pypi.org/pypi/pyhive-integration/$v/json" | jq -r '[.urls[]|select(.packagetype=="bdist_wheel")][0].url') + mkdir -p "$S/dl-$v" "$S/src-$v" && curl -fsSL -o "$S/dl-$v/pkg.whl" "$url" && unzip -qo "$S/dl-$v/pkg.whl" -d "$S/src-$v" +done +diff -rq "$S/src-/apyhiveapi" "$S/src-/apyhiveapi" +``` +Check anything this component, or core's re-exported platforms, calls: +- `Auth` methods used in `config_flow.py` and `__init__.py`: `login`, `sms_2fa`, `device_registration`, `get_device_data`, `is_device_registered`, `forget_device`. Also the attributes the flow sets: `access_token`, `device_group_key`, `device_key`. +- `Hive`, `session.startSession`, `session.deviceList`, `session.updateData`, `updateInterval`. +- Every `hive..(` call in the component and in core's hive platforms (`grep -hoE "hive\.[a-z_]+\.[A-Za-z_]+\(" ...`). Confirm each exists on the target with a compatible signature, at runtime rather than by reading code. +- How devices are accessed (`device["hiveType"]`, `.get("deviceData")`). 2.x devices are dataclasses with a legacy-key mapping. +- `PRODUCTS`, `DEVICES` and the sensor dispatch. A new or renamed `hiveType` needs a matching `SENSOR_TYPES` entry in `sensor.py`, or core's platform descriptions, before it shows up in HA. +- Exceptions in `helper/hive_exceptions.py`, especially anything `startSession` can now raise. `async_setup_entry` must map it: connection problems to `ConfigEntryNotReady`, credential or config problems to `ConfigEntryAuthFailed`. + +Also check that `pyhive-integration` isn't in HA's `homeassistant/package_constraints.txt`. If it ever is, HA won't install a different version, and principle 2 needs rethinking. + +## 3. Apply and verify +- Change only the `pyhive-integration==` pin in `manifest.json`. Don't change the component `version`; that happens at release. +- Install and test: + ```bash + VIRTUAL_ENV=.venv uv pip install --refresh-package pyhive-integration "pyhive-integration==" + script/test + script/lint --check + python3 .github/scripts/hassfest.py # needs Docker; the pyhive line should be a warning + ``` + (`--refresh-package` matters for a release published in the last few hours.) +- The tests mock the library. On 2.x, also run an offline session from the bundled `data/data.json` (username `use@file.com`) and call the real getters for every platform. +- Where the diff showed behaviour changes, add tests for them. +- For a pre-release target, the next step is a component beta (`/release`). For a stable target, it can go in the next stable release. + +## 4. Report +Report: +- the version change, and how it compares with core's pin +- a short summary of the library changes that matter to this component, with any risks +- the test, lint and hassfest results +- whether it's ready to merge, and whether it can ship stable or only as a beta + +If a bot PR has no CI runs, remind the user to close and reopen it, or to set up the `BOT_TOKEN` secret. Don't commit, push, or merge unless asked. diff --git a/.claude/skills/release/SKILL.md b/.claude/skills/release/SKILL.md new file mode 100644 index 0000000..4b8c4b9 --- /dev/null +++ b/.claude/skills/release/SKILL.md @@ -0,0 +1,62 @@ +--- +name: release +description: Cut a beta or stable release of the Hive custom component - check for the newest pyhive-integration (betas included) when releasing a beta, bump manifest.json, publish the GitHub release with a matching tag, and verify the Release workflow. Use when the user asks to release, ship, tag, or publish a version or beta. +--- + +# Release + +Follow MAINTAINING.md → "Releasing", and the principles in `CLAUDE.md`. The rules that matter: +- **Betas are the fast, opt-in channel.** They're how new `pyhive-integration` builds and fixes reach users before core HA ships them. Stable releases go to every HACS user. +- The tag must equal `version` in `custom_components/hive/manifest.json`, for example `2026.10.0` or `2026.10.0b1`. Use a lowercase `b`, with no dot before it. +- Beta tags (`bN`) are always published as pre-releases. Stable tags never are. +- A stable release must pin a stable `pyhive-integration`. A pre-release pin only ships in a beta. `check_release.py` fails the Release run otherwise, but by then the release is already public, so check before publishing. +- Publishing a release is visible to every HACS user, and so is deleting one. **Confirm the exact tag and whether it is a pre-release with the user before running `gh release create`.** Never commit, push, or open PRs unless the user asks. + +## Steps + +1. **Pick the version.** + - Read the current `version` from the manifest and list recent tags: `gh release list -L 10`. + - Propose the next version and let the user confirm or change it: + - New month: `YEAR.MONTH.0`. + - Same month: bump the patch number. + - Beta: add `b1`, or the next free `bN`. + +2. **Check pyhive-integration.** + - **Beta:** always look up the newest version on PyPI, pre-releases included: + ```bash + curl -fsS https://pypi.org/pypi/pyhive-integration/json | jq -r '.releases | keys[]' \ + | .venv/bin/python -c 'import sys; from packaging.version import Version; print(max(sys.stdin.read().split(), key=Version))' + jq -r '.requirements[]' custom_components/hive/manifest.json + ``` + If it's newer than the pin, run `/bump-pyhive` for it first, and get that merged to `master`, unless the user decides to skip it. Check for an open `deps/pyhive-integration-*` PR before starting a new one. + - **Stable:** the pin must not be a pre-release. If `master` pins a pyhive beta, stop: either wait for a stable pyhive, or move the pin to the latest stable with `/bump-pyhive` first. + +3. **Check it's safe to ship.** + - `gh run list -w ci.yml -b master -L 1` and `gh run list -w compat.yml -L 1` must both be green. If either is red, stop and report. For a red Compatibility run, suggest `/triage-compat`. + - A hassfest **warning** about `pyhive-integration` differing from core hive is expected (see `CLAUDE.md`). Only errors count. + - `script/test` and `script/lint --check` must pass locally. + - Check `git log ..origin/master --oneline`. If there's nothing to release, say so. + +4. **Bump the manifest.** Change only the `version` value in `manifest.json`. Don't touch `requirements`; that's `/bump-pyhive`. The change must reach `master` before tagging: + - If the user asks, make a branch `release/`, commit it, and open a PR. + - Otherwise hand the change over for them to commit. + - Wait until it's merged, then check with `git fetch && git show origin/master:custom_components/hive/manifest.json | jq -r '.version, .requirements[]'`. + +5. **Publish** (only after the user confirms the tag): + ```bash + gh release create --target master --generate-notes --prerelease # beta + gh release create --target master --generate-notes --latest # stable + ``` + For a beta, add the `pyhive-integration` version to the notes, and say whether it's ahead of core's. + +6. **Verify.** + - Watch the Release workflow: + ```bash + gh run watch $(gh run list -w release.yml -L1 --json databaseId -q '.[0].databaseId') --exit-status + ``` + - Then confirm `hive.zip` is attached: `gh release view --json assets -q '.assets[].name'`. + - If the check job fails, the release is already visible to HACS users. Tell the user, and offer `gh release delete --cleanup-tag` (it needs their OK), then a corrected release. + +7. **Clean up** after a stable release that replaces betas. Offer `gh workflow run delete_beta.yml`. It keeps the newest pre-release and never touches stable releases. + +Report the release URL, the `pyhive-integration` version it ships, the Release run result and anything left for the user to do. diff --git a/.claude/skills/repo-health/SKILL.md b/.claude/skills/repo-health/SKILL.md new file mode 100644 index 0000000..c303011 --- /dev/null +++ b/.claude/skills/repo-health/SKILL.md @@ -0,0 +1,37 @@ +--- +name: repo-health +description: One-shot health report for the Hive custom component repo - workflow states and latest results, open bot/dependency PRs, stale-labelled items, pending release, branch protection and required secrets. Use when the user asks for status, "is everything OK", a maintenance check, or what needs attention. +--- + +# Repo health + +This is read-only. Gather everything first, then report. Don't change settings, rerun workflows, or merge anything unless the user asks. + +```bash +R=Pyhass/Hive-Custom-Component +gh workflow list --all -R $R # any "disabled_inactivity"? +for w in ci.yml compat.yml pyhive_bump.yml stale.yml release.yml; do + echo "== $w"; gh run list -R $R -w $w -L 3 --json conclusion,createdAt,headBranch,event -q '.[] | "\(.createdAt) \(.event) \(.headBranch) \(.conclusion)"' +done +gh pr list -R $R --state open --json number,title,author,labels,statusCheckRollup,createdAt +gh issue list -R $R --label no-issue-activity +gh pr list -R $R --label no-pr-activity +gh release list -R $R -L 5 +git fetch -q origin && git log $(gh release list -R $R -L1 --exclude-pre-releases --json tagName -q '.[0].tagName')..origin/master --oneline +gh api repos/$R/branches/master/protection 2>&1 | jq '{checks: .required_status_checks.contexts, code_owners: .required_pull_request_reviews.require_code_owner_reviews}' +gh secret list -R $R # expect BOT_TOKEN +``` +(The protection and secrets calls need admin access. If they fail, say so rather than guessing.) + +Compare what you find with MAINTAINING.md: +- **Workflows:** all active, with no `disabled_inactivity`. The latest CI run on master and the latest Compatibility run should both be green. The last Compatibility run should be under ~26 hours old. +- **Bot PRs:** Dependabot and pyhive bump PRs with no checks at all mean `BOT_TOKEN` is missing (for pyhive ones). PRs failing checks need attention. Anything older than about 2 weeks is going stale. +- **Unreleased commits on master:** suggest a release if there are user-facing changes. +- **Branch protection:** the required checks should be `HACS validation`, `Hassfest`, `Lint` and `Tests`, with code owner review on. +- **Secrets:** `BOT_TOKEN` should be present. +- **Hassfest:** a warning that `pyhive-integration` differs from core hive is expected (see `CLAUDE.md`), so don't report it as a problem. +- **pyhive-integration:** compare the manifest pin with core hive's pin and with the newest version on PyPI, pre-releases included. A newer pyhive beta than the pin is a candidate for the next component beta (`/bump-pyhive`, then `/release`). A pre-release pin on `master` blocks stable releases until it's moved to a stable version. +- **Latest beta release:** the tag should match the `version` in its manifest (`git show :custom_components/hive/manifest.json | jq -r .version`). +- **Pinned HA:** compare the HA version in the `requirements_test.txt` comment with the latest stable on PyPI (`curl -fsS https://pypi.org/pypi/homeassistant/json | jq -r .info.version`). A gap of more than one minor release means the Dependabot PR is stuck. + +Report as a short table with ✅ / ⚠️ / ❌ and one line each. Then list the actions in priority order, each with the skill to use (`/triage-compat`, `/bump-pyhive`, `/release`) or the settings page to change. diff --git a/.claude/skills/triage-compat/SKILL.md b/.claude/skills/triage-compat/SKILL.md new file mode 100644 index 0000000..d1645df --- /dev/null +++ b/.claude/skills/triage-compat/SKILL.md @@ -0,0 +1,59 @@ +--- +name: triage-compat +description: Diagnose and fix a failing nightly Compatibility workflow (compat.yml) for the Hive custom component - identifies which Home Assistant channel broke, reproduces it locally against that HA version, and fixes it. Use when Compatibility is red, a new HA release/beta broke the component, or the user asks whether the component works with a given HA version. +--- + +# Triage Compatibility + +Principle 1 in `CLAUDE.md` applies: this component extends core's hive integration and reuses it wherever possible, so fixes adapt to core rather than fork it. + +Background: most platform files (`binary_sensor.py`, `climate.py`, `light.py`, `switch.py`, `water_heater.py`, `entity.py`) re-export `homeassistant.components.hive.*`. `__init__.py`, `sensor.py` and `config_flow.py` are this repo's own code, but they rely on HA helpers and on core's `HiveEntity`. HA changes break things here without any commit in this repo. + +## 1. Find what failed +```bash +gh run list -w compat.yml -L 5 +gh run view # which jobs failed +gh run view --log-failed | tail -200 +``` +From the log, note the job and the HA version. The "Find Home Assistant … release" step prints `homeassistant=` and `test_plugin=`. + +Map it using the table in MAINTAINING.md → "Compatibility is red": +- **stable** fails: users are broken now, so treat it as urgent. +- **beta** fails: must be fixed before the next monthly HA release. +- **dev** smoke import fails: an import was renamed or removed upstream. +- The resolver step fails with "No pytest-homeassistant-custom-component release pins…": the plugin isn't published yet. Rerun later with `gh run rerun --failed`. There's nothing to fix. +- **HACS/hassfest** fails: follow the validator's message. A `[REQUIREMENTS]` message about `pyhive-integration` differing from core hive is expected, and `.github/scripts/hassfest.py` reports it as a warning (see `CLAUDE.md`). If it's failing on that, hassfest has reworded the message, so update the `ALLOWED` pattern in that script. Don't loosen the pin. + +## 2. Reproduce locally +Use a separate venv so `.venv` (which matches CI's pinned HA) stays untouched: +```bash +VENV=.venv-ha-beta script/setup +VIRTUAL_ENV=.venv-ha-beta uv pip install "pytest-homeassistant-custom-component==" +VENV=.venv-ha-beta script/test -x +``` +For a dev failure, run the smoke test instead: +```bash +VIRTUAL_ENV=.venv-ha-dev uv pip install "homeassistant @ git+https://github.com/home-assistant/core@dev" +.venv-ha-dev/bin/python .github/scripts/smoke_import.py +``` +(Create `.venv-ha-dev` with `VENV=.venv-ha-dev script/setup` first.) + +## 3. Find the upstream change +- Compare core's hive integration between the two HA versions: + `https://github.com/home-assistant/core/commits/dev/homeassistant/components/hive`. +- Search https://developers.home-assistant.io/blog for deprecations of the symbol that failed. +- Check the installed source: `.venv-ha-beta/lib/python3.*/site-packages/homeassistant/components/hive/`. + +## 4. Fix +- Keep the fix working on **both** the pinned HA (`.venv`) and the failing version. Run `script/test` in both venvs. +- If core changed a re-exported platform in a way that conflicts with this component (for example it now expects something `__init__.py` doesn't provide), adapt `__init__.py`. Only replace the re-export with a local module as a last resort, and tell the user. +- Add or adjust a test that would have caught it. +- Run `script/lint`. + +## 5. Report +Tell the user: +- which HA version and channel broke, and the root cause (with the upstream link) +- the fix, and the test results in both venvs +- whether a release is needed: stable breakage needs a patch release now (suggest `/release`); beta breakage needs one before HA's release date + +Don't commit, push, or open PRs unless asked. diff --git a/.github/CODEOWNERS b/.github/CODEOWNERS new file mode 100644 index 0000000..7b022a9 --- /dev/null +++ b/.github/CODEOWNERS @@ -0,0 +1,5 @@ +# Code owners are requested for review automatically on every PR. +# With "Require review from Code Owners" on master, their approval is needed to merge. +# https://docs.github.com/en/repositories/managing-your-repositorys-settings-and-features/customizing-your-repository/about-code-owners + +* @KJonline diff --git a/.github/ISSUE_TEMPLATE/bug_report.md b/.github/ISSUE_TEMPLATE/bug_report.md deleted file mode 100644 index 7f6c579..0000000 --- a/.github/ISSUE_TEMPLATE/bug_report.md +++ /dev/null @@ -1,34 +0,0 @@ ---- -name: Bug report -about: Create a report to help us improve -title: "[BUG]" -labels: bug -assignees: KJonline - ---- - -**Describe the bug** -A clear and concise description of what the bug is. - -**To Reproduce** -Steps to reproduce the behaviour: - -1. Go to '...' -2. Click on '....' -3. Scroll down to '....' -4. See error - -**Expected behaviour** -A clear and concise description of what you expected to happen. - -**Screenshots** -If applicable, add screenshots to help explain your problem. - -**Desktop (please complete the following information):** - -- OS: [e.g. iOS] -- Browser [e.g. chrome, safari] -- Version [e.g. 22] - -**Additional context** -Add any other context about the problem here. diff --git a/.github/ISSUE_TEMPLATE/bug_report.yml b/.github/ISSUE_TEMPLATE/bug_report.yml new file mode 100644 index 0000000..75cb477 --- /dev/null +++ b/.github/ISSUE_TEMPLATE/bug_report.yml @@ -0,0 +1,110 @@ +name: Bug report +description: Something isn't working with the Hive custom component +title: "[BUG] " +labels: [bug] +assignees: [KJonline] +body: + - type: markdown + attributes: + value: | + Thanks for reporting a problem. Please check the [open issues](https://github.com/Pyhass/Hive-Custom-Component/issues) first in case it's already reported. + + **Security issues:** don't report them here. Use [private vulnerability reporting](https://github.com/Pyhass/Hive-Custom-Component/security/advisories/new) instead. + + - type: textarea + id: description + attributes: + label: What happened? + description: What went wrong, and what did you expect to happen instead? + validations: + required: true + + - type: textarea + id: reproduce + attributes: + label: Steps to reproduce + placeholder: | + 1. Go to Settings > Devices & services > Hive + 2. ... + validations: + required: false + + - type: input + id: component-version + attributes: + label: Hive custom component version + description: Shown in HACS, or `version` in `custom_components/hive/manifest.json`. + placeholder: "2026.8.0" + validations: + required: true + + - type: input + id: ha-version + attributes: + label: Home Assistant version + description: Settings > About. + placeholder: "2026.9.4" + validations: + required: true + + - type: dropdown + id: install-method + attributes: + label: How did you install the component? + options: + - HACS + - Manually + validations: + required: true + + - type: dropdown + id: devices + attributes: + label: Which Hive devices are affected? + multiple: true + options: + - Heating / thermostat + - Hot water + - Radiator valves (TRVs) + - Lights + - Smart plugs + - Sensors (motion, contact) + - Hub + - Login / 2FA / setup + - Other + validations: + required: true + + - type: textarea + id: logs + attributes: + label: Debug logs + description: | + Add this to `configuration.yaml`, restart, reproduce the problem, then paste the relevant lines from **Settings > System > Logs** (select *Show raw logs*): + ```yaml + logger: + default: warning + logs: + custom_components.hive: debug + apyhiveapi: debug + ``` + **Remove your email address, tokens and any other personal details before posting.** + render: text + validations: + required: false + + - type: textarea + id: context + attributes: + label: Anything else? + description: Screenshots, when it started, whether it worked on an earlier version, etc. + validations: + required: false + + - type: checkboxes + id: checks + attributes: + label: Checks + options: + - label: I've removed personal information (email, tokens, device IDs) from the logs above. + required: true diff --git a/.github/ISSUE_TEMPLATE/config.yml b/.github/ISSUE_TEMPLATE/config.yml new file mode 100644 index 0000000..2647a16 --- /dev/null +++ b/.github/ISSUE_TEMPLATE/config.yml @@ -0,0 +1,8 @@ +blank_issues_enabled: false +contact_links: + - name: Report a security vulnerability + url: https://github.com/Pyhass/Hive-Custom-Component/security/advisories/new + about: Report privately so it can be fixed before it's public. + - name: Home Assistant Hive integration docs + url: https://www.home-assistant.io/integrations/hive/ + about: Setup and usage of the Hive integration this component extends. diff --git a/.github/ISSUE_TEMPLATE/feature_request.md b/.github/ISSUE_TEMPLATE/feature_request.md deleted file mode 100644 index 76d928d..0000000 --- a/.github/ISSUE_TEMPLATE/feature_request.md +++ /dev/null @@ -1,20 +0,0 @@ ---- -name: Feature request -about: Suggest an idea for this project -title: "[FEATURE]" -labels: enhancement -assignees: KJonline - ---- - -**Is your feature request related to a problem? Please describe.** -A clear and concise description of what the problem is. Ex. I'm always frustrated when [...] - -**Describe the solution you'd like** -A clear and concise description of what you want to happen. - -**Describe alternatives you've considered** -A clear and concise description of any alternative solutions or features you've considered. - -**Additional context** -Add any other context or screenshots about the feature request here. diff --git a/.github/ISSUE_TEMPLATE/feature_request.yml b/.github/ISSUE_TEMPLATE/feature_request.yml new file mode 100644 index 0000000..2bb783c --- /dev/null +++ b/.github/ISSUE_TEMPLATE/feature_request.yml @@ -0,0 +1,35 @@ +name: Feature request +description: Suggest an improvement or new feature +title: "[FEATURE] " +labels: [enhancement] +assignees: [KJonline] +body: + - type: textarea + id: problem + attributes: + label: What problem would this solve? + description: For example, "I can't see when my hot water boost ends." + validations: + required: true + + - type: textarea + id: solution + attributes: + label: What would you like to happen? + validations: + required: true + + - type: textarea + id: alternatives + attributes: + label: Alternatives you've considered + validations: + required: false + + - type: input + id: devices + attributes: + label: Hive devices involved + placeholder: "e.g. Hive Thermostat mini, radiator valves" + validations: + required: false diff --git a/.github/PULL_REQUEST_TEMPLATE/pull_request_template.md b/.github/PULL_REQUEST_TEMPLATE/pull_request_template.md deleted file mode 100644 index dea4213..0000000 --- a/.github/PULL_REQUEST_TEMPLATE/pull_request_template.md +++ /dev/null @@ -1,16 +0,0 @@ ---- -name: Pull Request -about: Create PR to update HA Custom Component -title: "[PR]" -labels: PR -assignees: KJonline - ---- -**Related Issues** -PLease tag any related issues this PR fixes - -**Describe the change proposed** -A clear and concise description of what the PR is. - -**Additional context** -Add any other context about the problem here. diff --git a/.github/dependabot.yml b/.github/dependabot.yml new file mode 100644 index 0000000..970ab31 --- /dev/null +++ b/.github/dependabot.yml @@ -0,0 +1,19 @@ +version: 2 +updates: + # Keeps action versions in .github/workflows current. + - package-ecosystem: github-actions + directory: / + schedule: + interval: weekly + groups: + github-actions: + patterns: ["*"] + labels: [dependencies] + + # requirements_test.txt: the HA test plugin (which pins the HA version CI + # tests against) and ruff. pyhive-integration is handled by pyhive_bump.yml. + - package-ecosystem: pip + directory: / + schedule: + interval: weekly + labels: [dependencies] diff --git a/.github/pull_request_template.md b/.github/pull_request_template.md new file mode 100644 index 0000000..0a52d37 --- /dev/null +++ b/.github/pull_request_template.md @@ -0,0 +1,13 @@ +## What does this change? + + + +## Related issues + + + +## Checklist + +- [ ] Tests added or updated, and `script/test` passes +- [ ] `script/lint --check` passes (after `script/lint`, which also regenerates translations) +- [ ] If this is going into a release: bumped `version` in `manifest.json` diff --git a/.github/scripts/check_release.py b/.github/scripts/check_release.py new file mode 100644 index 0000000..cc901b6 --- /dev/null +++ b/.github/scripts/check_release.py @@ -0,0 +1,68 @@ +"""Check a release tag agrees with manifest.json before it reaches HACS users. + + python check_release.py + +HACS installs by tag, so the tag must match the manifest version (compared as +versions, so tag 2026.3.1.b1 matches manifest 2026.3.1b1). A beta version must be +a GitHub pre-release, otherwise HACS offers it to every user. A stable release +must also pin a stable pyhive-integration: pre-release libraries only ship in the +opt-in beta channel (see CLAUDE.md). +""" + +import json +from pathlib import Path +import sys + +from packaging.requirements import Requirement +from packaging.utils import canonicalize_name +from packaging.version import InvalidVersion, Version + +MANIFEST = ( + Path(__file__).resolve().parents[2] / "custom_components" / "hive" / "manifest.json" +) + + +def main(tag: str, prerelease: bool) -> int: + manifest = json.loads(MANIFEST.read_text(encoding="utf-8")) + manifest_version = manifest["version"] + errors = [] + try: + tag_version = Version(tag) + except InvalidVersion: + print(f"::error::Tag {tag!r} is not a valid version") + return 1 + + if tag_version != Version(manifest_version): + errors.append( + f"Tag {tag} doesn't match manifest.json version {manifest_version}. " + "Bump the manifest version before tagging." + ) + if tag_version.is_prerelease and not prerelease: + errors.append( + f"{tag} is a beta version but the release isn't marked as a pre-release, " + "so HACS will offer it to every user." + ) + if prerelease and not tag_version.is_prerelease: + errors.append( + f"{tag} is marked as a pre-release but isn't a beta version " + "(expected something like 2026.9.0b1)." + ) + if not tag_version.is_prerelease: + for req in map(Requirement, manifest.get("requirements", [])): + if canonicalize_name(req.name) == "pyhive-integration" and any( + Version(spec.version).is_prerelease for spec in req.specifier + ): + errors.append( + f"{tag} is a stable release but pins {req}. Stable releases go " + "to every HACS user, so ship pre-release pyhive in a beta instead." + ) + + for error in errors: + print(f"::error::{error}") + if not errors: + print(f"Tag {tag} matches manifest.json version {manifest_version}") + return 1 if errors else 0 + + +if __name__ == "__main__": + sys.exit(main(sys.argv[1], sys.argv[2].lower() == "true")) diff --git a/.github/scripts/hassfest.py b/.github/scripts/hassfest.py new file mode 100644 index 0000000..09fc159 --- /dev/null +++ b/.github/scripts/hassfest.py @@ -0,0 +1,69 @@ +"""Run hassfest, allowing only the errors this repo causes on purpose. + + python .github/scripts/hassfest.py + +This component replaces Home Assistant core's hive integration and may pin a +different pyhive-integration than core does (see CLAUDE.md). hassfest checks a +custom integration's requirements against every core integration's pins, including +core hive's own, so it reports that difference as an error. Those errors are shown +as warnings here. Any other error, or a failure with no error lines, still fails. +""" + +from pathlib import Path +import re +import subprocess +import sys + +ROOT = Path(__file__).resolve().parents[2] +IMAGE = "ghcr.io/home-assistant/hassfest" + +# Packages whose core pin belongs to the core integration this repo replaces. +OVERRIDDEN_PACKAGES = {"pyhive-integration"} + +# The two hassfest errors about differing from a core integration's pin. Errors +# about Home Assistant's own dependencies or package constraints are not here: +# those can break the whole installation, so they must fail. +ALLOWED = re.compile( + r"\[REQUIREMENTS\] Requirement (?P[A-Za-z0-9][A-Za-z0-9._-]*)\S* " + r"(pins a package Home Assistant depends on" + r"|is incompatible with \S+, which Home Assistant depends on\.)" +) + + +def is_allowed(line: str) -> bool: + """Return True if a hassfest error line is an expected override difference.""" + match = ALLOWED.search(line) + return bool(match) and match["package"].lower() in OVERRIDDEN_PACKAGES + + +def main() -> int: + result = subprocess.run( + ["docker", "run", "--rm", "-v", f"{ROOT}:/github/workspace", IMAGE], + capture_output=True, + text=True, + check=False, + ) + output = result.stdout + result.stderr + print(output) + if result.returncode == 0: + return 0 + + errors = [line for line in output.splitlines() if "[ERROR]" in line] + if not errors: + print( + f"::error::hassfest exited with {result.returncode} without an error line" + ) + return result.returncode + + blocking = [line for line in errors if not is_allowed(line)] + for line in errors: + level = "error" if line in blocking else "warning" + print(f"::{level}::{line.lstrip('* ').strip()}") + if blocking: + return 1 + print("Only expected differences from core hive's requirements; passing.") + return 0 + + +if __name__ == "__main__": + sys.exit(main()) diff --git a/.github/scripts/resolve_ha_release.py b/.github/scripts/resolve_ha_release.py new file mode 100644 index 0000000..ee219dc --- /dev/null +++ b/.github/scripts/resolve_ha_release.py @@ -0,0 +1,83 @@ +"""Find the newest Home Assistant release in a channel and its test plugin build. + +Prints GitHub Actions outputs: + homeassistant= + test_plugin= + skip=true|false + + python resolve_ha_release.py stable|beta +""" + +import json +import sys +from urllib.request import urlopen + +from packaging.version import Version + +PYPI = "https://pypi.org/pypi/{}/json" +TEST_PLUGIN = "pytest-homeassistant-custom-component" +# How many recent test plugin releases to search for a matching HA pin. +SEARCH_DEPTH = 40 + + +def _get(url: str) -> dict: + with urlopen(url, timeout=30) as response: + return json.load(response) + + +def _newest(releases: dict[str, list], *, prerelease: bool) -> Version | None: + versions = [ + Version(v) + for v, files in releases.items() + if files and not all(f.get("yanked") for f in files) + ] + matching = [v for v in versions if v.is_prerelease == prerelease] + return max(matching, default=None) + + +def _test_plugin_for(ha_version: Version) -> str | None: + releases = _get(PYPI.format(TEST_PLUGIN))["releases"] + recent = sorted( + (v for v, files in releases.items() if files), + key=lambda v: max(f["upload_time"] for f in releases[v]), + reverse=True, + )[:SEARCH_DEPTH] + pin = f"homeassistant=={ha_version}" + for version in recent: + info = _get(PYPI.format(f"{TEST_PLUGIN}/{version}"))["info"] + if pin in (info["requires_dist"] or []): + return version + return None + + +def main(channel: str) -> None: + releases = _get(PYPI.format("homeassistant"))["releases"] + stable = _newest(releases, prerelease=False) + if channel == "stable": + target = stable + elif channel == "beta": + beta = _newest(releases, prerelease=True) + target = beta if beta and stable and beta > stable else None + else: + sys.exit(f"unknown channel {channel!r}, expected stable or beta") + + if target is None: + print( + f"::notice::No Home Assistant {channel} release newer than stable", + file=sys.stderr, + ) + print("skip=true") + return + + plugin = _test_plugin_for(target) + if plugin is None: + # Fail loudly: the plugin normally ships within a day of an HA release. + sys.exit(f"No {TEST_PLUGIN} release pins homeassistant=={target} yet") + + print(f"homeassistant={target}") + print(f"test_plugin={plugin}") + print("skip=false") + + +if __name__ == "__main__": + main(sys.argv[1] if len(sys.argv) > 1 else "stable") diff --git a/.github/scripts/smoke_import.py b/.github/scripts/smoke_import.py new file mode 100644 index 0000000..9ef323e --- /dev/null +++ b/.github/scripts/smoke_import.py @@ -0,0 +1,30 @@ +"""Import every module of the component, including the core platforms it re-exports. + +Catches Home Assistant removing or renaming something the component depends on. +""" + +import importlib +from pathlib import Path +import sys +import traceback + +ROOT = Path(__file__).resolve().parents[2] +COMPONENT = ROOT / "custom_components" / "hive" +sys.path.insert(0, str(ROOT)) + +failures = 0 +for path in sorted(COMPONENT.glob("*.py")): + module = f"custom_components.hive.{path.stem}".removesuffix(".__init__") + try: + importlib.import_module(module) + except Exception: # report every failure, not just the first + failures += 1 + print(f"::error file={path.relative_to(ROOT)}::Failed to import {module}") + traceback.print_exc() + else: + print(f"ok {module}") + +from homeassistant.const import __version__ # noqa: E402 + +print(f"Home Assistant {__version__}") +sys.exit(1 if failures else 0) diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml new file mode 100644 index 0000000..cb7d3ea --- /dev/null +++ b/.github/workflows/ci.yml @@ -0,0 +1,89 @@ +# Checks every PR and push to master. Make the jobs below required checks on master. +# +# This workflow deliberately has no schedule: GitHub auto-disables scheduled +# workflows after 60 days without repo activity, which also stops their +# push/pull_request triggers. Nightly jobs live in compat.yml instead. +name: CI + +on: + pull_request: + push: + branches: [master] + workflow_dispatch: + +permissions: + contents: read + +concurrency: + group: ${{ github.workflow }}-${{ github.ref }} + cancel-in-progress: true + +jobs: + hacs: + name: HACS validation + runs-on: ubuntu-latest + steps: + - uses: actions/checkout@v7 + - uses: hacs/action@22.5.0 + with: + category: integration + ignore: brands + + hassfest: + name: Hassfest + runs-on: ubuntu-latest + steps: + - uses: actions/checkout@v7 + # Runs the same image as home-assistant/actions/hassfest (latest rules), + # but lets our pyhive-integration pin differ from core hive's. See CLAUDE.md. + - run: python3 .github/scripts/hassfest.py + + lint: + name: Lint + runs-on: ubuntu-latest + steps: + - uses: actions/checkout@v7 + - uses: astral-sh/setup-uv@v10.3.2 + - name: Ruff version from requirements_test.txt + id: ruff + run: echo "spec=$(grep '^ruff==' requirements_test.txt)" >> "$GITHUB_OUTPUT" + - run: uvx "${{ steps.ruff.outputs.spec }}" check --output-format=github . + - run: uvx "${{ steps.ruff.outputs.spec }}" format --check . + + test: + name: Tests + runs-on: ubuntu-latest + steps: + - uses: actions/checkout@v7 + - uses: astral-sh/setup-uv@v10.3.2 + with: + python-version: "3.14" + activate-environment: true + enable-cache: true + cache-dependency-glob: | + requirements_test.txt + custom_components/hive/manifest.json + - name: Install dependencies + run: uv pip install -r requirements_test.txt $(jq -r '.requirements[]' custom_components/hive/manifest.json) + - run: python -m pytest + + enable-scheduled-workflows: + # Self-heal: switch nightly/weekly workflows back on if GitHub disabled them + # for inactivity, so they don't stay off unnoticed like they did in 2026. + name: Re-enable scheduled workflows + if: github.event_name == 'push' + runs-on: ubuntu-latest + permissions: + actions: write + env: + GH_TOKEN: ${{ github.token }} + GH_REPO: ${{ github.repository }} + steps: + - run: | + for workflow in compat.yml stale.yml pyhive_bump.yml; do + state=$(gh api "repos/$GH_REPO/actions/workflows/$workflow" --jq .state) + if [ "$state" = "disabled_inactivity" ]; then + gh workflow enable "$workflow" + echo "::notice::Re-enabled $workflow (was disabled for inactivity)" + fi + done diff --git a/.github/workflows/compat.yml b/.github/workflows/compat.yml new file mode 100644 index 0000000..2406dc0 --- /dev/null +++ b/.github/workflows/compat.yml @@ -0,0 +1,73 @@ +# Nightly check against Home Assistant releases this repo doesn't pin. +# +# Most platforms here re-export core's hive platforms, so a new HA release can +# break the component without any change in this repo. This catches that before +# users do. +# stable/beta: full test suite on the newest release in that channel +# (skipped for beta when no beta is newer than stable). +# dev: import smoke test against core's dev branch (the test plugin +# isn't published for dev builds). +name: Compatibility + +on: + schedule: + - cron: "17 4 * * *" + workflow_dispatch: + +permissions: + contents: read + +jobs: + validate: + name: HACS and hassfest + runs-on: ubuntu-latest + steps: + - uses: actions/checkout@v7 + - uses: hacs/action@22.5.0 + with: + category: integration + ignore: brands + - run: python3 .github/scripts/hassfest.py + + tests: + name: Tests (HA ${{ matrix.channel }}) + runs-on: ubuntu-latest + strategy: + fail-fast: false + matrix: + channel: [stable, beta] + steps: + - uses: actions/checkout@v7 + - uses: astral-sh/setup-uv@v10.3.2 + with: + python-version: "3.14" + activate-environment: true + - run: uv pip install packaging + - name: Find Home Assistant ${{ matrix.channel }} release + id: ha + run: python .github/scripts/resolve_ha_release.py ${{ matrix.channel }} >> "$GITHUB_OUTPUT" + - name: Install dependencies + if: steps.ha.outputs.skip != 'true' + run: >- + uv pip install + "pytest-homeassistant-custom-component==${{ steps.ha.outputs.test_plugin }}" + $(jq -r '.requirements[]' custom_components/hive/manifest.json) + - name: Run tests against Home Assistant ${{ steps.ha.outputs.homeassistant }} + if: steps.ha.outputs.skip != 'true' + run: python -m pytest + + dev: + name: Import smoke test (HA dev) + runs-on: ubuntu-latest + steps: + - uses: actions/checkout@v7 + - uses: astral-sh/setup-uv@v10.3.2 + with: + python-version: "3.14" + activate-environment: true + - name: Install Home Assistant dev + run: >- + uv pip install + "homeassistant @ git+https://github.com/home-assistant/core@dev" + $(jq -r '.requirements[]' custom_components/hive/manifest.json) + - run: python .github/scripts/smoke_import.py diff --git a/.github/workflows/delete_beta.yml b/.github/workflows/delete_beta.yml index 3375064..f388a00 100644 --- a/.github/workflows/delete_beta.yml +++ b/.github/workflows/delete_beta.yml @@ -1,16 +1,21 @@ +# Manually clean up old beta releases (and their tags), keeping the newest one. +# Stable releases are never touched. name: Delete Beta Releases -on: +on: workflow_dispatch: - + +permissions: + contents: write + jobs: - close: + delete: runs-on: ubuntu-latest steps: - - uses: dev-drprasad/delete-older-releases@v0.2.0 + - uses: dev-drprasad/delete-older-releases@v0.3.4 with: keep_latest: 1 - delete_tags: true - delete_tag_pattern: _b + delete_prerelease_only: true + delete_tags: true env: - GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }} + GITHUB_TOKEN: ${{ github.token }} diff --git a/.github/workflows/hassfest.yaml b/.github/workflows/hassfest.yaml deleted file mode 100644 index c422ec3..0000000 --- a/.github/workflows/hassfest.yaml +++ /dev/null @@ -1,18 +0,0 @@ -name: Validate - -on: - push: - pull_request: - schedule: - - cron: "0 0 * * *" - workflow_dispatch: - -jobs: - validate-hacs: - runs-on: "ubuntu-latest" - steps: - - uses: "actions/checkout@v3" - - name: HACS validation - uses: "hacs/action@main" - with: - category: "integration" diff --git a/.github/workflows/pyhive_bump.yml b/.github/workflows/pyhive_bump.yml new file mode 100644 index 0000000..7301dc1 --- /dev/null +++ b/.github/workflows/pyhive_bump.yml @@ -0,0 +1,91 @@ +# Opens a PR bumping pyhive-integration in manifest.json. Dependabot can't do +# this because the requirement lives in manifest.json, not a requirements file. +# +# Triggers: +# - weekly check of PyPI for a new stable release +# - manually, optionally with a specific version (e.g. a beta) +# - from the Pyhive repo after it publishes, with a step like: +# - run: >- +# gh api repos/Pyhass/Hive-Custom-Component/dispatches +# -f event_type=pyhive-release +# -F "client_payload[version]=${{ github.ref_name }}" +# env: +# GH_TOKEN: ${{ secrets.HIVE_COMPONENT_DISPATCH_TOKEN }} +# +# PRs opened with the default GITHUB_TOKEN don't trigger CI. Add a BOT_TOKEN +# secret (fine-grained PAT with contents + pull-requests write on this repo) so +# CI runs on them; without it, close and reopen the PR to start CI. +name: Bump pyhive-integration + +on: + schedule: + - cron: "23 6 * * 1" + workflow_dispatch: + inputs: + version: + description: Version to bump to (blank = latest stable on PyPI) + required: false + repository_dispatch: + types: [pyhive-release] + +permissions: + contents: read + +jobs: + bump: + runs-on: ubuntu-latest + permissions: + contents: write + pull-requests: write + steps: + - uses: actions/checkout@v7 + + - name: Work out versions + id: versions + env: + REQUESTED: ${{ inputs.version || github.event.client_payload.version }} + run: | + current=$(jq -r '.requirements[] | select(startswith("pyhive-integration==")) | ltrimstr("pyhive-integration==")' custom_components/hive/manifest.json) + target="${REQUESTED#v}" + if [ -z "$target" ]; then + target=$(curl -fsS https://pypi.org/pypi/pyhive-integration/json | jq -r .info.version) + fi + # Make sure the version exists on PyPI before opening a PR for it. + curl -fsS "https://pypi.org/pypi/pyhive-integration/$target/json" > /dev/null + echo "current=$current" >> "$GITHUB_OUTPUT" + echo "target=$target" >> "$GITHUB_OUTPUT" + echo "pyhive-integration: current $current, target $target" + + - name: Update manifest.json + if: steps.versions.outputs.current != steps.versions.outputs.target + env: + TARGET: ${{ steps.versions.outputs.target }} + run: | + python3 - <<'EOF' + import os, pathlib, re + path = pathlib.Path("custom_components/hive/manifest.json") + text = path.read_text() + text, count = re.subn( + r'"pyhive-integration==[^"]+"', + f'"pyhive-integration=={os.environ["TARGET"]}"', + text, + ) + assert count == 1, "pyhive-integration requirement not found" + path.write_text(text) + EOF + + - name: Open pull request + if: steps.versions.outputs.current != steps.versions.outputs.target + uses: peter-evans/create-pull-request@v8 + with: + token: ${{ secrets.BOT_TOKEN || github.token }} + branch: deps/pyhive-integration-${{ steps.versions.outputs.target }} + commit-message: "chore: bump pyhive-integration to ${{ steps.versions.outputs.target }}" + title: "chore: bump pyhive-integration to ${{ steps.versions.outputs.target }}" + body: | + Bumps `pyhive-integration` from `${{ steps.versions.outputs.current }}` to `${{ steps.versions.outputs.target }}`. + + - Release notes: https://pypi.org/project/pyhive-integration/${{ steps.versions.outputs.target }}/ + - The component `version` in manifest.json is **not** changed; bump it when releasing. + labels: dependencies + delete-branch: true diff --git a/.github/workflows/release.yml b/.github/workflows/release.yml new file mode 100644 index 0000000..5706c4d --- /dev/null +++ b/.github/workflows/release.yml @@ -0,0 +1,42 @@ +# Runs when a GitHub release is published (including pre-releases). +# Fails the run if the tag doesn't match manifest.json, then attaches hive.zip +# for manual installs. +name: Release + +on: + release: + types: [published] + +permissions: + contents: read + +jobs: + check: + name: Check tag matches manifest + runs-on: ubuntu-latest + steps: + - uses: actions/checkout@v7 + - uses: astral-sh/setup-uv@v10.3.2 + - env: + TAG: ${{ github.event.release.tag_name }} + PRERELEASE: ${{ github.event.release.prerelease }} + run: >- + uv run --no-project --with packaging + python .github/scripts/check_release.py "$TAG" "$PRERELEASE" + + attach-zip: + name: Attach hive.zip + needs: check + runs-on: ubuntu-latest + permissions: + contents: write + env: + GH_TOKEN: ${{ github.token }} + GH_REPO: ${{ github.repository }} + TAG: ${{ github.event.release.tag_name }} + steps: + - uses: actions/checkout@v7 + - name: Build zip + working-directory: custom_components/hive + run: zip -r "$GITHUB_WORKSPACE/hive.zip" . -x '__pycache__/*' + - run: gh release upload "$TAG" hive.zip --clobber diff --git a/.github/workflows/stale.yml b/.github/workflows/stale.yml new file mode 100644 index 0000000..f331445 --- /dev/null +++ b/.github/workflows/stale.yml @@ -0,0 +1,34 @@ +# Warns and then closes issues and PRs with no activity. +# https://github.com/actions/stale +name: Mark stale issues and pull requests + +on: + schedule: + - cron: "29 5 * * *" + workflow_dispatch: + +permissions: + contents: read + +jobs: + stale: + runs-on: ubuntu-latest + permissions: + issues: write + pull-requests: write + steps: + - uses: actions/stale@v11 + with: + days-before-stale: 60 + days-before-close: 30 + days-before-pr-close: 14 + stale-issue-message: >- + There has been no activity on this issue for 60 days. It will be + closed in 30 days unless there is new activity. + stale-pr-message: >- + There has been no activity on this PR for 60 days. It will be closed + in 14 days unless there is new activity. + stale-issue-label: no-issue-activity + stale-pr-label: no-pr-activity + exempt-issue-labels: enhancement,question,vulnerability,pinned + exempt-pr-labels: dependencies,pinned diff --git a/.gitignore b/.gitignore index b0f2192..722b5d5 100644 --- a/.gitignore +++ b/.gitignore @@ -1,2 +1,12 @@ -__pycache__ -.venv \ No newline at end of file +__pycache__/ +*.py[cod] +.venv/ +.venv-*/ +.pytest_cache/ +.ruff_cache/ +.coverage +hive.zip + +# script/develop's Home Assistant instance +config/* +!config/configuration.yaml diff --git a/.vscode/settings.json b/.vscode/settings.json index de288e1..5bf97ab 100644 --- a/.vscode/settings.json +++ b/.vscode/settings.json @@ -1,3 +1,4 @@ { - "python.formatting.provider": "black" + "python.formatting.provider": "black", + "python.defaultInterpreterPath": "/Users/kholejones/Git/Home-Automation/Hive-Custom-Component/.venv/bin/python" } \ No newline at end of file diff --git a/CLAUDE.md b/CLAUDE.md new file mode 100644 index 0000000..195765e --- /dev/null +++ b/CLAUDE.md @@ -0,0 +1,65 @@ +# Hive Custom Component + +A HACS custom component that replaces Home Assistant core's `hive` integration +(same `domain`). Procedures live in [MAINTAINING.md](MAINTAINING.md), setup in +[CONTRIBUTING.md](CONTRIBUTING.md), and step-by-step skills in `.claude/skills/`. + +## Why this repo exists + +Two principles decide most questions here. Apply them to code, CI, releases and +the skills. + +### 1. Extend core, reuse it wherever possible + +The component adds capability on top of core's hive integration, such as the extra +attribute sensors in `sensor.py`. It is not a fork. + +- Re-export core's platforms (`binary_sensor.py`, `climate.py`, `light.py`, + `switch.py`, `water_heater.py`, `entity.py`) instead of copying them. Only write + local code for something core doesn't do, and keep it as small as possible. +- When core changes, adapt to it. Replacing a re-export with a local module is a + last resort, and the user should know. +- A fix or feature that would help everyone belongs upstream in core or + `pyhive-integration` as well. This repo can ship it first. + +### 2. The opt-in fast channel + +Everyone on core's integration gets the official, slower release train. Installing +this component is an opt-in to get changes sooner, and its HACS betas go further +still, as a testing channel. + +- `manifest.json` may pin a **newer `pyhive-integration` than core does**, including + pre-releases. That divergence is the point of the repo, not a mistake. +- The pin stays exact (`==`). Users get the version we tested. +- **Pre-release `pyhive-integration` only ships in component betas** (pre-releases, + which HACS offers only to users who opt in). A stable component release must pin a + stable `pyhive-integration`. `.github/scripts/check_release.py` enforces this. +- When cutting a component beta, always check PyPI for the newest + `pyhive-integration`, pre-releases included, and bump to it first if it's newer + than the pin (`/bump-pyhive`, then `/release`). +- Never let the fast channel break people. Stable releases need green CI and a + green Compatibility run. + +## What this means for CI + +hassfest compares a custom integration's requirements with every core +integration's pins, including core hive's own. With principle 2 that always gives a +`[REQUIREMENTS]` error for `pyhive-integration`: "pins a package Home Assistant +depends on" when we match core, or "is incompatible with …" when we're ahead. +`.github/scripts/hassfest.py` runs the official hassfest image and turns only those +`pyhive-integration` errors into warnings. Every other error still fails, including +conflicts with Home Assistant's own dependencies or package constraints, because +those can break a user's whole installation. Don't loosen the pin to `>=` to +silence it. + +## Working here + +- `script/setup`, `script/test`, `script/lint` (`--check` in CI). `.venv` must be + Python 3.14 (`script/setup --recreate`). +- Tests mock `apyhiveapi`. When the library changes, also exercise the real code: + from 2.0 the library ships `apyhiveapi/data/data.json`, and + `startSession({"username": "use@file.com"})` runs a session from it offline. +- The tag of a release must equal `version` in `manifest.json`. Beta tags (`bN`) + are always pre-releases, and stable tags never are. +- Don't commit, push, release or merge unless asked. Releases are visible to every + HACS user. diff --git a/CONTRIBUTING.md b/CONTRIBUTING.md new file mode 100644 index 0000000..a8bd5e9 --- /dev/null +++ b/CONTRIBUTING.md @@ -0,0 +1,67 @@ +# Contributing + +Thanks for helping out. This is a Home Assistant custom component for Hive. It is +installed through HACS and builds on the Hive integration in Home Assistant core. + +## Set up + +You need [uv](https://docs.astral.sh/uv/getting-started/installation/) and `jq`. + +```bash +script/setup # .venv with Python 3.14, Home Assistant and the test tools, same as CI +``` + +## Everyday commands + +| Command | What it does | +|---|---| +| `script/test` | Run the tests. Extra arguments go to pytest: `script/test tests/test_climate.py -x` | +| `script/lint` | Fix lint and formatting, and regenerate `translations/en.json` | +| `script/lint --check` | The checks CI runs, without changing anything | +| `script/develop` | Run Home Assistant at http://localhost:8123 with this component loaded | + +`script/develop` keeps its Home Assistant instance in `config/`. The first time, +go through onboarding, then add the Hive integration with a real Hive account. +Restart it after changing code. + +## How the component is put together + +- `sensor.py` and `config_flow.py` are this repo's own code. `__init__.py` is too. +- `binary_sensor.py`, `climate.py`, `light.py`, `switch.py`, `water_heater.py` and + `entity.py` are one-line re-exports of Home Assistant core's hive platforms. To + change their behaviour, either replace the re-export with a real module here, or + change it in core. +- Talking to Hive is done by [`pyhive-integration`](https://pypi.org/project/pyhive-integration/) + (imported as `apyhiveapi`). Its version is pinned in `manifest.json`. +- Text shown in the UI lives in `strings.json`. Run `script/lint` after editing it; + `translations/en.json` is generated from it and a test checks they match. + +## Tests + +The tests start a real Home Assistant in memory and mock the Hive API, so they +need no network or account. There is one file per platform. The fixtures in +`tests/conftest.py` do most of the work: + +- `make_device(...)` builds a device the way pyhive returns it. +- Parametrize `sensor_devices` or `platform_devices` to choose what Hive reports. +- `setup_integration` loads the integration with those devices. + +```python +@pytest.mark.parametrize( + "platform_devices", + [{"switch": [make_device("activeplug", True, ha_type="switch", ha_name="Fan")]}], +) +@pytest.mark.usefixtures("setup_integration") +async def test_plug(hass: HomeAssistant) -> None: + assert hass.states.get("switch.fan").state == "on" +``` + +Add or update a test with every behaviour change. + +## Pull requests + +- Branch from `master` and open the PR against `master`. +- CI must pass: HACS validation, hassfest, lint and tests. +- @KJonline is asked to review automatically. +- Don't bump `version` in `manifest.json` unless the PR is meant to be released + (see [MAINTAINING.md](MAINTAINING.md)). diff --git a/MAINTAINING.md b/MAINTAINING.md new file mode 100644 index 0000000..ad16d25 --- /dev/null +++ b/MAINTAINING.md @@ -0,0 +1,189 @@ +# Maintaining + +This is the runbook for keeping the component released, compatible and healthy. +For development setup, see [CONTRIBUTING.md](CONTRIBUTING.md). Each procedure also +has a Claude Code skill in `.claude/skills/`, listed at the end. + +## Principles + +The full version is in [CLAUDE.md](CLAUDE.md). Everything below follows from these two: + +1. **Extend core, reuse it wherever possible.** This component replaces core's + `hive` integration to add capability, but re-exports core's platforms instead of + copying them. Local code only covers what core doesn't do. +2. **An opt-in fast channel.** Users on core get the official release train. + Installing this component opts in to changes sooner, and its betas are the + testing channel. It may pin a newer `pyhive-integration` than core, including + pre-releases, but **pre-release pyhive only ships in component betas**. Stable + releases pin stable pyhive. + +## What runs automatically + +| When | Workflow | What it does | If it fails | +|---|---|---|---| +| Every PR and every push to `master` | `ci.yml` | HACS validation, hassfest (through `.github/scripts/hassfest.py`, see [Hassfest and the pyhive pin](#hassfest-and-the-pyhive-pin)), lint and tests. A push to master also re-enables scheduled workflows that GitHub turned off. | Fix it in the PR before merging | +| Daily, 04:17 UTC | `compat.yml` | Tests against the newest HA stable and beta, plus an import check against HA `dev` | [Compatibility is red](#compatibility-is-red) | +| Daily, 05:29 UTC | `stale.yml` | Labels issues and PRs inactive for 60 days, then closes issues after 30 more days and PRs after 14 | Add the `pinned` label to keep something open | +| Monday, 06:23 UTC | `pyhive_bump.yml` | Opens a PR if a newer `pyhive-integration` is on PyPI | [Dependency PRs](#dependency-prs) | +| Weekly | Dependabot | PRs for GitHub Actions versions and for `requirements_test.txt` | [Dependency PRs](#dependency-prs) | +| A GitHub release is published | `release.yml` | Checks the tag matches `manifest.json`, and that a stable release doesn't pin pre-release pyhive, then attaches `hive.zip` | [Releasing](#releasing) | +| Manual | `delete_beta.yml` | Deletes old pre-releases and their tags, keeping the newest | Not applicable | + +## Releasing + +Versions are `YEAR.MONTH.PATCH`, for example `2026.10.0`. Betas add `bN`, for example +`2026.10.0b1` (lowercase `b`, no dot before it). HACS installs by tag, so **the tag must +equal `version` in `manifest.json`**. + +Betas are the normal way to get something out quickly: HACS only offers them to users +who opt in. Stable releases go to everyone. + +1. **Check `pyhive-integration`:** + - **Beta:** look up the newest version on PyPI, pre-releases included, and if it's + newer than the pin, bump to it first ([Dependency PRs](#dependency-prs)): + + ```bash + curl -fsS https://pypi.org/pypi/pyhive-integration/json | jq -r '.releases | keys[]' \ + | .venv/bin/python -c 'import sys; from packaging.version import Version; print(max(sys.stdin.read().split(), key=Version))' + ``` + + - **Stable:** the pin must be a stable version. If `master` pins a pyhive beta, wait + for a stable pyhive, or move the pin back to the latest stable first. +2. Open a PR that sets `version` in `custom_components/hive/manifest.json`. Merge it + once CI passes. +3. Check that the last Compatibility run on `master` passed, so you aren't shipping + something current HA versions break. +4. Publish the release from the same version: + + ```bash + # beta: HACS offers it only to users who opt into betas + gh release create 2026.10.0b1 --target master --prerelease --generate-notes + # stable + gh release create 2026.10.0 --target master --latest --generate-notes + ``` + + For a beta, mention the `pyhive-integration` version in the release notes. +5. Watch the **Release** run: `gh run watch $(gh run list -w release.yml -L1 --json databaseId -q '.[0].databaseId')`. + - It checks the tag *after* publishing. If it fails, the release is already + visible to HACS users. Delete it straight away with + `gh release delete --cleanup-tag`, fix the cause, and release again. + - A beta tag must be a pre-release, and a pre-release must have a beta tag. + - A stable release must not pin a pre-release `pyhive-integration`. +6. After a stable release that replaces a run of betas, run **Delete Beta Releases**: + `gh workflow run delete_beta.yml`. + +## Compatibility is red + +Most platforms re-export Home Assistant core's hive code, so a new HA release can +break the component with no change here. Open the failing run +(`gh run list -w compat.yml`) and check which job failed: + +| Failing job | Usually means | Do this | +|---|---|---| +| **Tests (HA stable)** | Users on the latest HA are probably broken now | Fix first, and release a patch | +| **Tests (HA beta)** | The next HA release (first Wednesday of the month) will break it | Fix before that release. Ship a beta if needed | +| **Import smoke test (HA dev)** | Something the component imports was renamed or removed in core | Adapt before it reaches beta | +| **Find Home Assistant … release** step | The test plugin for a brand-new HA release isn't on PyPI yet | Usually fixes itself within a day. Rerun it | +| **HACS and hassfest** | New validation rules | Update the manifest or repo structure as it says. A pyhive `[REQUIREMENTS]` warning is expected; see [Hassfest and the pyhive pin](#hassfest-and-the-pyhive-pin) | + +To reproduce locally, install the HA version that failed into a separate venv: + +```bash +VENV=.venv-ha-beta script/setup +VIRTUAL_ENV=.venv-ha-beta uv pip install "pytest-homeassistant-custom-component==" +VENV=.venv-ha-beta script/test +``` + +Common causes are renamed imports, changed entity base classes, and new +required manifest keys. The Home Assistant developer blog +(https://developers.home-assistant.io/blog) announces these ahead of time. + +## Dependency PRs + +- **`pyhive-integration`** (from `pyhive_bump.yml`, or `/bump-pyhive`): read the release + notes linked in the PR. If CI hasn't run, close and reopen the PR (see the `BOT_TOKEN` + note below). Merge it once green. + - Keep the pin exact (`==`), even when it's ahead of core's. + - The weekly run only proposes stable versions. For a pyhive beta, run the workflow + with its version (`gh workflow run pyhive_bump.yml -f version=`) or use + `/bump-pyhive`. + - A stable pyhive can go out in the next release. A pyhive beta can only go out in a + component beta. + - The tests mock the library. For anything beyond a patch release, also run an + offline session against the library's bundled data (see `/bump-pyhive`). + +### Hassfest and the pyhive pin + +hassfest checks a custom integration's requirements against the pins of every core +integration, including core hive's own `pyhive-integration`. Because this component +replaces core hive, and may pin a different version on purpose, that check always +reports an error, worded either as "pins a package Home Assistant depends on" or as +"is incompatible with …, which Home Assistant depends on". + +`.github/scripts/hassfest.py` runs the official hassfest image and shows only those +`pyhive-integration` errors as warnings. Any other error still fails, including a +conflict with Home Assistant's own dependencies or package constraints, because those +would break a user's installation. If hassfest rewords these messages, update the +`ALLOWED` pattern in the script. Don't switch the pin to `>=` to silence it. + +If `pyhive-integration` ever appears in HA's `homeassistant/package_constraints.txt`, +HA will refuse to install a different version, and the fast channel needs rethinking. +- **`pytest-homeassistant-custom-component`** (Dependabot): this moves the HA version CI + tests against. Update the comment in `requirements_test.txt` to say which HA + version it pins. If HA has raised its minimum Python version, see below. +- **`ruff`** (Dependabot): if lint fails, run `script/lint` on the branch and push. +- **GitHub Actions** (Dependabot, grouped): merge once CI passes. + +### When Home Assistant needs a newer Python + +Update every one of these together: + +- `python-version` in `.github/workflows/ci.yml` and `compat.yml` (3 places) +- `PYTHON_VERSION` in `script/_common.sh` +- `target-version` in `pyproject.toml` + +Then run `script/setup --recreate`. + +### When dropping support for old Home Assistant versions + +Raise `homeassistant` in `hacs.json`. It stops HACS offering new releases to +users on older HA versions. + +## Repo settings (one-time; check they're still on) + +- **Branch protection on `master`:** + - Require the checks *HACS validation*, *Hassfest*, *Lint* and *Tests*. + - Turn on *Require review from Code Owners*. +- **Secret `BOT_TOKEN`:** a fine-grained PAT with Contents and Pull requests write + access on this repo. Without it, PRs from `pyhive_bump.yml` don't trigger CI. +- **Pyhive repo:** add a `HIVE_COMPONENT_DISPATCH_TOKEN` secret and a publish step + that sends `repository_dispatch`. The snippet is in the header of `pyhive_bump.yml`. + It triggers a bump PR as soon as Pyhive releases. +- **Scheduled workflows enabled:** + - Check with `gh workflow list --all`. + - CI switches them back on after the next push to master, but if the repo goes + quiet for 60 days they stop again. + +## Known issues in the code + +- `sensor.py` has update branches for `CurrentTemperature`, `Heating_Boost` and + `Hotwater_Boost` that never run, because no sensor description matches those + types. `get_current_temp_sa()` also calls `heating.minmaxTemperature`, + `currentTemperature` and `targetTemperature`. In pyhive 1.x only the first of + those exists, so pointing it at `Current_Temperature` would crash there. 2.x adds + the other two as aliases. Either delete this code or fix it along with the pyhive + method names. +- `async_setup_hive_entry` raises `UnknownHiveError` from the user step. That path + is unreachable, because the step checks for `AuthenticationResult` first. + +## Claude Code skills + +Run these in Claude Code from the repo root. Each one follows the matching +section above. + +| Skill | Use it to | +|---|---| +| `/release` | Cut a beta or stable release, from the pyhive check and version bump through to checking the Release run | +| `/triage-compat` | Find out why Compatibility is red, reproduce it locally and fix it | +| `/bump-pyhive` | Move to a new `pyhive-integration` (stable or beta), and check whether its changes affect this component | +| `/repo-health` | Check workflows, recent runs, open bot PRs, branch protection and secrets in one report | diff --git a/README.md b/README.md index 572d4f2..c8891ba 100644 --- a/README.md +++ b/README.md @@ -1,7 +1,8 @@ # Hive Custom Component -![Pylint](https://github.com/Pyhive/HA-Hive-Custom-Component/workflows/Pylint/badge.svg) -![GitHub Release](https://img.shields.io/github/v/release/Pyhive/HA-Hive-Custom-Component?display_name=tag&logo=Github) +[![CI](https://github.com/Pyhass/Hive-Custom-Component/actions/workflows/ci.yml/badge.svg)](https://github.com/Pyhass/Hive-Custom-Component/actions/workflows/ci.yml) +[![Compatibility](https://github.com/Pyhass/Hive-Custom-Component/actions/workflows/compat.yml/badge.svg)](https://github.com/Pyhass/Hive-Custom-Component/actions/workflows/compat.yml) +![GitHub Release](https://img.shields.io/github/v/release/Pyhass/Hive-Custom-Component?display_name=tag&logo=Github) @@ -20,6 +21,17 @@ sensors e.g `Living Room Lamp Battery Level` * Current State - Heating/Hotwater only * Boost State - Heating/Hotwater only +## How this relates to the built-in Hive integration + +This component replaces Home Assistant's built-in Hive integration. It reuses the +built-in code wherever it can and adds the extras above on top. + +Think of it as an opt-in fast channel. Fixes and new versions of the Hive library +([`pyhive-integration`](https://pypi.org/project/pyhive-integration/)) usually reach +this component before they reach Home Assistant itself. If you want to help test the +newest changes, turn on beta releases for this repository in HACS. Betas may use +pre-release versions of the library. Stable releases only use stable ones. + For details on what the Home Assistant Hive component supports, please see below: [**>> Hive Component Documentation <<**](https://www.home-assistant.io/integrations/hive/) @@ -27,7 +39,7 @@ For details on what the Home Assistant Hive component supports, please see below Issues and trouble reports should be reported in the issues tab: -[**>> Report issues here <<**](https://github.com/Pyhive/HA-Hive-Custom-Component/issues) +[**>> Report issues here <<**](https://github.com/Pyhass/Hive-Custom-Component/issues) ## Install @@ -39,11 +51,13 @@ The recommended way to is to install via [HACS](https://hacs.xyz/). Once HACS has been installed and setup. You just need to navigate to the HACS panel and choose integrations. This will show and option to add an integration click it and search for Hive in the presented popup. +[![Open your Home Assistant instance and open a repository inside the Home Assistant Community Store.](https://my.home-assistant.io/badges/hacs_repository.svg)](https://my.home-assistant.io/redirect/hacs_repository/?owner=Pyhass&repository=Hive-Custom-Component) + Once installation is complete please follow the [setup section](#setup) to set the Hive integration up. -### Manally +### Manually -To install the Hive integration manually you need to download the [latest version](https://github.com/Pyhive/HA-Hive-Custom-Component/releases/latest). +To install the Hive integration manually you need to download the [latest version](https://github.com/Pyhass/Hive-Custom-Component/releases/latest). Once downloaded you will need to copy the Hive folder into the custom_components folder within your home assistant configuration, if this does not exist then the folder will need creating. Once installation is complete please follow the [setup section](#setup) to set the Hive integration up. @@ -79,8 +93,33 @@ Hacs will auto notify you within the HACS panel that there is a pending update. ### Manual Update -To update to the next version download the [latest version](https://github.com/Pyhive/HA-Hive-Custom-Component/releases/latest) again +To update to the next version download the [latest version](https://github.com/Pyhass/Hive-Custom-Component/releases/latest) again and replace the current hive folder with the newly downloaded one. :warning: **Setting up this custom version will overwrite the default integration.** + +## Development + +Tests use [pytest-homeassistant-custom-component](https://github.com/MatthewFlamm/pytest-homeassistant-custom-component), +which pins the Home Assistant version they run against. Python 3.14 is required. + +```bash +uv venv -p 3.14 && source .venv/bin/activate +uv pip install -r requirements_test.txt $(jq -r '.requirements[]' custom_components/hive/manifest.json) + +python -m pytest # tests +ruff check . && ruff format --check # lint +python script/gen_translations.py # regenerate translations/en.json after editing strings.json +``` + +### CI + +| Workflow | When | What | +| --- | --- | --- | +| `ci.yml` | PRs and pushes to master | HACS validation, hassfest, ruff, tests | +| `compat.yml` | Nightly | Tests against the latest HA stable and beta, import check against HA dev | +| `release.yml` | Release published | Checks the tag matches `manifest.json`, attaches `hive.zip` | +| `pyhive_bump.yml` | Weekly, manual, or dispatched from Pyhive | Opens a PR bumping `pyhive-integration` | +| `stale.yml` | Daily | Marks and closes inactive issues and PRs | +| `delete_beta.yml` | Manual | Deletes old beta releases | diff --git a/SECURITY.md b/SECURITY.md index 902fb00..bd06b0a 100644 --- a/SECURITY.md +++ b/SECURITY.md @@ -2,15 +2,15 @@ ## Supported Versions -We support the below versions of the Hive Custom Component. - -| Version | Supported | -| ------- | ------------------ | -| > 2025.1.x | :white_check_mark: | | -| < 2025 | :x: | +Only the latest release of the Hive Custom Component receives security fixes. +Update through HACS or download the [latest release](https://github.com/Pyhass/Hive-Custom-Component/releases/latest). ## Reporting a Vulnerability -To report a vulnerability, please raise a bug with a label of vulnerability. +Please **don't** open a public issue for security problems. + +Report it privately through GitHub instead: +[**>> Report a vulnerability <<**](https://github.com/Pyhass/Hive-Custom-Component/security/advisories/new) -[**>> Report vulnerability here <<**](https://github.com/Pyhive/HA-Hive-Custom-Component/issues) +Include what you found, how to reproduce it, and which version you tested. Please +remove any Hive account details, tokens or logs containing personal information. diff --git a/config/configuration.yaml b/config/configuration.yaml new file mode 100644 index 0000000..5256bf2 --- /dev/null +++ b/config/configuration.yaml @@ -0,0 +1,8 @@ +# Local Home Assistant for script/develop. Everything else in config/ is ignored by git. +default_config: + +logger: + default: info + logs: + custom_components.hive: debug + apyhiveapi: debug diff --git a/custom_components/hive/config_flow.py b/custom_components/hive/config_flow.py index 7a89548..26174c2 100755 --- a/custom_components/hive/config_flow.py +++ b/custom_components/hive/config_flow.py @@ -1 +1,296 @@ -from homeassistant.components.hive.config_flow import * \ No newline at end of file +"""Config Flow for Hive.""" + +from __future__ import annotations + +from collections.abc import Mapping +import copy +from typing import Any + +from apyhiveapi import Auth +from apyhiveapi.helper.hive_exceptions import ( + HiveApiError, + HiveInvalid2FACode, + HiveInvalidPassword, + HiveInvalidUsername, +) +import voluptuous as vol + +from homeassistant.config_entries import ( + SOURCE_REAUTH, + ConfigFlow, + ConfigFlowResult, + OptionsFlow, +) +from homeassistant.const import CONF_PASSWORD, CONF_SCAN_INTERVAL, CONF_USERNAME +from homeassistant.core import callback +import logging + +from . import HiveConfigEntry +from .const import ( + CONF_CODE, + CONF_DEVICE_NAME, + CONF_DISABLE_2FA_DEBUG, + CONFIG_ENTRY_VERSION, + DOMAIN, +) + +_LOGGER = logging.getLogger(__name__) + + +def _sanitize_payload(payload: dict[str, Any]) -> dict[str, Any]: + """Return a copy of payload with sensitive values masked for logs.""" + + def _mask(value: Any) -> Any: + if not isinstance(value, str): + return value + if len(value) <= 8: + return "***" + return f"{value[:4]}...{value[-4:]}" + + def _walk(node: Any) -> Any: + if isinstance(node, dict): + result: dict[str, Any] = {} + for key, value in node.items(): + key_lower = key.lower() + if any(part in key_lower for part in ("password", "token", "secret", "code", "session")): + result[key] = _mask(value) + else: + result[key] = _walk(value) + return result + if isinstance(node, list): + return [_walk(item) for item in node] + return node + + return _walk(copy.deepcopy(payload)) + + +class HiveFlowHandler(ConfigFlow, domain=DOMAIN): + """Handle a Hive config flow.""" + + VERSION = CONFIG_ENTRY_VERSION + hive_auth: Auth + + def __init__(self) -> None: + """Initialize the config flow.""" + self.data: dict[str, Any] = {} + self.tokens: dict[str, str] = {} + self.device_registration: bool = False + self.device_name = "Home Assistant" + + async def async_step_user( + self, user_input: dict[str, Any] | None = None + ) -> ConfigFlowResult: + """Prompt user input. Create or edit entry.""" + errors: dict[str, str] = {} + if user_input is not None: + self.data.update( + { + CONF_USERNAME: user_input[CONF_USERNAME], + CONF_PASSWORD: user_input[CONF_PASSWORD], + CONF_DISABLE_2FA_DEBUG: bool( + user_input.get(CONF_DISABLE_2FA_DEBUG, False) + ), + } + ) + self.hive_auth = Auth( + username=self.data[CONF_USERNAME], password=self.data[CONF_PASSWORD] + ) + + await self.async_set_unique_id(self.data[CONF_USERNAME]) + if self.context["source"] != SOURCE_REAUTH: + self._abort_if_unique_id_configured() + + try: + self.tokens = await self.hive_auth.login() + _LOGGER.debug( + "Hive login response (sanitized): %s", + _sanitize_payload(self.tokens), + ) + except HiveInvalidUsername: + errors["base"] = "invalid_username" + except HiveInvalidPassword: + errors["base"] = "invalid_password" + except HiveApiError: + errors["base"] = "no_internet_available" + + if self.tokens.get("ChallengeName") == "SMS_MFA": + if self.data.get(CONF_DISABLE_2FA_DEBUG): + _LOGGER.warning( + "Hive returned SMS_MFA and disable_2fa_debug is enabled. " + "Skipping 2FA submission for debug. Challenge payload: %s", + _sanitize_payload(self.tokens), + ) + errors["base"] = "twofa_bypassed_debug" + else: + return await self.async_step_2fa() + + if not errors and "AuthenticationResult" in self.tokens: + auth_result = self.tokens.get("AuthenticationResult", {}) + new_device = auth_result.get("NewDeviceMetadata") or {} + access_token = auth_result.get("AccessToken") + if new_device.get("DeviceGroupKey") and new_device.get("DeviceKey") and access_token: + # If Hive returned fresh device metadata directly from login, register it now + # so fallback device auth works when refresh tokens expire. + self.hive_auth.access_token = access_token + self.hive_auth.device_group_key = new_device["DeviceGroupKey"] + self.hive_auth.device_key = new_device["DeviceKey"] + try: + await self.hive_auth.device_registration(self.device_name) + self.data["device_data"] = await self.hive_auth.get_device_data() + _LOGGER.debug("Stored Hive device_data from login NewDeviceMetadata.") + except HiveApiError: + _LOGGER.warning("Hive device registration failed after login; continuing without device_data.") + + try: + return await self.async_setup_hive_entry() + except UnknownHiveError: + errors["base"] = "unknown" + + schema = vol.Schema( + { + vol.Required(CONF_USERNAME): str, + vol.Required(CONF_PASSWORD): str, + vol.Optional(CONF_DISABLE_2FA_DEBUG, default=False): bool, + } + ) + return self.async_show_form(step_id="user", data_schema=schema, errors=errors) + + async def async_step_2fa( + self, user_input: dict[str, Any] | None = None + ) -> ConfigFlowResult: + """Handle 2fa step.""" + errors = {} + + if user_input and user_input["2fa"] == "0000": + _LOGGER.debug("2FA resend requested (code 0000).") + self.tokens = await self.hive_auth.login() + _LOGGER.debug( + "Hive login response after 2FA resend request (sanitized): %s", + _sanitize_payload(self.tokens), + ) + elif user_input: + try: + self.tokens = await self.hive_auth.sms_2fa( + user_input["2fa"], self.tokens + ) + _LOGGER.debug( + "Hive 2FA response (sanitized): %s", + _sanitize_payload(self.tokens), + ) + except HiveInvalid2FACode: + errors["base"] = "invalid_code" + except HiveApiError: + errors["base"] = "no_internet_available" + + if not errors: + _LOGGER.debug("2FA successful") + if self.source == SOURCE_REAUTH: + device_registered = await self.hive_auth.is_device_registered() + if device_registered: + return await self.async_setup_hive_entry() + + self.device_registration = True + return await self.async_step_configuration() + + schema = vol.Schema({vol.Required(CONF_CODE): str}) + return self.async_show_form(step_id="2fa", data_schema=schema, errors=errors) + + async def async_step_configuration( + self, user_input: dict[str, Any] | None = None + ) -> ConfigFlowResult: + """Handle hive configuration step.""" + errors = {} + + if user_input: + if self.device_registration: + self.device_name = user_input["device_name"] + await self.hive_auth.device_registration(user_input["device_name"]) + self.data["device_data"] = await self.hive_auth.get_device_data() + + try: + return await self.async_setup_hive_entry() + except UnknownHiveError: + errors["base"] = "unknown" + + schema = vol.Schema( + {vol.Optional(CONF_DEVICE_NAME, default=self.device_name): str} + ) + return self.async_show_form( + step_id="configuration", data_schema=schema, errors=errors + ) + + async def async_setup_hive_entry(self) -> ConfigFlowResult: + """Finish setup and create the config entry.""" + + if "AuthenticationResult" not in self.tokens: + raise UnknownHiveError + + self.data["tokens"] = self.tokens + if self.source == SOURCE_REAUTH: + return self.async_update_reload_and_abort( + self._get_reauth_entry(), + title=self.data["username"], + data=self.data, + reason="reauth_successful", + ) + return self.async_create_entry(title=self.data["username"], data=self.data) + + async def async_step_reauth( + self, entry_data: Mapping[str, Any] + ) -> ConfigFlowResult: + """Re Authenticate a user.""" + data = { + CONF_USERNAME: entry_data[CONF_USERNAME], + CONF_PASSWORD: entry_data[CONF_PASSWORD], + } + return await self.async_step_user(data) + + @staticmethod + @callback + def async_get_options_flow( + config_entry: HiveConfigEntry, + ) -> HiveOptionsFlowHandler: + """Hive options callback.""" + return HiveOptionsFlowHandler(config_entry) + + +class HiveOptionsFlowHandler(OptionsFlow): + """Config flow options for Hive.""" + + config_entry: HiveConfigEntry + + def __init__(self, config_entry: HiveConfigEntry) -> None: + """Initialize Hive options flow.""" + self.hive = None + self.interval = config_entry.options.get(CONF_SCAN_INTERVAL, 120) + + async def async_step_init( + self, user_input: dict[str, Any] | None = None + ) -> ConfigFlowResult: + """Manage the options.""" + return await self.async_step_user() + + async def async_step_user( + self, user_input: dict[str, Any] | None = None + ) -> ConfigFlowResult: + """Handle a flow initialized by the user.""" + self.hive = self.config_entry.runtime_data + errors: dict[str, str] = {} + if user_input is not None: + new_interval = user_input.get(CONF_SCAN_INTERVAL) + assert self.hive + await self.hive.updateInterval(new_interval) + return self.async_create_entry(title="", data=user_input) + + schema = vol.Schema( + { + vol.Optional(CONF_SCAN_INTERVAL, default=self.interval): vol.All( + vol.Coerce(int), vol.Range(min=30) + ) + } + ) + return self.async_show_form(step_id="user", data_schema=schema, errors=errors) + + +class UnknownHiveError(Exception): + """Catch unknown hive error.""" diff --git a/custom_components/hive/const.py b/custom_components/hive/const.py index 8271495..0caf965 100755 --- a/custom_components/hive/const.py +++ b/custom_components/hive/const.py @@ -6,6 +6,7 @@ ATTR_ONOFF = "on_off" CONF_CODE = "2fa" CONF_DEVICE_NAME = "device_name" +CONF_DISABLE_2FA_DEBUG = "disable_2fa_debug" CONFIG_ENTRY_VERSION = 1 DEFAULT_NAME = "Hive" DOMAIN = "hive" diff --git a/custom_components/hive/manifest.json b/custom_components/hive/manifest.json index 72f7d31..ac3c013 100755 --- a/custom_components/hive/manifest.json +++ b/custom_components/hive/manifest.json @@ -1,15 +1,16 @@ { "domain": "hive", "name": "Hive", + "codeowners": ["@KJonline"], "config_flow": true, - "documentation": "https://www.home-assistant.io/integrations/hive", - "issue_tracker": "https://github.com/Pyhass/Hive-Custom-Component/issues", - "version": "2025.11.0", + "documentation": "https://github.com/Pyhass/Hive-Custom-Component", "homekit": { "models": ["HHKBridge*"] }, - "requirements": ["pyhive-integration==1.0.6"], - "codeowners": ["@KJonline"], + "integration_type": "hub", "iot_class": "cloud_polling", - "loggers": ["apyhiveapi"] + "issue_tracker": "https://github.com/Pyhass/Hive-Custom-Component/issues", + "loggers": ["apyhiveapi"], + "requirements": ["pyhive-integration==1.0.10"], + "version": "2026.10.1b2" } diff --git a/custom_components/hive/sensor.py b/custom_components/hive/sensor.py index be34455..0c3030c 100755 --- a/custom_components/hive/sensor.py +++ b/custom_components/hive/sensor.py @@ -1,6 +1,9 @@ """Support for the Hive sensors.""" +from collections.abc import Callable +from dataclasses import dataclass from datetime import timedelta +from typing import Any from homeassistant.components.sensor import ( SensorDeviceClass, @@ -16,70 +19,77 @@ ) from homeassistant.core import HomeAssistant from homeassistant.helpers.entity_platform import AddConfigEntryEntitiesCallback +from homeassistant.helpers.typing import StateType from . import HiveConfigEntry from .entity import HiveEntity +from apyhiveapi import Hive PARALLEL_UPDATES = 0 SCAN_INTERVAL = timedelta(seconds=15) -SENSOR_TYPES: tuple[SensorEntityDescription, ...] = ( - SensorEntityDescription( + + +@dataclass(frozen=True) +class HiveSensorEntityDescription(SensorEntityDescription): + """Describes Hive sensor entity.""" + + fn: Callable[[StateType], StateType] = lambda x: x + + +SENSOR_TYPES: tuple[HiveSensorEntityDescription, ...] = ( + HiveSensorEntityDescription( key="Battery", native_unit_of_measurement=PERCENTAGE, device_class=SensorDeviceClass.BATTERY, entity_category=EntityCategory.DIAGNOSTIC, ), - SensorEntityDescription( + HiveSensorEntityDescription( key="Power", native_unit_of_measurement=UnitOfPower.WATT, state_class=SensorStateClass.MEASUREMENT, device_class=SensorDeviceClass.POWER, entity_category=EntityCategory.DIAGNOSTIC, ), - SensorEntityDescription( + HiveSensorEntityDescription( + key="Current_Temperature", + native_unit_of_measurement=UnitOfTemperature.CELSIUS, + state_class=SensorStateClass.MEASUREMENT, + device_class=SensorDeviceClass.TEMPERATURE, + entity_category=EntityCategory.DIAGNOSTIC, + ), + HiveSensorEntityDescription( key="Heating_Current_Temperature", device_class=SensorDeviceClass.TEMPERATURE, state_class=SensorStateClass.MEASUREMENT, native_unit_of_measurement=UnitOfTemperature.CELSIUS, - icon="mdi:thermometer", ), - SensorEntityDescription( + HiveSensorEntityDescription( key="Heating_Target_Temperature", device_class=SensorDeviceClass.TEMPERATURE, state_class=SensorStateClass.MEASUREMENT, native_unit_of_measurement=UnitOfTemperature.CELSIUS, icon="mdi:thermometer", ), - SensorEntityDescription( - key="Heating_State", - icon="mdi:radiator", - ), - SensorEntityDescription( + HiveSensorEntityDescription( key="Heating_Mode", - icon="mdi:radiator", - ), - SensorEntityDescription( - key="Heating_Boost", - icon="mdi:radiator", - ), - SensorEntityDescription( - key="Hotwater_State", - icon="mdi:water-pump", + device_class=SensorDeviceClass.ENUM, + options=["schedule", "manual", "off"], + translation_key="heating", + fn=lambda x: x.lower() if isinstance(x, str) else None, ), - SensorEntityDescription( + HiveSensorEntityDescription( key="Hotwater_Mode", - icon="mdi:water-pump", + device_class=SensorDeviceClass.ENUM, + options=["schedule", "on", "off"], + translation_key="hot_water", + fn=lambda x: x.lower() if isinstance(x, str) else None, ), - SensorEntityDescription( - key="Hotwater_Boost", - icon="mdi:water-pump", - ), - SensorEntityDescription( + HiveSensorEntityDescription( key="Mode", icon="mdi:eye", ), - SensorEntityDescription(key="Availability", icon="mdi:check-circle"), + HiveSensorEntityDescription(key="Availability", icon="mdi:check-circle"), ) @@ -95,7 +105,7 @@ async def async_setup_entry( return async_add_entities( ( - HiveSensorEntity(hive, dev, description) + HiveSensorEntity(hass, entry, hive, dev, description) for dev in devices for description in SENSOR_TYPES if dev["hiveType"] == description.key @@ -107,9 +117,18 @@ async def async_setup_entry( class HiveSensorEntity(HiveEntity, SensorEntity): """Hive Sensor Entity.""" - def __init__(self, hive, hive_device, entity_description): + entity_description: HiveSensorEntityDescription + + def __init__( + self, + hass: HomeAssistant, + entry: HiveConfigEntry, + hive: Hive, + hive_device: dict[str, Any], + entity_description: HiveSensorEntityDescription, + ) -> None: """Initialise hive sensor.""" - super().__init__(hive, hive_device) + super().__init__(hass, entry, hive, hive_device) self.entity_description = entity_description async def async_update(self): @@ -119,9 +138,7 @@ async def async_update(self): if self.device["hiveType"] == "CurrentTemperature": self._attr_extra_state_attributes = await self.get_current_temp_sa() - elif self.device["hiveType"] == "Heating_State": - self._attr_extra_state_attributes = await self.get_heating_state_sa() - elif self.device["hiveType"] == "Heating_Mode": + elif self.device["hiveType"] in ("Heating_State", "Heating_Mode"): self._attr_extra_state_attributes = await self.get_heating_state_sa() elif self.device["hiveType"] == "Heating_Boost": s_a = {} @@ -129,9 +146,7 @@ async def async_update(self): minsend = await self.hive.heating.getBoostTime(self.device) s_a.update({"Boost ends in": (str(minsend) + " minutes")}) self._attr_extra_state_attributes = s_a - elif self.device["hiveType"] == "Hotwater_State": - self._attr_extra_state_attributes = await self.get_hotwater_state_sa() - elif self.device["hiveType"] == "Hotwater_Mode": + elif self.device["hiveType"] in ("Hotwater_State", "Hotwater_Mode"): self._attr_extra_state_attributes = await self.get_hotwater_state_sa() elif self.device["hiveType"] == "Hotwater_Boost": s_a = {} @@ -145,8 +160,9 @@ async def async_update(self): else: self._attr_available = True - if self._attr_available: - self._attr_native_value = self.device["status"]["state"] + self._attr_native_value = self.entity_description.fn( + self.device.get("status", {}).get("state") + ) async def get_current_temp_sa(self): """Get current heating temperature state attributes.""" diff --git a/custom_components/hive/strings.json b/custom_components/hive/strings.json index 874b86a..2bca947 100755 --- a/custom_components/hive/strings.json +++ b/custom_components/hive/strings.json @@ -7,6 +7,7 @@ "data": { "username": "[%key:common::config_flow::data::username%]", "password": "[%key:common::config_flow::data::password%]", + "disable_2fa_debug": "Disable 2FA (debug)", "scan_interval": "Scan interval (seconds)" } }, @@ -37,6 +38,7 @@ "invalid_username": "Failed to sign in to Hive. Your email address is not recognized.", "invalid_password": "Failed to sign in to Hive. Incorrect password, please try again.", "invalid_code": "Failed to sign in to Hive. Your two-factor authentication code was incorrect.", + "twofa_bypassed_debug": "2FA step was intentionally bypassed for debug. Check Home Assistant logs for Hive auth responses.", "no_internet_available": "An Internet connection is required to connect to Hive.", "unknown": "[%key:common::config_flow::error::unknown%]" }, @@ -119,4 +121,4 @@ } } } -} \ No newline at end of file +} diff --git a/custom_components/hive/translations/en.json b/custom_components/hive/translations/en.json index 5f3ae19..4ff73ae 100755 --- a/custom_components/hive/translations/en.json +++ b/custom_components/hive/translations/en.json @@ -9,6 +9,7 @@ "invalid_code": "Failed to sign into Hive. Your two-factor authentication code was incorrect.", "invalid_password": "Failed to sign into Hive. Incorrect password please try again.", "invalid_username": "Failed to sign into Hive. Your email address is not recognised.", + "twofa_bypassed_debug": "2FA step was intentionally bypassed for debug. Check Home Assistant logs for Hive auth responses.", "no_internet_available": "An internet connection is required to connect to Hive.", "unknown": "Unexpected error" }, @@ -38,6 +39,7 @@ "user": { "data": { "password": "Password", + "disable_2fa_debug": "Disable 2FA (debug)", "scan_interval": "Scan Interval (seconds)", "username": "Username" }, @@ -57,4 +59,4 @@ } } } -} \ No newline at end of file +} diff --git a/hacs.json b/hacs.json index b5fe413..6752d1f 100644 --- a/hacs.json +++ b/hacs.json @@ -1,5 +1,6 @@ { "name": "Hive Custom Component", "render_readme": true, - "content_in_root": false + "content_in_root": false, + "homeassistant": "2025.6.0" } diff --git a/pyproject.toml b/pyproject.toml new file mode 100644 index 0000000..16f9fb4 --- /dev/null +++ b/pyproject.toml @@ -0,0 +1,38 @@ +# Tooling config only - this repo is a Home Assistant custom component, not a package. + +[tool.ruff] +target-version = "py314" +extend-exclude = [".vscode"] + +[tool.ruff.lint] +select = [ + "B", # flake8-bugbear + "E", # pycodestyle errors + "F", # pyflakes + "I", # isort + "UP", # pyupgrade + "W", # pycodestyle warnings +] +ignore = [ + "E501", # line length is handled by the formatter +] + +[tool.ruff.lint.per-file-ignores] +# These platforms re-export Home Assistant core's hive platforms on purpose. +"custom_components/hive/{binary_sensor,climate,entity,light,switch,water_heater}.py" = ["F403"] + +[tool.ruff.lint.isort] +force-sort-within-sections = true +combine-as-imports = true +known-first-party = ["custom_components.hive"] +known-third-party = ["apyhiveapi"] +section-order = ["future", "standard-library", "third-party", "homeassistant", "first-party", "local-folder"] +split-on-trailing-comma = false + +[tool.ruff.lint.isort.sections] +homeassistant = ["homeassistant"] + +[tool.pytest.ini_options] +testpaths = ["tests"] +asyncio_mode = "auto" +asyncio_default_fixture_loop_scope = "function" diff --git a/requirements_test.txt b/requirements_test.txt new file mode 100644 index 0000000..f8a0b8e --- /dev/null +++ b/requirements_test.txt @@ -0,0 +1,5 @@ +# Pins the Home Assistant version the tests run against (0.13.367 -> homeassistant 2026.9.4). +# Bumped by Dependabot; the nightly compat workflow also tests the latest stable and beta. + +ruff==0.16.10 +pytest-homeassistant-custom-component==0.13.370 diff --git a/script/_common.sh b/script/_common.sh new file mode 100644 index 0000000..9d86975 --- /dev/null +++ b/script/_common.sh @@ -0,0 +1,14 @@ +# Shared by the scripts in this folder. Source it, don't run it. +set -euo pipefail + +ROOT="$(cd "$(dirname "${BASH_SOURCE[0]}")/.." && pwd)" +VENV="${VENV:-$ROOT/.venv}" +PYTHON_VERSION="3.14" +cd "$ROOT" + +need_venv() { + if [ ! -x "$VENV/bin/python" ]; then + echo "No virtualenv at $VENV. Run script/setup first." >&2 + exit 1 + fi +} diff --git a/script/develop b/script/develop new file mode 100755 index 0000000..a894c44 --- /dev/null +++ b/script/develop @@ -0,0 +1,15 @@ +#!/usr/bin/env bash +# Run a local Home Assistant with this component loaded, at http://localhost:8123. +# +# config/ holds the HA instance (onboarding, your Hive login, the database). Only +# config/configuration.yaml is committed. Stop with Ctrl+C; code changes need a restart. +source "$(dirname "$0")/_common.sh" +need_venv + +mkdir -p config +# HA loads custom components from /custom_components. +if [ ! -e config/custom_components ]; then + ln -s ../custom_components config/custom_components +fi + +exec "$VENV/bin/hass" --config config --debug "$@" diff --git a/script/gen_translations.py b/script/gen_translations.py new file mode 100644 index 0000000..6b4a5d3 --- /dev/null +++ b/script/gen_translations.py @@ -0,0 +1,89 @@ +"""Generate translations/en.json from strings.json. + +strings.json uses Home Assistant's [%key:...%] references, which only core resolves. +Custom components load translations/en.json as-is, so the references have to be +expanded here. Needs homeassistant installed (it provides the common:: strings). + + python script/gen_translations.py # rewrite translations/en.json + python script/gen_translations.py --check # exit 1 if en.json is out of date +""" + +import argparse +import json +from pathlib import Path +import re +import sys +from typing import Any + +import homeassistant + +COMPONENT = Path(__file__).resolve().parent.parent / "custom_components" / "hive" +STRINGS = COMPONENT / "strings.json" +EN_JSON = COMPONENT / "translations" / "en.json" +REFERENCE = re.compile(r"\[%key:([a-z0-9_:]+)%\]") + + +def _lookup(tree: dict[str, Any], path: list[str]) -> str: + node: Any = tree + for part in path: + node = node[part] + if not isinstance(node, str): + raise TypeError(f"{'::'.join(path)} is not a string") + return node + + +def generate() -> dict[str, Any]: + """Return strings.json with every [%key:...%] reference expanded.""" + strings = json.loads(STRINGS.read_text(encoding="utf-8")) + core = json.loads( + (Path(homeassistant.__file__).parent / "strings.json").read_text( + encoding="utf-8" + ) + ) + trees = {"common": core["common"], "component::hive": strings} + + def resolve(value: str) -> str: + def replace(match: re.Match[str]) -> str: + key = match.group(1) + if key.startswith("component::hive::"): + path = key.removeprefix("component::hive::").split("::") + return resolve(_lookup(strings, path)) + if key.startswith("common::"): + return _lookup(trees["common"], key.split("::")[1:]) + raise KeyError(f"can't resolve reference {key}") + + return REFERENCE.sub(replace, value) + + def walk(node: Any) -> Any: + if isinstance(node, dict): + return {key: walk(value) for key, value in node.items()} + return resolve(node) + + return walk(strings) + + +def render() -> str: + """Return en.json content as it should be on disk.""" + return json.dumps(generate(), indent=2, ensure_ascii=False) + "\n" + + +def main() -> int: + """Write or check translations/en.json.""" + parser = argparse.ArgumentParser(description=__doc__.splitlines()[0]) + parser.add_argument("--check", action="store_true", help="only check, don't write") + args = parser.parse_args() + + expected = render() + if args.check: + if EN_JSON.read_text(encoding="utf-8") != expected: + print(f"{EN_JSON} is out of date, run: python script/gen_translations.py") + return 1 + return 0 + + EN_JSON.write_text(expected, encoding="utf-8") + print(f"Wrote {EN_JSON}") + return 0 + + +if __name__ == "__main__": + sys.exit(main()) diff --git a/script/lint b/script/lint new file mode 100755 index 0000000..01300ab --- /dev/null +++ b/script/lint @@ -0,0 +1,17 @@ +#!/usr/bin/env bash +# Fix what can be fixed, then run the same checks as CI's Lint job. +# script/lint # fix and check +# script/lint --check # check only (what CI does) +source "$(dirname "$0")/_common.sh" +need_venv + +ruff="$VENV/bin/ruff" +if [ "${1:-}" = "--check" ]; then + "$ruff" check . + "$ruff" format --check . + "$VENV/bin/python" script/gen_translations.py --check +else + "$ruff" check --fix . + "$ruff" format . + "$VENV/bin/python" script/gen_translations.py +fi diff --git a/script/setup b/script/setup new file mode 100755 index 0000000..9eaf514 --- /dev/null +++ b/script/setup @@ -0,0 +1,36 @@ +#!/usr/bin/env bash +# Create .venv with the same Python and dependencies CI uses. +# +# script/setup # create or update .venv +# script/setup --recreate # delete .venv first (e.g. it was built with the wrong Python) +source "$(dirname "$0")/_common.sh" + +if ! command -v uv >/dev/null; then + echo "uv is required: https://docs.astral.sh/uv/getting-started/installation/" >&2 + exit 1 +fi + +if [ "${1:-}" = "--recreate" ]; then + rm -rf "$VENV" +fi + +if [ -x "$VENV/bin/python" ]; then + current=$("$VENV/bin/python" -c 'import sys; print(f"{sys.version_info[0]}.{sys.version_info[1]}")') + if [ "$current" != "$PYTHON_VERSION" ]; then + echo "$VENV uses Python $current but Home Assistant needs $PYTHON_VERSION." >&2 + echo "Run: script/setup --recreate" >&2 + exit 1 + fi +else + uv venv --python "$PYTHON_VERSION" "$VENV" +fi + +# Same install as the CI test job: the HA test plugin (which pins homeassistant), +# ruff, and the component's own requirements from manifest.json. +VIRTUAL_ENV="$VENV" uv pip install \ + -r requirements_test.txt \ + $(jq -r '.requirements[]' custom_components/hive/manifest.json) + +echo +"$VENV/bin/python" -c 'from homeassistant.const import __version__; print(f"Ready: Home Assistant {__version__}")' +echo "Next: script/test, script/lint, script/develop" diff --git a/script/test b/script/test new file mode 100755 index 0000000..de928e1 --- /dev/null +++ b/script/test @@ -0,0 +1,6 @@ +#!/usr/bin/env bash +# Run the test suite. Extra arguments go to pytest, e.g. +# script/test tests/test_climate.py -k boost -x +source "$(dirname "$0")/_common.sh" +need_venv +exec "$VENV/bin/python" -m pytest "$@" diff --git a/setup.cfg b/setup.cfg deleted file mode 100644 index 3009b91..0000000 --- a/setup.cfg +++ /dev/null @@ -1,2 +0,0 @@ -[settings] -known_third_party = aiohttp,homeassistant,pyhiveapi,voluptuous diff --git a/tests/__init__.py b/tests/__init__.py new file mode 100644 index 0000000..fefaa1d --- /dev/null +++ b/tests/__init__.py @@ -0,0 +1 @@ +"""Tests for the Hive custom component.""" diff --git a/tests/conftest.py b/tests/conftest.py new file mode 100644 index 0000000..b0b8d9d --- /dev/null +++ b/tests/conftest.py @@ -0,0 +1,168 @@ +"""Fixtures for Hive custom component tests.""" + +from collections.abc import Generator +from typing import Any +from unittest.mock import AsyncMock, MagicMock, patch + +import pytest +from pytest_homeassistant_custom_component.common import MockConfigEntry + +from homeassistant.const import CONF_PASSWORD, CONF_USERNAME +from homeassistant.core import HomeAssistant + +from custom_components.hive.const import DOMAIN + +USERNAME = "user@example.com" +PASSWORD = "test-password" +HUB_ID = "hub-1" +TOKENS = { + "AuthenticationResult": { + "AccessToken": "access-token", + "RefreshToken": "refresh-token", + "IdToken": "id-token", + } +} +DEVICE_DATA = ["device-group-key", "device-key", "device-password"] + + +@pytest.fixture(autouse=True) +def auto_enable_custom_integrations(enable_custom_integrations: None) -> None: + """Load custom_components/hive instead of the core hive integration.""" + + +def make_device( + hive_type: str, + state: Any = None, + *, + ha_type: str = "sensor", + hive_id: str = "trv-1", + name: str = "Lounge TRV", + ha_name: str | None = None, + online: bool = True, + status: dict[str, Any] | None = None, + **extra: Any, +) -> dict[str, Any]: + """Build a device dict shaped like the ones pyhive returns. + + status defaults to {"state": state}; extra keys (e.g. temperatureunit, min_temp) + are added at the top level, the way pyhive's addList adds them. + """ + return { + "hiveID": hive_id, + "hiveName": name, + "hiveType": hive_type, + "haType": ha_type, + "haName": ha_name or f"{name} {hive_type.replace('_', ' ')}", + "device_id": hive_id, + "device_name": name, + "parentDevice": HUB_ID, + "deviceData": { + "model": "TRV001", + "manufacturer": "Hive", + "version": "1.0.0", + "online": online, + }, + "status": {"state": state} if status is None else status, + **extra, + } + + +HUB_DEVICE = { + "device_id": HUB_ID, + "hiveName": "Hive Hub", + "deviceData": {"model": "NANO2", "manufacturer": "Hive", "version": "4.0.0"}, +} + + +@pytest.fixture +def mock_config_entry() -> MockConfigEntry: + """Return a config entry for an account that finished setup.""" + return MockConfigEntry( + domain=DOMAIN, + title=USERNAME, + unique_id=USERNAME, + data={ + CONF_USERNAME: USERNAME, + CONF_PASSWORD: PASSWORD, + "tokens": TOKENS, + "device_data": DEVICE_DATA, + }, + ) + + +@pytest.fixture +def sensor_devices() -> list[dict[str, Any]]: + """Sensor devices returned by the mocked Hive session.""" + return [make_device("Battery", 87)] + + +@pytest.fixture +def platform_devices() -> dict[str, list[dict[str, Any]]]: + """Devices for the other platforms, keyed like pyhive's deviceList.""" + return {} + + +def _echo(device: dict[str, Any]) -> dict[str, Any]: + return device + + +@pytest.fixture +def mock_hive( + sensor_devices: list[dict[str, Any]], + platform_devices: dict[str, list[dict[str, Any]]], +) -> Generator[MagicMock]: + """Patch the Hive API client used by async_setup_entry. + + Every getter hands the device back unchanged, so a test controls entity + state through the device dicts it passes in. + """ + devices = {"parent": [HUB_DEVICE], "sensor": sensor_devices, **platform_devices} + hive = MagicMock() + hive.session.startSession = AsyncMock(return_value=devices) + hive.session.deviceList = devices + hive.session.updateData = AsyncMock() + hive.sensor.getSensor = AsyncMock(side_effect=_echo) + hive.heating.getClimate = AsyncMock(side_effect=_echo) + hive.hotwater.getWaterHeater = AsyncMock(side_effect=_echo) + hive.light.getLight = AsyncMock(side_effect=_echo) + hive.switch.getSwitch = AsyncMock(side_effect=_echo) + hive.updateInterval = AsyncMock() + with patch("custom_components.hive.Hive", return_value=hive): + yield hive + + +@pytest.fixture +def mock_auth() -> Generator[MagicMock]: + """Patch the Hive Auth client used by the config flow.""" + auth = MagicMock() + auth.login = AsyncMock(return_value=TOKENS) + auth.sms_2fa = AsyncMock(return_value=TOKENS) + auth.device_registration = AsyncMock() + auth.get_device_data = AsyncMock(return_value=DEVICE_DATA) + auth.is_device_registered = AsyncMock(return_value=True) + auth.forget_device = AsyncMock() + with ( + patch("custom_components.hive.config_flow.Auth", return_value=auth), + patch("custom_components.hive.Auth", return_value=auth), + ): + yield auth + + +@pytest.fixture +def mock_setup_entry() -> Generator[AsyncMock]: + """Stop config flow tests from setting up the integration.""" + with patch( + "custom_components.hive.async_setup_entry", return_value=True + ) as setup_entry: + yield setup_entry + + +@pytest.fixture +async def setup_integration( + hass: HomeAssistant, mock_hive: MagicMock, mock_config_entry: MockConfigEntry +) -> MockConfigEntry: + """Set up the integration with the mocked Hive client.""" + mock_config_entry.add_to_hass(hass) + assert await hass.config_entries.async_setup(mock_config_entry.entry_id) + await hass.async_block_till_done() + return mock_config_entry diff --git a/tests/test_binary_sensor.py b/tests/test_binary_sensor.py new file mode 100644 index 0000000..759f76e --- /dev/null +++ b/tests/test_binary_sensor.py @@ -0,0 +1,85 @@ +"""Tests for the binary sensors re-exported from Home Assistant core.""" + +from typing import Any + +import pytest +from pytest_homeassistant_custom_component.common import MockConfigEntry + +from homeassistant.const import STATE_OFF, STATE_ON, STATE_UNAVAILABLE +from homeassistant.core import HomeAssistant + +from .conftest import make_device + +CONTACT = make_device( + "contactsensor", + True, + ha_type="binary_sensor", + hive_id="contact-1", + name="Front Door", + ha_name="Front Door", +) +MOTION_OFFLINE = make_device( + "motionsensor", + False, + ha_type="binary_sensor", + hive_id="motion-1", + name="Hallway", + ha_name="Hallway", + online=False, +) +HUB_STATUS_OFFLINE = make_device( + "Connectivity", + False, + ha_type="binary_sensor", + hive_id="hub-1", + name="Hive Hub", + ha_name="Hive Hub Status", + online=False, +) + + +@pytest.fixture +def platform_devices() -> dict[str, list[dict[str, Any]]]: + """Binary sensor devices returned by the mocked Hive session.""" + return {"binary_sensor": [CONTACT, MOTION_OFFLINE, HUB_STATUS_OFFLINE]} + + +@pytest.mark.usefixtures("setup_integration") +async def test_binary_sensors(hass: HomeAssistant) -> None: + """Device class and state come from the Hive device.""" + state = hass.states.get("binary_sensor.front_door") + assert state.state == STATE_ON + assert state.attributes["device_class"] == "opening" + + # Offline devices go unavailable, except the hub's own connectivity sensor. + assert hass.states.get("binary_sensor.hallway").state == STATE_UNAVAILABLE + state = hass.states.get("binary_sensor.hive_hub_status") + assert state.state == STATE_OFF + assert state.attributes["device_class"] == "connectivity" + + +@pytest.mark.parametrize( + "sensor_devices", + [ + [ + make_device("Heating_State", "ON", name="Thermostat"), + make_device("Heating_Boost", "OFF", name="Thermostat"), + make_device("Hotwater_Boost", "ON", name="Hot Water", online=False), + ] + ], +) +async def test_heating_and_hot_water_state_sensors( + hass: HomeAssistant, setup_integration: MockConfigEntry +) -> None: + """Heating and hot water state/boost come from the sensor list as binary sensors. + + They have no description in this component's sensor platform, so they don't + also show up as sensors. + """ + assert hass.states.get("binary_sensor.thermostat_heating_state").state == STATE_ON + assert hass.states.get("binary_sensor.thermostat_heating_boost").state == STATE_OFF + assert ( + hass.states.get("binary_sensor.hot_water_hotwater_boost").state + == STATE_UNAVAILABLE + ) + assert hass.states.async_entity_ids("sensor") == [] diff --git a/tests/test_climate.py b/tests/test_climate.py new file mode 100644 index 0000000..37fecc3 --- /dev/null +++ b/tests/test_climate.py @@ -0,0 +1,180 @@ +"""Tests for the climate entity re-exported from Home Assistant core.""" + +from typing import Any +from unittest.mock import AsyncMock, MagicMock + +import pytest + +from homeassistant.components.climate import ( + ATTR_HVAC_ACTION, + ATTR_HVAC_MODE, + ATTR_PRESET_MODE, + DOMAIN as CLIMATE_DOMAIN, + PRESET_BOOST, + PRESET_NONE, + SERVICE_SET_HVAC_MODE, + SERVICE_SET_PRESET_MODE, + SERVICE_SET_TEMPERATURE, + HVACAction, + HVACMode, +) +from homeassistant.const import ATTR_ENTITY_ID, ATTR_TEMPERATURE, STATE_UNAVAILABLE +from homeassistant.core import HomeAssistant + +from custom_components.hive.const import ( + DOMAIN, + SERVICE_BOOST_HEATING_OFF, + SERVICE_BOOST_HEATING_ON, +) + +from .conftest import make_device + +ENTITY_ID = "climate.heating" + + +def heating( + *, mode: str = "SCHEDULE", boost: str = "OFF", online: bool = True +) -> dict[str, Any]: + """A heating product as pyhive's getClimate returns it.""" + return make_device( + "heating", + ha_type="climate", + hive_id="heating-1", + name="Heating", + ha_name="Heating", + online=online, + temperatureunit="C", + min_temp=5, + max_temp=32, + status={ + "mode": mode, + "action": True, + "current_temperature": 19.2, + "target_temperature": 21, + "boost": boost, + }, + ) + + +@pytest.fixture +def platform_devices() -> dict[str, list[dict[str, Any]]]: + """Climate devices returned by the mocked Hive session.""" + return {"climate": [heating()]} + + +@pytest.fixture +def mock_heating(mock_hive: MagicMock) -> MagicMock: + """Make the heating setters awaitable.""" + for method in ("setMode", "setTargetTemperature", "setBoostOn", "setBoostOff"): + setattr(mock_hive.heating, method, AsyncMock()) + return mock_hive.heating + + +@pytest.mark.usefixtures("setup_integration") +async def test_climate_state(hass: HomeAssistant) -> None: + """Hive heating status maps to HA climate state.""" + state = hass.states.get(ENTITY_ID) + assert state.state == HVACMode.AUTO + assert state.attributes[ATTR_HVAC_ACTION] == HVACAction.HEATING + assert state.attributes["current_temperature"] == 19.2 + assert state.attributes[ATTR_TEMPERATURE] == 21 + assert state.attributes["min_temp"] == 5 + assert state.attributes["max_temp"] == 32 + assert state.attributes[ATTR_PRESET_MODE] == PRESET_NONE + + +@pytest.mark.parametrize( + "platform_devices", [{"climate": [heating(mode="OFF", boost="ON")]}] +) +@pytest.mark.usefixtures("setup_integration") +async def test_climate_boost_shows_as_heat(hass: HomeAssistant) -> None: + """While boosting, the mode reads heat and the preset reads boost.""" + state = hass.states.get(ENTITY_ID) + assert state.state == HVACMode.HEAT + assert state.attributes[ATTR_PRESET_MODE] == PRESET_BOOST + + +@pytest.mark.parametrize("platform_devices", [{"climate": [heating(online=False)]}]) +@pytest.mark.usefixtures("setup_integration") +async def test_climate_offline(hass: HomeAssistant) -> None: + """An offline thermostat is unavailable.""" + assert hass.states.get(ENTITY_ID).state == STATE_UNAVAILABLE + + +@pytest.mark.parametrize( + ("hvac_mode", "hive_mode"), + [(HVACMode.AUTO, "SCHEDULE"), (HVACMode.HEAT, "MANUAL"), (HVACMode.OFF, "OFF")], +) +@pytest.mark.usefixtures("setup_integration") +async def test_set_hvac_mode( + hass: HomeAssistant, mock_heating: MagicMock, hvac_mode: HVACMode, hive_mode: str +) -> None: + """HVAC modes are sent to Hive as its own mode names.""" + await hass.services.async_call( + CLIMATE_DOMAIN, + SERVICE_SET_HVAC_MODE, + {ATTR_ENTITY_ID: ENTITY_ID, ATTR_HVAC_MODE: hvac_mode}, + blocking=True, + ) + + mock_heating.setMode.assert_awaited_once() + assert mock_heating.setMode.await_args.args[1] == hive_mode + + +@pytest.mark.usefixtures("setup_integration") +async def test_set_temperature(hass: HomeAssistant, mock_heating: MagicMock) -> None: + """The target temperature is sent to Hive.""" + await hass.services.async_call( + CLIMATE_DOMAIN, + SERVICE_SET_TEMPERATURE, + {ATTR_ENTITY_ID: ENTITY_ID, ATTR_TEMPERATURE: 22.5}, + blocking=True, + ) + + assert mock_heating.setTargetTemperature.await_args.args[1] == 22.5 + + +@pytest.mark.usefixtures("setup_integration") +async def test_boost_preset_on(hass: HomeAssistant, mock_heating: MagicMock) -> None: + """The boost preset boosts for 30 minutes to half a degree above current.""" + await hass.services.async_call( + CLIMATE_DOMAIN, + SERVICE_SET_PRESET_MODE, + {ATTR_ENTITY_ID: ENTITY_ID, ATTR_PRESET_MODE: PRESET_BOOST}, + blocking=True, + ) + + assert mock_heating.setBoostOn.await_args.args[1:] == (30, 19.5) + + +@pytest.mark.parametrize("platform_devices", [{"climate": [heating(boost="ON")]}]) +@pytest.mark.usefixtures("setup_integration") +async def test_boost_preset_off(hass: HomeAssistant, mock_heating: MagicMock) -> None: + """Choosing no preset while boosting turns boost off.""" + await hass.services.async_call( + CLIMATE_DOMAIN, + SERVICE_SET_PRESET_MODE, + {ATTR_ENTITY_ID: ENTITY_ID, ATTR_PRESET_MODE: PRESET_NONE}, + blocking=True, + ) + + mock_heating.setBoostOff.assert_awaited_once() + + +@pytest.mark.usefixtures("setup_integration") +async def test_boost_heating_services( + hass: HomeAssistant, mock_heating: MagicMock +) -> None: + """hive.boost_heating_on/off call Hive with minutes and temperature.""" + await hass.services.async_call( + DOMAIN, + SERVICE_BOOST_HEATING_ON, + {ATTR_ENTITY_ID: ENTITY_ID, "time_period": "01:30:00", ATTR_TEMPERATURE: 23}, + blocking=True, + ) + assert mock_heating.setBoostOn.await_args.args[1:] == (90, 23.0) + + await hass.services.async_call( + DOMAIN, SERVICE_BOOST_HEATING_OFF, {ATTR_ENTITY_ID: ENTITY_ID}, blocking=True + ) + mock_heating.setBoostOff.assert_awaited_once() diff --git a/tests/test_config_flow.py b/tests/test_config_flow.py new file mode 100644 index 0000000..90cee7f --- /dev/null +++ b/tests/test_config_flow.py @@ -0,0 +1,337 @@ +"""Tests for the Hive config and options flows.""" + +from unittest.mock import AsyncMock, MagicMock + +from apyhiveapi.helper.hive_exceptions import ( + HiveApiError, + HiveInvalid2FACode, + HiveInvalidPassword, + HiveInvalidUsername, +) +import pytest +from pytest_homeassistant_custom_component.common import MockConfigEntry + +from homeassistant.config_entries import SOURCE_USER +from homeassistant.const import CONF_PASSWORD, CONF_SCAN_INTERVAL, CONF_USERNAME +from homeassistant.core import HomeAssistant +from homeassistant.data_entry_flow import FlowResultType + +from custom_components.hive.config_flow import _sanitize_payload +from custom_components.hive.const import CONF_CODE, CONF_DEVICE_NAME, DOMAIN + +from .conftest import DEVICE_DATA, PASSWORD, TOKENS, USERNAME + +SMS_CHALLENGE = {"ChallengeName": "SMS_MFA", "Session": "session-token"} + +pytestmark = pytest.mark.usefixtures("mock_setup_entry") + + +async def _start_user_flow(hass: HomeAssistant) -> dict: + result = await hass.config_entries.flow.async_init( + DOMAIN, context={"source": SOURCE_USER} + ) + assert result["type"] is FlowResultType.FORM + assert result["step_id"] == "user" + return await hass.config_entries.flow.async_configure( + result["flow_id"], {CONF_USERNAME: USERNAME, CONF_PASSWORD: PASSWORD} + ) + + +async def test_user_flow_without_2fa(hass: HomeAssistant, mock_auth: MagicMock) -> None: + """Login that returns tokens straight away creates the entry.""" + result = await _start_user_flow(hass) + + assert result["type"] is FlowResultType.CREATE_ENTRY + assert result["title"] == USERNAME + assert result["data"][CONF_USERNAME] == USERNAME + assert result["data"]["tokens"] == TOKENS + assert result["result"].unique_id == USERNAME + mock_auth.device_registration.assert_not_awaited() + + +async def test_user_flow_registers_device_from_login_metadata( + hass: HomeAssistant, mock_auth: MagicMock +) -> None: + """NewDeviceMetadata in the login response is registered and stored.""" + mock_auth.login.return_value = { + "AuthenticationResult": { + **TOKENS["AuthenticationResult"], + "NewDeviceMetadata": {"DeviceGroupKey": "group", "DeviceKey": "key"}, + } + } + + result = await _start_user_flow(hass) + + assert result["type"] is FlowResultType.CREATE_ENTRY + assert result["data"]["device_data"] == DEVICE_DATA + mock_auth.device_registration.assert_awaited_once_with("Home Assistant") + + +async def test_user_flow_with_2fa(hass: HomeAssistant, mock_auth: MagicMock) -> None: + """SMS 2FA goes through the code and device name steps.""" + mock_auth.login.return_value = SMS_CHALLENGE + + result = await _start_user_flow(hass) + assert result["type"] is FlowResultType.FORM + assert result["step_id"] == "2fa" + + result = await hass.config_entries.flow.async_configure( + result["flow_id"], {CONF_CODE: "123456"} + ) + assert result["type"] is FlowResultType.FORM + assert result["step_id"] == "configuration" + mock_auth.sms_2fa.assert_awaited_once_with("123456", SMS_CHALLENGE) + + result = await hass.config_entries.flow.async_configure( + result["flow_id"], {CONF_DEVICE_NAME: "My HA"} + ) + assert result["type"] is FlowResultType.CREATE_ENTRY + assert result["data"]["device_data"] == DEVICE_DATA + mock_auth.device_registration.assert_awaited_once_with("My HA") + + +async def test_2fa_resend_code(hass: HomeAssistant, mock_auth: MagicMock) -> None: + """Entering 0000 requests a new SMS code.""" + mock_auth.login.return_value = SMS_CHALLENGE + result = await _start_user_flow(hass) + + result = await hass.config_entries.flow.async_configure( + result["flow_id"], {CONF_CODE: "0000"} + ) + + assert result["type"] is FlowResultType.FORM + assert result["step_id"] == "2fa" + assert mock_auth.login.await_count == 2 + mock_auth.sms_2fa.assert_not_awaited() + + +@pytest.mark.parametrize( + ("exception", "error"), + [ + (HiveInvalid2FACode, "invalid_code"), + (HiveApiError, "no_internet_available"), + ], +) +async def test_2fa_errors( + hass: HomeAssistant, mock_auth: MagicMock, exception: type[Exception], error: str +) -> None: + """2FA failures keep the user on the code step.""" + mock_auth.login.return_value = SMS_CHALLENGE + mock_auth.sms_2fa.side_effect = exception + result = await _start_user_flow(hass) + + result = await hass.config_entries.flow.async_configure( + result["flow_id"], {CONF_CODE: "123456"} + ) + + assert result["type"] is FlowResultType.FORM + assert result["step_id"] == "2fa" + assert result["errors"] == {"base": error} + + +@pytest.mark.parametrize( + ("exception", "error"), + [ + (HiveInvalidUsername, "invalid_username"), + (HiveInvalidPassword, "invalid_password"), + (HiveApiError, "no_internet_available"), + ], +) +async def test_user_flow_login_errors( + hass: HomeAssistant, mock_auth: MagicMock, exception: type[Exception], error: str +) -> None: + """Login failures are shown on the user step and can be retried.""" + mock_auth.login.side_effect = exception + + result = await _start_user_flow(hass) + + assert result["type"] is FlowResultType.FORM + assert result["step_id"] == "user" + assert result["errors"] == {"base": error} + + mock_auth.login.side_effect = None + result = await hass.config_entries.flow.async_configure( + result["flow_id"], {CONF_USERNAME: USERNAME, CONF_PASSWORD: PASSWORD} + ) + assert result["type"] is FlowResultType.CREATE_ENTRY + + +async def test_user_flow_unexpected_login_response( + hass: HomeAssistant, mock_auth: MagicMock +) -> None: + """A login response without tokens or a challenge doesn't create an entry. + + The form is shown again without an error message; this pins current behaviour. + """ + mock_auth.login.return_value = {} + + result = await _start_user_flow(hass) + + assert result["type"] is FlowResultType.FORM + assert result["step_id"] == "user" + assert result["errors"] == {} + + +async def test_2fa_debug_bypass(hass: HomeAssistant, mock_auth: MagicMock) -> None: + """The debug toggle stops at the SMS challenge instead of asking for a code.""" + mock_auth.login.return_value = SMS_CHALLENGE + result = await hass.config_entries.flow.async_init( + DOMAIN, context={"source": SOURCE_USER} + ) + + result = await hass.config_entries.flow.async_configure( + result["flow_id"], + {CONF_USERNAME: USERNAME, CONF_PASSWORD: PASSWORD, "disable_2fa_debug": True}, + ) + + assert result["type"] is FlowResultType.FORM + assert result["step_id"] == "user" + assert result["errors"] == {"base": "twofa_bypassed_debug"} + + +async def test_user_flow_already_configured( + hass: HomeAssistant, mock_auth: MagicMock, mock_config_entry: MockConfigEntry +) -> None: + """The same account can't be added twice.""" + mock_config_entry.add_to_hass(hass) + + result = await _start_user_flow(hass) + + assert result["type"] is FlowResultType.ABORT + assert result["reason"] == "already_configured" + mock_auth.login.assert_not_awaited() + + +async def test_reauth( + hass: HomeAssistant, mock_auth: MagicMock, mock_config_entry: MockConfigEntry +) -> None: + """Reauth logs in again and updates the existing entry.""" + mock_config_entry.add_to_hass(hass) + new_tokens = {"AuthenticationResult": {"AccessToken": "new-access-token"}} + mock_auth.login.return_value = new_tokens + + result = await mock_config_entry.start_reauth_flow(hass) + + assert result["type"] is FlowResultType.ABORT + assert result["reason"] == "reauth_successful" + assert mock_config_entry.data["tokens"] == new_tokens + + +async def test_reauth_with_2fa_on_registered_device( + hass: HomeAssistant, mock_auth: MagicMock, mock_config_entry: MockConfigEntry +) -> None: + """Reauth with 2FA skips device registration when the device is known.""" + mock_config_entry.add_to_hass(hass) + mock_auth.login.return_value = SMS_CHALLENGE + + result = await mock_config_entry.start_reauth_flow(hass) + assert result["step_id"] == "2fa" + + result = await hass.config_entries.flow.async_configure( + result["flow_id"], {CONF_CODE: "123456"} + ) + + assert result["type"] is FlowResultType.ABORT + assert result["reason"] == "reauth_successful" + mock_auth.device_registration.assert_not_awaited() + + +async def test_options_flow( + hass: HomeAssistant, mock_config_entry: MockConfigEntry +) -> None: + """The scan interval option is saved and pushed to the Hive client.""" + mock_config_entry.add_to_hass(hass) + hive = MagicMock() + hive.updateInterval = AsyncMock() + mock_config_entry.runtime_data = hive + + result = await hass.config_entries.options.async_init(mock_config_entry.entry_id) + assert result["type"] is FlowResultType.FORM + assert result["step_id"] == "user" + + result = await hass.config_entries.options.async_configure( + result["flow_id"], {CONF_SCAN_INTERVAL: 60} + ) + + assert result["type"] is FlowResultType.CREATE_ENTRY + assert mock_config_entry.options == {CONF_SCAN_INTERVAL: 60} + hive.updateInterval.assert_awaited_once_with(60) + + +async def test_device_registration_failure_still_creates_entry( + hass: HomeAssistant, mock_auth: MagicMock +) -> None: + """If registering the device fails, setup carries on without device_data.""" + mock_auth.login.return_value = { + "AuthenticationResult": { + **TOKENS["AuthenticationResult"], + "NewDeviceMetadata": {"DeviceGroupKey": "group", "DeviceKey": "key"}, + } + } + mock_auth.device_registration.side_effect = HiveApiError + + result = await _start_user_flow(hass) + + assert result["type"] is FlowResultType.CREATE_ENTRY + assert "device_data" not in result["data"] + + +async def test_reauth_with_2fa_on_unregistered_device( + hass: HomeAssistant, mock_auth: MagicMock, mock_config_entry: MockConfigEntry +) -> None: + """Reauth with 2FA registers the device again if Hive has forgotten it.""" + mock_config_entry.add_to_hass(hass) + mock_auth.login.return_value = SMS_CHALLENGE + mock_auth.is_device_registered.return_value = False + + result = await mock_config_entry.start_reauth_flow(hass) + result = await hass.config_entries.flow.async_configure( + result["flow_id"], {CONF_CODE: "123456"} + ) + assert result["step_id"] == "configuration" + + result = await hass.config_entries.flow.async_configure( + result["flow_id"], {CONF_DEVICE_NAME: "My HA"} + ) + + assert result["type"] is FlowResultType.ABORT + assert result["reason"] == "reauth_successful" + mock_auth.device_registration.assert_awaited_once_with("My HA") + + +async def test_2fa_response_without_tokens( + hass: HomeAssistant, mock_auth: MagicMock +) -> None: + """A 2FA response without tokens shows an unknown error on the last step.""" + mock_auth.login.return_value = SMS_CHALLENGE + mock_auth.sms_2fa.return_value = {"ChallengeName": "SOMETHING_ELSE"} + result = await _start_user_flow(hass) + result = await hass.config_entries.flow.async_configure( + result["flow_id"], {CONF_CODE: "123456"} + ) + + result = await hass.config_entries.flow.async_configure( + result["flow_id"], {CONF_DEVICE_NAME: "My HA"} + ) + + assert result["type"] is FlowResultType.FORM + assert result["step_id"] == "configuration" + assert result["errors"] == {"base": "unknown"} + + +def test_sanitize_payload() -> None: + """Secrets are masked in logged payloads; other values are left alone.""" + payload = { + "ChallengeName": "SMS_MFA", + "Session": "abcdefghijklmnop", + "AuthenticationResult": {"AccessToken": "short", "ExpiresIn": 3600}, + "Devices": [{"DeviceKey": "key", "RefreshToken": 12345}], + } + + assert _sanitize_payload(payload) == { + "ChallengeName": "SMS_MFA", + "Session": "abcd...mnop", + "AuthenticationResult": {"AccessToken": "***", "ExpiresIn": 3600}, + "Devices": [{"DeviceKey": "key", "RefreshToken": 12345}], + } + assert payload["Session"] == "abcdefghijklmnop" diff --git a/tests/test_init.py b/tests/test_init.py new file mode 100644 index 0000000..231f9fd --- /dev/null +++ b/tests/test_init.py @@ -0,0 +1,152 @@ +"""Tests for setting up and unloading the Hive integration.""" + +from unittest.mock import MagicMock + +from aiohttp.web_exceptions import HTTPServiceUnavailable +from apyhiveapi.helper.hive_exceptions import ( + HiveConnectionError, + HiveReauthRequired, + HiveUnknownConfiguration, +) +import pytest +from pytest_homeassistant_custom_component.common import MockConfigEntry + +from homeassistant.config_entries import SOURCE_REAUTH, ConfigEntryState +from homeassistant.const import CONF_SCAN_INTERVAL +from homeassistant.core import HomeAssistant +from homeassistant.helpers import device_registry as dr +from homeassistant.helpers.dispatcher import async_dispatcher_connect + +from custom_components.hive import async_remove_config_entry_device, refresh_system +from custom_components.hive.const import DOMAIN + +from .conftest import HUB_ID + + +async def test_setup_and_unload( + hass: HomeAssistant, mock_hive: MagicMock, mock_config_entry: MockConfigEntry +) -> None: + """The entry loads, registers the hub and unloads cleanly.""" + mock_config_entry.add_to_hass(hass) + + assert await hass.config_entries.async_setup(mock_config_entry.entry_id) + await hass.async_block_till_done() + + assert mock_config_entry.state is ConfigEntryState.LOADED + assert mock_config_entry.runtime_data is mock_hive + hub = dr.async_get(hass).async_get_device_by_identifier( + (DOMAIN, HUB_ID), mock_config_entry.entry_id + ) + assert hub is not None + assert hub.name == "Hive Hub" + + assert await hass.config_entries.async_unload(mock_config_entry.entry_id) + await hass.async_block_till_done() + assert mock_config_entry.state is ConfigEntryState.NOT_LOADED + + +@pytest.mark.parametrize( + ("exception", "state", "reauth"), + [ + (HTTPServiceUnavailable(), ConfigEntryState.SETUP_RETRY, False), + (HiveConnectionError(), ConfigEntryState.SETUP_RETRY, False), + (HiveReauthRequired(), ConfigEntryState.SETUP_ERROR, True), + (HiveUnknownConfiguration(), ConfigEntryState.SETUP_ERROR, True), + ], +) +async def test_setup_failures( + hass: HomeAssistant, + mock_hive: MagicMock, + mock_auth: MagicMock, + mock_config_entry: MockConfigEntry, + exception: Exception, + state: ConfigEntryState, + reauth: bool, +) -> None: + """Network errors retry setup, auth errors start reauth.""" + mock_hive.session.startSession.side_effect = exception + # Keep the reauth flow waiting on the 2FA step so it can be observed. + mock_auth.login.return_value = {"ChallengeName": "SMS_MFA"} + mock_config_entry.add_to_hass(hass) + + await hass.config_entries.async_setup(mock_config_entry.entry_id) + await hass.async_block_till_done() + + assert mock_config_entry.state is state + reauth_flows = mock_config_entry.async_get_active_flows(hass, {SOURCE_REAUTH}) + assert bool(list(reauth_flows)) is reauth + + +@pytest.mark.parametrize( + ("options", "interval"), [({}, 120), ({CONF_SCAN_INTERVAL: 60}, 60)] +) +async def test_scan_interval_passed_to_session( + hass: HomeAssistant, + mock_hive: MagicMock, + mock_config_entry: MockConfigEntry, + options: dict, + interval: int, +) -> None: + """The scan interval option (default 120s) is handed to the Hive session.""" + mock_config_entry.add_to_hass(hass) + hass.config_entries.async_update_entry(mock_config_entry, options=options) + + await hass.config_entries.async_setup(mock_config_entry.entry_id) + await hass.async_block_till_done() + + session_config = mock_hive.session.startSession.await_args.args[0] + assert session_config["options"] == {CONF_SCAN_INTERVAL: interval} + assert session_config["tokens"] == mock_config_entry.data["tokens"] + + +@pytest.mark.usefixtures("setup_integration") +async def test_only_platforms_with_devices_are_set_up(hass: HomeAssistant) -> None: + """Platforms Hive reports no devices for aren't loaded.""" + assert "hive.sensor" in hass.config.components + for platform in ("binary_sensor", "climate", "light", "switch", "water_heater"): + assert f"hive.{platform}" not in hass.config.components + + +async def test_remove_entry_forgets_device( + hass: HomeAssistant, + mock_hive: MagicMock, + mock_auth: MagicMock, + setup_integration: MockConfigEntry, +) -> None: + """Deleting the entry deregisters this Home Assistant device from Hive.""" + await hass.config_entries.async_remove(setup_integration.entry_id) + await hass.async_block_till_done() + + mock_auth.forget_device.assert_awaited_once_with("access-token", "device-key") + + +async def test_remove_device( + hass: HomeAssistant, setup_integration: MockConfigEntry +) -> None: + """Any Hive device can be removed from the device page.""" + hub = dr.async_get(hass).async_get_device_by_identifier( + (DOMAIN, HUB_ID), setup_integration.entry_id + ) + + assert await async_remove_config_entry_device(hass, setup_integration, hub) + + +async def test_refresh_system(hass: HomeAssistant) -> None: + """refresh_system runs the method, then signals every entity to update.""" + calls = [] + signals = [] + async_dispatcher_connect(hass, DOMAIN, lambda: signals.append(True)) + + class FakeEntity: + def __init__(self) -> None: + self.hass = hass + + @refresh_system + async def turn_on(self, value: int) -> None: + calls.append(value) + + await FakeEntity().turn_on(5) + await hass.async_block_till_done() + + assert calls == [5] + assert signals == [True] diff --git a/tests/test_light.py b/tests/test_light.py new file mode 100644 index 0000000..b01db5e --- /dev/null +++ b/tests/test_light.py @@ -0,0 +1,151 @@ +"""Tests for the lights re-exported from Home Assistant core.""" + +from typing import Any +from unittest.mock import AsyncMock, MagicMock + +import pytest + +from homeassistant.components.light import ( + ATTR_BRIGHTNESS, + ATTR_COLOR_MODE, + ATTR_COLOR_TEMP_KELVIN, + ATTR_HS_COLOR, + ATTR_SUPPORTED_COLOR_MODES, + DOMAIN as LIGHT_DOMAIN, + ColorMode, +) +from homeassistant.const import ( + ATTR_ENTITY_ID, + SERVICE_TURN_OFF, + SERVICE_TURN_ON, + STATE_OFF, + STATE_ON, + STATE_UNAVAILABLE, +) +from homeassistant.core import HomeAssistant + +from .conftest import make_device + + +def light( + hive_type: str, name: str, *, online: bool = True, **status: Any +) -> dict[str, Any]: + """A light product as pyhive's getLight returns it.""" + return make_device( + hive_type, + ha_type="light", + hive_id=f"{hive_type}-1", + name=name, + ha_name=name, + online=online, + status={"state": True, "brightness": 128, **status}, + attributes={"mode": "SCHEDULE"}, + ) + + +WARM_WHITE = light("warmwhitelight", "Kitchen") +TUNEABLE = light("tuneablelight", "Bedroom", color_temp=370) +COLOUR = light( + "colourtuneablelight", "Lounge Lamp", mode="COLOUR", hs_color=(255, 0, 0) +) +COLOUR_WHITE = light( + "colourtuneablelight", "Desk Lamp", mode="WHITE", color_temp=153 +) | {"hiveID": "colour-white-1", "device_id": "colour-white-1"} + + +@pytest.fixture +def platform_devices() -> dict[str, list[dict[str, Any]]]: + """Light devices returned by the mocked Hive session.""" + return {"light": [WARM_WHITE, TUNEABLE, COLOUR, COLOUR_WHITE]} + + +@pytest.fixture +def mock_light(mock_hive: MagicMock) -> MagicMock: + """Make the light setters awaitable.""" + mock_hive.light.turnOn = AsyncMock() + mock_hive.light.turnOff = AsyncMock() + return mock_hive.light + + +@pytest.mark.usefixtures("setup_integration") +async def test_light_states(hass: HomeAssistant) -> None: + """Each Hive light type exposes the matching colour modes.""" + state = hass.states.get("light.kitchen") + assert state.state == STATE_ON + assert state.attributes[ATTR_BRIGHTNESS] == 128 + assert state.attributes[ATTR_SUPPORTED_COLOR_MODES] == [ColorMode.BRIGHTNESS] + assert state.attributes["mode"] == "SCHEDULE" + + state = hass.states.get("light.bedroom") + assert state.attributes[ATTR_COLOR_MODE] == ColorMode.COLOR_TEMP + assert state.attributes[ATTR_COLOR_TEMP_KELVIN] == 2702 # 370 mireds + + state = hass.states.get("light.lounge_lamp") + assert state.attributes[ATTR_COLOR_MODE] == ColorMode.HS + assert state.attributes[ATTR_HS_COLOR] == (0.0, 100.0) + + state = hass.states.get("light.desk_lamp") + assert state.attributes[ATTR_COLOR_MODE] == ColorMode.COLOR_TEMP + assert state.attributes[ATTR_COLOR_TEMP_KELVIN] == 6535 # 153 mireds + + +@pytest.mark.parametrize( + "platform_devices", + [ + { + "light": [ + light("warmwhitelight", "Kitchen", state=False), + light("warmwhitelight", "Porch", online=False) + | {"hiveID": "porch-1", "device_id": "porch-1"}, + ] + } + ], +) +@pytest.mark.usefixtures("setup_integration") +async def test_light_off_and_offline(hass: HomeAssistant) -> None: + """A light that is off reads off; an offline light is unavailable.""" + assert hass.states.get("light.kitchen").state == STATE_OFF + assert hass.states.get("light.porch").state == STATE_UNAVAILABLE + + +@pytest.mark.parametrize( + ("entity_id", "data", "expected"), + [ + ("light.kitchen", {}, (None, None, None)), + # Brightness is sent as a percentage rounded to 5, never below 5. + ("light.kitchen", {ATTR_BRIGHTNESS: 255}, (100, None, None)), + ("light.kitchen", {ATTR_BRIGHTNESS: 1}, (5, None, None)), + ("light.bedroom", {ATTR_COLOR_TEMP_KELVIN: 4000}, (None, 4000, None)), + ("light.lounge_lamp", {ATTR_HS_COLOR: (120, 50)}, (None, None, (120, 50, 100))), + ], +) +@pytest.mark.usefixtures("setup_integration") +async def test_turn_on( + hass: HomeAssistant, + mock_light: MagicMock, + entity_id: str, + data: dict[str, Any], + expected: tuple, +) -> None: + """turn_on converts HA values to what Hive expects.""" + await hass.services.async_call( + LIGHT_DOMAIN, + SERVICE_TURN_ON, + {ATTR_ENTITY_ID: entity_id, **data}, + blocking=True, + ) + + assert mock_light.turnOn.await_args.args[1:] == expected + + +@pytest.mark.usefixtures("setup_integration") +async def test_turn_off(hass: HomeAssistant, mock_light: MagicMock) -> None: + """turn_off is passed straight to Hive.""" + await hass.services.async_call( + LIGHT_DOMAIN, + SERVICE_TURN_OFF, + {ATTR_ENTITY_ID: "light.kitchen"}, + blocking=True, + ) + + mock_light.turnOff.assert_awaited_once() diff --git a/tests/test_sensor.py b/tests/test_sensor.py new file mode 100644 index 0000000..db644eb --- /dev/null +++ b/tests/test_sensor.py @@ -0,0 +1,305 @@ +"""Tests for the Hive sensors added by this component.""" + +from datetime import datetime +from typing import Any +from unittest.mock import AsyncMock, MagicMock + +import pytest +from pytest_homeassistant_custom_component.common import MockConfigEntry + +from homeassistant.const import PERCENTAGE, STATE_UNAVAILABLE, STATE_UNKNOWN +from homeassistant.core import HomeAssistant +from homeassistant.helpers import entity_registry as er + +from custom_components.hive import sensor + +from .conftest import make_device + + +async def _setup(hass: HomeAssistant, entry: MockConfigEntry) -> None: + entry.add_to_hass(hass) + assert await hass.config_entries.async_setup(entry.entry_id) + await hass.async_block_till_done() + + +async def test_battery_sensor( + hass: HomeAssistant, mock_hive: MagicMock, mock_config_entry: MockConfigEntry +) -> None: + """Battery level is exposed as a diagnostic percentage sensor.""" + await _setup(hass, mock_config_entry) + + state = hass.states.get("sensor.lounge_trv_battery") + assert state is not None + assert state.state == "87" + assert state.attributes["unit_of_measurement"] == PERCENTAGE + assert state.attributes["device_class"] == "battery" + + entry = er.async_get(hass).async_get("sensor.lounge_trv_battery") + assert entry.unique_id == "trv-1-Battery" + assert entry.entity_category == "diagnostic" + + +@pytest.mark.parametrize( + "sensor_devices", + [ + [ + make_device("Battery", 50, online=False), + make_device("Availability", "Offline"), + ] + ], +) +async def test_offline_device( + hass: HomeAssistant, mock_hive: MagicMock, mock_config_entry: MockConfigEntry +) -> None: + """Offline devices are unavailable, but their Availability sensor still reports.""" + await _setup(hass, mock_config_entry) + + assert hass.states.get("sensor.lounge_trv_battery").state == STATE_UNAVAILABLE + assert hass.states.get("sensor.lounge_trv_availability").state == "Offline" + + +@pytest.mark.parametrize( + "sensor_devices", [[make_device("Heating_Mode", "SCHEDULE", name="Thermostat")]] +) +async def test_heating_mode_sensor( + hass: HomeAssistant, mock_hive: MagicMock, mock_config_entry: MockConfigEntry +) -> None: + """Heating mode is an enum sensor with lower-cased state.""" + mock_hive.heating.getScheduleNowNextLater = AsyncMock(return_value=None) + + await _setup(hass, mock_config_entry) + + state = hass.states.get("sensor.thermostat_heating_mode") + assert state.state == "schedule" + assert state.attributes["options"] == ["schedule", "manual", "off"] + assert state.attributes["Schedule not active"] == "" + + +@pytest.mark.parametrize( + "sensor_devices", [[make_device("Hotwater_Mode", "ON", name="Hot Water")]] +) +async def test_hotwater_mode_schedule_attributes( + hass: HomeAssistant, mock_hive: MagicMock, mock_config_entry: MockConfigEntry +) -> None: + """Hot water mode shows the now/next schedule slots as attributes.""" + + def slot(status: str, start: int, end: int) -> dict[str, Any]: + return { + "value": {"status": status}, + "start": start * 60, + "Start_DateTime": datetime(2026, 1, 1, start, 0), + "End_DateTime": datetime(2026, 1, 1, end, 0), + } + + mock_hive.hotwater.getScheduleNowNextLater = AsyncMock( + return_value={"now": slot("ON", 6, 8), "next": slot("OFF", 8, 17)} + ) + + await _setup(hass, mock_config_entry) + + state = hass.states.get("sensor.hot_water_hotwater_mode") + assert state.state == "on" + assert state.attributes["Now"] == "ON : 06:00 - 08:00" + assert state.attributes["Next"] == "OFF : 08:00 - 17:00" + assert "Later" not in state.attributes + + +@pytest.mark.parametrize("sensor_devices", [[make_device("Unknown_Type", 1)]]) +async def test_unknown_sensor_type_is_ignored( + hass: HomeAssistant, mock_hive: MagicMock, mock_config_entry: MockConfigEntry +) -> None: + """Device types without a description don't create entities.""" + await _setup(hass, mock_config_entry) + + assert hass.states.async_entity_ids("sensor") == [] + + +@pytest.mark.parametrize( + ("sensor_devices", "entity_id", "expected"), + [ + ( + [make_device("Power", 42.5, name="Fan Plug")], + "sensor.fan_plug_power", + {"state": "42.5", "unit_of_measurement": "W", "device_class": "power"}, + ), + ( + [make_device("Current_Temperature", 19.5, name="Hallway")], + "sensor.hallway_current_temperature", + { + "state": "19.5", + "unit_of_measurement": "°C", + "device_class": "temperature", + }, + ), + ( + [make_device("Heating_Current_Temperature", 20.1, name="Heating")], + "sensor.heating_heating_current_temperature", + { + "state": "20.1", + "unit_of_measurement": "°C", + "state_class": "measurement", + }, + ), + ( + [make_device("Heating_Target_Temperature", 21, name="Heating")], + "sensor.heating_heating_target_temperature", + {"state": "21", "icon": "mdi:thermometer"}, + ), + ( + [make_device("Mode", "SCHEDULE", name="Fan Plug")], + "sensor.fan_plug_mode", + {"state": "SCHEDULE", "icon": "mdi:eye"}, + ), + ], +) +async def test_value_sensors( + hass: HomeAssistant, + mock_hive: MagicMock, + mock_config_entry: MockConfigEntry, + entity_id: str, + expected: dict[str, str], +) -> None: + """Each simple sensor type reports its value with the right unit and class.""" + await _setup(hass, mock_config_entry) + + state = hass.states.get(entity_id) + assert state.state == expected.pop("state") + for attribute, value in expected.items(): + assert state.attributes[attribute] == value + + +@pytest.mark.parametrize( + "sensor_devices", [[make_device("Heating_Mode", "MANUAL", name="Thermostat")]] +) +async def test_heating_mode_schedule_attributes( + hass: HomeAssistant, mock_hive: MagicMock, mock_config_entry: MockConfigEntry +) -> None: + """Heating mode shows now/next/later target temperatures; incomplete slots are skipped.""" + + def slot(target: float, start: int, end: int) -> dict[str, Any]: + return { + "value": {"target": target}, + "start": start * 60, + "Start_DateTime": datetime(2026, 1, 1, start, 0), + "End_DateTime": datetime(2026, 1, 1, end, 0), + } + + mock_hive.heating.getScheduleNowNextLater = AsyncMock( + return_value={ + "now": slot(20, 6, 9), + "next": slot(16, 9, 17), + "later": slot(21, 17, 22), + } + ) + + await _setup(hass, mock_config_entry) + + state = hass.states.get("sensor.thermostat_heating_mode") + assert state.state == "manual" + assert state.attributes["Now"] == "20 °C : 06:00 - 09:00" + assert state.attributes["Next"] == "16 °C : 09:00 - 17:00" + assert state.attributes["Later"] == "21 °C : 17:00 - 22:00" + + +INCOMPLETE_SCHEDULES = [ + {}, + {"now": {"value": {}, "start": 0}, "next": {"value": {}}, "later": {}}, +] + + +@pytest.mark.parametrize( + "sensor_devices", + [ + [ + make_device("Heating_Mode", "SCHEDULE", name="Thermostat"), + make_device("Hotwater_Mode", "SCHEDULE", name="Hot Water"), + ] + ], +) +@pytest.mark.parametrize("schedule", INCOMPLETE_SCHEDULES) +async def test_incomplete_schedule( + hass: HomeAssistant, + mock_hive: MagicMock, + mock_config_entry: MockConfigEntry, + schedule: dict[str, Any], +) -> None: + """Schedule slots missing a target, status or time are left out.""" + mock_hive.heating.getScheduleNowNextLater = AsyncMock(return_value=schedule) + mock_hive.hotwater.getScheduleNowNextLater = AsyncMock(return_value=schedule) + + await _setup(hass, mock_config_entry) + + for entity_id in ( + "sensor.thermostat_heating_mode", + "sensor.hot_water_hotwater_mode", + ): + attributes = hass.states.get(entity_id).attributes + assert not {"Now", "Next", "Later", "Schedule not active"} & set(attributes) + + +@pytest.mark.parametrize( + "sensor_devices", [[make_device("Hotwater_Mode", "SCHEDULE", name="Hot Water")]] +) +async def test_hotwater_mode_later_slot( + hass: HomeAssistant, mock_hive: MagicMock, mock_config_entry: MockConfigEntry +) -> None: + """Hot water shows the later slot when Hive sends one.""" + mock_hive.hotwater.getScheduleNowNextLater = AsyncMock( + return_value={ + "later": { + "value": {"status": "ON"}, + "start": 1020, + "Start_DateTime": datetime(2026, 1, 1, 17, 0), + "End_DateTime": datetime(2026, 1, 1, 18, 0), + }, + } + ) + + await _setup(hass, mock_config_entry) + + attributes = hass.states.get("sensor.hot_water_hotwater_mode").attributes + assert attributes["Later"] == "ON : 17:00 - 18:00" + + +@pytest.mark.parametrize( + "sensor_devices", [[make_device("Hotwater_Mode", "OFF", name="Hot Water")]] +) +async def test_hotwater_mode_no_schedule( + hass: HomeAssistant, mock_hive: MagicMock, mock_config_entry: MockConfigEntry +) -> None: + """Without a schedule the hot water sensor says so.""" + mock_hive.hotwater.getScheduleNowNextLater = AsyncMock(return_value=None) + + await _setup(hass, mock_config_entry) + + state = hass.states.get("sensor.hot_water_hotwater_mode") + assert state.state == "off" + assert state.attributes["Schedule not active"] == "" + + +@pytest.mark.parametrize( + "sensor_devices", [[make_device("Heating_Mode", None, name="Thermostat")]] +) +async def test_mode_sensor_without_state( + hass: HomeAssistant, mock_hive: MagicMock, mock_config_entry: MockConfigEntry +) -> None: + """A mode sensor with no state reads unknown instead of failing.""" + mock_hive.heating.getScheduleNowNextLater = AsyncMock(return_value=None) + + await _setup(hass, mock_config_entry) + + assert hass.states.get("sensor.thermostat_heating_mode").state == STATE_UNKNOWN + + +async def test_sensor_platform_without_devices( + hass: HomeAssistant, mock_config_entry: MockConfigEntry +) -> None: + """The sensor platform adds nothing when Hive reports no sensors.""" + hive = MagicMock() + hive.session.deviceList = {"sensor": []} + mock_config_entry.runtime_data = hive + add_entities = MagicMock() + + await sensor.async_setup_entry(hass, mock_config_entry, add_entities) + + add_entities.assert_not_called() diff --git a/tests/test_switch.py b/tests/test_switch.py new file mode 100644 index 0000000..01636eb --- /dev/null +++ b/tests/test_switch.py @@ -0,0 +1,90 @@ +"""Tests for the switches re-exported from Home Assistant core.""" + +from typing import Any +from unittest.mock import AsyncMock, MagicMock + +import pytest + +from homeassistant.components.switch import DOMAIN as SWITCH_DOMAIN +from homeassistant.const import ( + ATTR_ENTITY_ID, + SERVICE_TURN_OFF, + SERVICE_TURN_ON, + STATE_OFF, + STATE_ON, + STATE_UNAVAILABLE, +) +from homeassistant.core import HomeAssistant +from homeassistant.helpers import entity_registry as er + +from .conftest import make_device + +PLUG = make_device( + "activeplug", + True, + ha_type="switch", + hive_id="plug-1", + name="Fan Plug", + ha_name="Fan Plug", + attributes={"mode": "MANUAL"}, +) +HEAT_ON_DEMAND = make_device( + "Heating_Heat_On_Demand", + False, + ha_type="switch", + hive_id="heating-1", + name="Heating", + ha_name="Heating Heat on Demand", +) +OFFLINE_PLUG = make_device( + "activeplug", + True, + ha_type="switch", + hive_id="plug-2", + name="Lamp Plug", + ha_name="Lamp Plug", + online=False, +) +# pyhive lists Hive actions as switches, but there is no description for them. +ACTION = make_device( + "action", True, ha_type="switch", hive_id="action-1", ha_name="Leaving Home" +) + + +@pytest.fixture +def platform_devices() -> dict[str, list[dict[str, Any]]]: + """Switch devices returned by the mocked Hive session.""" + return {"switch": [PLUG, HEAT_ON_DEMAND, OFFLINE_PLUG, ACTION]} + + +@pytest.mark.usefixtures("setup_integration") +async def test_switch_states(hass: HomeAssistant) -> None: + """Plugs and heat on demand are switches; actions are not.""" + state = hass.states.get("switch.fan_plug") + assert state.state == STATE_ON + assert state.attributes["mode"] == "MANUAL" + + assert hass.states.get("switch.heating_heat_on_demand").state == STATE_OFF + entry = er.async_get(hass).async_get("switch.heating_heat_on_demand") + assert entry.entity_category == "config" + + assert hass.states.get("switch.lamp_plug").state == STATE_UNAVAILABLE + assert hass.states.get("switch.leaving_home") is None + + +@pytest.mark.parametrize( + ("service", "method"), + [(SERVICE_TURN_ON, "turnOn"), (SERVICE_TURN_OFF, "turnOff")], +) +@pytest.mark.usefixtures("setup_integration") +async def test_turn_on_off( + hass: HomeAssistant, mock_hive: MagicMock, service: str, method: str +) -> None: + """Turning a switch on or off calls Hive.""" + setattr(mock_hive.switch, method, AsyncMock()) + + await hass.services.async_call( + SWITCH_DOMAIN, service, {ATTR_ENTITY_ID: "switch.fan_plug"}, blocking=True + ) + + getattr(mock_hive.switch, method).assert_awaited_once() diff --git a/tests/test_translations.py b/tests/test_translations.py new file mode 100644 index 0000000..f427174 --- /dev/null +++ b/tests/test_translations.py @@ -0,0 +1,43 @@ +"""Check the translation files stay in step with the code.""" + +import json +from pathlib import Path +import re +import sys + +import yaml + +ROOT = Path(__file__).parent.parent +COMPONENT = ROOT / "custom_components" / "hive" +EN_JSON = COMPONENT / "translations" / "en.json" + +sys.path.insert(0, str(ROOT / "script")) +import gen_translations # noqa: E402 + + +def _en() -> dict: + return json.loads(EN_JSON.read_text(encoding="utf-8")) + + +def test_en_json_is_generated_from_strings_json() -> None: + """translations/en.json matches strings.json with references expanded. + + Fix with: python script/gen_translations.py + """ + assert EN_JSON.read_text(encoding="utf-8") == gen_translations.render() + + +def test_config_flow_errors_are_translated() -> None: + """Every error the config flow can set has English text.""" + source = (COMPONENT / "config_flow.py").read_text(encoding="utf-8") + used = set(re.findall(r'errors\["base"\] = "([a-z0-9_]+)"', source)) + + assert used + assert used - set(_en()["config"]["error"]) == set() + + +def test_services_are_translated() -> None: + """Every service in services.yaml has a name in en.json.""" + services = yaml.safe_load((COMPONENT / "services.yaml").read_text(encoding="utf-8")) + + assert set(services) - set(_en().get("services", {})) == set() diff --git a/tests/test_water_heater.py b/tests/test_water_heater.py new file mode 100644 index 0000000..c13cee0 --- /dev/null +++ b/tests/test_water_heater.py @@ -0,0 +1,128 @@ +"""Tests for the water heater re-exported from Home Assistant core.""" + +from typing import Any +from unittest.mock import AsyncMock, MagicMock + +import pytest + +from homeassistant.components.water_heater import ( + ATTR_OPERATION_MODE, + DOMAIN as WATER_HEATER_DOMAIN, + SERVICE_SET_OPERATION_MODE, + STATE_ECO, +) +from homeassistant.const import ( + ATTR_ENTITY_ID, + SERVICE_TURN_OFF, + SERVICE_TURN_ON, + STATE_OFF, + STATE_ON, + STATE_UNAVAILABLE, +) +from homeassistant.core import HomeAssistant + +from custom_components.hive.const import DOMAIN, SERVICE_BOOST_HOT_WATER + +from .conftest import make_device + +ENTITY_ID = "water_heater.hot_water" + + +def hot_water(operation: str = "SCHEDULE", *, online: bool = True) -> dict[str, Any]: + """A hot water product as pyhive's getWaterHeater returns it.""" + return make_device( + "hotwater", + ha_type="water_heater", + hive_id="hotwater-1", + name="Hot Water", + ha_name="Hot Water", + online=online, + status={"current_operation": operation}, + ) + + +@pytest.fixture +def platform_devices() -> dict[str, list[dict[str, Any]]]: + """Water heater devices returned by the mocked Hive session.""" + return {"water_heater": [hot_water()]} + + +@pytest.fixture +def mock_hotwater(mock_hive: MagicMock) -> MagicMock: + """Make the hot water setters awaitable.""" + for method in ("setMode", "setBoostOn", "setBoostOff"): + setattr(mock_hive.hotwater, method, AsyncMock()) + return mock_hive.hotwater + + +@pytest.mark.parametrize( + ("platform_devices", "expected"), + [ + ({"water_heater": [hot_water("SCHEDULE")]}, STATE_ECO), + ({"water_heater": [hot_water("ON")]}, STATE_ON), + ({"water_heater": [hot_water("OFF")]}, STATE_OFF), + ], +) +@pytest.mark.usefixtures("setup_integration") +async def test_water_heater_state(hass: HomeAssistant, expected: str) -> None: + """Hive operation names map to HA water heater states.""" + assert hass.states.get(ENTITY_ID).state == expected + + +@pytest.mark.parametrize( + "platform_devices", [{"water_heater": [hot_water(online=False)]}] +) +@pytest.mark.usefixtures("setup_integration") +async def test_water_heater_offline(hass: HomeAssistant) -> None: + """An offline hot water controller is unavailable.""" + assert hass.states.get(ENTITY_ID).state == STATE_UNAVAILABLE + + +@pytest.mark.parametrize( + ("service", "data", "hive_mode"), + [ + (SERVICE_TURN_ON, {}, "MANUAL"), + (SERVICE_TURN_OFF, {}, "OFF"), + (SERVICE_SET_OPERATION_MODE, {ATTR_OPERATION_MODE: STATE_ECO}, "SCHEDULE"), + (SERVICE_SET_OPERATION_MODE, {ATTR_OPERATION_MODE: STATE_ON}, "MANUAL"), + ], +) +@pytest.mark.usefixtures("setup_integration") +async def test_set_mode( + hass: HomeAssistant, + mock_hotwater: MagicMock, + service: str, + data: dict[str, Any], + hive_mode: str, +) -> None: + """Turning on/off and changing operation set the Hive mode.""" + await hass.services.async_call( + WATER_HEATER_DOMAIN, + service, + {ATTR_ENTITY_ID: ENTITY_ID, **data}, + blocking=True, + ) + + assert mock_hotwater.setMode.await_args.args[1] == hive_mode + + +@pytest.mark.usefixtures("setup_integration") +async def test_boost_hot_water_service( + hass: HomeAssistant, mock_hotwater: MagicMock +) -> None: + """hive.boost_hot_water boosts for the given minutes, or turns boost off.""" + await hass.services.async_call( + DOMAIN, + SERVICE_BOOST_HOT_WATER, + {ATTR_ENTITY_ID: ENTITY_ID, "time_period": "01:00:00", "on_off": "on"}, + blocking=True, + ) + assert mock_hotwater.setBoostOn.await_args.args[1] == 60 + + await hass.services.async_call( + DOMAIN, + SERVICE_BOOST_HOT_WATER, + {ATTR_ENTITY_ID: ENTITY_ID, "on_off": "off"}, + blocking=True, + ) + mock_hotwater.setBoostOff.assert_awaited_once()