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/lib/hass-test.js DELETED
@@ -1,411 +0,0 @@
1
- "use strict";
2
- var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
3
- if (k2 === undefined) k2 = k;
4
- Object.defineProperty(o, k2, { enumerable: true, get: function() { return m[k]; } });
5
- }) : (function(o, m, k, k2) {
6
- if (k2 === undefined) k2 = k;
7
- o[k2] = m[k];
8
- }));
9
- var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {
10
- Object.defineProperty(o, "default", { enumerable: true, value: v });
11
- }) : function(o, v) {
12
- o["default"] = v;
13
- });
14
- var __importStar = (this && this.__importStar) || function (mod) {
15
- if (mod && mod.__esModule) return mod;
16
- var result = {};
17
- if (mod != null) for (var k in mod) if (k !== "default" && Object.prototype.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k);
18
- __setModuleDefault(result, mod);
19
- return result;
20
- };
21
- var __importDefault = (this && this.__importDefault) || function (mod) {
22
- return (mod && mod.__esModule) ? mod : { "default": mod };
23
- };
24
- Object.defineProperty(exports, "__esModule", { value: true });
25
- exports.multiply = exports.HassCard = void 0;
26
- const child_process_1 = require("child_process");
27
- const path_1 = require("path");
28
- const os_1 = require("os");
29
- const node_fetch_1 = __importDefault(require("node-fetch"));
30
- const fs = __importStar(require("fs/promises"));
31
- const net = __importStar(require("net"));
32
- const hass = __importStar(require("home-assistant-js-websocket"));
33
- const socket_1 = require("./socket");
34
- const proper_lockfile_1 = __importDefault(require("proper-lockfile"));
35
- /** Sleeps for 100 ms */
36
- const sleep = () => new Promise((r) => setTimeout(r, 100));
37
- const exec = (command, args) => new Promise((resolve, reject) => {
38
- const proc = child_process_1.spawn(command, args, { stdio: 'inherit' });
39
- proc.on('error', (err) => reject(err));
40
- proc.on('close', (code) => resolve(code));
41
- });
42
- class HassTest {
43
- config;
44
- venvDir;
45
- configDir;
46
- cache;
47
- chosenPort;
48
- process;
49
- accessCode;
50
- accessToken;
51
- options;
52
- dashboards = 0;
53
- ws;
54
- constructor(config, options) {
55
- this.config = config;
56
- this.venvDir = path_1.join(os_1.tmpdir(), 'hasstest-venv');
57
- this.options = {
58
- python: 'python3',
59
- hassArgs: [],
60
- host: '127.0.0.1',
61
- port: null,
62
- username: 'dev',
63
- password: 'dev',
64
- userLanguage: 'en',
65
- userDisplayName: 'Developer',
66
- customComponents: [],
67
- ...options,
68
- };
69
- }
70
- path_confFile = () => path_1.join(this.configDir, 'configuration.yaml');
71
- path_componentsDir = () => path_1.join(this.configDir, 'custom_components');
72
- path_wwwDir = () => path_1.join(this.configDir, 'www');
73
- path_hass = () => path_1.join(this.venvDir, 'bin/hass');
74
- path_pip = () => path_1.join(this.venvDir, 'bin/pip');
75
- path_cache = () => path_1.join(os_1.tmpdir(), 'hasstest-cache');
76
- /** Start the HomeAssistant server and connect to its websocket */
77
- async start() {
78
- this.configDir = await fs.mkdtemp(path_1.join(os_1.tmpdir(), 'hasstest-'));
79
- // Step 1: Create necessary directories
80
- await Promise.all([
81
- fs.mkdir(this.path_wwwDir()),
82
- fs.mkdir(this.path_componentsDir()).then(() => this.linkComponents()),
83
- ]);
84
- // Step 2: Create venv and sort out networking under lock
85
- const releaseLock = await this.acquireLock();
86
- this.cache = await this.readCache();
87
- await Promise.all([
88
- this.findPort().then(() => this.writeYAMLConfiguration()),
89
- this.setupVenv(),
90
- fs.writeFile(this.path_cache(), JSON.stringify(this.cache)),
91
- ]);
92
- await releaseLock();
93
- // Step 3: Start Home Assistant and onboard
94
- this.process = child_process_1.spawn(this.path_hass(), ['-c', this.configDir, ...this.options.hassArgs], {
95
- stdio: 'inherit',
96
- });
97
- while (!(await this.isUp()))
98
- await sleep();
99
- await this.onboard();
100
- }
101
- /** Write configuration.yaml */
102
- async writeYAMLConfiguration() {
103
- const config = [
104
- 'frontend:',
105
- 'http:',
106
- ` server_host: ${this.options.host}`,
107
- ` server_port: ${this.chosenPort}`,
108
- this.config,
109
- ].join('\n');
110
- fs.writeFile(this.path_confFile(), config);
111
- }
112
- /** Symlink custom component directories to the configuration directory */
113
- async linkComponents() {
114
- await Promise.all(this.options.customComponents.map((component) => fs.symlink(component, path_1.join(this.path_componentsDir(), path_1.basename(component)), 'junction')));
115
- }
116
- /** Wait for lockfile to become released. Forces HassTest instances to start up one at a time */
117
- async acquireLock() {
118
- for (let iterations = 0; iterations < 600; iterations++)
119
- try {
120
- return await proper_lockfile_1.default.lock(os_1.tmpdir(), { lockfilePath: 'hasstest.lock' });
121
- }
122
- catch (e) {
123
- if (e.code !== 'ELOCKED')
124
- throw e;
125
- await sleep();
126
- }
127
- throw new Error('Timed out waiting for lockfile');
128
- }
129
- /** Find an open port to launch Home Assistant */
130
- async findPort() {
131
- this.chosenPort = this.cache.startPort++;
132
- const server = net.createServer();
133
- server.listen(this.chosenPort, this.options.host);
134
- const success = await new Promise((resolve, reject) => {
135
- server.on('error', (e) => {
136
- if (e.code === 'EADDRINUSE' || e.code === 'EACCESS')
137
- resolve(false);
138
- else
139
- reject(e);
140
- });
141
- server.on('listening', () => {
142
- server.close();
143
- resolve(true);
144
- });
145
- });
146
- if (!success)
147
- await this.findPort();
148
- }
149
- /** Creates a python virtual environment and installs Home Assistant */
150
- async setupVenv() {
151
- // Create virtual environment if it does not already exist
152
- await fs
153
- .access(this.venvDir)
154
- .catch(() => exec(this.options.python, ['-m', 'venv', this.venvDir]));
155
- // Check if homeassistant needs an upgrade; saves a bit of time if it doesn't need one
156
- const installed = await this.hassVersion();
157
- if (!installed || installed !== this.cache.latestHass) {
158
- await exec(this.path_pip(), ['install', '--upgrade', 'homeassistant']);
159
- }
160
- }
161
- async readCache() {
162
- try {
163
- const versionFile = await fs.stat(this.path_cache());
164
- if (Date.now() - versionFile.mtimeMs < 2000) {
165
- return await JSON.parse(await fs.readFile(this.path_cache(), 'utf-8'));
166
- }
167
- }
168
- catch (e) { }
169
- return {
170
- latestHass: await this.latestHAVersion(),
171
- startPort: 8130,
172
- };
173
- }
174
- /** Fetch the latest hass version from online, caching for 2 minutes */
175
- async latestHAVersion() {
176
- const latest = await node_fetch_1.default('https://pypi.org/pypi/homeassistant/json').then((r) => r.json());
177
- return latest.info.version;
178
- }
179
- /** Finds the version of Home Assistant installed */
180
- async hassVersion() {
181
- const libFolders = await fs.readdir(path_1.join(this.venvDir, 'lib'));
182
- const libs = await Promise.all(libFolders.map((f) => fs.readdir(path_1.join(this.venvDir, 'lib', f, 'site-packages'))));
183
- const homeAssistant = libs
184
- .flat()
185
- .map((f) => f.match(/homeassistant-(.*)\.dist-info/))
186
- .find((f) => f !== null);
187
- return homeAssistant ? homeAssistant[1] : null;
188
- }
189
- /** Checks if Home Assistant is listening on its TCP port */
190
- isUp = () => new Promise((resolve) => {
191
- net.createConnection(this.chosenPort, this.options.host)
192
- .on('connect', () => resolve(true))
193
- .on('error', () => resolve(false));
194
- });
195
- /** Complete onboarding and fetch short-lived access token */
196
- async onboard() {
197
- const login = await this.post('/api/onboarding/users', {
198
- language: this.options.userLanguage,
199
- name: this.options.userDisplayName,
200
- username: this.options.username,
201
- password: this.options.password,
202
- });
203
- this.accessCode = login.auth_code;
204
- await this.launchWebsocket(this.accessCode);
205
- // Step through the onboarding pages
206
- await this.post('/api/onboarding/core_config', {}, true);
207
- await this.post('/api/onboarding/analytics', {}, true);
208
- const response = await this.post('/api/onboarding/integration', { redirect_uri: this.url + '/?auth_callback=1' }, true);
209
- this.accessCode = response.auth_code;
210
- }
211
- get url() {
212
- return `http://${this.options.host}:${this.chosenPort}`;
213
- }
214
- get clientId() {
215
- return this.url + '/';
216
- }
217
- get link() {
218
- return this.customDashboard('');
219
- }
220
- customDashboard(name, code = this.accessCode) {
221
- if (!code)
222
- throw new Error('You have not logged into Home Assistant yet. Have you called hasstest.start()?');
223
- const state = Buffer.from(JSON.stringify({ hassUrl: this.url, clientId: this.clientId })).toString('base64');
224
- return `${this.url}/${name}?auth_callback=1&code=${encodeURIComponent(code)}&state=${encodeURIComponent(state)}`;
225
- }
226
- async post(url, body, authorize = false) {
227
- const response = await node_fetch_1.default(this.url + url, {
228
- method: 'post',
229
- headers: {
230
- 'Content-Type': 'application/json',
231
- ...(authorize ? { Authorization: 'Bearer ' + this.accessToken } : undefined),
232
- },
233
- body: JSON.stringify({ client_id: this.clientId, ...body }),
234
- });
235
- return await response.json();
236
- }
237
- /** Fetch a access code from username and password */
238
- async fetchLoginCode() {
239
- const login = await this.post('/auth/login_flow', {
240
- handler: ['homeassistant', null],
241
- redirect_uri: this.url + '/?auth_callback=1',
242
- });
243
- const response = await this.post('/auth/login_flow/' + login.flow_id, {
244
- username: this.options.username,
245
- password: this.options.password,
246
- });
247
- return response.result;
248
- }
249
- /** Login and create tokens and websocket */
250
- async login() {
251
- this.accessCode = await this.fetchLoginCode();
252
- await this.launchWebsocket(this.accessCode);
253
- }
254
- async launchWebsocket(code) {
255
- const params = new URLSearchParams();
256
- params.append('client_id', this.clientId);
257
- params.append('code', code);
258
- params.append('grant_type', 'authorization_code');
259
- const response = await node_fetch_1.default(this.url + '/auth/token', {
260
- method: 'post',
261
- body: params,
262
- });
263
- const tokens = await response.json();
264
- this.accessToken = tokens.access_token;
265
- const auth = new hass.Auth({
266
- ...tokens,
267
- hassUrl: this.url,
268
- clientId: this.clientId,
269
- });
270
- this.ws = await hass.createConnection({
271
- auth,
272
- createSocket: async () => socket_1.createSocket(auth, false),
273
- });
274
- }
275
- async addIntegration(name) {
276
- const response = await this.post('/api/config/config_entries/flow', {
277
- handler: name,
278
- show_advanced_options: false,
279
- }, true);
280
- if (!response.result)
281
- throw new Error('Multi-step integration flows are not yet suppoted');
282
- return response.result;
283
- }
284
- async addResource(filename, resourceType) {
285
- if (resourceType === 'module') {
286
- await fs.copyFile(filename, path_1.join(this.path_wwwDir(), path_1.basename(filename)));
287
- }
288
- else {
289
- throw new Error('Only the module type is supported for now');
290
- }
291
- await this.ws.sendMessagePromise({
292
- type: 'lovelace/resources/create',
293
- res_type: resourceType,
294
- url: '/local/' + path_1.basename(filename),
295
- });
296
- }
297
- async createDashboard(options) {
298
- if (!this.ws)
299
- throw new Error('Hass-test has not yet been initialized. Did you call hass.start()?');
300
- const id = ++this.dashboards;
301
- const args = {
302
- type: 'lovelace/dashboards/create',
303
- url_path: `lovelace-${id}`,
304
- mode: 'storage',
305
- require_admin: false,
306
- show_in_sidebar: true,
307
- title: `Dashboard ${id}`,
308
- ...options,
309
- };
310
- await this.ws.sendMessagePromise(args);
311
- return args.url_path;
312
- }
313
- async setDashboardView(dashboard_path, config) {
314
- if (!this.ws)
315
- throw new Error('Hass-test has not yet been initialized. Did you call hass.start()?');
316
- await this.ws.sendMessagePromise({
317
- type: 'lovelace/config/save',
318
- url_path: dashboard_path,
319
- config: {
320
- title: 'View',
321
- views: [{ path: 'default_view', title: 'View', cards: config }],
322
- },
323
- });
324
- }
325
- async callService(domain, service, serviceData, target) {
326
- return await hass.callService(this.ws, domain, service, serviceData, target);
327
- }
328
- async Dashboard(config, options) {
329
- if (!this.options.integration)
330
- throw new Error('Cannot launch a dashboard without a browser integration. Make sure to specify options.integration');
331
- const dashboard = await this.createDashboard();
332
- await this.setDashboardView(dashboard, config);
333
- const code = await this.fetchLoginCode();
334
- const page = await this.options.integration.open(this.customDashboard(dashboard, code), options || {});
335
- return new this.HassDashboard(this, dashboard, config, page);
336
- }
337
- /** Clean up connections and stop the HomeAssistant server */
338
- async close() {
339
- if (this.options.integration)
340
- await this.options.integration.close();
341
- if (this.ws)
342
- this.ws.close();
343
- if (this.process) {
344
- this.process.kill('SIGINT');
345
- await new Promise((resolve) => this.process.on('exit', resolve));
346
- }
347
- if (this.configDir)
348
- await fs.rm(this.configDir, { recursive: true });
349
- }
350
- HassDashboard = class {
351
- parent;
352
- name;
353
- cards = [];
354
- constructor(parent, name, config, page) {
355
- this.parent = parent;
356
- this.name = name;
357
- for (let i = 0; i < config.length; i++) {
358
- this.cards.push(new HassCard(i, page));
359
- }
360
- }
361
- async link() {
362
- const code = await this.parent.fetchLoginCode();
363
- return this.parent.customDashboard(this.name, code);
364
- }
365
- async openInBrowser() {
366
- await this.parent.options.integration.openInHeaded(await this.link());
367
- }
368
- };
369
- }
370
- exports.default = HassTest;
371
- class HassCard {
372
- n;
373
- page;
374
- selectors;
375
- constructor(n, page, selectors) {
376
- this.n = n;
377
- this.page = page;
378
- this.selectors = selectors || [];
379
- }
380
- async element() {
381
- let el = await this.page.getNthCard(this.n);
382
- for (const sel of this.selectors) {
383
- const element = await this.page.find(el, sel);
384
- if (!element)
385
- throw new Error('Could not find selector ' + sel);
386
- el = element;
387
- }
388
- return el;
389
- }
390
- narrow(selector) {
391
- return new HassCard(this.n, this.page, [...this.selectors, selector]);
392
- }
393
- async html(options) {
394
- return await this.page.shadowHTML(await this.element(), options);
395
- }
396
- async text() {
397
- return (await this.page.textContent(await this.element())).trim();
398
- }
399
- async screenshot() {
400
- return await this.page.screenshot(await this.element());
401
- }
402
- }
403
- exports.HassCard = HassCard;
404
- function multiply(n, configFn) {
405
- let config = '';
406
- for (let i = 1; i <= n; i++) {
407
- config += configFn(i) + '\n';
408
- }
409
- return config;
410
- }
411
- exports.multiply = multiply;
@@ -1 +0,0 @@
1
- export {};
@@ -1,48 +0,0 @@
1
- "use strict";
2
- var __importDefault = (this && this.__importDefault) || function (mod) {
3
- return (mod && mod.__esModule) ? mod : { "default": mod };
4
- };
5
- Object.defineProperty(exports, "__esModule", { value: true });
6
- const hass_test_1 = __importDefault(require("./hass-test"));
7
- const playwright_1 = __importDefault(require("playwright"));
8
- // @ts-ignore
9
- const playwright_2 = require("./integrations/playwright");
10
- let browser;
11
- const hass = new hass_test_1.default(`
12
- input_number:
13
- slider1:
14
- name: Slider
15
- initial: 30
16
- min: -20
17
- max: 35
18
- step: 1
19
- `);
20
- (async () => {
21
- await hass.start();
22
- browser = await playwright_1.default.firefox.launch({ headless: false }); //, slowMo: 100 })
23
- const context = await browser.newContext();
24
- const page = await context.newPage();
25
- console.log('new page');
26
- page.on('console', msg => console.log(msg.text()));
27
- const dashboard = await hass.createDashboard();
28
- await hass.setDashboardView(dashboard, [
29
- { type: "entities", entities: ["binary_sensor.bedroom_occupancy", "binary_sensor.theater_room_occupancy", "binary_sensor.updater"], title: "Binary sensor" },
30
- { type: "thermostat", entity: "climate.upstairs" },
31
- { type: "entities", entities: ["sensor.bedroom_temperature", "sensor.theater_room_temperature", "sensor.upstairs_humidity", "sensor.upstairs_temperature"], title: "Sensor" }
32
- ]);
33
- console.log('created dashboard');
34
- await page.goto(hass.customDashboard(dashboard));
35
- try {
36
- const cards = await playwright_2.selectCards(page);
37
- console.log(cards);
38
- const html = await playwright_2.shadowHTML(page, cards[0]);
39
- console.log(html);
40
- }
41
- catch (e) {
42
- console.log(e);
43
- await new Promise(r => setTimeout(r, 500000));
44
- }
45
- await browser.close();
46
- })().finally(() => {
47
- return hass.close();
48
- });
package/lib/hasstest.d.ts DELETED
@@ -1,62 +0,0 @@
1
- import { Connection } from 'home-assistant-js-websocket';
2
- import { LovelaceDashboardCreateParams } from './types';
3
- import { BrowserIntegration, Page } from './types';
4
- interface HassTestOptions {
5
- python: string;
6
- hassArgs: string[];
7
- host: string;
8
- port: number;
9
- username: string;
10
- password: string;
11
- userLanguage: string;
12
- userDisplayName: string;
13
- integration?: BrowserIntegration;
14
- }
15
- export default class HassTest {
16
- private config;
17
- private venvDir;
18
- private configDir;
19
- private configFile;
20
- private process;
21
- private accessCode;
22
- private accessToken;
23
- private options;
24
- private dashboards;
25
- ws: Connection;
26
- constructor(config: string, options?: Partial<HassTestOptions>);
27
- /** Start the HomeAssistant server and connect to its websocket */
28
- start(): Promise<void>;
29
- /** Creates a python virtual environment and installs Home Assistant */
30
- private setupVenv;
31
- /** Checks if Home Assistant is listening on its TCP port */
32
- private isUp;
33
- /** Complete onboarding and fetch short-lived access token */
34
- onboard(): Promise<void>;
35
- get url(): string;
36
- get clientId(): string;
37
- get dashboard(): string;
38
- customDashboard(name: string, code?: string): string;
39
- post(url: string, body: any, authorize?: boolean): Promise<any>;
40
- /** Fetch a access code from username and password */
41
- fetchLoginCode(): Promise<any>;
42
- /** Login and create tokens and websocket */
43
- login(): Promise<void>;
44
- launchWebsocket(code: string): Promise<void>;
45
- createDashboard(options?: Partial<LovelaceDashboardCreateParams>): Promise<string>;
46
- setDashboardView(dashboard_path: string, config: object[]): Promise<void>;
47
- Dashboard(config: object[]): Promise<HassDashboard>;
48
- /** Clean up connections and stop the HomeAssistant server */
49
- close(): Promise<void>;
50
- }
51
- export declare class HassDashboard {
52
- private parent;
53
- cards: HassCard[];
54
- constructor(parent: HassTest, config: object[], page: Page);
55
- }
56
- export declare class HassCard {
57
- private n;
58
- private page;
59
- constructor(n: number, page: Page);
60
- html(): Promise<string>;
61
- }
62
- export {};