hass-taste-test 0.2.7 → 0.3.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/README.md CHANGED
@@ -30,19 +30,27 @@ This guide will walk you through setting up tests for visual regression testing.
30
30
 
31
31
  I recommend using either [Jest](https://jestjs.io) or [AVA](https://avajs.dev) for writing tests and [Playwright](https://playwright.dev) for browser automation. Both Jest and AVA run test files in parallel, and Playwright allows you to test on Chromium, Firefox, and WebKit. Since Jest has great support for [image snapshots](https://github.com/americanexpress/jest-image-snapshot), this guide will use Jest.
32
32
 
33
- 1. Install dependencies
33
+ 1. Optional: Install uv (helps speed up the HA download)
34
+
35
+ ```bash
36
+ curl -LsSf https://astral.sh/uv/install.sh | sh
37
+ ```
38
+
39
+ 2. Install dependencies
34
40
 
35
41
  ```bash
36
42
  npm install --save-dev hass-taste-test jest jest-image-snapshot playwright
37
43
  ```
38
44
 
39
- 2. Verify that Hass Taste Test can download and run Home Assistant:
45
+ 3. Verify that Hass Taste Test can download and run Home Assistant:
40
46
 
41
47
  ```bash
42
48
  npx hass-taste-test
43
49
  ```
44
50
 
45
- 3. Create a tests directory `__tests__` and create a file within it: `__tests__/card.test.js`. Add this code:
51
+ Installing [uv](https://docs.astral.sh/uv/) is strongly recommended: Hass Taste Test uses it when it is on your `PATH`, and it installs Home Assistant much faster and downloads a Python version that Home Assistant supports. Without uv, Hass Taste Test falls back to pip, which uses your `python3`; this must meet Home Assistant's minimum Python version.
52
+
53
+ 4. Create a tests directory `__tests__` and create a file within it: `__tests__/card.test.js`. Add this code:
46
54
 
47
55
  ```javascript
48
56
  const { HomeAssistant, PlaywrightBrowser } = require('hass-taste-test')
@@ -85,7 +93,7 @@ You may now consider customizing your Jest configuration using (`npx jest --init
85
93
 
86
94
  ## Developing
87
95
 
88
- If you wish to make changes to this repository, follow these instructions. Tests are run with `ts-node`, so no recompilation of typescript is necessary.
96
+ If you wish to make changes to this repository, follow these instructions. The source is written so Node (and Jest, via its built-in type stripping) can run it directly (Node 22.18+), so no recompilation of typescript is necessary.
89
97
 
90
98
  1. Install dependencies
91
99
 
@@ -104,26 +112,26 @@ To update snapshots, use `npx jest -u` and `npx ava -u`.
104
112
 
105
113
  ### But I want to write my tests in TypeScript
106
114
 
107
- Install [`ts-jest`](https://kulshekhar.github.io/ts-jest/docs/getting-started/installation/), `@types/jest`, and `@types/jest-image-snapshot` along with the other dependencies, then run `npx ts-jest config:init` to configure Jest for Typescript. Browse the [examples](https://github.com/rianadon/hass-taste-test/tree/main/test) for example tests; they are all written in TypeScript.
115
+ Install [`ts-jest`](https://kulshekhar.github.io/ts-jest/docs/getting-started/installation/), `@types/jest`, and `@types/jest-image-snapshot` along with the other dependencies, then run `npx ts-jest config:init` to configure Jest for Typescript. The bundled type declarations require TypeScript 5.0 or later. Browse the [examples](https://github.com/rianadon/hass-taste-test/tree/main/test) for example tests; they are all written in TypeScript.
108
116
 
109
117
  ## Why visual regression testing?
110
118
 
111
119
  I could've shown off how you can check that the text in the selectors you care about has the right substrings, or how to check that the correct number of `div`s got added to the special container. Here's why I didn't:
112
120
 
113
- - **These tests are a pain to write**: Home Assistant is very complex, so your card may run into many edge cases that require tests. I believe test quantity is better than test quality for this domain.
114
- - **Styles don't change much**: Most of the time, you are likely adding additonal features to the card rather than giving it a new paint job; so you won't be needing to update snapshots often. Testing visual regressions ensures that the card will remain stable for the features you've already added.
115
- - **Cards are small and simple**: Small cards make for small visual diffs, which makes it easy to spot what regressed.
121
+ - **These tests are a pain to write**: Home Assistant is very complex, so your card may run into many edge cases that require tests. I believe test quantity is better than test quality for this domain.
122
+ - **Styles don't change much**: Most of the time, you are likely adding additonal features to the card rather than giving it a new paint job; so you won't be needing to update snapshots often. Testing visual regressions ensures that the card will remain stable for the features you've already added.
123
+ - **Cards are small and simple**: Small cards make for small visual diffs, which makes it easy to spot what regressed.
116
124
 
117
125
  What if visual regression testing is not for me?
118
126
 
119
- - Grab the card's HTML and [snapshot](https://jestjs.io/docs/snapshot-testing) [it](https://github.com/avajs/ava/blob/main/docs/04-snapshot-testing.md). This works similar to visual regression tests but does not catch CSS changes.
127
+ - Grab the card's HTML and [snapshot](https://jestjs.io/docs/snapshot-testing) [it](https://github.com/avajs/ava/blob/main/docs/04-snapshot-testing.md). This works similar to visual regression tests but does not catch CSS changes.
120
128
 
121
129
  ```javascript
122
130
  expect(await dashboard.cards[0].hmtl()).toMatchSnapshot() // Jest
123
131
  t.snapshot(await dashboard.cards[0].hmtl()) // AVA
124
132
  ```
125
133
 
126
- - Narrow the card to an important selector and check the text.
134
+ - Narrow the card to an important selector and check the text.
127
135
 
128
136
  ```javascript
129
137
  expect(await dashboard.cards[0].narrow('.text-content').text()).to… // Jest
@@ -132,15 +140,15 @@ What if visual regression testing is not for me?
132
140
 
133
141
  ## Important concepts
134
142
 
135
- - **Home Assistant objects**: The `HomeAssistant` class creates a new Home Assistant Core instance. Each of these is fully isolated, so you can write multiple tests files each doing wildly different things without worrying about conflicts. They start up in parallel, except for about <100ms when multiple instances coordinate amongst themselves sequentially to choose unique ports and ensure Home Assistant is installed and upgraded.
143
+ - **Home Assistant objects**: The `HomeAssistant` class creates a new Home Assistant Core instance. Each of these is fully isolated, so you can write multiple tests files each doing wildly different things without worrying about conflicts. They start up in parallel, except for about <100ms when multiple instances coordinate amongst themselves sequentially to choose unique ports and ensure Home Assistant is installed and upgraded.
136
144
 
137
145
  Each instance creates a configuration directory in your [temporary directory](https://en.wikipedia.org/wiki/Temporary_folder), and these are deleted when `hass.close()` is called. The Home Assistant Core virtual environment is also stored in the temp directory, but is kept around for reuse.
138
146
 
139
- - **Dashboards**: Individual tests are isolated by using unique Lovelace Dashboards. This isolation is good for tracking down which test broke and for, if you are using AVA, running tests within a file in parallel. The name and id for dashboards are automatically generated.
147
+ - **Dashboards**: Individual tests are isolated by using unique Lovelace Dashboards. This isolation is good for tracking down which test broke and for, if you are using AVA, running tests within a file in parallel. The name and id for dashboards are automatically generated.
140
148
 
141
149
  You can grab references to cards and elements using `dashboard.cards[0]` or `dashboards.cards[1].narrow('.text-content')`. These are merely references; the test will not look for these elements inside the page until you call `.screenshot()`, `.html()`, or `.text()`, which all return [Promises](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise).
142
150
 
143
- - **Browser Integrations**: Hass Taste Test only requires a browser for working with cards in the dashboard; Home Assistant is configured entirely through the REST API. If you'd like to use the Dashboard card methods, you'll need to pass a browser integration instance to the `browser` option when configuring a `HomeAssistant` object.
151
+ - **Browser Integrations**: Hass Taste Test only requires a browser for working with cards in the dashboard; Home Assistant is configured entirely through the REST API. If you'd like to use the Dashboard card methods, you'll need to pass a browser integration instance to the `browser` option when configuring a `HomeAssistant` object.
144
152
 
145
153
  Currently only [Playwright](https://playwright.dev) is supported, but you can write your own for other tools.
146
154
 
@@ -205,7 +213,6 @@ Configures, starts, and connects to a new Home Assistant instance. Appends the s
205
213
 
206
214
  | Option | Description | Default |
207
215
  | ------------------ | ---------------------------------------------------------------------------------------- | ----------- |
208
- | `python` | Python executable used to create virtual environment | `python3` |
209
216
  | `hassArgs` | Arguments to pass to the `hass` binary | `[]` |
210
217
  | `host` | Host to which the Home Assistant frontend and api will be bound | `127.0.0.1` |
211
218
  | `port` | Port used to host the Home Assistant instance. If `null`, an unused port will be chosen. | `null` |
@@ -262,8 +269,8 @@ Creates and configures a dashboard using `createDashboard` and `setDashboardView
262
269
 
263
270
  Cards should be listed in `config`, and options allows you to set:
264
271
 
265
- - `colorScheme`: Can be `light` or `dark` to use the page's light or dark theme
266
- - That's all!
272
+ - `colorScheme`: Can be `light` or `dark` to use the page's light or dark theme
273
+ - That's all!
267
274
 
268
275
  #### `async close()`
269
276
 
@@ -295,10 +302,10 @@ Returns a Buffer containing image data for the card's screenshot.
295
302
 
296
303
  Returns normalized HTML for of the card. This differs from `outerHTML` in that:
297
304
 
298
- - Traversal crosses Shadow DOM boundaries
299
- - Polymer and Lit properties are included as attributes
300
- - Indentation is normalized
301
- - Attributes are sorted by name, and you can ignore attributes (`options.ignoreAttributes`)
302
- - Script and style tags are not included (`options.ignoreTags`)
303
- - The children of Common Home Assistant elements are not included (`options.ignoreChildren` for descendants, `options.ignoreShadowChildren` for Shadow DOM children)
304
- - Empty and undefined attributes are not included
305
+ - Traversal crosses Shadow DOM boundaries
306
+ - Polymer and Lit properties are included as attributes
307
+ - Indentation is normalized
308
+ - Attributes are sorted by name, and you can ignore attributes (`options.ignoreAttributes`)
309
+ - Script and style tags are not included (`options.ignoreTags`)
310
+ - The children of Common Home Assistant elements are not included (`options.ignoreChildren` for descendants, `options.ignoreShadowChildren` for Shadow DOM children)
311
+ - Empty and undefined attributes are not included
package/lib/bin.js CHANGED
@@ -1,10 +1,10 @@
1
1
  #!/usr/bin/env node
2
2
  "use strict";
3
3
  Object.defineProperty(exports, "__esModule", { value: true });
4
- const _1 = require("./");
4
+ const index_ts_1 = require("./index.js");
5
5
  (async () => {
6
6
  console.log('Ensuring Home Assistant packages are installed...');
7
- const hass = await _1.HomeAssistant.create('recorder:', {});
7
+ const hass = await index_ts_1.HomeAssistant.create('recorder:', {});
8
8
  await hass.close();
9
9
  console.log('All set!');
10
10
  })();
package/lib/index.d.ts CHANGED
@@ -1,10 +1,8 @@
1
- /// <reference types="node" />
2
1
  import * as hass from 'home-assistant-js-websocket';
3
- import { BrowserPage, DashboardOptions, DiffOptions, LovelaceDashboardCreateParams, LovelaceResourceType } from './types';
4
- import { BrowserIntegration } from './types';
5
- export { PlaywrightBrowser, PlaywrightElement } from './integrations/playwright';
2
+ import type { BrowserIntegration, BrowserPage, DashboardOptions, DiffOptions, LovelaceDashboardCreateParams, LovelaceResourceType } from './types.ts';
3
+ import { type HassEntityStates } from 'home-assistant-js-websocket';
4
+ export { PlaywrightBrowser, PlaywrightPage, type PlaywrightElement, } from './integrations/playwright.ts';
6
5
  interface HassOptions<E> {
7
- python: string;
8
6
  hassArgs: string[];
9
7
  host: string;
10
8
  port: number | null;
@@ -26,14 +24,14 @@ export declare class HomeAssistant<E> {
26
24
  private options;
27
25
  private dashboards;
28
26
  private entities;
29
- private started;
30
27
  ws: hass.Connection;
31
28
  private constructor();
32
29
  private path_confFile;
33
30
  private path_componentsDir;
34
31
  private path_wwwDir;
32
+ private path_storageDir;
35
33
  private path_hass;
36
- private path_pip;
34
+ private path_python;
37
35
  private path_cache;
38
36
  /** Create and connect to an isolated Home Assistant instance */
39
37
  static create<E>(config: string, options?: Partial<HassOptions<E>>): Promise<HomeAssistant<E>>;
@@ -41,23 +39,53 @@ export declare class HomeAssistant<E> {
41
39
  static connect<E>(options?: Partial<HassOptions<E>>): Promise<HomeAssistant<E>>;
42
40
  /** Start the Home Assistant server and connect to its websocket */
43
41
  private start;
44
- /** Write configuration.yaml */
45
- private writeYAMLConfiguration;
42
+ /** Write configuration.yaml, plus HTTP settings in whichever form this Home Assistant expects */
43
+ private writeConfiguration;
44
+ /**
45
+ * Newer Home Assistant versions keep HTTP settings in `.storage/http` and only import the
46
+ * `http:` YAML block once. That import is applied as an unconfirmed trial configuration,
47
+ * which pops up a confirmation dialog in the frontend and reverts (restarting Home
48
+ * Assistant) after 5 minutes. Detect these versions so we can skip the YAML entirely.
49
+ */
50
+ private usesHttpStorage;
51
+ /**
52
+ * Seed the HTTP config store so Home Assistant boots straight into our host and port.
53
+ * This uses the original (version 1) storage format, which Home Assistant migrates on load
54
+ * into a confirmed ("stable") config with all defaults filled in.
55
+ */
56
+ private writeHttpStorage;
57
+ /**
58
+ * Seed the onboarding store so the core config and analytics steps start out done. Finishing
59
+ * the core config step kicks off config flows for shopping_list, met, google_translate, and
60
+ * radio_browser, which are never needed for tests and log errors when Home Assistant is closed
61
+ * before they finish setting up. Storage version 2 predates both steps, so every Home Assistant
62
+ * release since then migrates this file by marking them done, leaving only the user and
63
+ * integration steps (which hand us auth codes) for onboard() to complete.
64
+ */
65
+ private writeOnboardingStorage;
46
66
  /** Symlink custom component directories to the configuration directory */
47
67
  private linkComponents;
48
68
  /** Wait for lockfile to become released. Forces HassTest instances to start up one at a time */
49
69
  private acquireLock;
50
70
  /** Find an open port to launch Home Assistant */
51
71
  private findPort;
52
- /** Creates a python virtual environment and installs Home Assistant */
72
+ /** Creates a python virtual environment and installs Home Assistant (using uv if available) */
73
+ private chooseInstaller;
53
74
  private setupVenv;
54
75
  private readCache;
55
- /** Fetch the latest hass version from pypi */
76
+ /** Fetch the latest hass version, and the Python versions it supports, from pypi */
56
77
  private latestHAVersion;
78
+ /** Path to the venv's site-packages directory */
79
+ private sitePackages;
57
80
  /** Finds the version of Home Assistant installed, if any */
58
81
  private hassVersion;
59
- /** Checks if Home Assistant is listening on its TCP port */
82
+ /** Checks if Home Assistant is serving the onboarding API, which onboard() starts with */
60
83
  private isUp;
84
+ /**
85
+ * Wait for Home Assistant to finish starting. Until then it has not installed its signal
86
+ * handlers, so close() would interrupt startup and log a KeyboardInterrupt traceback.
87
+ */
88
+ private waitUntilRunning;
61
89
  /** Complete onboarding and fetch short-lived access token */
62
90
  private onboard;
63
91
  private get url();
@@ -83,7 +111,7 @@ export declare class HomeAssistant<E> {
83
111
  link(): Promise<string>;
84
112
  openInBrowser(): Promise<void>;
85
113
  }>;
86
- states(): Promise<hass.HassEntities>;
114
+ states(): Promise<HassEntityStates>;
87
115
  /** Clean up connections and stop the HomeAssistant server */
88
116
  close(): Promise<void>;
89
117
  HassDashboard: {
@@ -98,14 +126,14 @@ export declare class HomeAssistant<E> {
98
126
  };
99
127
  }
100
128
  export declare class HassCard<E> {
129
+ private selectors;
101
130
  private n;
102
131
  private page;
103
- private selectors;
104
132
  constructor(n: number, page: BrowserPage<E>, selectors?: string[]);
105
133
  element(): Promise<E>;
106
134
  narrow(selector: string): HassCard<E>;
107
135
  html(options?: Partial<DiffOptions>): Promise<string>;
108
136
  text(): Promise<string>;
109
- screenshot(): Promise<Buffer>;
137
+ screenshot(): Promise<Buffer<ArrayBufferLike>>;
110
138
  }
111
139
  export declare function multiply(n: number, configFn: (i: number) => string): string;