refactor: Cache device information centrally (#1598)

This commit is contained in:
Dermot Duffy
2024-09-29 17:17:40 -07:00
committed by GitHub
parent 02fb6e1d4c
commit 9393722fa6
14 changed files with 281 additions and 93 deletions
+47 -45
View File
@@ -1,9 +1,10 @@
import { HassConfig } from 'home-assistant-js-websocket';
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
import { mock } from 'vitest-mock-extended';
import { getLanguage } from '../../src/localize/localize';
import { getDiagnostics, getReleaseVersion } from '../../src/utils/diagnostics.js';
import { getAllDevices } from '../../src/utils/ha/registry/device/index.js';
import { createHASS } from '../test-utils';
import { DeviceRegistryManager } from '../../src/utils/ha/registry/device';
import { createHASS, createRegistryDevice } from '../test-utils';
vi.mock('../../package.json', () => ({
default: {
@@ -34,18 +35,6 @@ describe('getDiagnostics', () => {
vi.mocked(getLanguage).mockReturnValue('en');
vi.stubGlobal('navigator', { userAgent: 'FrigateCardTest/1.0' });
vi.mocked(getAllDevices).mockResolvedValue([
{
id: 'id',
model: '4.0.0/0.13.0-aded314',
config_entries: [
'ac4e79d258449a83bc0cf6d47a021c46',
'b03e70c659d58ae2ce7f2dc76fed2929',
],
manufacturer: 'Frigate',
},
]);
});
afterEach(() => {
@@ -54,8 +43,27 @@ describe('getDiagnostics', () => {
});
it('should fetch diagnostics', async () => {
const deviceRegistryManager = mock<DeviceRegistryManager>();
deviceRegistryManager.getMatchingDevices.mockResolvedValue([
createRegistryDevice({
id: 'id1',
model: '4.0.0/0.13.0-aded314',
config_entries: ['ac4e79d258449a83bc0cf6d47a021c46'],
}),
createRegistryDevice({
id: 'id2',
model: '4.0.0/0.13.0-aded314',
config_entries: ['b03e70c659d58ae2ce7f2dc76fed2929'],
}),
createRegistryDevice({
id: 'no-model',
model: null,
config_entries: ['b03e70c659d58ae2ce7f2dc76fed2920'],
}),
]);
expect(
await getDiagnostics(hass, {
await getDiagnostics(hass, deviceRegistryManager, {
cameras: [{ camera_entity: 'camera.office' }],
}),
).toEqual({
@@ -80,6 +88,27 @@ describe('getDiagnostics', () => {
});
});
it('should use correct device registry matcher', async () => {
const deviceRegistryManager = mock<DeviceRegistryManager>();
deviceRegistryManager.getMatchingDevices.mockResolvedValue([]);
await getDiagnostics(hass, deviceRegistryManager, {
cameras: [{ camera_entity: 'camera.office' }],
});
// Verify the matcher passed into the deviceRegistryManager correctly filters
// Frigate cameras.
const matcher = deviceRegistryManager.getMatchingDevices.mock.calls[0][1];
expect(matcher(createRegistryDevice())).toBe(false);
expect(
matcher(
createRegistryDevice({
manufacturer: 'Frigate',
}),
),
).toBe(true);
});
it('should fetch diagnostics without hass or config', async () => {
expect(await getDiagnostics()).toEqual({
browser: 'FrigateCardTest/1.0',
@@ -96,37 +125,10 @@ describe('getDiagnostics', () => {
});
it('should fetch diagnostics without device model', async () => {
vi.mocked(getAllDevices).mockResolvedValue([
{
id: 'id',
model: null,
config_entries: [
'ac4e79d258449a83bc0cf6d47a021c46',
'b03e70c659d58ae2ce7f2dc76fed2929',
],
manufacturer: 'Frigate',
},
]);
const deviceRegistryManager = mock<DeviceRegistryManager>();
deviceRegistryManager.getMatchingDevices.mockResolvedValue([]);
expect(await getDiagnostics(hass)).toEqual({
browser: 'FrigateCardTest/1.0',
card_version: '__FRIGATE_CARD_RELEASE_VERSION__',
git: {
build_date: 'Tue, 19 Sep 2023 04:59:27 GMT',
commit_date: 'Wed, 6 Sep 2023 21:27:28 -0700',
hash: 'g4cf13b1',
},
ha_version: '2023.9.0',
date: now,
lang: 'en',
timezone: expect.anything(),
});
});
it('should fetch diagnostics if getAllDevices errors', async () => {
vi.mocked(getAllDevices).mockRejectedValue(new Error());
expect(await getDiagnostics(hass)).toEqual({
expect(await getDiagnostics(hass, deviceRegistryManager)).toEqual({
browser: 'FrigateCardTest/1.0',
card_version: '__FRIGATE_CARD_RELEASE_VERSION__',
git: {
@@ -0,0 +1,73 @@
import { afterEach, describe, expect, it, vi } from 'vitest';
import { homeAssistantWSRequest } from '../../../../../src/utils/ha';
import { createHASS, createRegistryDevice } from '../../../../test-utils.js';
import {
createDeviceRegistryCache,
DeviceRegistryManager,
} from '../../../../../src/utils/ha/registry/device';
vi.mock('../../../../../src/utils/ha');
vi.spyOn(global.console, 'warn').mockImplementation(() => true);
describe('DeviceRegistryManager', () => {
afterEach(() => {
vi.clearAllMocks();
});
describe('getDevice', () => {
it('should not fetch when cached', async () => {
const cache = createDeviceRegistryCache();
const testDevice = createRegistryDevice({ id: 'test' });
cache.add(testDevice);
const manager = new DeviceRegistryManager(cache);
expect(await manager.getDevice(createHASS(), 'test')).toEqual(testDevice);
expect(homeAssistantWSRequest).not.toHaveBeenCalled();
});
it('should fetch and cache when not cached', async () => {
const testDevice = createRegistryDevice({ id: 'test' });
const manager = new DeviceRegistryManager(createDeviceRegistryCache());
vi.mocked(homeAssistantWSRequest).mockResolvedValueOnce([testDevice]);
expect(await manager.getDevice(createHASS(), 'test')).toEqual(testDevice);
expect(homeAssistantWSRequest).toBeCalledTimes(1);
expect(await manager.getDevice(createHASS(), 'test')).toEqual(testDevice);
expect(homeAssistantWSRequest).toBeCalledTimes(1);
expect(await manager.getDevice(createHASS(), 'missing')).toBeNull();
// The fetch call is called exactly once.
expect(homeAssistantWSRequest).toBeCalledTimes(1);
});
it('should return null when fetch fails', async () => {
vi.mocked(homeAssistantWSRequest).mockRejectedValueOnce(new Error('Fetch error'));
const manager = new DeviceRegistryManager(createDeviceRegistryCache());
expect(await manager.getDevice(createHASS(), 'test')).toBeNull();
vi.mocked(expect(console.warn)).toBeCalledWith('Fetch error');
});
});
it('getMatchingDevices', async () => {
const matchingDevice = createRegistryDevice({ id: 'matching' });
const notMatchingDevice = createRegistryDevice({ id: 'not-matching' });
const hass = createHASS();
vi.mocked(homeAssistantWSRequest).mockResolvedValueOnce([
matchingDevice,
notMatchingDevice,
]);
const manager = new DeviceRegistryManager(createDeviceRegistryCache());
expect(
await manager.getMatchingDevices(hass, (entity) => entity.id == 'matching'),
).toEqual([matchingDevice]);
});
});
+38 -16
View File
@@ -7,6 +7,7 @@ import {
import { createHASS, createRegistryEntity } from '../../../../test-utils.js';
vi.mock('../../../../../src/utils/ha');
vi.spyOn(global.console, 'warn').mockImplementation(() => true);
describe('EntityRegistryManager', () => {
afterEach(() => {
@@ -44,10 +45,12 @@ describe('EntityRegistryManager', () => {
const manager = new EntityRegistryManager(createEntityRegistryCache());
expect(await manager.getEntity(createHASS(), 'missing')).toBeNull();
vi.mocked(expect(console.warn)).toBeCalledWith('Not found');
});
});
it('getEntities', () => {
it('getEntities', async () => {
const cachedEntity = createRegistryEntity({ entity_id: 'cached' });
const notCachedEntity = createRegistryEntity({ entity_id: 'not-cached' });
@@ -59,34 +62,53 @@ describe('EntityRegistryManager', () => {
vi.mocked(homeAssistantWSRequest).mockRejectedValueOnce(new Error('Not found'));
expect(
manager.getEntities(createHASS(), ['cached', 'not-cached', 'missing']),
).resolves.toEqual(
await manager.getEntities(createHASS(), ['cached', 'not-cached', 'missing']),
).toEqual(
new Map([
['cached', cachedEntity],
['not-cached', notCachedEntity],
]),
);
vi.mocked(expect(console.warn)).toBeCalledWith('Not found');
});
it('fetchEntityList', async () => {
const hass = createHASS();
const entity = createRegistryEntity({ entity_id: 'cached' });
vi.mocked(homeAssistantWSRequest).mockResolvedValueOnce([entity]);
describe('fetchEntityList', async () => {
it('should fetch entire entity list once', async () => {
const hass = createHASS();
const entity = createRegistryEntity({ entity_id: 'cached' });
vi.mocked(homeAssistantWSRequest).mockResolvedValueOnce([entity]);
const manager = new EntityRegistryManager(createEntityRegistryCache());
const manager = new EntityRegistryManager(createEntityRegistryCache());
await manager.fetchEntityList(hass);
await manager.fetchEntityList(hass);
expect(homeAssistantWSRequest).toBeCalledTimes(1);
expect(homeAssistantWSRequest).toBeCalledWith(expect.anything(), expect.anything(), {
type: 'config/entity_registry/list',
expect(homeAssistantWSRequest).toBeCalledTimes(1);
expect(homeAssistantWSRequest).toBeCalledWith(
expect.anything(),
expect.anything(),
{
type: 'config/entity_registry/list',
},
);
expect(await manager.getEntity(hass, 'cached')).toEqual(entity);
expect(homeAssistantWSRequest).toBeCalledTimes(1);
await manager.fetchEntityList(hass);
expect(homeAssistantWSRequest).toBeCalledTimes(1);
});
expect(await manager.getEntity(hass, 'cached')).toEqual(entity);
expect(homeAssistantWSRequest).toBeCalledTimes(1);
it('should log to console on error', async () => {
const hass = createHASS();
vi.mocked(homeAssistantWSRequest).mockRejectedValueOnce(new Error('Fetch error'));
await manager.fetchEntityList(hass);
expect(homeAssistantWSRequest).toBeCalledTimes(1);
const manager = new EntityRegistryManager(createEntityRegistryCache());
await manager.fetchEntityList(hass);
vi.mocked(expect(console.warn)).toBeCalledWith('Fetch error');
});
});
it('getMatchingEntities', async () => {