testing

A testing ruleset defines how to test a Home Assistant custom component with pytest, an automated Python testing tool, and related fixtures.

In plain words
What is it for?
It is for writing unit tests for Git operations and Home Assistant integrations, including push, pull, fetch, SSH behavior, sensors, and buttons.
Why use it?
It gives the project consistent test structure, reusable setup, and coverage targets for important modules.

Cursor rule for Cursor

Install

Getting it into your agent

One page per mod, every tool's command on it. A separate URL per tool would split the same page into five that compete with each other.

agentmods
npx agentmods add rules/ckrl/ha-gitops/testing
Clone the repo
git clone --depth 1 https://github.com/ckrl/ha-gitops

Made for: Cursor.

Per session 0 Nothing until a file matches its globs; then the whole rule loads.
When invoked 1,113 The whole file, excluding the scripts and references it only reads on demand.
Security scan A 0 findings. Scan, not verified.
Origin original No closer match found in the catalogue.
Token cost

What it costs to keep this loaded

Counted locally with the o200k_base tokenizer, which is exact for GPT models; Claude uses its own tokenizer and its counts differ. Treat this as one consistent yardstick across the catalogue rather than a bill. Prices are per million input tokens.

ModelPer sessionOnce invoked
Fable 5 $0.00000 $0.01113
Opus 5 $0.00000 $0.00557
Sonnet 5 $0.00000 $0.00223
Haiku 4.5 $0.00000 $0.00111

Measured yesterday against content hash 6ac7991ea18e, method: parsed. Prices are Anthropic first-party input rates as of 2026-08-30, from the pricing page.

Security

Grade A, and why

testing scanned grade A with 0 findings against 26 rules in 11 categories — prompt injection, anti-refusal, data exfiltration, privilege escalation, supply chain, agent snooping, system-prompt leakage, SSRF and excessive agency — measured yesterday.

A static scan of the body, not an audit. Every finding is printed with the line that produced it so you can judge whether it matters here. A mod is markdown that instructs an agent; that is exactly why what it instructs is worth reading.

Nothing flagged

None of the 26 patterns this scan looks for appear in this file: no shell pipes, no recursive deletes, no credential paths, no hidden text, no instruction-override or anti-refusal phrasing, no agent-config snooping. That is not a guarantee, it is the absence of the things that are checkable.

.cursor/rules/testing.mdc · 66 lines

How it starts

The opening of the file, as written. The whole thing — 66 lines — stays where its author put it; the contents beside it link to each section on GitHub.

Testing Rules

Стек

  • pytest + pytest-asyncio (asyncio_mode = "auto" в pyproject.toml).
  • pytest-homeassistant-custom-component — фикстуры hass, enable_custom_integrations, mock_config_entry.
  • Покрытие — pytest-cov. Цель MVP: ≥ 80% по git_manager.py, ≥ 60% по sensor.py/button.py.

Структура

  • Файлы: tests/test_<module>.py (по одному на модуль custom_components/ha_gitops/).
  • tests/conftest.py — общие фикстуры: hass (из HA testing), временные директории, реальный bare git remote.
  • Один тест — одна проверка. Имена: test_<unit>_<condition>_<expected> (например, test_push_no_changes_returns_clean).

Фикстуры

  • tmp_path — для конфиг-директории HA.
  • bare_remote — фикстура с реальным git init --bare во временном каталоге; URL — file://{path}. Это позволяет тестировать push/pull/fetch без сети и без моков subprocess.
  • git_manager — собранный GitManager с tmp_path как config_dir и bare_remote как repo_url. SSH-ключ для file:// remote не нужен.
  • Для тестов SSH-логики (env, аргументы) — мокать asyncio.create_subprocess_exec через monkeypatch/AsyncMock.

Что тестировать обязательно

git_manager.py:

  • initialize создаёт .git/, .gitignore с блоком # ha-gitops:, не дублирует блок при повторном запуске.
  • _get_yaml_files() исключает secrets.yaml, secrets_backup.yaml, *.secrets.yaml, файлы из подпапок (только корень).
  • Panic guard: вручную staged secrets.yamlpush делает reset, не пушит, возвращает ERROR.
  • push без изменений и без unpushed коммитов → no-op, SyncStatus.CLEAN, нет пустого коммита.
  • push с unpushed коммитом, но без staged изменений → выполняется только git push.
  • pull ff-only: успех при behind, отказ + DIVERGED при diverged ветках.
  • get_status возвращает корректный SyncStatus для всех 7 вариантов (clean, modified, ahead, behind, diverged, error, unknown).
  • _build_commit_message: 1 файл / 2-3 файла / 4+ файла — формат subject из спеки §8.3, body содержит timestamp и Co-authored-by.
  • _build_ssh_env содержит GIT_SSH_COMMAND с правильным путём ключа, IdentitiesOnly=yes, не пробрасывает ~/.ssh.
  • Author/email подставляются через -c user.name=... -c user.email=..., не через global config (проверяется через argv мока).
  • SSH-ключ при генерации получает права 0o600 (проверять Path.stat().st_mode & 0o777).

Read the full file on GitHub · 66 lines

Changes

What this file has done since we first saw it

Hashed on every crawl. A supply-chain change to an agent config is a question of when, not whether, so the history is kept rather than the latest state alone.

  1. yesterday First seen · 66 lines · 0 tokens per session scan A 6ac7991ea18e

Subscribe to this mod's changes

testing is a cursor rule published in the GitHub repository ckrl/ha-gitops (4 stars, last pushed 3mo ago), licensed MIT. It costs nothing until one of its globs matches a file; then it loads 1,113 tokens. A static security scan graded it A with 0 findings. No closer match exists in the catalogue, so it is treated as the original; first seen 2026-08-31.