feat: Add hardened error handling and retries (#2451)
- Closes #1830 - Closes #2099
This commit is contained in:
committed by
dermotduffy
parent
4bc787e2b7
commit
47bcce93d3
@@ -5,6 +5,11 @@ import { Camera } from '../../src/camera-manager/camera.js';
|
||||
import { Capabilities } from '../../src/camera-manager/capabilities.js';
|
||||
import { CameraManagerEngineFactory } from '../../src/camera-manager/engine-factory.js';
|
||||
import { CameraManagerEngine } from '../../src/camera-manager/engine.js';
|
||||
import {
|
||||
CameraDuplicateIDError,
|
||||
CameraNoEngineError,
|
||||
CameraNoIDError,
|
||||
} from '../../src/camera-manager/error.js';
|
||||
import {
|
||||
CameraManager,
|
||||
CameraQueryClassifier,
|
||||
@@ -314,7 +319,7 @@ describe('CameraManager', () => {
|
||||
vi.clearAllMocks();
|
||||
});
|
||||
|
||||
it('successfully', async () => {
|
||||
it('should succeed', async () => {
|
||||
const api = createCardAPI();
|
||||
vi.mocked(api.getHASSManager().getHASS).mockReturnValue(createHASS());
|
||||
const manager = createCameraManager(api);
|
||||
@@ -324,14 +329,14 @@ describe('CameraManager', () => {
|
||||
expect(manager.isInitialized()).toBeTruthy();
|
||||
});
|
||||
|
||||
it('without hass', async () => {
|
||||
it('should handle missing hass', async () => {
|
||||
const manager = createCameraManager(createCardAPI());
|
||||
|
||||
await manager.initializeCamerasFromConfig();
|
||||
expect(manager.getStore().getCameraCount()).toBe(0);
|
||||
});
|
||||
|
||||
it('without a config', async () => {
|
||||
it('should handle missing config', async () => {
|
||||
const api = createCardAPI();
|
||||
vi.mocked(api.getConfigManager().getConfig).mockReturnValue(null);
|
||||
|
||||
@@ -341,7 +346,7 @@ describe('CameraManager', () => {
|
||||
expect(manager.getStore().getCameraCount()).toBe(0);
|
||||
});
|
||||
|
||||
it('without cameras in config', async () => {
|
||||
it('should handle missing cameras in config', async () => {
|
||||
const api = createCardAPI();
|
||||
vi.mocked(api.getHASSManager().getHASS).mockReturnValue(createHASS());
|
||||
vi.mocked(api.getConfigManager().getConfig).mockReturnValue(
|
||||
@@ -356,7 +361,7 @@ describe('CameraManager', () => {
|
||||
expect(manager.getStore().getCameraCount()).toBe(0);
|
||||
});
|
||||
|
||||
it('without an id', async () => {
|
||||
it('should reject missing id', async () => {
|
||||
const api = createCardAPI();
|
||||
vi.mocked(api.getHASSManager().getHASS).mockReturnValue(createHASS());
|
||||
|
||||
@@ -368,17 +373,12 @@ describe('CameraManager', () => {
|
||||
}),
|
||||
},
|
||||
]);
|
||||
expect(await manager.initializeCamerasFromConfig()).toBeFalsy();
|
||||
expect(api.getMessageManager().setErrorIfHigherPriority).toBeCalledWith(
|
||||
new Error(
|
||||
'Could not determine camera id for the following camera, ' +
|
||||
"may need to set 'id' parameter manually",
|
||||
),
|
||||
'Camera initialization failed',
|
||||
await expect(manager.initializeCamerasFromConfig()).rejects.toThrow(
|
||||
CameraNoIDError,
|
||||
);
|
||||
});
|
||||
|
||||
it('with a duplicate id', async () => {
|
||||
it('should reject duplicate id', async () => {
|
||||
const api = createCardAPI();
|
||||
vi.mocked(api.getHASSManager().getHASS).mockReturnValue(createHASS());
|
||||
|
||||
@@ -394,17 +394,12 @@ describe('CameraManager', () => {
|
||||
config: cameraConfig,
|
||||
},
|
||||
]);
|
||||
expect(await manager.initializeCamerasFromConfig()).toBeFalsy();
|
||||
expect(api.getMessageManager().setErrorIfHigherPriority).toBeCalledWith(
|
||||
new Error(
|
||||
'Duplicate camera id for the following camera, ' +
|
||||
"use the 'id' parameter to uniquely identify cameras",
|
||||
),
|
||||
'Camera initialization failed',
|
||||
await expect(manager.initializeCamerasFromConfig()).rejects.toThrow(
|
||||
CameraDuplicateIDError,
|
||||
);
|
||||
});
|
||||
|
||||
it('with no engine', async () => {
|
||||
it('should reject missing engine', async () => {
|
||||
const api = createCardAPI();
|
||||
vi.mocked(api.getHASSManager().getHASS).mockReturnValue(createHASS());
|
||||
|
||||
@@ -416,10 +411,8 @@ describe('CameraManager', () => {
|
||||
engineType: null,
|
||||
},
|
||||
]);
|
||||
expect(await manager.initializeCamerasFromConfig()).toBeFalsy();
|
||||
expect(api.getMessageManager().setErrorIfHigherPriority).toBeCalledWith(
|
||||
new Error('Could not determine suitable engine for camera'),
|
||||
'Camera initialization failed',
|
||||
await expect(manager.initializeCamerasFromConfig()).rejects.toThrow(
|
||||
CameraNoEngineError,
|
||||
);
|
||||
});
|
||||
|
||||
@@ -434,7 +427,7 @@ describe('CameraManager', () => {
|
||||
[{}],
|
||||
factory,
|
||||
);
|
||||
expect(await manager.initializeCamerasFromConfig()).toBeTruthy();
|
||||
await manager.initializeCamerasFromConfig();
|
||||
const eventCallback = factory.createEngine.mock.calls[0][1].eventCallback;
|
||||
|
||||
const cameraEvent: CameraEvent = {
|
||||
@@ -447,7 +440,7 @@ describe('CameraManager', () => {
|
||||
});
|
||||
|
||||
describe('should fetch entity list when required', () => {
|
||||
it('with entity based trigger', async () => {
|
||||
it('should fetch with entity based trigger', async () => {
|
||||
const api = createCardAPI();
|
||||
vi.mocked(api.getHASSManager().getHASS).mockReturnValue(createHASS());
|
||||
|
||||
@@ -462,17 +455,17 @@ describe('CameraManager', () => {
|
||||
},
|
||||
]);
|
||||
|
||||
expect(await manager.initializeCamerasFromConfig()).toBeTruthy();
|
||||
await manager.initializeCamerasFromConfig();
|
||||
expect(api.getEntityRegistryManager().fetchEntityList).toBeCalled();
|
||||
});
|
||||
|
||||
it('without entity based trigger', async () => {
|
||||
it('should skip without entity based trigger', async () => {
|
||||
const api = createCardAPI();
|
||||
vi.mocked(api.getHASSManager().getHASS).mockReturnValue(createHASS());
|
||||
|
||||
const manager = createCameraManager(api);
|
||||
|
||||
expect(await manager.initializeCamerasFromConfig()).toBeTruthy();
|
||||
await manager.initializeCamerasFromConfig();
|
||||
expect(api.getEntityRegistryManager().fetchEntityList).not.toBeCalled();
|
||||
});
|
||||
});
|
||||
@@ -511,7 +504,7 @@ describe('CameraManager', () => {
|
||||
|
||||
const engine = mock<CameraManagerEngine>();
|
||||
const manager = createCameraManager(api, engine);
|
||||
expect(await manager.initializeCamerasFromConfig()).toBeTruthy();
|
||||
await manager.initializeCamerasFromConfig();
|
||||
|
||||
const queries = [{ type: queryType, cameraIDs: new Set(['id']) }];
|
||||
engine[engineMethodName].mockReturnValue(queries);
|
||||
@@ -519,7 +512,7 @@ describe('CameraManager', () => {
|
||||
},
|
||||
);
|
||||
|
||||
it('without camera', async () => {
|
||||
it('should handle missing camera', async () => {
|
||||
const api = createCardAPI();
|
||||
vi.mocked(api.getHASSManager().getHASS).mockReturnValue(createHASS());
|
||||
|
||||
@@ -528,13 +521,13 @@ describe('CameraManager', () => {
|
||||
expect(manager.generateDefaultEventQueries('not_a_camera')).toBeNull();
|
||||
});
|
||||
|
||||
it('without queries', async () => {
|
||||
it('should handle missing queries', async () => {
|
||||
const api = createCardAPI();
|
||||
vi.mocked(api.getHASSManager().getHASS).mockReturnValue(createHASS());
|
||||
|
||||
const engine = mock<CameraManagerEngine>();
|
||||
const manager = createCameraManager(api, engine);
|
||||
expect(await manager.initializeCamerasFromConfig()).toBeTruthy();
|
||||
await manager.initializeCamerasFromConfig();
|
||||
|
||||
engine.generateDefaultEventQuery.mockReturnValue(null);
|
||||
expect(manager.generateDefaultEventQueries('id')).toBeNull();
|
||||
@@ -559,7 +552,7 @@ describe('CameraManager', () => {
|
||||
|
||||
const engine = mock<CameraManagerEngine>();
|
||||
const manager = createCameraManager(api, engine);
|
||||
expect(await manager.initializeCamerasFromConfig()).toBeTruthy();
|
||||
await manager.initializeCamerasFromConfig();
|
||||
|
||||
engine.getDefaultQueryParameters.mockReturnValue({ what: new Set(['person']) });
|
||||
expect(manager.getDefaultQueryParameters('id', QueryType.Event)).toEqual({
|
||||
@@ -583,7 +576,7 @@ describe('CameraManager', () => {
|
||||
}),
|
||||
},
|
||||
]);
|
||||
expect(await manager.initializeCamerasFromConfig()).toBeTruthy();
|
||||
await manager.initializeCamerasFromConfig();
|
||||
expect(manager.getStore().getCamera('id')?.getConfig().triggers.events).toEqual([
|
||||
'snapshots',
|
||||
]);
|
||||
@@ -596,13 +589,13 @@ describe('CameraManager', () => {
|
||||
cameraIDs: new Set('id'),
|
||||
};
|
||||
|
||||
it('with nothing', async () => {
|
||||
it('should handle empty metadata', async () => {
|
||||
const api = createCardAPI();
|
||||
vi.mocked(api.getHASSManager().getHASS).mockReturnValue(createHASS());
|
||||
|
||||
const engine = mock<CameraManagerEngine>();
|
||||
const manager = createCameraManager(api, engine);
|
||||
expect(await manager.initializeCamerasFromConfig()).toBeTruthy();
|
||||
await manager.initializeCamerasFromConfig();
|
||||
|
||||
const queryResults = {
|
||||
type: QueryResultsType.MediaMetadata as const,
|
||||
@@ -622,7 +615,7 @@ describe('CameraManager', () => {
|
||||
|
||||
const engine = mock<CameraManagerEngine>();
|
||||
const manager = createCameraManager(api, engine);
|
||||
expect(await manager.initializeCamerasFromConfig()).toBeTruthy();
|
||||
await manager.initializeCamerasFromConfig();
|
||||
|
||||
const metadata: MediaMetadata = {
|
||||
[metadataType]: new Set(['data']),
|
||||
@@ -640,12 +633,12 @@ describe('CameraManager', () => {
|
||||
});
|
||||
|
||||
describe('should get events', () => {
|
||||
it('without hass', async () => {
|
||||
it('should handle missing hass', async () => {
|
||||
const manager = createCameraManager(createCardAPI());
|
||||
expect(await manager.getEvents(baseEventQuery)).toEqual(new Map());
|
||||
});
|
||||
|
||||
it('without cameras', async () => {
|
||||
it('should handle missing cameras', async () => {
|
||||
const api = createCardAPI();
|
||||
const hass = createHASS();
|
||||
vi.mocked(api.getHASSManager().getHASS).mockReturnValue(hass);
|
||||
@@ -654,14 +647,14 @@ describe('CameraManager', () => {
|
||||
expect(await manager.getEvents(baseEventQuery)).toEqual(new Map());
|
||||
});
|
||||
|
||||
it('successfully', async () => {
|
||||
it('should succeed', async () => {
|
||||
const api = createCardAPI();
|
||||
const hass = createHASS();
|
||||
vi.mocked(api.getHASSManager().getHASS).mockReturnValue(hass);
|
||||
|
||||
const engine = mock<CameraManagerEngine>();
|
||||
const manager = createCameraManager(api, engine);
|
||||
expect(await manager.initializeCamerasFromConfig()).toBeTruthy();
|
||||
await manager.initializeCamerasFromConfig();
|
||||
|
||||
const engineOptions = {};
|
||||
const results = new Map([[baseEventQuery, baseEventQueryResults]]);
|
||||
@@ -677,7 +670,7 @@ describe('CameraManager', () => {
|
||||
});
|
||||
|
||||
describe('should review media', () => {
|
||||
it('without camera', async () => {
|
||||
it('should handle missing camera', async () => {
|
||||
const api = createCardAPI();
|
||||
vi.mocked(api.getHASSManager().getHASS).mockReturnValue(createHASS());
|
||||
const manager = createCameraManager(api);
|
||||
@@ -686,7 +679,7 @@ describe('CameraManager', () => {
|
||||
await manager.reviewMedia(media, true);
|
||||
});
|
||||
|
||||
it('successfully', async () => {
|
||||
it('should succeed', async () => {
|
||||
const api = createCardAPI();
|
||||
const hass = createHASS();
|
||||
vi.mocked(api.getHASSManager().getHASS).mockReturnValue(hass);
|
||||
@@ -695,7 +688,7 @@ describe('CameraManager', () => {
|
||||
vi.mocked(engine.getEngineType).mockReturnValue(Engine.Generic);
|
||||
|
||||
const manager = createCameraManager(api, engine);
|
||||
expect(await manager.initializeCamerasFromConfig()).toBeTruthy();
|
||||
await manager.initializeCamerasFromConfig();
|
||||
const media = new TestViewMedia({ cameraID: 'id' });
|
||||
|
||||
await manager.reviewMedia(media, true);
|
||||
@@ -705,14 +698,14 @@ describe('CameraManager', () => {
|
||||
});
|
||||
|
||||
describe('should get recordings', () => {
|
||||
it('successfully', async () => {
|
||||
it('should succeed', async () => {
|
||||
const api = createCardAPI();
|
||||
const hass = createHASS();
|
||||
vi.mocked(api.getHASSManager().getHASS).mockReturnValue(hass);
|
||||
|
||||
const engine = mock<CameraManagerEngine>();
|
||||
const manager = createCameraManager(api, engine);
|
||||
expect(await manager.initializeCamerasFromConfig()).toBeTruthy();
|
||||
await manager.initializeCamerasFromConfig();
|
||||
|
||||
const engineOptions = {};
|
||||
const results = new Map([[baseRecordingQuery, baseRecordingQueryResults]]);
|
||||
@@ -737,14 +730,14 @@ describe('CameraManager', () => {
|
||||
segments: [],
|
||||
};
|
||||
|
||||
it('successfully', async () => {
|
||||
it('should succeed', async () => {
|
||||
const api = createCardAPI();
|
||||
const hass = createHASS();
|
||||
vi.mocked(api.getHASSManager().getHASS).mockReturnValue(hass);
|
||||
|
||||
const engine = mock<CameraManagerEngine>();
|
||||
const manager = createCameraManager(api, engine);
|
||||
expect(await manager.initializeCamerasFromConfig()).toBeTruthy();
|
||||
await manager.initializeCamerasFromConfig();
|
||||
|
||||
const engineOptions = {};
|
||||
const results = new Map([[query, queryResults]]);
|
||||
@@ -754,7 +747,7 @@ describe('CameraManager', () => {
|
||||
});
|
||||
|
||||
describe('should execute media queries', () => {
|
||||
it('events', async () => {
|
||||
it('should handle events', async () => {
|
||||
const api = createCardAPI();
|
||||
const hass = createHASS();
|
||||
vi.mocked(api.getHASSManager().getHASS).mockReturnValue(hass);
|
||||
@@ -763,7 +756,7 @@ describe('CameraManager', () => {
|
||||
vi.mocked(engine.getEngineType).mockReturnValue(Engine.Generic);
|
||||
|
||||
const manager = createCameraManager(api, engine);
|
||||
expect(await manager.initializeCamerasFromConfig()).toBeTruthy();
|
||||
await manager.initializeCamerasFromConfig();
|
||||
|
||||
const results = new Map([[baseEventQuery, baseEventQueryResults]]);
|
||||
engine.getEvents.mockResolvedValue(results);
|
||||
@@ -773,7 +766,7 @@ describe('CameraManager', () => {
|
||||
expect(await manager.executeMediaQueries([baseEventQuery])).toEqual(media);
|
||||
});
|
||||
|
||||
it('no converted media', async () => {
|
||||
it('should handle no converted media', async () => {
|
||||
const api = createCardAPI();
|
||||
const hass = createHASS();
|
||||
vi.mocked(api.getHASSManager().getHASS).mockReturnValue(hass);
|
||||
@@ -782,7 +775,7 @@ describe('CameraManager', () => {
|
||||
vi.mocked(engine.getEngineType).mockReturnValue(Engine.Generic);
|
||||
|
||||
const manager = createCameraManager(api, engine);
|
||||
expect(await manager.initializeCamerasFromConfig()).toBeTruthy();
|
||||
await manager.initializeCamerasFromConfig();
|
||||
|
||||
const results = new Map([[baseEventQuery, baseEventQueryResults]]);
|
||||
engine.getEvents.mockResolvedValue(results);
|
||||
@@ -791,7 +784,7 @@ describe('CameraManager', () => {
|
||||
expect(await manager.executeMediaQueries([baseEventQuery])).toEqual([]);
|
||||
});
|
||||
|
||||
it('without matching camera engine during conversion', async () => {
|
||||
it('should handle missing camera engine during conversion', async () => {
|
||||
const api = createCardAPI();
|
||||
const hass = createHASS();
|
||||
vi.mocked(api.getHASSManager().getHASS).mockReturnValue(hass);
|
||||
@@ -800,7 +793,7 @@ describe('CameraManager', () => {
|
||||
vi.mocked(engine.getEngineType).mockReturnValue(Engine.Generic);
|
||||
|
||||
const manager = createCameraManager(api, engine);
|
||||
expect(await manager.initializeCamerasFromConfig()).toBeTruthy();
|
||||
await manager.initializeCamerasFromConfig();
|
||||
|
||||
const results = new Map([
|
||||
[baseEventQuery, { ...baseEventQueryResults, engine: Engine.MotionEye }],
|
||||
@@ -810,7 +803,7 @@ describe('CameraManager', () => {
|
||||
expect(await manager.executeMediaQueries([baseEventQuery])).toEqual([]);
|
||||
});
|
||||
|
||||
it('recordings', async () => {
|
||||
it('should handle recordings', async () => {
|
||||
const api = createCardAPI();
|
||||
const hass = createHASS();
|
||||
vi.mocked(api.getHASSManager().getHASS).mockReturnValue(hass);
|
||||
@@ -819,7 +812,7 @@ describe('CameraManager', () => {
|
||||
vi.mocked(engine.getEngineType).mockReturnValue(Engine.Generic);
|
||||
|
||||
const manager = createCameraManager(api, engine);
|
||||
expect(await manager.initializeCamerasFromConfig()).toBeTruthy();
|
||||
await manager.initializeCamerasFromConfig();
|
||||
|
||||
const results = new Map([[baseRecordingQuery, baseRecordingQueryResults]]);
|
||||
engine.getRecordings.mockResolvedValue(results);
|
||||
@@ -829,7 +822,7 @@ describe('CameraManager', () => {
|
||||
expect(await manager.executeMediaQueries([baseRecordingQuery])).toEqual(media);
|
||||
});
|
||||
|
||||
it('without hass', async () => {
|
||||
it('should handle missing hass', async () => {
|
||||
const engine = mock<CameraManagerEngine>();
|
||||
vi.mocked(engine.getEngineType).mockReturnValue(Engine.Generic);
|
||||
|
||||
@@ -841,7 +834,7 @@ describe('CameraManager', () => {
|
||||
});
|
||||
|
||||
describe('should merge compatible queries', () => {
|
||||
it('merges queries with identical properties', async () => {
|
||||
it('should merge queries with identical properties', async () => {
|
||||
const api = createCardAPI();
|
||||
const engine = mock<CameraManagerEngine>();
|
||||
vi.mocked(engine.getEngineType).mockReturnValue(Engine.Generic);
|
||||
@@ -851,7 +844,7 @@ describe('CameraManager', () => {
|
||||
{ config: createCameraConfig({ ...baseCameraConfig, id: 'cam1' }) },
|
||||
{ config: createCameraConfig({ ...baseCameraConfig, id: 'cam2' }) },
|
||||
]);
|
||||
expect(await manager.initializeCamerasFromConfig()).toBeTruthy();
|
||||
await manager.initializeCamerasFromConfig();
|
||||
|
||||
const query1: EventQuery = {
|
||||
source: QuerySource.Camera,
|
||||
@@ -884,7 +877,7 @@ describe('CameraManager', () => {
|
||||
);
|
||||
});
|
||||
|
||||
it('does not merge queries with different properties', async () => {
|
||||
it('should not merge queries with different properties', async () => {
|
||||
const api = createCardAPI();
|
||||
const engine = mock<CameraManagerEngine>();
|
||||
vi.mocked(engine.getEngineType).mockReturnValue(Engine.Generic);
|
||||
@@ -894,7 +887,7 @@ describe('CameraManager', () => {
|
||||
{ config: createCameraConfig({ ...baseCameraConfig, id: 'cam1' }) },
|
||||
{ config: createCameraConfig({ ...baseCameraConfig, id: 'cam2' }) },
|
||||
]);
|
||||
expect(await manager.initializeCamerasFromConfig()).toBeTruthy();
|
||||
await manager.initializeCamerasFromConfig();
|
||||
|
||||
const query1: EventQuery = {
|
||||
source: QuerySource.Camera,
|
||||
@@ -918,14 +911,14 @@ describe('CameraManager', () => {
|
||||
expect(engine.getEvents).toHaveBeenCalledTimes(2);
|
||||
});
|
||||
|
||||
it('handles single query without merging', async () => {
|
||||
it('should handle single query without merging', async () => {
|
||||
const api = createCardAPI();
|
||||
const engine = mock<CameraManagerEngine>();
|
||||
vi.mocked(engine.getEngineType).mockReturnValue(Engine.Generic);
|
||||
vi.mocked(api.getHASSManager().getHASS).mockReturnValue(createHASS());
|
||||
|
||||
const manager = createCameraManager(api, engine);
|
||||
expect(await manager.initializeCamerasFromConfig()).toBeTruthy();
|
||||
await manager.initializeCamerasFromConfig();
|
||||
|
||||
engine.getEvents.mockResolvedValue(
|
||||
new Map([[baseEventQuery, baseEventQueryResults]]),
|
||||
@@ -961,7 +954,7 @@ describe('CameraManager', () => {
|
||||
new ViewFolder(createFolder(), []),
|
||||
];
|
||||
|
||||
it('without hass', async () => {
|
||||
it('should handle missing hass', async () => {
|
||||
const engine = mock<CameraManagerEngine>();
|
||||
vi.mocked(engine.getEngineType).mockReturnValue(Engine.Generic);
|
||||
|
||||
@@ -1076,7 +1069,7 @@ describe('CameraManager', () => {
|
||||
vi.mocked(api.getHASSManager().getHASS).mockReturnValue(createHASS());
|
||||
|
||||
const manager = createCameraManager(api, engine);
|
||||
expect(await manager.initializeCamerasFromConfig()).toBeTruthy();
|
||||
await manager.initializeCamerasFromConfig();
|
||||
|
||||
engine.getEvents.mockResolvedValue(inputQueries);
|
||||
engine.generateMediaFromEvents.mockReturnValue(outputMediaResults);
|
||||
@@ -1103,28 +1096,28 @@ describe('CameraManager', () => {
|
||||
});
|
||||
|
||||
describe('should get media download path', () => {
|
||||
it('without camera', async () => {
|
||||
it('should handle missing camera', async () => {
|
||||
const manager = createCameraManager(createCardAPI());
|
||||
expect(await manager.getMediaDownloadPath(new TestViewMedia())).toBeNull();
|
||||
});
|
||||
|
||||
it('without hass', async () => {
|
||||
it('should handle missing hass', async () => {
|
||||
const api = createCardAPI();
|
||||
const manager = createCameraManager(api);
|
||||
vi.mocked(api.getHASSManager().getHASS).mockReturnValue(createHASS());
|
||||
expect(await manager.initializeCamerasFromConfig()).toBeTruthy();
|
||||
await manager.initializeCamerasFromConfig();
|
||||
|
||||
vi.mocked(api.getHASSManager().getHASS).mockReturnValue(null);
|
||||
expect(await manager.getMediaDownloadPath(new TestViewMedia())).toBeNull();
|
||||
});
|
||||
|
||||
it('successfully', async () => {
|
||||
it('should succeed', async () => {
|
||||
const api = createCardAPI();
|
||||
const engine = mock<CameraManagerEngine>();
|
||||
const manager = createCameraManager(api, engine);
|
||||
|
||||
vi.mocked(api.getHASSManager().getHASS).mockReturnValue(createHASS());
|
||||
expect(await manager.initializeCamerasFromConfig()).toBeTruthy();
|
||||
await manager.initializeCamerasFromConfig();
|
||||
|
||||
const result: Endpoint = {
|
||||
endpoint: 'http://localhost/path/to/media',
|
||||
@@ -1137,18 +1130,18 @@ describe('CameraManager', () => {
|
||||
});
|
||||
|
||||
describe('should get media capabilities', () => {
|
||||
it('without camera', async () => {
|
||||
it('should handle missing camera', async () => {
|
||||
const manager = createCameraManager(createCardAPI());
|
||||
expect(manager.getMediaCapabilities(new TestViewMedia())).toBeNull();
|
||||
});
|
||||
|
||||
it('successfully', async () => {
|
||||
it('should succeed', async () => {
|
||||
const api = createCardAPI();
|
||||
const engine = mock<CameraManagerEngine>();
|
||||
const manager = createCameraManager(api, engine);
|
||||
vi.mocked(api.getHASSManager().getHASS).mockReturnValue(createHASS());
|
||||
|
||||
expect(await manager.initializeCamerasFromConfig()).toBeTruthy();
|
||||
await manager.initializeCamerasFromConfig();
|
||||
|
||||
const result: ViewItemCapabilities = {
|
||||
canFavorite: false,
|
||||
@@ -1162,7 +1155,7 @@ describe('CameraManager', () => {
|
||||
});
|
||||
|
||||
describe('should favorite media', () => {
|
||||
it('without camera', async () => {
|
||||
it('should handle missing camera', async () => {
|
||||
const engine = mock<CameraManagerEngine>();
|
||||
const manager = createCameraManager(createCardAPI(), engine);
|
||||
manager.favoriteMedia(new TestViewMedia(), true);
|
||||
@@ -1170,7 +1163,7 @@ describe('CameraManager', () => {
|
||||
expect(engine.favoriteMedia).not.toBeCalled();
|
||||
});
|
||||
|
||||
it('successfully', async () => {
|
||||
it('should succeed', async () => {
|
||||
const api = createCardAPI();
|
||||
const engine = mock<CameraManagerEngine>();
|
||||
const manager = createCameraManager(api, engine);
|
||||
@@ -1178,7 +1171,7 @@ describe('CameraManager', () => {
|
||||
const hass = createHASS();
|
||||
vi.mocked(api.getHASSManager().getHASS).mockReturnValue(hass);
|
||||
|
||||
expect(await manager.initializeCamerasFromConfig()).toBeTruthy();
|
||||
await manager.initializeCamerasFromConfig();
|
||||
|
||||
const media = new TestViewMedia({ cameraID: 'id' });
|
||||
manager.favoriteMedia(media, true);
|
||||
@@ -1187,12 +1180,12 @@ describe('CameraManager', () => {
|
||||
});
|
||||
|
||||
describe('should get camera endpoints', () => {
|
||||
it('without camera', () => {
|
||||
it('should handle missing camera', () => {
|
||||
const manager = createCameraManager(createCardAPI());
|
||||
expect(manager.getCameraEndpoints('BAD')).toBeNull();
|
||||
});
|
||||
|
||||
it('successfully', async () => {
|
||||
it('should succeed', async () => {
|
||||
const api = createCardAPI();
|
||||
const engine = mock<CameraManagerEngine>();
|
||||
const manager = createCameraManager(api, engine);
|
||||
@@ -1200,19 +1193,19 @@ describe('CameraManager', () => {
|
||||
const hass = createHASS();
|
||||
vi.mocked(api.getHASSManager().getHASS).mockReturnValue(hass);
|
||||
|
||||
expect(await manager.initializeCamerasFromConfig()).toBeTruthy();
|
||||
await manager.initializeCamerasFromConfig();
|
||||
|
||||
expect(manager.getCameraEndpoints('id', { view: 'live' })).toBeDefined();
|
||||
});
|
||||
});
|
||||
|
||||
describe('should get camera metadata', () => {
|
||||
it('without camera', () => {
|
||||
it('should handle missing camera', () => {
|
||||
const manager = createCameraManager(createCardAPI());
|
||||
expect(manager.getCameraMetadata('BAD')).toBeNull();
|
||||
});
|
||||
|
||||
it('successfully', async () => {
|
||||
it('should succeed', async () => {
|
||||
const api = createCardAPI();
|
||||
const engine = mock<CameraManagerEngine>();
|
||||
const manager = createCameraManager(api, engine);
|
||||
@@ -1220,7 +1213,7 @@ describe('CameraManager', () => {
|
||||
const hass = createHASS();
|
||||
vi.mocked(api.getHASSManager().getHASS).mockReturnValue(hass);
|
||||
|
||||
expect(await manager.initializeCamerasFromConfig()).toBeTruthy();
|
||||
await manager.initializeCamerasFromConfig();
|
||||
|
||||
const result: CameraManagerCameraMetadata = {
|
||||
title: 'My Camera',
|
||||
@@ -1235,12 +1228,12 @@ describe('CameraManager', () => {
|
||||
});
|
||||
|
||||
describe('should get camera capabilities', () => {
|
||||
it('without camera', () => {
|
||||
it('should handle missing camera', () => {
|
||||
const manager = createCameraManager(createCardAPI());
|
||||
expect(manager.getCameraCapabilities('BAD')).toBeNull();
|
||||
});
|
||||
|
||||
it('successfully', async () => {
|
||||
it('should succeed', async () => {
|
||||
const api = createCardAPI();
|
||||
const engine = mock<CameraManagerEngine>();
|
||||
const manager = createCameraManager(api, engine);
|
||||
@@ -1248,13 +1241,13 @@ describe('CameraManager', () => {
|
||||
const hass = createHASS();
|
||||
vi.mocked(api.getHASSManager().getHASS).mockReturnValue(hass);
|
||||
|
||||
expect(await manager.initializeCamerasFromConfig()).toBeTruthy();
|
||||
await manager.initializeCamerasFromConfig();
|
||||
expect(manager.getCameraCapabilities('id')).toEqual(createCapabilities());
|
||||
});
|
||||
});
|
||||
|
||||
describe('should get aggregate camera capabilities', () => {
|
||||
it('without camera', () => {
|
||||
it('should handle missing camera', () => {
|
||||
const manager = createCameraManager(createCardAPI());
|
||||
const capabilities = manager.getAggregateCameraCapabilities();
|
||||
|
||||
@@ -1268,7 +1261,7 @@ describe('CameraManager', () => {
|
||||
expect(capabilities.has('snapshots')).toBeFalsy();
|
||||
});
|
||||
|
||||
it('successfully', async () => {
|
||||
it('should succeed', async () => {
|
||||
const api = createCardAPI();
|
||||
const manager = createCameraManager(api, mock<CameraManagerEngine>(), [
|
||||
{
|
||||
@@ -1303,7 +1296,7 @@ describe('CameraManager', () => {
|
||||
]);
|
||||
const hass = createHASS();
|
||||
vi.mocked(api.getHASSManager().getHASS).mockReturnValue(hass);
|
||||
expect(await manager.initializeCamerasFromConfig()).toBeTruthy();
|
||||
await manager.initializeCamerasFromConfig();
|
||||
|
||||
const capabilities = manager.getAggregateCameraCapabilities();
|
||||
|
||||
@@ -1319,7 +1312,7 @@ describe('CameraManager', () => {
|
||||
});
|
||||
|
||||
describe('should execute PTZ action', () => {
|
||||
it('without camera', () => {
|
||||
it('should handle missing camera', () => {
|
||||
const engine = mock<CameraManagerEngine>();
|
||||
const manager = createCameraManager(createCardAPI(), engine);
|
||||
|
||||
@@ -1328,7 +1321,7 @@ describe('CameraManager', () => {
|
||||
// No visible action.
|
||||
});
|
||||
|
||||
it('successfully with null hass', async () => {
|
||||
it('should succeed with null hass', async () => {
|
||||
const api = createCardAPI();
|
||||
const engine = mock<CameraManagerEngine>();
|
||||
const hass = createHASS();
|
||||
@@ -1348,7 +1341,7 @@ describe('CameraManager', () => {
|
||||
}),
|
||||
},
|
||||
]);
|
||||
expect(await manager.initializeCamerasFromConfig()).toBeTruthy();
|
||||
await manager.initializeCamerasFromConfig();
|
||||
|
||||
vi.mocked(api.getHASSManager().getHASS).mockReturnValue(null);
|
||||
manager.executePTZAction('another', 'left');
|
||||
@@ -1358,7 +1351,7 @@ describe('CameraManager', () => {
|
||||
});
|
||||
});
|
||||
|
||||
it('successfully', async () => {
|
||||
it('should succeed', async () => {
|
||||
const api = createCardAPI();
|
||||
const engine = mock<CameraManagerEngine>();
|
||||
const hass = createHASS();
|
||||
@@ -1378,7 +1371,7 @@ describe('CameraManager', () => {
|
||||
}),
|
||||
},
|
||||
]);
|
||||
expect(await manager.initializeCamerasFromConfig()).toBeTruthy();
|
||||
await manager.initializeCamerasFromConfig();
|
||||
|
||||
manager.executePTZAction('another', 'left');
|
||||
|
||||
@@ -1482,7 +1475,7 @@ describe('CameraManager', () => {
|
||||
}),
|
||||
},
|
||||
]);
|
||||
expect(await manager.initializeCamerasFromConfig()).toBeTruthy();
|
||||
await manager.initializeCamerasFromConfig();
|
||||
|
||||
manager.executePTZAction(
|
||||
'rotated-camera',
|
||||
@@ -1551,7 +1544,7 @@ describe('CameraManager', () => {
|
||||
vi.mocked(api.getHASSManager().getHASS).mockReturnValue(createHASS());
|
||||
const manager = createCameraManager(api, engine);
|
||||
|
||||
expect(await manager.initializeCamerasFromConfig()).toBeTruthy();
|
||||
await manager.initializeCamerasFromConfig();
|
||||
|
||||
engine.getQueryResultMaxAge.mockReturnValue(60);
|
||||
expect(manager.areMediaQueriesResultsFresh(resultsTimestamp, queries)).toBe(
|
||||
@@ -1586,7 +1579,7 @@ describe('CameraManager', () => {
|
||||
vi.mocked(api.getHASSManager().getHASS).mockReturnValue(createHASS());
|
||||
const manager = createCameraManager(api, engine);
|
||||
|
||||
expect(await manager.initializeCamerasFromConfig()).toBeTruthy();
|
||||
await manager.initializeCamerasFromConfig();
|
||||
|
||||
expect(
|
||||
await manager.getMediaSeekTime(
|
||||
@@ -1598,13 +1591,13 @@ describe('CameraManager', () => {
|
||||
);
|
||||
});
|
||||
|
||||
it('successfully', async () => {
|
||||
it('should succeed', async () => {
|
||||
const api = createCardAPI();
|
||||
const engine = mock<CameraManagerEngine>();
|
||||
vi.mocked(api.getHASSManager().getHASS).mockReturnValue(createHASS());
|
||||
const manager = createCameraManager(api, engine);
|
||||
|
||||
expect(await manager.initializeCamerasFromConfig()).toBeTruthy();
|
||||
await manager.initializeCamerasFromConfig();
|
||||
engine.getMediaSeekTime.mockResolvedValue(42);
|
||||
|
||||
const media = new TestViewMedia({
|
||||
@@ -1622,13 +1615,13 @@ describe('CameraManager', () => {
|
||||
);
|
||||
});
|
||||
|
||||
it('handles null return value', async () => {
|
||||
it('should handle null return value', async () => {
|
||||
const api = createCardAPI();
|
||||
const engine = mock<CameraManagerEngine>();
|
||||
vi.mocked(api.getHASSManager().getHASS).mockReturnValue(createHASS());
|
||||
const manager = createCameraManager(api, engine);
|
||||
|
||||
expect(await manager.initializeCamerasFromConfig()).toBeTruthy();
|
||||
await manager.initializeCamerasFromConfig();
|
||||
engine.getMediaSeekTime.mockResolvedValue(null);
|
||||
|
||||
const media = new TestViewMedia({
|
||||
@@ -1646,7 +1639,7 @@ describe('CameraManager', () => {
|
||||
vi.mocked(api.getHASSManager().getHASS).mockReturnValue(createHASS());
|
||||
const manager = createCameraManager(api, engine);
|
||||
|
||||
expect(await manager.initializeCamerasFromConfig()).toBeTruthy();
|
||||
await manager.initializeCamerasFromConfig();
|
||||
|
||||
expect(manager.getStore().getCameraCount()).toBe(1);
|
||||
|
||||
|
||||
@@ -68,12 +68,14 @@ describe('ActionsManager', () => {
|
||||
vi.restoreAllMocks();
|
||||
});
|
||||
|
||||
it('should get no merged actions with a message', () => {
|
||||
it('should get no merged actions with an issue', () => {
|
||||
const api = createCardAPI();
|
||||
vi.mocked(api.getViewManager().getView).mockReturnValue(
|
||||
createView({ view: 'live' }),
|
||||
);
|
||||
vi.mocked(api.getMessageManager().hasMessage).mockReturnValue(true);
|
||||
vi.mocked(
|
||||
api.getIssueManager().getStateManager().hasFullCardIssue,
|
||||
).mockReturnValue(true);
|
||||
|
||||
const manager = new ActionsManager(api);
|
||||
|
||||
|
||||
@@ -49,7 +49,7 @@ import { ActionConfig } from '../../../src/config/schema/actions/types';
|
||||
|
||||
// @vitest-environment jsdom
|
||||
describe('ActionFactory', () => {
|
||||
it('mismatched card-id', () => {
|
||||
it('should return null for mismatched card-id', () => {
|
||||
const factory = new ActionFactory();
|
||||
expect(
|
||||
factory.createAction(
|
||||
@@ -130,7 +130,7 @@ describe('ActionFactory', () => {
|
||||
[
|
||||
{
|
||||
advanced_camera_card_action: 'notification' as const,
|
||||
notification: { text: 'test' },
|
||||
notification: { body: { text: 'test' } },
|
||||
},
|
||||
NotificationAction,
|
||||
],
|
||||
|
||||
@@ -56,13 +56,15 @@ describe('AutomationsManager', () => {
|
||||
expect(api.getActionsManager().executeActions).not.toBeCalled();
|
||||
});
|
||||
|
||||
it('should do nothing with an error message present', () => {
|
||||
it('should do nothing when an issue is present', () => {
|
||||
const api = createCardAPI();
|
||||
vi.mocked(api.getHASSManager().hasHASS).mockReturnValue(true);
|
||||
vi.mocked(api.getInitializationManager().isInitializedMandatory).mockReturnValue(
|
||||
true,
|
||||
);
|
||||
vi.mocked(api.getMessageManager().hasErrorMessage).mockReturnValue(true);
|
||||
vi.mocked(
|
||||
api.getIssueManager().getStateManager().hasFullCardIssue,
|
||||
).mockReturnValue(true);
|
||||
|
||||
const stateManager = new ConditionStateManager();
|
||||
vi.mocked(api.getConditionStateManager).mockReturnValue(stateManager);
|
||||
@@ -159,13 +161,13 @@ describe('AutomationsManager', () => {
|
||||
|
||||
stateManager.setState({ fullscreen: fullscreen });
|
||||
|
||||
expect(api.getMessageManager().setMessageIfHigherPriority).toBeCalledWith(
|
||||
expect.objectContaining({
|
||||
type: 'error',
|
||||
message:
|
||||
'Too many nested automation calls, please check your configuration for loops',
|
||||
}),
|
||||
);
|
||||
expect(api.getNotificationManager().setNotification).toBeCalledWith({
|
||||
heading: {
|
||||
text: 'Too many nested automation calls, please check your configuration for loops',
|
||||
icon: 'mdi:alert',
|
||||
severity: 'high',
|
||||
},
|
||||
});
|
||||
|
||||
expect(api.getActionsManager().executeActions).toBeCalledTimes(10);
|
||||
});
|
||||
|
||||
@@ -75,12 +75,12 @@ describe('ConfigManager', () => {
|
||||
});
|
||||
|
||||
describe('should handle error when', () => {
|
||||
it('no input', () => {
|
||||
it('should handle no input', () => {
|
||||
const manager = new ConfigManager(createCardAPI());
|
||||
expect(() => manager.setConfig()).toThrowError(/Invalid configuration/);
|
||||
});
|
||||
|
||||
it('invalid configuration', () => {
|
||||
it('should handle invalid configuration', () => {
|
||||
const schemaForMock: z.ZodType = advancedCameraCardConfigSchema;
|
||||
const spy = vi
|
||||
.spyOn(schemaForMock, 'safeParse')
|
||||
@@ -94,14 +94,14 @@ describe('ConfigManager', () => {
|
||||
spy.mockRestore();
|
||||
});
|
||||
|
||||
it('invalid configuration with hint', () => {
|
||||
it('should handle invalid configuration with hint', () => {
|
||||
const manager = new ConfigManager(createCardAPI());
|
||||
expect(() => manager.setConfig({})).toThrowError(
|
||||
'Invalid configuration: [\n "type"\n]',
|
||||
);
|
||||
});
|
||||
|
||||
it('upgradeable', () => {
|
||||
it('should handle upgradeable config', () => {
|
||||
const manager = new ConfigManager(createCardAPI());
|
||||
expect(() =>
|
||||
manager.setConfig({
|
||||
@@ -150,9 +150,9 @@ describe('ConfigManager', () => {
|
||||
displayMode: undefined,
|
||||
camera: undefined,
|
||||
});
|
||||
expect(api.getIssueManager().reset).toBeCalledWith('config_error');
|
||||
expect(api.getMediaLoadedInfoManager().clear).toBeCalled();
|
||||
expect(api.getViewManager().reset).toBeCalled();
|
||||
expect(api.getMessageManager().reset).toBeCalled();
|
||||
expect(api.getAutomationsManager().addAutomations).toBeCalled();
|
||||
expect(api.getStyleManager().updateFromConfig).toBeCalled();
|
||||
expect(api.getCardElementManager().update).toBeCalled();
|
||||
@@ -327,13 +327,14 @@ describe('ConfigManager', () => {
|
||||
|
||||
stateManager.setState({ fullscreen: true });
|
||||
expect(manager.getConfig()).not.toBeNull();
|
||||
expect(api.getMessageManager().setErrorIfHigherPriority).toBeCalledWith(
|
||||
expect.objectContaining({ message: 'Invalid override configuration' }),
|
||||
expect(api.getIssueManager().trigger).toBeCalledWith(
|
||||
'config_error',
|
||||
expect.objectContaining({ error: expect.any(Error) }),
|
||||
);
|
||||
});
|
||||
|
||||
describe('should uninitialize on override', () => {
|
||||
it('cameras', () => {
|
||||
it('should uninitialize cameras', () => {
|
||||
const api = createCardAPI();
|
||||
const stateManager = new ConditionStateManager();
|
||||
vi.mocked(api.getConditionStateManager).mockReturnValue(stateManager);
|
||||
@@ -365,7 +366,7 @@ describe('ConfigManager', () => {
|
||||
);
|
||||
});
|
||||
|
||||
it('cameras_global', () => {
|
||||
it('should uninitialize cameras_global', () => {
|
||||
const api = createCardAPI();
|
||||
const stateManager = new ConditionStateManager();
|
||||
vi.mocked(api.getConditionStateManager).mockReturnValue(stateManager);
|
||||
@@ -397,7 +398,7 @@ describe('ConfigManager', () => {
|
||||
);
|
||||
});
|
||||
|
||||
it('live.microphone.always_connected', () => {
|
||||
it('should uninitialize live.microphone.always_connected', () => {
|
||||
const api = createCardAPI();
|
||||
const stateManager = new ConditionStateManager();
|
||||
vi.mocked(api.getConditionStateManager).mockReturnValue(stateManager);
|
||||
|
||||
@@ -39,6 +39,8 @@ describe('setFoldersFromConfig', () => {
|
||||
|
||||
setFoldersFromConfig(api);
|
||||
|
||||
expect(api.getMessageManager().setErrorIfHigherPriority).toBeCalledWith(error);
|
||||
expect(api.getIssueManager().trigger).toBeCalledWith('config_error', {
|
||||
error,
|
||||
});
|
||||
});
|
||||
});
|
||||
|
||||
@@ -1,6 +1,8 @@
|
||||
import { describe, expect, it, vi } from 'vitest';
|
||||
import { assert, describe, expect, it, vi } from 'vitest';
|
||||
import { OverridesManager } from '../../../src/card-controller/config/overrides-manager';
|
||||
import { AdvancedCameraCardConfig } from '../../../src/config/schema/types';
|
||||
import { ConditionStateManager } from '../../../src/conditions/state-manager';
|
||||
import { AdvancedCameraCardError } from '../../../src/types';
|
||||
import { createConfig } from '../../test-utils';
|
||||
|
||||
describe('OverridesManager', () => {
|
||||
@@ -316,30 +318,93 @@ describe('OverridesManager', () => {
|
||||
});
|
||||
});
|
||||
|
||||
it('should throw on invalid schema', () => {
|
||||
const config = createConfig({
|
||||
overrides: [
|
||||
{
|
||||
conditions: [
|
||||
{
|
||||
condition: 'fullscreen' as const,
|
||||
fullscreen: true,
|
||||
},
|
||||
],
|
||||
},
|
||||
],
|
||||
describe('should throw on invalid schema', () => {
|
||||
const runInvalidOverride = (
|
||||
mutate: (config: AdvancedCameraCardConfig) => void,
|
||||
): AdvancedCameraCardError => {
|
||||
const config = createConfig({
|
||||
overrides: [
|
||||
{
|
||||
conditions: [
|
||||
{
|
||||
condition: 'fullscreen' as const,
|
||||
fullscreen: true,
|
||||
},
|
||||
],
|
||||
},
|
||||
],
|
||||
});
|
||||
mutate(config);
|
||||
|
||||
const stateManager = new ConditionStateManager();
|
||||
stateManager.setState({ fullscreen: true });
|
||||
|
||||
const manager = new OverridesManager(vi.fn());
|
||||
manager.set(stateManager, config.overrides);
|
||||
|
||||
let thrown: unknown = null;
|
||||
try {
|
||||
manager.getConfig(config);
|
||||
} catch (e) {
|
||||
thrown = e;
|
||||
}
|
||||
assert(thrown instanceof AdvancedCameraCardError);
|
||||
return thrown;
|
||||
};
|
||||
|
||||
it('with `invalid_type` surfacing the attempted value', () => {
|
||||
const error = runInvalidOverride((config) => {
|
||||
assert(config.overrides);
|
||||
// @ts-expect-error — intentionally invalid runtime value to trigger
|
||||
// Zod's `invalid_type` issue code.
|
||||
config.overrides[0].merge = 6;
|
||||
});
|
||||
|
||||
expect(error.message).toMatch(/Invalid override configuration/);
|
||||
expect(error.context).toMatchObject({
|
||||
failures: expect.arrayContaining([
|
||||
expect.objectContaining({
|
||||
path: expect.any(String),
|
||||
expected: expect.anything(),
|
||||
}),
|
||||
]),
|
||||
});
|
||||
});
|
||||
config.overrides![0].merge = 6 as unknown as Record<string, unknown>;
|
||||
|
||||
const stateManager = new ConditionStateManager();
|
||||
stateManager.setState({ fullscreen: true });
|
||||
it('with `invalid_value` surfacing the allowed enum values', () => {
|
||||
const error = runInvalidOverride((config) => {
|
||||
assert(config.overrides);
|
||||
config.overrides[0].set = { 'view.default': 'not_a_real_view' };
|
||||
});
|
||||
|
||||
const manager = new OverridesManager(vi.fn());
|
||||
manager.set(stateManager, config.overrides);
|
||||
expect(error.context).toMatchObject({
|
||||
failures: expect.arrayContaining([
|
||||
expect.objectContaining({
|
||||
path: 'view.default',
|
||||
received: 'not_a_real_view',
|
||||
expected: expect.arrayContaining(['live']),
|
||||
}),
|
||||
]),
|
||||
});
|
||||
});
|
||||
|
||||
expect(() => manager.getConfig(config)).toThrowError(
|
||||
/Invalid override configuration/,
|
||||
);
|
||||
it('with a fallback to the issue message for unhandled codes', () => {
|
||||
// Hits the ternary's fallback branch: `too_small` is neither
|
||||
// invalid_value nor invalid_type, so we surface `issue.message`.
|
||||
const error = runInvalidOverride((config) => {
|
||||
assert(config.overrides);
|
||||
config.overrides[0].set = { 'status_bar.height': -1 };
|
||||
});
|
||||
|
||||
expect(error.context).toMatchObject({
|
||||
failures: expect.arrayContaining([
|
||||
expect.objectContaining({
|
||||
path: 'status_bar.height',
|
||||
expected: expect.any(String),
|
||||
}),
|
||||
]),
|
||||
});
|
||||
});
|
||||
});
|
||||
|
||||
// See: https://github.com/dermotduffy/advanced-camera-card/issues/1954
|
||||
|
||||
@@ -16,14 +16,13 @@ import { FullscreenManager } from '../../src/card-controller/fullscreen/fullscre
|
||||
import { HASSManager } from '../../src/card-controller/hass/hass-manager';
|
||||
import { InitializationManager } from '../../src/card-controller/initialization-manager';
|
||||
import { InteractionManager } from '../../src/card-controller/interaction-manager';
|
||||
import { IssueManager } from '../../src/card-controller/issues/issue-manager';
|
||||
import { KeyboardStateManager } from '../../src/card-controller/keyboard-state-manager';
|
||||
import { MediaLoadedInfoManager } from '../../src/card-controller/media-info-manager';
|
||||
import { MediaPlayerManager } from '../../src/card-controller/media-player-manager';
|
||||
import { MessageManager } from '../../src/card-controller/message-manager';
|
||||
import { MicrophoneManager } from '../../src/card-controller/microphone-manager';
|
||||
import { NotificationManager } from '../../src/card-controller/notification-manager';
|
||||
import { PIPManager } from '../../src/card-controller/pip-manager';
|
||||
import { ProblemManager } from '../../src/card-controller/problems/manager';
|
||||
import { QueryStringManager } from '../../src/card-controller/query-string-manager';
|
||||
import { StatusBarItemManager } from '../../src/card-controller/status-bar-item-manager';
|
||||
import { StyleManager } from '../../src/card-controller/style-manager';
|
||||
@@ -53,11 +52,11 @@ vi.mock('../../src/card-controller/interaction-manager');
|
||||
vi.mock('../../src/card-controller/keyboard-state-manager');
|
||||
vi.mock('../../src/card-controller/media-info-manager');
|
||||
vi.mock('../../src/card-controller/media-player-manager');
|
||||
vi.mock('../../src/card-controller/message-manager');
|
||||
vi.mock('../../src/card-controller/microphone-manager');
|
||||
vi.mock('../../src/card-controller/notification-manager');
|
||||
vi.mock('../../src/card-controller/pip-manager');
|
||||
vi.mock('../../src/card-controller/problems/manager');
|
||||
vi.mock('../../src/card-controller/issues/state-manager');
|
||||
vi.mock('../../src/card-controller/issues/issue-manager');
|
||||
vi.mock('../../src/card-controller/query-string-manager');
|
||||
vi.mock('../../src/card-controller/status-bar-item-manager');
|
||||
vi.mock('../../src/card-controller/style-manager');
|
||||
@@ -102,164 +101,158 @@ describe('CardController', () => {
|
||||
});
|
||||
|
||||
describe('accessors', () => {
|
||||
it('getActionsManager', () => {
|
||||
it('should return getActionsManager', () => {
|
||||
expect(createController().getActionsManager()).toBe(
|
||||
vi.mocked(ActionsManager).mock.instances[0],
|
||||
);
|
||||
});
|
||||
|
||||
it('getAutomationsManager', () => {
|
||||
it('should return getAutomationsManager', () => {
|
||||
expect(createController().getAutomationsManager()).toBe(
|
||||
vi.mocked(AutomationsManager).mock.instances[0],
|
||||
);
|
||||
});
|
||||
|
||||
it('getDefaultManager', () => {
|
||||
it('should return getDefaultManager', () => {
|
||||
expect(createController().getDefaultManager()).toBe(
|
||||
vi.mocked(DefaultManager).mock.instances[0],
|
||||
);
|
||||
});
|
||||
|
||||
it('getCameraManager', () => {
|
||||
it('should return getCameraManager', () => {
|
||||
expect(createController().getCameraManager()).toBe(
|
||||
vi.mocked(CameraManager).mock.instances[0],
|
||||
);
|
||||
});
|
||||
|
||||
it('getCameraURLManager', () => {
|
||||
it('should return getCameraURLManager', () => {
|
||||
expect(createController().getCameraURLManager()).toBe(
|
||||
vi.mocked(CameraURLManager).mock.instances[0],
|
||||
);
|
||||
});
|
||||
|
||||
it('getCardElementManager', () => {
|
||||
it('should return getCardElementManager', () => {
|
||||
expect(createController().getCardElementManager()).toBe(
|
||||
vi.mocked(CardElementManager).mock.instances[0],
|
||||
);
|
||||
});
|
||||
|
||||
it('ConditionStateManager', () => {
|
||||
it('should return ConditionStateManager', () => {
|
||||
expect(createController().getConditionStateManager()).toBe(
|
||||
vi.mocked(ConditionStateManager).mock.instances[0],
|
||||
);
|
||||
});
|
||||
|
||||
it('getConfigElement', async () => {
|
||||
it('should return getConfigElement', async () => {
|
||||
expect(
|
||||
(await CardController.getConfigElement()) instanceof AdvancedCameraCardEditor,
|
||||
);
|
||||
});
|
||||
|
||||
it('getConfigManager', () => {
|
||||
it('should return getConfigManager', () => {
|
||||
expect(createController().getConfigManager()).toBe(
|
||||
vi.mocked(ConfigManager).mock.instances[0],
|
||||
);
|
||||
});
|
||||
|
||||
it('getDeviceRegistryManager', () => {
|
||||
it('should return getDeviceRegistryManager', () => {
|
||||
expect(createController().getDeviceRegistryManager()).toBe(
|
||||
vi.mocked(DeviceRegistryManager).mock.instances[0],
|
||||
);
|
||||
});
|
||||
|
||||
it('getEntityRegistryManager', () => {
|
||||
it('should return getEntityRegistryManager', () => {
|
||||
expect(createController().getEntityRegistryManager()).toBe(
|
||||
vi.mocked(EntityRegistryManagerLive).mock.instances[0],
|
||||
);
|
||||
});
|
||||
|
||||
it('getExpandManager', () => {
|
||||
it('should return getExpandManager', () => {
|
||||
expect(createController().getExpandManager()).toBe(
|
||||
vi.mocked(ExpandManager).mock.instances[0],
|
||||
);
|
||||
});
|
||||
|
||||
it('getFoldersManager', () => {
|
||||
it('should return getFoldersManager', () => {
|
||||
expect(createController().getFoldersManager()).toBe(
|
||||
vi.mocked(FoldersManager).mock.instances[0],
|
||||
);
|
||||
});
|
||||
|
||||
it('getFullscreenManager', () => {
|
||||
it('should return getFullscreenManager', () => {
|
||||
expect(createController().getFullscreenManager()).toBe(
|
||||
vi.mocked(FullscreenManager).mock.instances[0],
|
||||
);
|
||||
});
|
||||
|
||||
it('getHASSManager', () => {
|
||||
it('should return getHASSManager', () => {
|
||||
expect(createController().getHASSManager()).toBe(
|
||||
vi.mocked(HASSManager).mock.instances[0],
|
||||
);
|
||||
});
|
||||
|
||||
it('getInitializationManager', () => {
|
||||
it('should return getInitializationManager', () => {
|
||||
expect(createController().getInitializationManager()).toBe(
|
||||
vi.mocked(InitializationManager).mock.instances[0],
|
||||
);
|
||||
});
|
||||
|
||||
it('getInteractionManager', () => {
|
||||
it('should return getInteractionManager', () => {
|
||||
expect(createController().getInteractionManager()).toBe(
|
||||
vi.mocked(InteractionManager).mock.instances[0],
|
||||
);
|
||||
});
|
||||
|
||||
it('getKeyboardStateManager', () => {
|
||||
it('should return getKeyboardStateManager', () => {
|
||||
expect(createController().getKeyboardStateManager()).toBe(
|
||||
vi.mocked(KeyboardStateManager).mock.instances[0],
|
||||
);
|
||||
});
|
||||
|
||||
it('getMediaLoadedInfoManager', () => {
|
||||
it('should return getMediaLoadedInfoManager', () => {
|
||||
expect(createController().getMediaLoadedInfoManager()).toBe(
|
||||
vi.mocked(MediaLoadedInfoManager).mock.instances[0],
|
||||
);
|
||||
});
|
||||
|
||||
it('getMediaPlayerManager', () => {
|
||||
it('should return getMediaPlayerManager', () => {
|
||||
expect(createController().getMediaPlayerManager()).toBe(
|
||||
vi.mocked(MediaPlayerManager).mock.instances[0],
|
||||
);
|
||||
});
|
||||
|
||||
it('getMessageManager', () => {
|
||||
expect(createController().getMessageManager()).toBe(
|
||||
vi.mocked(MessageManager).mock.instances[0],
|
||||
);
|
||||
});
|
||||
|
||||
it('getNotificationManager', () => {
|
||||
it('should return getNotificationManager', () => {
|
||||
expect(createController().getNotificationManager()).toBe(
|
||||
vi.mocked(NotificationManager).mock.instances[0],
|
||||
);
|
||||
});
|
||||
|
||||
it('getPIPManager', () => {
|
||||
it('should return getPIPManager', () => {
|
||||
expect(createController().getPIPManager()).toBe(
|
||||
vi.mocked(PIPManager).mock.instances[0],
|
||||
);
|
||||
});
|
||||
|
||||
it('getProblemManager', () => {
|
||||
expect(createController().getProblemManager()).toBe(
|
||||
vi.mocked(ProblemManager).mock.instances[0],
|
||||
it('should return getIssueManager', () => {
|
||||
expect(createController().getIssueManager()).toBe(
|
||||
vi.mocked(IssueManager).mock.instances[0],
|
||||
);
|
||||
});
|
||||
|
||||
it('getMicrophoneManager', () => {
|
||||
it('should return getMicrophoneManager', () => {
|
||||
expect(createController().getMicrophoneManager()).toBe(
|
||||
vi.mocked(MicrophoneManager).mock.instances[0],
|
||||
);
|
||||
});
|
||||
|
||||
it('getResolvedMediaCache', () => {
|
||||
it('should return getResolvedMediaCache', () => {
|
||||
expect(createController().getResolvedMediaCache()).toBe(
|
||||
vi.mocked(ResolvedMediaCache).mock.instances[0],
|
||||
);
|
||||
});
|
||||
|
||||
describe('getStubConfig', () => {
|
||||
it('with camera entities', () => {
|
||||
it('should handle with camera entities', () => {
|
||||
expect(
|
||||
CardController.getStubConfig(['camera.office', 'binary_sensor.motion']),
|
||||
).toEqual({
|
||||
@@ -267,44 +260,44 @@ describe('CardController', () => {
|
||||
});
|
||||
});
|
||||
|
||||
it('without camera entities', () => {
|
||||
it('should handle without camera entities', () => {
|
||||
expect(CardController.getStubConfig(['binary_sensor.motion'])).toEqual({
|
||||
cameras: [{ camera_entity: 'camera.demo' }],
|
||||
});
|
||||
});
|
||||
});
|
||||
|
||||
it('getQueryStringManager', () => {
|
||||
it('should return getQueryStringManager', () => {
|
||||
expect(createController().getQueryStringManager()).toBe(
|
||||
vi.mocked(QueryStringManager).mock.instances[0],
|
||||
);
|
||||
});
|
||||
|
||||
it('getStatusBarItemManager', () => {
|
||||
it('should return getStatusBarItemManager', () => {
|
||||
expect(createController().getStatusBarItemManager()).toBe(
|
||||
vi.mocked(StatusBarItemManager).mock.instances[0],
|
||||
);
|
||||
});
|
||||
|
||||
it('getStyleManager', () => {
|
||||
it('should return getStyleManager', () => {
|
||||
expect(createController().getStyleManager()).toBe(
|
||||
vi.mocked(StyleManager).mock.instances[0],
|
||||
);
|
||||
});
|
||||
|
||||
it('getTriggersManager', () => {
|
||||
it('should return getTriggersManager', () => {
|
||||
expect(createController().getTriggersManager()).toBe(
|
||||
vi.mocked(TriggersManager).mock.instances[0],
|
||||
);
|
||||
});
|
||||
|
||||
it('getViewItemManager', () => {
|
||||
it('should return getViewItemManager', () => {
|
||||
expect(createController().getViewItemManager()).toBe(
|
||||
vi.mocked(ViewItemManager).mock.instances[0],
|
||||
);
|
||||
});
|
||||
|
||||
it('getViewManager', () => {
|
||||
it('should return getViewManager', () => {
|
||||
expect(createController().getViewManager()).toBe(
|
||||
vi.mocked(ViewManager).mock.instances[0],
|
||||
);
|
||||
@@ -312,7 +305,7 @@ describe('CardController', () => {
|
||||
});
|
||||
|
||||
describe('creaters ', () => {
|
||||
it('createCameraManager', () => {
|
||||
it('should create createCameraManager', () => {
|
||||
const controller = createController();
|
||||
const original = controller.getCameraManager();
|
||||
|
||||
@@ -321,7 +314,7 @@ describe('CardController', () => {
|
||||
expect(controller.getCameraManager()).not.toBe(original);
|
||||
});
|
||||
|
||||
it('createMicrophoneManager', () => {
|
||||
it('should create createMicrophoneManager', () => {
|
||||
const controller = createController();
|
||||
const original = controller.getMicrophoneManager();
|
||||
|
||||
@@ -332,14 +325,14 @@ describe('CardController', () => {
|
||||
});
|
||||
|
||||
describe('handlers', () => {
|
||||
it('hostConnected', () => {
|
||||
it('should handle hostConnected', () => {
|
||||
createController().hostConnected();
|
||||
expect(
|
||||
vi.mocked(CardElementManager).mock.instances[0].elementConnected,
|
||||
).toBeCalled();
|
||||
});
|
||||
|
||||
it('hostDisconnected', () => {
|
||||
it('should handle hostDisconnected', () => {
|
||||
createController().hostDisconnected();
|
||||
expect(
|
||||
vi.mocked(CardElementManager).mock.instances[0].elementDisconnected,
|
||||
|
||||
@@ -1,3 +1,4 @@
|
||||
import { STATE_RUNNING, STATE_STARTING } from 'home-assistant-js-websocket';
|
||||
import { beforeEach, describe, expect, it, vi } from 'vitest';
|
||||
import { HASSManager } from '../../../src/card-controller/hass/hass-manager';
|
||||
import { StateWatcher } from '../../../src/card-controller/hass/state-watcher';
|
||||
@@ -61,77 +62,26 @@ describe('HASSManager', () => {
|
||||
});
|
||||
|
||||
describe('should handle connection state change when', () => {
|
||||
it('initially disconnected', () => {
|
||||
it('should reinitialize cameras and view on lost → ready transition', () => {
|
||||
const api = createCardAPI();
|
||||
const manager = new HASSManager(api);
|
||||
|
||||
const disconnectedHASS = createHASS();
|
||||
disconnectedHASS.connected = false;
|
||||
|
||||
manager.setHASS(disconnectedHASS);
|
||||
|
||||
expect(api.getMessageManager().setMessageIfHigherPriority).toBeCalledWith(
|
||||
expect.objectContaining({
|
||||
message: 'Reconnecting',
|
||||
icon: 'mdi:lan-disconnect',
|
||||
type: 'connection',
|
||||
dotdotdot: true,
|
||||
}),
|
||||
);
|
||||
});
|
||||
|
||||
it('disconnected', () => {
|
||||
const api = createCardAPI();
|
||||
const manager = new HASSManager(api);
|
||||
|
||||
manager.setHASS(createHASS());
|
||||
|
||||
const disconnectedHASS = createHASS();
|
||||
disconnectedHASS.connected = false;
|
||||
manager.setHASS(disconnectedHASS);
|
||||
|
||||
expect(api.getMessageManager().setMessageIfHigherPriority).toBeCalledWith(
|
||||
expect.objectContaining({
|
||||
message: 'Reconnecting',
|
||||
icon: 'mdi:lan-disconnect',
|
||||
type: 'connection',
|
||||
dotdotdot: true,
|
||||
}),
|
||||
);
|
||||
});
|
||||
|
||||
it('reconnected', () => {
|
||||
const api = createCardAPI();
|
||||
const manager = new HASSManager(api);
|
||||
|
||||
const disconnectedHASS = createHASS();
|
||||
disconnectedHASS.connected = false;
|
||||
manager.setHASS(disconnectedHASS);
|
||||
|
||||
const reconnectedHASS = createHASS();
|
||||
manager.setHASS(reconnectedHASS);
|
||||
|
||||
expect(api.getMessageManager().resetType).toBeCalled();
|
||||
});
|
||||
|
||||
it('reconnected reinitializes cameras and view', () => {
|
||||
const api = createCardAPI();
|
||||
const manager = new HASSManager(api);
|
||||
|
||||
// First establish a connected state.
|
||||
const connectedHASS = createHASS();
|
||||
connectedHASS.connected = true;
|
||||
manager.setHASS(connectedHASS);
|
||||
// First establish a fully-ready state.
|
||||
const readyHASS = createHASS();
|
||||
readyHASS.connected = true;
|
||||
readyHASS.config.state = STATE_RUNNING;
|
||||
manager.setHASS(readyHASS);
|
||||
|
||||
// Simulate disconnection.
|
||||
const disconnectedHASS = createHASS();
|
||||
disconnectedHASS.connected = false;
|
||||
manager.setHASS(disconnectedHASS);
|
||||
|
||||
// Simulate reconnection.
|
||||
const reconnectedHASS = createHASS();
|
||||
reconnectedHASS.connected = true;
|
||||
manager.setHASS(reconnectedHASS);
|
||||
// Simulate full recovery (connected AND running).
|
||||
const recoveredHASS = createHASS();
|
||||
recoveredHASS.connected = true;
|
||||
recoveredHASS.config.state = STATE_RUNNING;
|
||||
manager.setHASS(recoveredHASS);
|
||||
|
||||
// Cameras and view should be uninitialized so they get re-subscribed
|
||||
// to event sources (e.g. Frigate WebSocket events) on the next
|
||||
@@ -144,7 +94,87 @@ describe('HASSManager', () => {
|
||||
);
|
||||
});
|
||||
|
||||
it('hass is null', () => {
|
||||
it('should reinitialize on starting → ready transition (integrations finished loading)', () => {
|
||||
const api = createCardAPI();
|
||||
const manager = new HASSManager(api);
|
||||
|
||||
// WebSocket reconnected but HA still booting.
|
||||
const startingHASS = createHASS();
|
||||
startingHASS.connected = true;
|
||||
startingHASS.config.state = STATE_STARTING;
|
||||
manager.setHASS(startingHASS);
|
||||
|
||||
// No reinit yet — HA isn't fully ready.
|
||||
expect(api.getInitializationManager().uninitialize).not.toBeCalled();
|
||||
expect(api.getCameraManager().destroy).not.toBeCalled();
|
||||
|
||||
// HA finishes booting.
|
||||
const readyHASS = createHASS();
|
||||
readyHASS.connected = true;
|
||||
readyHASS.config.state = STATE_RUNNING;
|
||||
manager.setHASS(readyHASS);
|
||||
|
||||
expect(api.getInitializationManager().uninitialize).toBeCalledWith('cameras');
|
||||
expect(api.getCameraManager().destroy).toBeCalled();
|
||||
expect(api.getInitializationManager().uninitialize).toBeCalledWith('view');
|
||||
expect(api.getInitializationManager().uninitialize).toBeCalledWith(
|
||||
'initial-trigger',
|
||||
);
|
||||
});
|
||||
|
||||
it('should not reinitialize on lost → starting transition', () => {
|
||||
const api = createCardAPI();
|
||||
const manager = new HASSManager(api);
|
||||
|
||||
const disconnectedHASS = createHASS();
|
||||
disconnectedHASS.connected = false;
|
||||
manager.setHASS(disconnectedHASS);
|
||||
|
||||
const startingHASS = createHASS();
|
||||
startingHASS.connected = true;
|
||||
startingHASS.config.state = STATE_STARTING;
|
||||
manager.setHASS(startingHASS);
|
||||
|
||||
// WS came back but integrations still loading — wait for RUNNING.
|
||||
expect(api.getInitializationManager().uninitialize).not.toBeCalled();
|
||||
expect(api.getCameraManager().destroy).not.toBeCalled();
|
||||
});
|
||||
|
||||
it('should not reinitialize on first hass set (no previous hass)', () => {
|
||||
const api = createCardAPI();
|
||||
const manager = new HASSManager(api);
|
||||
|
||||
const readyHASS = createHASS();
|
||||
readyHASS.connected = true;
|
||||
readyHASS.config.state = STATE_RUNNING;
|
||||
manager.setHASS(readyHASS);
|
||||
|
||||
// First-ever hass set — there's no "previous not-ready state" to
|
||||
// transition from, so the normal first-load init flow applies and we
|
||||
// must not blow away cameras.
|
||||
expect(api.getInitializationManager().uninitialize).not.toBeCalled();
|
||||
expect(api.getCameraManager().destroy).not.toBeCalled();
|
||||
});
|
||||
|
||||
it('should not reinitialize on ready → ready (no transition)', () => {
|
||||
const api = createCardAPI();
|
||||
const manager = new HASSManager(api);
|
||||
|
||||
const readyHASS = createHASS();
|
||||
readyHASS.connected = true;
|
||||
readyHASS.config.state = STATE_RUNNING;
|
||||
manager.setHASS(readyHASS);
|
||||
|
||||
const anotherReadyHASS = createHASS();
|
||||
anotherReadyHASS.connected = true;
|
||||
anotherReadyHASS.config.state = STATE_RUNNING;
|
||||
manager.setHASS(anotherReadyHASS);
|
||||
|
||||
expect(api.getInitializationManager().uninitialize).not.toBeCalled();
|
||||
expect(api.getCameraManager().destroy).not.toBeCalled();
|
||||
});
|
||||
|
||||
it('should not crash when hass is null', () => {
|
||||
const api = createCardAPI();
|
||||
const manager = new HASSManager(api);
|
||||
const connectedHASS = createHASS();
|
||||
@@ -152,23 +182,12 @@ describe('HASSManager', () => {
|
||||
|
||||
manager.setHASS(connectedHASS);
|
||||
manager.setHASS(null);
|
||||
|
||||
expect(api.getMessageManager().setMessageIfHigherPriority).toBeCalledWith(
|
||||
expect.objectContaining({
|
||||
message: 'Reconnecting',
|
||||
icon: 'mdi:lan-disconnect',
|
||||
type: 'connection',
|
||||
dotdotdot: true,
|
||||
}),
|
||||
);
|
||||
|
||||
manager.setHASS(connectedHASS);
|
||||
expect(api.getMessageManager().resetType).toBeCalled();
|
||||
});
|
||||
});
|
||||
|
||||
describe('should not set default view when', () => {
|
||||
it('selected camera is unknown', () => {
|
||||
it('should not set default view when selected camera is unknown', () => {
|
||||
const api = createCardAPI();
|
||||
vi.mocked(api.getCameraManager).mockReturnValue(createCameraManager());
|
||||
vi.mocked(api.getCameraManager().getStore).mockReturnValue(
|
||||
@@ -199,7 +218,7 @@ describe('HASSManager', () => {
|
||||
expect(api.getViewManager().setViewDefault).not.toBeCalled();
|
||||
});
|
||||
|
||||
it('when there is card interaction', () => {
|
||||
it('should not set default view when there is card interaction', () => {
|
||||
const api = createCardAPI();
|
||||
vi.mocked(api.getConfigManager().getConfig).mockReturnValue(
|
||||
createConfig({
|
||||
|
||||
@@ -1,3 +1,4 @@
|
||||
import { STATE_STARTING } from 'home-assistant-js-websocket';
|
||||
import { beforeEach, describe, expect, it, vi } from 'vitest';
|
||||
import { mock } from 'vitest-mock-extended';
|
||||
import {
|
||||
@@ -20,14 +21,14 @@ describe('InitializationManager', () => {
|
||||
});
|
||||
|
||||
describe('should correctly determine when mandatory initialization is required', () => {
|
||||
it('without config', () => {
|
||||
it('should handle without config', () => {
|
||||
const api = createCardAPI();
|
||||
const manager = new InitializationManager(api);
|
||||
|
||||
expect(manager.isInitializedMandatory()).toBeFalsy();
|
||||
});
|
||||
|
||||
it('without aspects', () => {
|
||||
it('should handle without aspects', () => {
|
||||
const api = createCardAPI();
|
||||
const manager = new InitializationManager(api);
|
||||
|
||||
@@ -36,7 +37,7 @@ describe('InitializationManager', () => {
|
||||
expect(manager.isInitializedMandatory()).toBeFalsy();
|
||||
});
|
||||
|
||||
it('with microphone if configured', () => {
|
||||
it('should handle with microphone if configured', () => {
|
||||
const api = createCardAPI();
|
||||
const manager = new InitializationManager(api);
|
||||
|
||||
@@ -50,24 +51,40 @@ describe('InitializationManager', () => {
|
||||
});
|
||||
|
||||
describe('should initialize mandatory', () => {
|
||||
it('without hass', async () => {
|
||||
it('should handle without hass', async () => {
|
||||
const manager = new InitializationManager(createCardAPI());
|
||||
await manager.initializeMandatory();
|
||||
expect(manager.wasEverInitialized()).toBeFalsy();
|
||||
});
|
||||
|
||||
it('without config', async () => {
|
||||
it('should handle without config', async () => {
|
||||
const api = createCardAPI();
|
||||
const manager = new InitializationManager(api);
|
||||
vi.mocked(api.getHASSManager().getHASS).mockReturnValue(createHASS());
|
||||
vi.mocked(loadLanguages).mockResolvedValue(true);
|
||||
vi.mocked(sideLoadHomeAssistantElements).mockResolvedValue(true);
|
||||
|
||||
await manager.initializeMandatory();
|
||||
expect(manager.wasEverInitialized()).toBeFalsy();
|
||||
});
|
||||
|
||||
it('successfully', async () => {
|
||||
it('should be a no-op when hass.config.state is not RUNNING', async () => {
|
||||
const api = createCardAPI();
|
||||
const hass = createHASS();
|
||||
hass.config.state = STATE_STARTING;
|
||||
vi.mocked(api.getHASSManager().getHASS).mockReturnValue(hass);
|
||||
vi.mocked(api.getConfigManager().getConfig).mockReturnValue(createConfig());
|
||||
|
||||
const initializer = mock<Initializer>();
|
||||
const manager = new InitializationManager(api, initializer);
|
||||
|
||||
await manager.initializeMandatory();
|
||||
|
||||
expect(initializer.initializeMultipleIfNecessary).not.toBeCalled();
|
||||
expect(initializer.initializeIfNecessary).not.toBeCalled();
|
||||
expect(api.getIssueManager().trigger).not.toBeCalled();
|
||||
expect(manager.wasEverInitialized()).toBeFalsy();
|
||||
});
|
||||
|
||||
it('should succeed', async () => {
|
||||
const stateListener = vi.fn();
|
||||
const stateMananger = new ConditionStateManager();
|
||||
stateMananger.addListener(stateListener);
|
||||
@@ -77,17 +94,12 @@ describe('InitializationManager', () => {
|
||||
vi.mocked(api.getHASSManager().getHASS).mockReturnValue(createHASS());
|
||||
const config = createConfig();
|
||||
vi.mocked(api.getConfigManager().getConfig).mockReturnValue(config);
|
||||
vi.mocked(api.getMessageManager().hasMessage).mockReturnValue(false);
|
||||
vi.mocked(
|
||||
api.getIssueManager().getStateManager().hasFullCardIssue,
|
||||
).mockReturnValue(false);
|
||||
vi.mocked(api.getQueryStringManager().hasViewRelatedActionsToRun).mockReturnValue(
|
||||
false,
|
||||
);
|
||||
vi.mocked(loadLanguages).mockResolvedValue(true);
|
||||
vi.mocked(sideLoadHomeAssistantElements).mockResolvedValue(true);
|
||||
vi.mocked(api.getCameraManager().initializeCamerasFromConfig).mockResolvedValue(
|
||||
true,
|
||||
);
|
||||
vi.mocked(api.getViewManager().initialize).mockResolvedValue(true);
|
||||
|
||||
const manager = new InitializationManager(api);
|
||||
|
||||
expect(manager.isInitialized(InitializationAspect.LANGUAGES)).toBeFalsy();
|
||||
@@ -126,18 +138,13 @@ describe('InitializationManager', () => {
|
||||
expect(manager.isInitialized(InitializationAspect.INITIAL_TRIGGER)).toBeTruthy();
|
||||
});
|
||||
|
||||
it('successfully with microphone if configured', async () => {
|
||||
it('should succeed with microphone if configured', async () => {
|
||||
const api = createCardAPI();
|
||||
vi.mocked(api.getHASSManager().getHASS).mockReturnValue(createHASS());
|
||||
vi.mocked(
|
||||
api.getMicrophoneManager().shouldConnectOnInitialization,
|
||||
).mockReturnValue(true);
|
||||
vi.mocked(api.getConfigManager().getConfig).mockReturnValue(createConfig());
|
||||
vi.mocked(loadLanguages).mockResolvedValue(true);
|
||||
vi.mocked(sideLoadHomeAssistantElements).mockResolvedValue(true);
|
||||
vi.mocked(api.getCameraManager().initializeCamerasFromConfig).mockResolvedValue(
|
||||
true,
|
||||
);
|
||||
|
||||
const manager = new InitializationManager(api);
|
||||
|
||||
@@ -146,19 +153,16 @@ describe('InitializationManager', () => {
|
||||
expect(api.getMicrophoneManager().connect).toBeCalled();
|
||||
});
|
||||
|
||||
it('with message set during initialization', async () => {
|
||||
it('should handle message set during initialization', async () => {
|
||||
const api = createCardAPI();
|
||||
vi.mocked(api.getHASSManager().getHASS).mockReturnValue(createHASS());
|
||||
vi.mocked(api.getConfigManager().getConfig).mockReturnValue(createConfig());
|
||||
vi.mocked(api.getMessageManager().hasMessage).mockReturnValue(true);
|
||||
vi.mocked(
|
||||
api.getIssueManager().getStateManager().hasFullCardIssue,
|
||||
).mockReturnValue(true);
|
||||
vi.mocked(api.getQueryStringManager().hasViewRelatedActionsToRun).mockReturnValue(
|
||||
false,
|
||||
);
|
||||
vi.mocked(loadLanguages).mockResolvedValue(true);
|
||||
vi.mocked(sideLoadHomeAssistantElements).mockResolvedValue(true);
|
||||
vi.mocked(api.getCameraManager().initializeCamerasFromConfig).mockResolvedValue(
|
||||
true,
|
||||
);
|
||||
|
||||
const manager = new InitializationManager(api);
|
||||
|
||||
@@ -167,111 +171,118 @@ describe('InitializationManager', () => {
|
||||
expect(api.getViewManager().initialize).not.toBeCalled();
|
||||
});
|
||||
|
||||
it('with languages and side load elements in progress', async () => {
|
||||
it('should handle languages and side load elements in progress', async () => {
|
||||
const api = createCardAPI();
|
||||
vi.mocked(api.getHASSManager().getHASS).mockReturnValue(createHASS());
|
||||
const initializer = mock<Initializer>();
|
||||
const manager = new InitializationManager(api, initializer);
|
||||
initializer.initializeMultipleIfNecessary.mockResolvedValue(false);
|
||||
initializer.initializeMultipleIfNecessary.mockRejectedValue(
|
||||
new Error('initialization failed'),
|
||||
);
|
||||
|
||||
await manager.initializeMandatory();
|
||||
|
||||
expect(manager.wasEverInitialized()).toBeFalsy();
|
||||
});
|
||||
|
||||
it('with cameras in progress', async () => {
|
||||
it('should handle cameras initialization failure', async () => {
|
||||
const api = createCardAPI();
|
||||
vi.mocked(api.getHASSManager().getHASS).mockReturnValue(createHASS());
|
||||
vi.mocked(api.getConfigManager().getConfig).mockReturnValue(createConfig());
|
||||
|
||||
const initializer = mock<Initializer>();
|
||||
const manager = new InitializationManager(api, initializer);
|
||||
|
||||
// First call (languages/side-load) succeeds, second (cameras) fails.
|
||||
initializer.initializeMultipleIfNecessary
|
||||
.mockResolvedValueOnce(true)
|
||||
.mockResolvedValueOnce(false);
|
||||
.mockResolvedValueOnce(undefined)
|
||||
.mockRejectedValueOnce(new Error('cameras failed'));
|
||||
|
||||
await manager.initializeMandatory();
|
||||
|
||||
expect(manager.wasEverInitialized()).toBeFalsy();
|
||||
});
|
||||
|
||||
it('with triggers in progress', async () => {
|
||||
const api = createCardAPI();
|
||||
vi.mocked(api.getHASSManager().getHASS).mockReturnValue(createHASS());
|
||||
vi.mocked(api.getConfigManager().getConfig).mockReturnValue(createConfig());
|
||||
|
||||
const initializer = mock<Initializer>();
|
||||
const manager = new InitializationManager(api, initializer);
|
||||
initializer.initializeMultipleIfNecessary
|
||||
.mockResolvedValueOnce(true)
|
||||
.mockResolvedValueOnce(true);
|
||||
initializer.initializeIfNecessary
|
||||
.mockResolvedValueOnce(true)
|
||||
.mockResolvedValueOnce(false);
|
||||
|
||||
await manager.initializeMandatory();
|
||||
|
||||
expect(manager.wasEverInitialized()).toBeFalsy();
|
||||
});
|
||||
});
|
||||
|
||||
it('should report background initialization status', () => {
|
||||
const initializer = mock<Initializer>();
|
||||
const manager = new InitializationManager(createCardAPI(), initializer);
|
||||
|
||||
initializer.isInitialized.mockReturnValue(false);
|
||||
expect(manager.isInitializedBackground()).toBe(false);
|
||||
|
||||
initializer.isInitialized.mockReturnValue(true);
|
||||
expect(manager.isInitializedBackground()).toBe(true);
|
||||
|
||||
expect(initializer.isInitialized).toBeCalledWith(InitializationAspect.PROBLEMS);
|
||||
});
|
||||
|
||||
describe('should initialize background', () => {
|
||||
it('without hass', async () => {
|
||||
const api = createCardAPI();
|
||||
const initializer = mock<Initializer>();
|
||||
const manager = new InitializationManager(api, initializer);
|
||||
|
||||
await manager.initializeBackground();
|
||||
|
||||
expect(initializer.initializeIfNecessary).not.toBeCalled();
|
||||
});
|
||||
|
||||
it('successfully', async () => {
|
||||
const api = createCardAPI();
|
||||
const hass = createHASS();
|
||||
vi.mocked(api.getHASSManager().getHASS).mockReturnValue(hass);
|
||||
|
||||
const initializer = mock<Initializer>();
|
||||
initializer.initializeIfNecessary.mockResolvedValue(true);
|
||||
const manager = new InitializationManager(api, initializer);
|
||||
|
||||
await manager.initializeBackground();
|
||||
|
||||
expect(initializer.initializeIfNecessary).toBeCalledWith(
|
||||
InitializationAspect.PROBLEMS,
|
||||
expect.any(Function),
|
||||
expect(api.getIssueManager().trigger).toBeCalledWith(
|
||||
'initialization',
|
||||
expect.objectContaining({ error: expect.any(Error) }),
|
||||
);
|
||||
});
|
||||
|
||||
it('should call detectStatic on problem manager', async () => {
|
||||
it('should handle initial trigger initialization failure', async () => {
|
||||
const api = createCardAPI();
|
||||
const hass = createHASS();
|
||||
vi.mocked(api.getHASSManager().getHASS).mockReturnValue(hass);
|
||||
vi.mocked(api.getHASSManager().getHASS).mockReturnValue(createHASS());
|
||||
vi.mocked(api.getConfigManager().getConfig).mockReturnValue(createConfig());
|
||||
|
||||
const initializer = mock<Initializer>();
|
||||
initializer.initializeIfNecessary.mockImplementation(async (_aspect, callback) => {
|
||||
return callback ? await callback() : true;
|
||||
});
|
||||
|
||||
const manager = new InitializationManager(api, initializer);
|
||||
|
||||
await manager.initializeBackground();
|
||||
// First initializeIfNecessary call (view) succeeds, second
|
||||
// (initial_trigger) fails.
|
||||
initializer.initializeIfNecessary
|
||||
.mockResolvedValueOnce(undefined)
|
||||
.mockRejectedValueOnce(new Error('triggers failed'));
|
||||
|
||||
expect(api.getProblemManager().detectStatic).toBeCalledWith(hass);
|
||||
await manager.initializeMandatory();
|
||||
|
||||
expect(manager.wasEverInitialized()).toBeFalsy();
|
||||
expect(api.getIssueManager().trigger).toBeCalledWith(
|
||||
'initialization',
|
||||
expect.objectContaining({ error: expect.any(Error) }),
|
||||
);
|
||||
});
|
||||
|
||||
it('should handle VIEW initialization failure', async () => {
|
||||
const api = createCardAPI();
|
||||
vi.mocked(api.getHASSManager().getHASS).mockReturnValue(createHASS());
|
||||
vi.mocked(api.getConfigManager().getConfig).mockReturnValue(createConfig());
|
||||
|
||||
const initializer = mock<Initializer>();
|
||||
const manager = new InitializationManager(api, initializer);
|
||||
initializer.initializeIfNecessary.mockRejectedValueOnce(
|
||||
new Error('view initialization failed'),
|
||||
);
|
||||
|
||||
await manager.initializeMandatory();
|
||||
|
||||
expect(manager.wasEverInitialized()).toBeFalsy();
|
||||
expect(api.getIssueManager().trigger).toBeCalledWith(
|
||||
'initialization',
|
||||
expect.objectContaining({ error: expect.any(Error) }),
|
||||
);
|
||||
});
|
||||
|
||||
it('should handle non-Error thrown during initialization', async () => {
|
||||
const api = createCardAPI();
|
||||
vi.mocked(api.getHASSManager().getHASS).mockReturnValue(createHASS());
|
||||
|
||||
const initializer = mock<Initializer>();
|
||||
const manager = new InitializationManager(api, initializer);
|
||||
// Throw a non-Error to exercise the else-branch in _tryInitialize
|
||||
initializer.initializeMultipleIfNecessary.mockRejectedValueOnce('string error');
|
||||
|
||||
await manager.initializeMandatory();
|
||||
|
||||
expect(manager.wasEverInitialized()).toBeFalsy();
|
||||
expect(api.getIssueManager().trigger).toBeCalledWith(
|
||||
'initialization',
|
||||
expect.objectContaining({ error: 'string error' }),
|
||||
);
|
||||
});
|
||||
});
|
||||
|
||||
it('should uninitialize mandatory aspects', () => {
|
||||
const initializer = mock<Initializer>();
|
||||
const manager = new InitializationManager(createCardAPI(), initializer);
|
||||
|
||||
manager.uninitializeMandatory();
|
||||
|
||||
expect(initializer.uninitialize).toBeCalledWith(InitializationAspect.CAMERAS);
|
||||
expect(initializer.uninitialize).toBeCalledWith(
|
||||
InitializationAspect.MICROPHONE_CONNECT,
|
||||
);
|
||||
expect(initializer.uninitialize).toBeCalledWith(InitializationAspect.VIEW);
|
||||
expect(initializer.uninitialize).toBeCalledWith(
|
||||
InitializationAspect.INITIAL_TRIGGER,
|
||||
);
|
||||
});
|
||||
|
||||
it('should uninitialize', () => {
|
||||
|
||||
@@ -4,7 +4,7 @@ import { InteractionManager } from '../../src/card-controller/interaction-manage
|
||||
import { createCardAPI, createConfig, createLitElement } from '../test-utils';
|
||||
|
||||
vi.mock('lodash-es', () => ({
|
||||
throttle: vi.fn((fn) => fn),
|
||||
throttle: vi.fn((fn) => Object.assign(fn, { cancel: vi.fn() })),
|
||||
}));
|
||||
|
||||
// @vitest-environment jsdom
|
||||
@@ -87,4 +87,33 @@ describe('InteractionManager', () => {
|
||||
expect(manager.hasInteraction()).toBeFalsy();
|
||||
expect(element.getAttribute('interaction')).toBeNull();
|
||||
});
|
||||
|
||||
it('should uninitialize', () => {
|
||||
const api = createCardAPI();
|
||||
const element = createLitElement();
|
||||
vi.mocked(api.getCardElementManager().getElement).mockReturnValue(element);
|
||||
vi.mocked(api.getConfigManager().getConfig).mockReturnValue(
|
||||
createConfig({
|
||||
view: {
|
||||
interaction_seconds: 10,
|
||||
},
|
||||
}),
|
||||
);
|
||||
const manager = new InteractionManager(api);
|
||||
|
||||
vi.useFakeTimers();
|
||||
vi.setSystemTime(start);
|
||||
|
||||
manager.reportInteraction();
|
||||
expect(manager.hasInteraction()).toBeTruthy();
|
||||
|
||||
manager.uninitialize();
|
||||
|
||||
// Timer should have been stopped: advancing time should not change
|
||||
// interaction state.
|
||||
vi.setSystemTime(add(start, { seconds: 10 }));
|
||||
vi.runOnlyPendingTimers();
|
||||
|
||||
expect(manager.hasInteraction()).toBeTruthy();
|
||||
});
|
||||
});
|
||||
|
||||
@@ -0,0 +1,91 @@
|
||||
// @vitest-environment jsdom
|
||||
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
|
||||
import { createIssueManager } from '../../../src/card-controller/issues/factory';
|
||||
import { IssueManager } from '../../../src/card-controller/issues/issue-manager';
|
||||
import { ConditionStateManager } from '../../../src/conditions/state-manager';
|
||||
import { createCardAPI } from '../../test-utils';
|
||||
|
||||
describe('createIssueManager', () => {
|
||||
beforeEach(() => {
|
||||
vi.useFakeTimers();
|
||||
});
|
||||
|
||||
afterEach(() => {
|
||||
vi.useRealTimers();
|
||||
});
|
||||
|
||||
it('should return a IssueManager instance', () => {
|
||||
const manager = createIssueManager(createCardAPI());
|
||||
expect(manager).toBeInstanceOf(IssueManager);
|
||||
});
|
||||
|
||||
it('should register all expected issues', () => {
|
||||
const manager = createIssueManager(createCardAPI()).getStateManager();
|
||||
|
||||
expect(manager.getIssueDescriptions()).toHaveLength(0);
|
||||
|
||||
const expectedKeys = [
|
||||
'config_error',
|
||||
'config_upgrade',
|
||||
'connection',
|
||||
'initialization',
|
||||
'legacy_resource',
|
||||
'media_query',
|
||||
'media_load',
|
||||
'view_incompatible',
|
||||
] as const;
|
||||
|
||||
for (const key of expectedKeys) {
|
||||
expect(() => manager.getNotification(key)).not.toThrow();
|
||||
}
|
||||
});
|
||||
|
||||
it('should register issues in an order that determines priority', () => {
|
||||
// Lock the registration order. The relative order of these issues
|
||||
// governs full-card display priority (getFullCardIssue returns the
|
||||
// first active full-card issue) and retry-loop priority. Alphabetizing
|
||||
// the list in factory.ts would silently change both. Triggering in a
|
||||
// scrambled order proves getIssueDescriptions reflects registration
|
||||
// order, not trigger order.
|
||||
const api = createCardAPI();
|
||||
const stateManager = new ConditionStateManager();
|
||||
vi.mocked(api.getConditionStateManager).mockReturnValue(stateManager);
|
||||
const manager = createIssueManager(api);
|
||||
|
||||
manager.trigger('media_query', { error: new Error('x') });
|
||||
manager.trigger('initialization', { error: new Error('x') });
|
||||
manager.trigger('config_error', { error: new Error('x') });
|
||||
manager.trigger('view_incompatible', { error: new Error('x') });
|
||||
|
||||
const keys = manager
|
||||
.getStateManager()
|
||||
.getIssueDescriptions()
|
||||
.map((d) => d.key);
|
||||
|
||||
expect(keys).toEqual([
|
||||
'config_error',
|
||||
'view_incompatible',
|
||||
'initialization',
|
||||
'media_query',
|
||||
]);
|
||||
});
|
||||
|
||||
it('should wire changeCallback so timer-based issues activate via evaluate', () => {
|
||||
const api = createCardAPI();
|
||||
const stateManager = new ConditionStateManager();
|
||||
vi.mocked(api.getConditionStateManager).mockReturnValue(stateManager);
|
||||
|
||||
const manager = createIssueManager(api);
|
||||
|
||||
// Setting view starts the media_load timer (via the condition state
|
||||
// listener → evaluate → detectDynamic).
|
||||
stateManager.setState({ targetID: 'camera-1', view: 'live' });
|
||||
expect(manager.getStateManager().getIssuePresence().has('media_load')).toBe(false);
|
||||
|
||||
// After the timeout, the changeCallback fires evaluate which
|
||||
// updates the card element.
|
||||
vi.advanceTimersByTime(10000);
|
||||
|
||||
expect(manager.getStateManager().getIssuePresence().has('media_load')).toBe(true);
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,884 @@
|
||||
// @vitest-environment jsdom
|
||||
import { afterEach, assert, beforeEach, describe, expect, it, vi } from 'vitest';
|
||||
import { mock } from 'vitest-mock-extended';
|
||||
import { CardController } from '../../../src/card-controller/controller';
|
||||
import {
|
||||
IssueManager,
|
||||
RETRY_EXPONENTIAL_BASE_SECONDS,
|
||||
RETRY_EXPONENTIAL_MAX_SECONDS,
|
||||
} from '../../../src/card-controller/issues/issue-manager';
|
||||
import {
|
||||
Issue,
|
||||
IssueDescription,
|
||||
IssueKey,
|
||||
} from '../../../src/card-controller/issues/types';
|
||||
import { ConditionStateManager } from '../../../src/conditions/state-manager';
|
||||
import { InteractionMode } from '../../../src/config/schema/view';
|
||||
import {
|
||||
createCardAPI,
|
||||
createConfig,
|
||||
createHASS,
|
||||
flushPromises,
|
||||
} from '../../test-utils';
|
||||
|
||||
const DEFAULT_RETRY_SECONDS = 1;
|
||||
|
||||
const createIssue = (key: IssueKey, overrides?: Partial<Issue>): Issue =>
|
||||
mock({
|
||||
key,
|
||||
hasIssue: vi.fn().mockReturnValue(false),
|
||||
getIssue: vi.fn().mockReturnValue(null),
|
||||
needsRetry: vi.fn().mockReturnValue(false),
|
||||
...overrides,
|
||||
});
|
||||
|
||||
const createIssueDescription = (
|
||||
overrides?: Partial<IssueDescription>,
|
||||
): IssueDescription => ({
|
||||
icon: 'mdi:alert',
|
||||
severity: 'high',
|
||||
notification: { body: { text: 'test' } },
|
||||
...overrides,
|
||||
});
|
||||
|
||||
const createRetriableSetup = (options?: {
|
||||
retrySeconds?: 'auto' | number;
|
||||
interactionMode?: InteractionMode;
|
||||
hasInteraction?: boolean;
|
||||
}): {
|
||||
api: CardController;
|
||||
manager: IssueManager;
|
||||
issue: Issue;
|
||||
} => {
|
||||
const api = createCardAPI();
|
||||
vi.mocked(api.getConditionStateManager().getState).mockReturnValue({});
|
||||
|
||||
if (options?.hasInteraction !== undefined) {
|
||||
vi.mocked(api.getInteractionManager().hasInteraction).mockReturnValue(
|
||||
options.hasInteraction,
|
||||
);
|
||||
}
|
||||
|
||||
const config = createConfig();
|
||||
vi.mocked(api.getConfigManager().getConfig).mockReturnValue({
|
||||
...config,
|
||||
view: {
|
||||
...config.view,
|
||||
issues: {
|
||||
interaction_mode: options?.interactionMode ?? 'inactive',
|
||||
retry_seconds: options?.retrySeconds ?? DEFAULT_RETRY_SECONDS,
|
||||
},
|
||||
},
|
||||
});
|
||||
|
||||
const manager = new IssueManager(api);
|
||||
|
||||
const issue = createIssue('media_load', {
|
||||
hasIssue: vi.fn().mockReturnValueOnce(false).mockReturnValue(true),
|
||||
needsRetry: vi.fn().mockReturnValue(true),
|
||||
retry: vi.fn().mockReturnValue(false),
|
||||
});
|
||||
manager.addIssue(issue);
|
||||
|
||||
return { api, manager, issue };
|
||||
};
|
||||
|
||||
describe('IssueManager', () => {
|
||||
beforeEach(() => {
|
||||
vi.useFakeTimers();
|
||||
});
|
||||
|
||||
afterEach(() => {
|
||||
vi.useRealTimers();
|
||||
vi.restoreAllMocks();
|
||||
});
|
||||
|
||||
it('should register a listener on the condition state manager on construction', () => {
|
||||
const api = createCardAPI();
|
||||
const stateManager = new ConditionStateManager();
|
||||
vi.mocked(api.getConditionStateManager).mockReturnValue(stateManager);
|
||||
|
||||
const manager = new IssueManager(api);
|
||||
const issue = createIssue('config_error', {
|
||||
detectDynamic: vi.fn(),
|
||||
});
|
||||
manager.addIssue(issue);
|
||||
|
||||
stateManager.setState({ view: 'live' });
|
||||
|
||||
expect(issue.detectDynamic).toBeCalled();
|
||||
});
|
||||
|
||||
describe('addIssue / getStateManager', () => {
|
||||
it('should make added issues accessible via getManager', () => {
|
||||
const manager = new IssueManager(createCardAPI());
|
||||
|
||||
const issue = createIssue('config_error');
|
||||
manager.addIssue(issue);
|
||||
|
||||
expect(manager.getStateManager().getIssuePresence().has('config_error')).toBe(
|
||||
false,
|
||||
);
|
||||
});
|
||||
});
|
||||
|
||||
describe('static detection via condition-state listener', () => {
|
||||
it('should run static detection when mandatory init completes', async () => {
|
||||
const api = createCardAPI();
|
||||
const conditionStateManager = new ConditionStateManager();
|
||||
vi.mocked(api.getConditionStateManager).mockReturnValue(conditionStateManager);
|
||||
|
||||
const manager = new IssueManager(api);
|
||||
const detectStatic = vi.fn().mockResolvedValue(undefined);
|
||||
const issue = createIssue('legacy_resource', { detectStatic });
|
||||
manager.addIssue(issue);
|
||||
|
||||
const hass = createHASS();
|
||||
conditionStateManager.setState({ hass });
|
||||
conditionStateManager.setState({ initialized: true });
|
||||
await flushPromises();
|
||||
|
||||
expect(detectStatic).toBeCalledWith(hass);
|
||||
});
|
||||
|
||||
it('should not run static detection when hass is unset', () => {
|
||||
const api = createCardAPI();
|
||||
const conditionStateManager = new ConditionStateManager();
|
||||
vi.mocked(api.getConditionStateManager).mockReturnValue(conditionStateManager);
|
||||
|
||||
const manager = new IssueManager(api);
|
||||
const detectStatic = vi.fn().mockResolvedValue(undefined);
|
||||
const issue = createIssue('legacy_resource', { detectStatic });
|
||||
manager.addIssue(issue);
|
||||
|
||||
conditionStateManager.setState({ initialized: true });
|
||||
|
||||
expect(detectStatic).not.toBeCalled();
|
||||
});
|
||||
|
||||
it('should not run static detection on unrelated state changes', () => {
|
||||
const api = createCardAPI();
|
||||
const conditionStateManager = new ConditionStateManager();
|
||||
vi.mocked(api.getConditionStateManager).mockReturnValue(conditionStateManager);
|
||||
|
||||
const manager = new IssueManager(api);
|
||||
const detectStatic = vi.fn().mockResolvedValue(undefined);
|
||||
const issue = createIssue('legacy_resource', { detectStatic });
|
||||
manager.addIssue(issue);
|
||||
|
||||
const hass = createHASS();
|
||||
conditionStateManager.setState({ hass });
|
||||
conditionStateManager.setState({ view: 'live' });
|
||||
|
||||
expect(detectStatic).not.toBeCalled();
|
||||
});
|
||||
});
|
||||
|
||||
describe('trigger', () => {
|
||||
it('should trigger the issue and call evaluate', () => {
|
||||
const api = createCardAPI();
|
||||
vi.mocked(api.getConditionStateManager().getState).mockReturnValue({});
|
||||
|
||||
const manager = new IssueManager(api);
|
||||
|
||||
const issue = createIssue('config_error', {
|
||||
trigger: vi.fn(),
|
||||
});
|
||||
manager.addIssue(issue);
|
||||
|
||||
manager.trigger('config_error', { error: new Error('cfg') });
|
||||
|
||||
expect(issue.trigger).toBeCalledWith({ error: expect.any(Error) });
|
||||
});
|
||||
|
||||
it('should update presence even when state was mutated before detectDynamic', () => {
|
||||
const api = createCardAPI();
|
||||
vi.mocked(api.getConditionStateManager().getState).mockReturnValue({});
|
||||
vi.mocked(api.getConditionStateManager().setState).mockReturnValue(true);
|
||||
|
||||
const manager = new IssueManager(api);
|
||||
|
||||
// hasIssue returns true from the start — simulates trigger() having
|
||||
// already mutated state before detectDynamic snapshots. The
|
||||
// before/after check inside detectDynamic sees true→true (no
|
||||
// transition), but the presence comparison against ConditionState
|
||||
// must still detect the change.
|
||||
const description = createIssueDescription();
|
||||
const issue = createIssue('config_error', {
|
||||
hasIssue: vi.fn().mockReturnValue(true),
|
||||
getIssue: vi.fn().mockReturnValue(description),
|
||||
trigger: vi.fn(),
|
||||
});
|
||||
manager.addIssue(issue);
|
||||
|
||||
manager.trigger('config_error', { error: new Error('cfg') });
|
||||
|
||||
expect(api.getConditionStateManager().setState).toBeCalledWith({
|
||||
issues: new Map([['config_error', description]]),
|
||||
});
|
||||
expect(api.getCardElementManager().update).toBeCalled();
|
||||
});
|
||||
|
||||
it('should never auto-popup on trigger — non-full-card issues surface via the status-bar icon; user clicks to open', () => {
|
||||
const api = createCardAPI();
|
||||
vi.mocked(api.getConditionStateManager().getState).mockReturnValue({});
|
||||
|
||||
const manager = new IssueManager(api);
|
||||
|
||||
const issue = createIssue('view_incompatible', {
|
||||
hasIssue: vi.fn().mockReturnValue(true),
|
||||
isFullCardIssue: vi.fn().mockReturnValue(false),
|
||||
getIssue: vi.fn().mockReturnValue(createIssueDescription()),
|
||||
getNotification: vi.fn().mockReturnValue({ body: { text: 'noop' } }),
|
||||
trigger: vi.fn(),
|
||||
});
|
||||
manager.addIssue(issue);
|
||||
|
||||
manager.trigger('view_incompatible', { error: new Error('mismatch') });
|
||||
|
||||
expect(api.getNotificationManager().setNotification).not.toBeCalled();
|
||||
});
|
||||
});
|
||||
|
||||
describe('retry', () => {
|
||||
it('should call retry on the manager and reset the timer', () => {
|
||||
const { manager, issue } = createRetriableSetup();
|
||||
|
||||
// Start the timer via evaluate, then immediately retry.
|
||||
manager.evaluate();
|
||||
manager.retry('media_load');
|
||||
|
||||
expect(issue.retry).toBeCalled();
|
||||
|
||||
// Timer should have been reset — advancing less than retrySeconds
|
||||
// should not fire it again.
|
||||
assert(issue.retry);
|
||||
vi.mocked(issue.retry).mockClear();
|
||||
vi.advanceTimersByTime(500);
|
||||
expect(issue.retry).not.toBeCalled();
|
||||
});
|
||||
|
||||
it('should force retry even when needsRetry is false', () => {
|
||||
const api = createCardAPI();
|
||||
vi.mocked(api.getConditionStateManager().getState).mockReturnValue({});
|
||||
const manager = new IssueManager(api);
|
||||
const issue = createIssue('media_load', {
|
||||
retry: vi.fn().mockReturnValue(false),
|
||||
});
|
||||
manager.addIssue(issue);
|
||||
|
||||
manager.retry('media_load', true);
|
||||
|
||||
expect(issue.retry).toBeCalled();
|
||||
});
|
||||
});
|
||||
|
||||
describe('evaluate', () => {
|
||||
it('should update condition state and card when presence differs from state', () => {
|
||||
const api = createCardAPI();
|
||||
vi.mocked(api.getConditionStateManager().getState).mockReturnValue({});
|
||||
vi.mocked(api.getConditionStateManager().setState).mockReturnValue(true);
|
||||
|
||||
const manager = new IssueManager(api);
|
||||
const description = createIssueDescription();
|
||||
const issue = createIssue('config_error', {
|
||||
hasIssue: vi.fn().mockReturnValue(true),
|
||||
getIssue: vi.fn().mockReturnValue(description),
|
||||
});
|
||||
manager.addIssue(issue);
|
||||
|
||||
manager.evaluate();
|
||||
|
||||
expect(api.getConditionStateManager().setState).toBeCalledWith({
|
||||
issues: new Map([['config_error', description]]),
|
||||
});
|
||||
expect(api.getCardElementManager().update).toBeCalled();
|
||||
});
|
||||
|
||||
it('should sync presence to condition state without update when unchanged', () => {
|
||||
const api = createCardAPI();
|
||||
vi.mocked(api.getConditionStateManager().getState).mockReturnValue({});
|
||||
|
||||
const manager = new IssueManager(api);
|
||||
const issue = createIssue('config_error');
|
||||
manager.addIssue(issue);
|
||||
|
||||
manager.evaluate();
|
||||
|
||||
expect(api.getConditionStateManager().setState).toBeCalledWith({
|
||||
issues: new Map(),
|
||||
});
|
||||
expect(api.getCardElementManager().update).not.toBeCalled();
|
||||
});
|
||||
|
||||
it('should call update when an active issue swaps sub-states without changing the key set', () => {
|
||||
// Simulates ConnectionIssue going from 'lost' to 'starting': the
|
||||
// presence key set ({connection}) is identical, but the description
|
||||
// value differs. Because IssuePresence is a Map<key, description>,
|
||||
// the condition state diff sees the value-level change and fires
|
||||
// listeners — the IssueManager's own listener calls update().
|
||||
const api = createCardAPI();
|
||||
|
||||
// Real ConditionStateManager so its isEqual-based diff actually runs.
|
||||
const stateManager = new ConditionStateManager();
|
||||
vi.mocked(api.getConditionStateManager).mockReturnValue(stateManager);
|
||||
|
||||
const manager = new IssueManager(api);
|
||||
const getIssue = vi
|
||||
.fn()
|
||||
.mockReturnValue(
|
||||
createIssueDescription({ notification: { body: { text: 'lost' } } }),
|
||||
);
|
||||
const issue = createIssue('connection', {
|
||||
hasIssue: vi.fn().mockReturnValue(true),
|
||||
getIssue,
|
||||
});
|
||||
manager.addIssue(issue);
|
||||
|
||||
manager.evaluate();
|
||||
vi.mocked(api.getCardElementManager().update).mockClear();
|
||||
|
||||
// Same key set ({connection}), different description value.
|
||||
getIssue.mockReturnValue(
|
||||
createIssueDescription({ notification: { body: { text: 'starting' } } }),
|
||||
);
|
||||
manager.evaluate();
|
||||
|
||||
expect(api.getCardElementManager().update).toBeCalled();
|
||||
});
|
||||
|
||||
it('should not call update when content is identical across evaluations', () => {
|
||||
const api = createCardAPI();
|
||||
const stateManager = new ConditionStateManager();
|
||||
vi.mocked(api.getConditionStateManager).mockReturnValue(stateManager);
|
||||
|
||||
const manager = new IssueManager(api);
|
||||
const issue = createIssue('connection', {
|
||||
hasIssue: vi.fn().mockReturnValue(true),
|
||||
getIssue: vi.fn().mockReturnValue(createIssueDescription()),
|
||||
});
|
||||
manager.addIssue(issue);
|
||||
|
||||
manager.evaluate();
|
||||
vi.mocked(api.getCardElementManager().update).mockClear();
|
||||
|
||||
// Re-evaluate without any change.
|
||||
manager.evaluate();
|
||||
|
||||
expect(api.getCardElementManager().update).not.toBeCalled();
|
||||
});
|
||||
|
||||
it('should trigger evaluate from listener on condition state manager', () => {
|
||||
const api = createCardAPI();
|
||||
const stateManager = new ConditionStateManager();
|
||||
vi.mocked(api.getConditionStateManager).mockReturnValue(stateManager);
|
||||
|
||||
const manager = new IssueManager(api);
|
||||
const issue = createIssue('config_error', {
|
||||
hasIssue: vi.fn().mockReturnValue(true),
|
||||
detectDynamic: vi.fn(),
|
||||
});
|
||||
manager.addIssue(issue);
|
||||
|
||||
stateManager.setState({ view: 'live' });
|
||||
|
||||
expect(issue.detectDynamic).toBeCalled();
|
||||
});
|
||||
|
||||
it('should not re-enter evaluate when setState triggers listener', () => {
|
||||
const api = createCardAPI();
|
||||
const stateManager = new ConditionStateManager();
|
||||
vi.mocked(api.getConditionStateManager).mockReturnValue(stateManager);
|
||||
|
||||
const manager = new IssueManager(api);
|
||||
const issue = createIssue('config_error', {
|
||||
hasIssue: vi.fn().mockReturnValue(true),
|
||||
detectDynamic: vi.fn(),
|
||||
});
|
||||
manager.addIssue(issue);
|
||||
|
||||
// Calling evaluate() will call setState() on the real
|
||||
// ConditionStateManager, which fires listeners synchronously. The
|
||||
// reentrancy guard must prevent detectDynamic from running twice.
|
||||
manager.evaluate();
|
||||
|
||||
expect(issue.detectDynamic).toBeCalledTimes(1);
|
||||
});
|
||||
});
|
||||
|
||||
describe('showNotification', () => {
|
||||
it('should call setNotification when a notification is available', () => {
|
||||
const api = createCardAPI();
|
||||
vi.mocked(api.getConditionStateManager().getState).mockReturnValue({});
|
||||
const manager = new IssueManager(api);
|
||||
|
||||
const notification = { body: { text: 'test notification' } };
|
||||
const issue = createIssue('media_query', {
|
||||
getNotification: vi.fn().mockReturnValue(notification),
|
||||
});
|
||||
manager.addIssue(issue);
|
||||
|
||||
manager.showNotification('media_query');
|
||||
|
||||
expect(api.getNotificationManager().setNotification).toBeCalledWith(notification);
|
||||
});
|
||||
|
||||
it('should not call setNotification when no notification exists for key', () => {
|
||||
const manager = new IssueManager(createCardAPI());
|
||||
|
||||
manager.showNotification('initialization');
|
||||
|
||||
expect(createCardAPI().getNotificationManager().setNotification).not.toBeCalled();
|
||||
});
|
||||
});
|
||||
|
||||
describe('scheduled retries', () => {
|
||||
it('should not schedule a retry when no issue wants retry', () => {
|
||||
const api = createCardAPI();
|
||||
vi.mocked(api.getConditionStateManager().getState).mockReturnValue({});
|
||||
vi.mocked(api.getConfigManager().getConfig).mockReturnValue(createConfig());
|
||||
|
||||
const manager = new IssueManager(api);
|
||||
const issue = createIssue('config_error');
|
||||
manager.addIssue(issue);
|
||||
|
||||
manager.evaluate();
|
||||
vi.runAllTimers();
|
||||
|
||||
expect(api.getViewManager().setViewWithMergedContext).not.toBeCalled();
|
||||
});
|
||||
|
||||
it('should not schedule a retry when config is null', () => {
|
||||
const api = createCardAPI();
|
||||
vi.mocked(api.getConditionStateManager().getState).mockReturnValue({});
|
||||
vi.mocked(api.getConfigManager().getConfig).mockReturnValue(null);
|
||||
|
||||
const manager = new IssueManager(api);
|
||||
|
||||
const issue = createIssue('media_load', {
|
||||
hasIssue: vi.fn().mockReturnValueOnce(false).mockReturnValue(true),
|
||||
needsRetry: vi.fn().mockReturnValue(true),
|
||||
retry: vi.fn().mockReturnValue(false),
|
||||
});
|
||||
manager.addIssue(issue);
|
||||
|
||||
manager.evaluate();
|
||||
vi.runAllTimers();
|
||||
|
||||
expect(issue.retry).not.toBeCalled();
|
||||
});
|
||||
|
||||
it('should not schedule a retry when retry_seconds is 0', () => {
|
||||
const { manager, issue } = createRetriableSetup({ retrySeconds: 0 });
|
||||
|
||||
manager.evaluate();
|
||||
vi.runAllTimers();
|
||||
|
||||
expect(issue.retry).not.toBeCalled();
|
||||
});
|
||||
|
||||
it('should schedule a retry when an issue wants retry and retry_seconds > 0', () => {
|
||||
const { manager, issue } = createRetriableSetup({ retrySeconds: 5 });
|
||||
|
||||
manager.evaluate();
|
||||
vi.advanceTimersByTime(5000);
|
||||
|
||||
expect(issue.retry).toBeCalled();
|
||||
});
|
||||
|
||||
it('should call retry on the issue when the timer fires', () => {
|
||||
const { manager, issue } = createRetriableSetup();
|
||||
|
||||
manager.evaluate();
|
||||
vi.advanceTimersByTime(DEFAULT_RETRY_SECONDS * 1000);
|
||||
|
||||
expect(issue.retry).toBeCalled();
|
||||
});
|
||||
|
||||
it('should not schedule a second timer if one is already running', () => {
|
||||
const { manager, issue } = createRetriableSetup({ retrySeconds: 10 });
|
||||
|
||||
manager.evaluate();
|
||||
manager.evaluate();
|
||||
|
||||
vi.advanceTimersByTime(10000);
|
||||
|
||||
expect(issue.retry).toBeCalledTimes(1);
|
||||
});
|
||||
|
||||
it('should stop repeated timer when needsRetry becomes false', () => {
|
||||
const { manager, issue } = createRetriableSetup();
|
||||
|
||||
manager.evaluate();
|
||||
vi.advanceTimersByTime(DEFAULT_RETRY_SECONDS * 1000);
|
||||
expect(issue.retry).toBeCalledTimes(1);
|
||||
|
||||
assert(issue.needsRetry);
|
||||
vi.mocked(issue.needsRetry).mockReturnValue(false);
|
||||
vi.advanceTimersByTime(DEFAULT_RETRY_SECONDS * 1000);
|
||||
|
||||
expect(issue.retry).toBeCalledTimes(1);
|
||||
|
||||
vi.advanceTimersByTime(5000);
|
||||
expect(issue.retry).toBeCalledTimes(1);
|
||||
});
|
||||
|
||||
it('should skip scheduled retry when user is interacting and mode is inactive', () => {
|
||||
const { manager, issue } = createRetriableSetup({
|
||||
hasInteraction: true,
|
||||
});
|
||||
|
||||
manager.evaluate();
|
||||
vi.advanceTimersByTime(DEFAULT_RETRY_SECONDS * 1000);
|
||||
|
||||
expect(issue.retry).not.toBeCalled();
|
||||
});
|
||||
|
||||
it('should allow scheduled retry when user is not interacting and mode is inactive', () => {
|
||||
const { manager, issue } = createRetriableSetup({
|
||||
hasInteraction: false,
|
||||
});
|
||||
|
||||
manager.evaluate();
|
||||
vi.advanceTimersByTime(DEFAULT_RETRY_SECONDS * 1000);
|
||||
|
||||
expect(issue.retry).toBeCalled();
|
||||
});
|
||||
|
||||
it('should allow scheduled retry when mode is all regardless of interaction', () => {
|
||||
const { manager, issue } = createRetriableSetup({
|
||||
interactionMode: 'all',
|
||||
hasInteraction: true,
|
||||
});
|
||||
|
||||
manager.evaluate();
|
||||
vi.advanceTimersByTime(DEFAULT_RETRY_SECONDS * 1000);
|
||||
|
||||
expect(issue.retry).toBeCalled();
|
||||
});
|
||||
|
||||
it('should retry on next interval after interaction ends', () => {
|
||||
const { api, manager, issue } = createRetriableSetup({
|
||||
hasInteraction: true,
|
||||
});
|
||||
|
||||
manager.evaluate();
|
||||
vi.advanceTimersByTime(DEFAULT_RETRY_SECONDS * 1000);
|
||||
expect(issue.retry).not.toBeCalled();
|
||||
|
||||
vi.mocked(api.getInteractionManager().hasInteraction).mockReturnValue(false);
|
||||
vi.advanceTimersByTime(DEFAULT_RETRY_SECONDS * 1000);
|
||||
expect(issue.retry).toBeCalled();
|
||||
});
|
||||
});
|
||||
|
||||
describe('auto retry (exponential backoff)', () => {
|
||||
it('should schedule the first retry within the 15s–30s jitter range', () => {
|
||||
// Math.random returns 0 → jitter = 0.5 → delay = base * 0.5 = 15s.
|
||||
vi.spyOn(Math, 'random').mockReturnValue(0);
|
||||
const { manager, issue } = createRetriableSetup({ retrySeconds: 'auto' });
|
||||
manager.evaluate();
|
||||
|
||||
vi.advanceTimersByTime(RETRY_EXPONENTIAL_BASE_SECONDS * 0.5 * 1000 - 1);
|
||||
expect(issue.retry).not.toBeCalled();
|
||||
|
||||
vi.advanceTimersByTime(1);
|
||||
expect(issue.retry).toBeCalledTimes(1);
|
||||
});
|
||||
|
||||
it('should schedule the first retry at the upper bound when jitter is max', () => {
|
||||
// Math.random returns 1 → jitter = 1.0 → delay = base * 1.0 = 30s.
|
||||
vi.spyOn(Math, 'random').mockReturnValue(1);
|
||||
const { manager, issue } = createRetriableSetup({ retrySeconds: 'auto' });
|
||||
manager.evaluate();
|
||||
|
||||
vi.advanceTimersByTime(RETRY_EXPONENTIAL_BASE_SECONDS * 1.0 * 1000 - 1);
|
||||
expect(issue.retry).not.toBeCalled();
|
||||
|
||||
vi.advanceTimersByTime(1);
|
||||
expect(issue.retry).toBeCalledTimes(1);
|
||||
});
|
||||
|
||||
it('should double the base delay on each successive attempt', () => {
|
||||
// Math.random returns 0.5 → jitter = 0.75 → delays: 22.5, 45, 90 seconds.
|
||||
vi.spyOn(Math, 'random').mockReturnValue(0.5);
|
||||
const { manager, issue } = createRetriableSetup({ retrySeconds: 'auto' });
|
||||
manager.evaluate();
|
||||
|
||||
vi.advanceTimersByTime(RETRY_EXPONENTIAL_BASE_SECONDS * 0.75 * 1000);
|
||||
expect(issue.retry).toBeCalledTimes(1);
|
||||
|
||||
vi.advanceTimersByTime(RETRY_EXPONENTIAL_BASE_SECONDS * 2 * 0.75 * 1000);
|
||||
expect(issue.retry).toBeCalledTimes(2);
|
||||
|
||||
vi.advanceTimersByTime(RETRY_EXPONENTIAL_BASE_SECONDS * 4 * 0.75 * 1000);
|
||||
expect(issue.retry).toBeCalledTimes(3);
|
||||
});
|
||||
|
||||
it('should cap the backoff at the max delay', () => {
|
||||
// Drive 5 pre-cap attempts (30, 60, 120, 240, 480 seconds), then assert
|
||||
// the 6th attempt clamps to MAX instead of the would-be 960.
|
||||
vi.spyOn(Math, 'random').mockReturnValue(1);
|
||||
const { manager, issue } = createRetriableSetup({ retrySeconds: 'auto' });
|
||||
manager.evaluate();
|
||||
|
||||
vi.advanceTimersByTime(RETRY_EXPONENTIAL_BASE_SECONDS * 1 * 1000);
|
||||
vi.advanceTimersByTime(RETRY_EXPONENTIAL_BASE_SECONDS * 2 * 1000);
|
||||
vi.advanceTimersByTime(RETRY_EXPONENTIAL_BASE_SECONDS * 4 * 1000);
|
||||
vi.advanceTimersByTime(RETRY_EXPONENTIAL_BASE_SECONDS * 8 * 1000);
|
||||
vi.advanceTimersByTime(RETRY_EXPONENTIAL_BASE_SECONDS * 16 * 1000);
|
||||
expect(issue.retry).toBeCalledTimes(5);
|
||||
|
||||
vi.advanceTimersByTime(RETRY_EXPONENTIAL_MAX_SECONDS * 1000);
|
||||
expect(issue.retry).toBeCalledTimes(6);
|
||||
});
|
||||
|
||||
it('should reset the attempt counter when the issue clears', () => {
|
||||
vi.spyOn(Math, 'random').mockReturnValue(0.5);
|
||||
const { manager, issue } = createRetriableSetup({ retrySeconds: 'auto' });
|
||||
manager.evaluate();
|
||||
|
||||
// Run two retries — second delay should be 2x the first.
|
||||
vi.advanceTimersByTime(RETRY_EXPONENTIAL_BASE_SECONDS * 0.75 * 1000);
|
||||
vi.advanceTimersByTime(RETRY_EXPONENTIAL_BASE_SECONDS * 2 * 0.75 * 1000);
|
||||
expect(issue.retry).toBeCalledTimes(2);
|
||||
|
||||
// Clear the issue: needsRetry returns false. The next timer fire sees
|
||||
// it cleared and resets the attempt counter.
|
||||
assert(issue.needsRetry);
|
||||
vi.mocked(issue.needsRetry).mockReturnValue(false);
|
||||
vi.advanceTimersByTime(RETRY_EXPONENTIAL_BASE_SECONDS * 4 * 0.75 * 1000);
|
||||
expect(issue.retry).toBeCalledTimes(2);
|
||||
|
||||
// Re-arm: needsRetry returns true again, evaluate to re-schedule.
|
||||
vi.mocked(issue.needsRetry).mockReturnValue(true);
|
||||
manager.evaluate();
|
||||
|
||||
// Next delay should be back at the base (attempt 0), not continuing
|
||||
// from where we left off.
|
||||
vi.advanceTimersByTime(RETRY_EXPONENTIAL_BASE_SECONDS * 0.75 * 1000);
|
||||
expect(issue.retry).toBeCalledTimes(3);
|
||||
});
|
||||
|
||||
it('should not grow the delay while retries are gated by user interaction', () => {
|
||||
// Auto mode + interaction gating: when the timer fires while the user
|
||||
// is interacting, the retry is skipped (not counted as an attempt) and
|
||||
// the timer re-arms at the *same* delay, not the next exponential step.
|
||||
vi.spyOn(Math, 'random').mockReturnValue(0.5);
|
||||
const { api, manager, issue } = createRetriableSetup({
|
||||
retrySeconds: 'auto',
|
||||
hasInteraction: true,
|
||||
});
|
||||
manager.evaluate();
|
||||
|
||||
// Three gated firings — each at the base delay (22.5s with 0.75 jitter).
|
||||
// If the counter were incrementing on gated fires, the second would be
|
||||
// at 45s and we'd never reach it after only 22.5s.
|
||||
vi.advanceTimersByTime(RETRY_EXPONENTIAL_BASE_SECONDS * 0.75 * 1000);
|
||||
vi.advanceTimersByTime(RETRY_EXPONENTIAL_BASE_SECONDS * 0.75 * 1000);
|
||||
vi.advanceTimersByTime(RETRY_EXPONENTIAL_BASE_SECONDS * 0.75 * 1000);
|
||||
expect(issue.retry).not.toBeCalled();
|
||||
|
||||
// Clear the interaction. The next firing — still at the base delay —
|
||||
// is now allowed and the retry runs.
|
||||
vi.mocked(api.getInteractionManager().hasInteraction).mockReturnValue(false);
|
||||
vi.advanceTimersByTime(RETRY_EXPONENTIAL_BASE_SECONDS * 0.75 * 1000);
|
||||
expect(issue.retry).toBeCalledTimes(1);
|
||||
});
|
||||
|
||||
it('should reset the attempt counter when retries are disabled and re-enabled', () => {
|
||||
// Drive auto-mode retries to push _retryAttempt > 0, then disable
|
||||
// retries (retry_seconds=0) and re-enable. The next retry must fire at
|
||||
// the base delay, not at the inflated delay the prior counter implies.
|
||||
vi.spyOn(Math, 'random').mockReturnValue(0.5);
|
||||
const { api, manager, issue } = createRetriableSetup({ retrySeconds: 'auto' });
|
||||
manager.evaluate();
|
||||
|
||||
vi.advanceTimersByTime(RETRY_EXPONENTIAL_BASE_SECONDS * 0.75 * 1000);
|
||||
vi.advanceTimersByTime(RETRY_EXPONENTIAL_BASE_SECONDS * 2 * 0.75 * 1000);
|
||||
expect(issue.retry).toBeCalledTimes(2);
|
||||
|
||||
// Disable retries via config.
|
||||
const config = createConfig();
|
||||
vi.mocked(api.getConfigManager().getConfig).mockReturnValue({
|
||||
...config,
|
||||
view: {
|
||||
...config.view,
|
||||
issues: { interaction_mode: 'inactive', retry_seconds: 0 },
|
||||
},
|
||||
});
|
||||
|
||||
// Let the pending timer fire. The retry runs (#3), then evaluate sees
|
||||
// retry_seconds=0 and resets _retryAttempt.
|
||||
vi.advanceTimersByTime(RETRY_EXPONENTIAL_BASE_SECONDS * 4 * 0.75 * 1000);
|
||||
expect(issue.retry).toBeCalledTimes(3);
|
||||
|
||||
// Re-enable.
|
||||
vi.mocked(api.getConfigManager().getConfig).mockReturnValue({
|
||||
...config,
|
||||
view: {
|
||||
...config.view,
|
||||
issues: { interaction_mode: 'inactive', retry_seconds: 'auto' },
|
||||
},
|
||||
});
|
||||
manager.evaluate();
|
||||
|
||||
// Without the reset, _retryAttempt would be 3 here, making the next
|
||||
// delay BASE * 8 * 0.75 = 180s. With the reset, it's BASE * 0.75 = 22.5s,
|
||||
// so advancing only the base interval triggers the next retry.
|
||||
vi.advanceTimersByTime(RETRY_EXPONENTIAL_BASE_SECONDS * 0.75 * 1000);
|
||||
expect(issue.retry).toBeCalledTimes(4);
|
||||
});
|
||||
});
|
||||
|
||||
describe('reset', () => {
|
||||
it('should reset a specific issue and re-evaluate', () => {
|
||||
const api = createCardAPI();
|
||||
vi.mocked(api.getConditionStateManager().getState).mockReturnValue({});
|
||||
|
||||
const manager = new IssueManager(api);
|
||||
|
||||
const issue = createIssue('config_error', {
|
||||
hasIssue: vi.fn().mockReturnValue(true),
|
||||
getIssue: vi.fn().mockReturnValue(createIssueDescription()),
|
||||
reset: vi.fn(),
|
||||
});
|
||||
manager.addIssue(issue);
|
||||
|
||||
manager.reset('config_error');
|
||||
|
||||
expect(issue.reset).toBeCalled();
|
||||
});
|
||||
|
||||
it('should skip reset when targeted key has no active issue', () => {
|
||||
const api = createCardAPI();
|
||||
vi.mocked(api.getConditionStateManager().getState).mockReturnValue({});
|
||||
|
||||
const manager = new IssueManager(api);
|
||||
|
||||
const issue = createIssue('config_error', {
|
||||
hasIssue: vi.fn().mockReturnValue(false),
|
||||
detectDynamic: vi.fn(),
|
||||
reset: vi.fn(),
|
||||
});
|
||||
manager.addIssue(issue);
|
||||
|
||||
manager.reset('config_error');
|
||||
|
||||
expect(issue.reset).not.toBeCalled();
|
||||
expect(issue.detectDynamic).not.toBeCalled();
|
||||
});
|
||||
});
|
||||
|
||||
describe('suspend / resume', () => {
|
||||
it('should stop the retry timer on suspend', () => {
|
||||
const { manager, issue } = createRetriableSetup({ retrySeconds: 5 });
|
||||
|
||||
manager.evaluate();
|
||||
manager.suspend();
|
||||
|
||||
vi.advanceTimersByTime(5000);
|
||||
|
||||
expect(issue.retry).not.toBeCalled();
|
||||
});
|
||||
|
||||
it('should gate evaluate while suspended', () => {
|
||||
const api = createCardAPI();
|
||||
vi.mocked(api.getConditionStateManager().getState).mockReturnValue({});
|
||||
|
||||
const manager = new IssueManager(api);
|
||||
const issue = createIssue('config_error', {
|
||||
hasIssue: vi.fn().mockReturnValue(true),
|
||||
detectDynamic: vi.fn(),
|
||||
});
|
||||
manager.addIssue(issue);
|
||||
|
||||
manager.suspend();
|
||||
manager.evaluate();
|
||||
|
||||
expect(issue.detectDynamic).not.toBeCalled();
|
||||
});
|
||||
|
||||
it('should preserve issue state across suspend', () => {
|
||||
const api = createCardAPI();
|
||||
vi.mocked(api.getConditionStateManager().getState).mockReturnValue({});
|
||||
|
||||
const manager = new IssueManager(api);
|
||||
const issue = createIssue('config_error', {
|
||||
hasIssue: vi.fn().mockReturnValue(true),
|
||||
getIssue: vi.fn().mockReturnValue(createIssueDescription()),
|
||||
});
|
||||
manager.addIssue(issue);
|
||||
|
||||
manager.suspend();
|
||||
|
||||
expect(manager.getStateManager().getIssuePresence().has('config_error')).toBe(
|
||||
true,
|
||||
);
|
||||
});
|
||||
|
||||
it('should resume evaluation on resume', () => {
|
||||
const api = createCardAPI();
|
||||
vi.mocked(api.getConditionStateManager().getState).mockReturnValue({});
|
||||
vi.mocked(api.getConditionStateManager().setState).mockReturnValue(true);
|
||||
|
||||
const manager = new IssueManager(api);
|
||||
const issue = createIssue('config_error', {
|
||||
hasIssue: vi.fn().mockReturnValue(true),
|
||||
detectDynamic: vi.fn(),
|
||||
});
|
||||
manager.addIssue(issue);
|
||||
|
||||
manager.suspend();
|
||||
manager.resume();
|
||||
|
||||
expect(issue.detectDynamic).toBeCalled();
|
||||
expect(api.getCardElementManager().update).toBeCalled();
|
||||
});
|
||||
|
||||
it('should invoke Issue.suspend on timer-backed issues when suspended', () => {
|
||||
const api = createCardAPI();
|
||||
vi.mocked(api.getConditionStateManager().getState).mockReturnValue({});
|
||||
|
||||
const manager = new IssueManager(api);
|
||||
const issue = createIssue('media_load', { suspend: vi.fn() });
|
||||
manager.addIssue(issue);
|
||||
|
||||
manager.suspend();
|
||||
|
||||
expect(issue.suspend).toBeCalled();
|
||||
});
|
||||
|
||||
it('should tolerate issues without a suspend hook', () => {
|
||||
const api = createCardAPI();
|
||||
vi.mocked(api.getConditionStateManager().getState).mockReturnValue({});
|
||||
|
||||
const manager = new IssueManager(api);
|
||||
// Plain Issue implementation — no optional methods installed.
|
||||
const issue: Issue = {
|
||||
key: 'config_error',
|
||||
hasIssue: () => false,
|
||||
getIssue: () => null,
|
||||
};
|
||||
manager.addIssue(issue);
|
||||
|
||||
// Must not throw.
|
||||
manager.suspend();
|
||||
});
|
||||
});
|
||||
|
||||
describe('destroy', () => {
|
||||
it('should stop the retry timer and destroy the manager', () => {
|
||||
const { manager, issue } = createRetriableSetup({ retrySeconds: 5 });
|
||||
assert(issue.reset);
|
||||
|
||||
manager.evaluate();
|
||||
manager.destroy();
|
||||
|
||||
vi.advanceTimersByTime(5000);
|
||||
|
||||
expect(issue.retry).not.toBeCalled();
|
||||
expect(issue.reset).toBeCalled();
|
||||
});
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,71 @@
|
||||
import { describe, expect, it } from 'vitest';
|
||||
import { ConfigErrorIssue } from '../../../../src/card-controller/issues/issues/config-error';
|
||||
|
||||
describe('ConfigErrorIssue', () => {
|
||||
it('should have correct key', () => {
|
||||
const issue = new ConfigErrorIssue();
|
||||
expect(issue.key).toBe('config_error');
|
||||
});
|
||||
|
||||
it('should report no issue when untriggered', () => {
|
||||
const issue = new ConfigErrorIssue();
|
||||
expect(issue.hasIssue()).toBe(false);
|
||||
expect(issue.getIssue()).toBeNull();
|
||||
});
|
||||
|
||||
it('should report an issue after trigger with an error', () => {
|
||||
const issue = new ConfigErrorIssue();
|
||||
issue.trigger({ error: new Error('bad config') });
|
||||
|
||||
expect(issue.hasIssue()).toBe(true);
|
||||
});
|
||||
|
||||
it('should report an issue after trigger with a string error', () => {
|
||||
const issue = new ConfigErrorIssue();
|
||||
issue.trigger({ error: 'string error' });
|
||||
|
||||
expect(issue.hasIssue()).toBe(true);
|
||||
});
|
||||
|
||||
it('should treat a triggered null/undefined error as no issue', () => {
|
||||
const issue = new ConfigErrorIssue();
|
||||
issue.trigger({ error: undefined });
|
||||
|
||||
expect(issue.hasIssue()).toBe(false);
|
||||
expect(issue.getIssue()).toBeNull();
|
||||
});
|
||||
|
||||
it('isFullCardIssue should return true', () => {
|
||||
const issue = new ConfigErrorIssue();
|
||||
expect(issue.isFullCardIssue()).toBe(true);
|
||||
});
|
||||
|
||||
it('getIssue should return a IssueDescription with expected shape', () => {
|
||||
const issue = new ConfigErrorIssue();
|
||||
issue.trigger({ error: new Error('config is invalid') });
|
||||
|
||||
const result = issue.getIssue();
|
||||
expect(result).toEqual(
|
||||
expect.objectContaining({
|
||||
icon: 'mdi:alert',
|
||||
severity: 'high',
|
||||
notification: expect.objectContaining({
|
||||
body: expect.objectContaining({
|
||||
text: 'config is invalid',
|
||||
}),
|
||||
}),
|
||||
}),
|
||||
);
|
||||
});
|
||||
|
||||
it('should clear the issue after reset', () => {
|
||||
const issue = new ConfigErrorIssue();
|
||||
issue.trigger({ error: new Error('oops') });
|
||||
expect(issue.hasIssue()).toBe(true);
|
||||
|
||||
issue.reset();
|
||||
|
||||
expect(issue.hasIssue()).toBe(false);
|
||||
expect(issue.getIssue()).toBeNull();
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,71 @@
|
||||
import { describe, expect, it, vi } from 'vitest';
|
||||
import { ConfigUpgradeIssue } from '../../../../src/card-controller/issues/issues/config-upgrade';
|
||||
import { isConfigUpgradeable } from '../../../../src/config/management';
|
||||
import { RawAdvancedCameraCardConfig } from '../../../../src/config/types';
|
||||
import { createCardAPI } from '../../../test-utils';
|
||||
|
||||
vi.mock('../../../../src/config/management.js');
|
||||
|
||||
const createAPI = (rawConfig?: RawAdvancedCameraCardConfig) => {
|
||||
const api = createCardAPI();
|
||||
vi.mocked(api.getConfigManager().getRawConfig).mockReturnValue(rawConfig ?? null);
|
||||
return api;
|
||||
};
|
||||
|
||||
describe('ConfigUpgradeIssue', () => {
|
||||
it('should have correct key', () => {
|
||||
const issue = new ConfigUpgradeIssue(createAPI());
|
||||
expect(issue.key).toBe('config_upgrade');
|
||||
});
|
||||
|
||||
it('should detect upgradeable config', async () => {
|
||||
vi.mocked(isConfigUpgradeable).mockReturnValue(true);
|
||||
const rawConfig = { type: 'custom:frigate-card' };
|
||||
const issue = new ConfigUpgradeIssue(createAPI(rawConfig));
|
||||
|
||||
await issue.detectStatic();
|
||||
|
||||
expect(issue.hasIssue()).toBe(true);
|
||||
expect(isConfigUpgradeable).toBeCalledWith(rawConfig);
|
||||
});
|
||||
|
||||
it('should detect non-upgradeable config', async () => {
|
||||
vi.mocked(isConfigUpgradeable).mockReturnValue(false);
|
||||
const rawConfig = { type: 'custom:advanced-camera-card' };
|
||||
const issue = new ConfigUpgradeIssue(createAPI(rawConfig));
|
||||
|
||||
await issue.detectStatic();
|
||||
|
||||
expect(issue.hasIssue()).toBe(false);
|
||||
});
|
||||
|
||||
it('should handle null raw config', async () => {
|
||||
const issue = new ConfigUpgradeIssue(createAPI());
|
||||
|
||||
await issue.detectStatic();
|
||||
|
||||
expect(issue.hasIssue()).toBe(false);
|
||||
expect(issue.getIssue()).toBeNull();
|
||||
});
|
||||
|
||||
it('should return result when upgradeable', async () => {
|
||||
vi.mocked(isConfigUpgradeable).mockReturnValue(true);
|
||||
const issue = new ConfigUpgradeIssue(createAPI({ type: 'custom:frigate-card' }));
|
||||
|
||||
await issue.detectStatic();
|
||||
|
||||
const result = issue.getIssue();
|
||||
expect(result).toEqual(
|
||||
expect.objectContaining({
|
||||
icon: 'mdi:update',
|
||||
severity: 'medium',
|
||||
notification: expect.objectContaining({
|
||||
heading: expect.objectContaining({
|
||||
icon: 'mdi:update',
|
||||
severity: 'medium',
|
||||
}),
|
||||
}),
|
||||
}),
|
||||
);
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,127 @@
|
||||
import { STATE_RUNNING, STATE_STARTING } from 'home-assistant-js-websocket';
|
||||
import { describe, expect, it } from 'vitest';
|
||||
import { ConnectionIssue } from '../../../../src/card-controller/issues/issues/connection';
|
||||
import { createHASS } from '../../../test-utils';
|
||||
|
||||
describe('ConnectionIssue', () => {
|
||||
it('should have correct key', () => {
|
||||
const issue = new ConnectionIssue();
|
||||
expect(issue.key).toBe('connection');
|
||||
});
|
||||
|
||||
it('should report no issue when hass has never been set', () => {
|
||||
const issue = new ConnectionIssue();
|
||||
|
||||
issue.detectDynamic({});
|
||||
|
||||
expect(issue.hasIssue()).toBe(false);
|
||||
expect(issue.getIssue()).toBeNull();
|
||||
});
|
||||
|
||||
it('should report a lost issue when hass is disconnected', () => {
|
||||
const issue = new ConnectionIssue();
|
||||
const hass = createHASS();
|
||||
hass.connected = false;
|
||||
|
||||
issue.detectDynamic({ hass });
|
||||
|
||||
expect(issue.hasIssue()).toBe(true);
|
||||
expect(issue.getIssue()).toEqual(
|
||||
expect.objectContaining({
|
||||
icon: 'mdi:lan-disconnect',
|
||||
severity: 'high',
|
||||
notification: expect.objectContaining({
|
||||
in_progress: true,
|
||||
heading: expect.objectContaining({
|
||||
text: 'Connection lost',
|
||||
icon: 'mdi:lan-disconnect',
|
||||
severity: 'high',
|
||||
}),
|
||||
body: expect.objectContaining({
|
||||
text: 'Connection to Home Assistant lost',
|
||||
}),
|
||||
}),
|
||||
}),
|
||||
);
|
||||
});
|
||||
|
||||
it('should report a starting issue when hass is connected but not running', () => {
|
||||
const issue = new ConnectionIssue();
|
||||
const hass = createHASS();
|
||||
hass.connected = true;
|
||||
hass.config.state = STATE_STARTING;
|
||||
|
||||
issue.detectDynamic({ hass });
|
||||
|
||||
expect(issue.hasIssue()).toBe(true);
|
||||
expect(issue.getIssue()).toEqual(
|
||||
expect.objectContaining({
|
||||
icon: 'mdi:home-assistant',
|
||||
severity: 'medium',
|
||||
notification: expect.objectContaining({
|
||||
in_progress: true,
|
||||
heading: expect.objectContaining({
|
||||
text: 'Home Assistant is starting',
|
||||
icon: 'mdi:home-assistant',
|
||||
severity: 'medium',
|
||||
}),
|
||||
body: expect.objectContaining({
|
||||
text: 'Waiting for Home Assistant startup to complete',
|
||||
}),
|
||||
}),
|
||||
}),
|
||||
);
|
||||
});
|
||||
|
||||
it('should not report an issue when hass is connected and running', () => {
|
||||
const issue = new ConnectionIssue();
|
||||
const hass = createHASS();
|
||||
hass.connected = true;
|
||||
hass.config.state = STATE_RUNNING;
|
||||
|
||||
issue.detectDynamic({ hass });
|
||||
|
||||
expect(issue.hasIssue()).toBe(false);
|
||||
expect(issue.getIssue()).toBeNull();
|
||||
});
|
||||
|
||||
it('should clear when hass transitions lost → starting → ready', () => {
|
||||
const issue = new ConnectionIssue();
|
||||
const hass = createHASS();
|
||||
|
||||
hass.connected = false;
|
||||
issue.detectDynamic({ hass });
|
||||
expect(issue.hasIssue()).toBe(true);
|
||||
expect(issue.getIssue()?.notification.heading?.text).toBe('Connection lost');
|
||||
|
||||
hass.connected = true;
|
||||
hass.config.state = STATE_STARTING;
|
||||
issue.detectDynamic({ hass });
|
||||
expect(issue.hasIssue()).toBe(true);
|
||||
expect(issue.getIssue()?.notification.heading?.text).toBe(
|
||||
'Home Assistant is starting',
|
||||
);
|
||||
|
||||
hass.config.state = STATE_RUNNING;
|
||||
issue.detectDynamic({ hass });
|
||||
expect(issue.hasIssue()).toBe(false);
|
||||
});
|
||||
|
||||
it('should return true for isFullCardIssue', () => {
|
||||
const issue = new ConnectionIssue();
|
||||
expect(issue.isFullCardIssue()).toBe(true);
|
||||
});
|
||||
|
||||
it('should clear the issue after reset', () => {
|
||||
const issue = new ConnectionIssue();
|
||||
const hass = createHASS();
|
||||
hass.connected = false;
|
||||
issue.detectDynamic({ hass });
|
||||
expect(issue.hasIssue()).toBe(true);
|
||||
|
||||
issue.reset();
|
||||
|
||||
expect(issue.hasIssue()).toBe(false);
|
||||
expect(issue.getIssue()).toBeNull();
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,153 @@
|
||||
import { assert, describe, expect, it, vi } from 'vitest';
|
||||
import { CardController } from '../../../../src/card-controller/controller';
|
||||
import { InitializationIssue } from '../../../../src/card-controller/issues/issues/initialization';
|
||||
import { InternalCallbackActionConfig } from '../../../../src/config/schema/actions/custom/internal';
|
||||
import { createCardAPI } from '../../../test-utils';
|
||||
|
||||
describe('InitializationIssue', () => {
|
||||
const createAPI = (isInitializedMandatory = false): CardController => {
|
||||
const api = createCardAPI();
|
||||
vi.mocked(api.getInitializationManager().isInitializedMandatory).mockReturnValue(
|
||||
isInitializedMandatory,
|
||||
);
|
||||
return api;
|
||||
};
|
||||
|
||||
it('should have correct key', () => {
|
||||
const issue = new InitializationIssue(createAPI());
|
||||
expect(issue.key).toBe('initialization');
|
||||
});
|
||||
|
||||
it('should report no issue when untriggered', () => {
|
||||
const issue = new InitializationIssue(createAPI());
|
||||
expect(issue.hasIssue()).toBe(false);
|
||||
expect(issue.getIssue()).toBeNull();
|
||||
});
|
||||
|
||||
it('should report an issue after trigger', () => {
|
||||
const issue = new InitializationIssue(createAPI());
|
||||
issue.trigger({ error: new Error('init failed') });
|
||||
|
||||
expect(issue.hasIssue()).toBe(true);
|
||||
});
|
||||
|
||||
it('should treat a triggered null/undefined error as no issue', () => {
|
||||
const issue = new InitializationIssue(createAPI());
|
||||
issue.trigger({ error: undefined });
|
||||
|
||||
expect(issue.hasIssue()).toBe(false);
|
||||
expect(issue.getIssue()).toBeNull();
|
||||
expect(issue.needsRetry()).toBe(false);
|
||||
});
|
||||
|
||||
it('should return true for isFullCardIssue', () => {
|
||||
const issue = new InitializationIssue(createAPI());
|
||||
expect(issue.isFullCardIssue()).toBe(true);
|
||||
});
|
||||
|
||||
it('should return notification from error via getIssue', () => {
|
||||
const issue = new InitializationIssue(createAPI());
|
||||
issue.trigger({ error: new Error('init failed') });
|
||||
|
||||
const result = issue.getIssue();
|
||||
expect(result).toEqual(
|
||||
expect.objectContaining({
|
||||
icon: 'mdi:alert',
|
||||
severity: 'high',
|
||||
notification: expect.objectContaining({
|
||||
heading: expect.objectContaining({ text: 'Initialization failed' }),
|
||||
body: expect.objectContaining({ text: 'init failed' }),
|
||||
controls: expect.arrayContaining([
|
||||
expect.objectContaining({ icon: 'mdi:refresh', dismiss: true }),
|
||||
]),
|
||||
}),
|
||||
}),
|
||||
);
|
||||
expect(result?.notification.in_progress).toBeUndefined();
|
||||
});
|
||||
|
||||
it('should call manager.retry with the issue key from getIssue retry control callback', async () => {
|
||||
const api = createCardAPI();
|
||||
const issue = new InitializationIssue(api);
|
||||
issue.trigger({ error: new Error('init failed') });
|
||||
|
||||
const control = issue.getIssue()?.notification.controls?.[0];
|
||||
assert(control);
|
||||
const tapAction = control.actions?.tap_action as InternalCallbackActionConfig;
|
||||
await tapAction.callback(api);
|
||||
|
||||
expect(api.getIssueManager().retry).toBeCalledWith('initialization', true);
|
||||
});
|
||||
|
||||
describe('detectDynamic', () => {
|
||||
it('should clear the issue when initialization is now mandatory', () => {
|
||||
const issue = new InitializationIssue(createAPI(true));
|
||||
issue.trigger({ error: new Error('init failed') });
|
||||
expect(issue.hasIssue()).toBe(true);
|
||||
|
||||
issue.detectDynamic();
|
||||
|
||||
expect(issue.hasIssue()).toBe(false);
|
||||
expect(issue.getIssue()).toBeNull();
|
||||
});
|
||||
|
||||
it('should keep the issue when initialization is still not mandatory', () => {
|
||||
const issue = new InitializationIssue(createAPI(false));
|
||||
issue.trigger({ error: new Error('init failed') });
|
||||
|
||||
issue.detectDynamic();
|
||||
|
||||
expect(issue.hasIssue()).toBe(true);
|
||||
});
|
||||
|
||||
it('should do nothing when not failed', () => {
|
||||
const api = createAPI(false);
|
||||
const issue = new InitializationIssue(api);
|
||||
|
||||
issue.detectDynamic();
|
||||
|
||||
expect(issue.hasIssue()).toBe(false);
|
||||
expect(api.getInitializationManager().isInitializedMandatory).not.toBeCalled();
|
||||
});
|
||||
});
|
||||
|
||||
describe('needsRetry', () => {
|
||||
it('should return true when failed', () => {
|
||||
const issue = new InitializationIssue(createAPI());
|
||||
issue.trigger({ error: new Error('init failed') });
|
||||
expect(issue.needsRetry()).toBe(true);
|
||||
});
|
||||
|
||||
it('should return false when not failed', () => {
|
||||
const issue = new InitializationIssue(createAPI());
|
||||
expect(issue.needsRetry()).toBe(false);
|
||||
});
|
||||
});
|
||||
|
||||
describe('retry', () => {
|
||||
it('should uninitialize mandatory initialization and destroy camera manager', () => {
|
||||
const api = createAPI();
|
||||
const issue = new InitializationIssue(api);
|
||||
issue.trigger({ error: new Error('init failed') });
|
||||
|
||||
const result = issue.retry();
|
||||
|
||||
expect(result).toBe(false);
|
||||
expect(issue.hasIssue()).toBe(false);
|
||||
expect(issue.needsRetry()).toBe(false);
|
||||
expect(api.getInitializationManager().uninitializeMandatory).toBeCalled();
|
||||
expect(api.getCameraManager().destroy).toBeCalled();
|
||||
});
|
||||
});
|
||||
|
||||
it('should clear the issue after reset', () => {
|
||||
const issue = new InitializationIssue(createAPI());
|
||||
issue.trigger({ error: new Error('oops') });
|
||||
expect(issue.hasIssue()).toBe(true);
|
||||
|
||||
issue.reset();
|
||||
|
||||
expect(issue.hasIssue()).toBe(false);
|
||||
expect(issue.getIssue()).toBeNull();
|
||||
});
|
||||
});
|
||||
+103
-69
@@ -1,5 +1,5 @@
|
||||
import { beforeEach, describe, expect, it, vi } from 'vitest';
|
||||
import { LegacyResourceProblem } from '../../../../src/card-controller/problems/problems/legacy-resource';
|
||||
import { LegacyResourceIssue } from '../../../../src/card-controller/issues/issues/legacy-resource';
|
||||
import { HomeAssistant } from '../../../../src/ha/types';
|
||||
import { createCardAPI, createHASS, createUser } from '../../../test-utils';
|
||||
|
||||
@@ -11,28 +11,28 @@ const setupHASSResources = (
|
||||
vi.mocked(hass.callWS).mockResolvedValue(resources);
|
||||
};
|
||||
|
||||
describe('LegacyResourceProblem', () => {
|
||||
describe('LegacyResourceIssue', () => {
|
||||
beforeEach(() => {
|
||||
vi.resetAllMocks();
|
||||
});
|
||||
|
||||
it('should have correct key', () => {
|
||||
const problem = new LegacyResourceProblem(vi.fn());
|
||||
expect(problem.key).toBe('legacy_resource');
|
||||
const issue = new LegacyResourceIssue();
|
||||
expect(issue.key).toBe('legacy_resource');
|
||||
});
|
||||
|
||||
describe('detectStatic', () => {
|
||||
it('should skip non-admin users', async () => {
|
||||
const problem = new LegacyResourceProblem(vi.fn());
|
||||
const issue = new LegacyResourceIssue();
|
||||
const hass = createHASS(undefined, createUser({ is_admin: false }));
|
||||
|
||||
await problem.detectStatic(hass);
|
||||
await issue.detectStatic(hass);
|
||||
|
||||
expect(problem.hasResult()).toBe(false);
|
||||
expect(issue.hasIssue()).toBe(false);
|
||||
});
|
||||
|
||||
it('should detect legacy resource regardless of directory', async () => {
|
||||
const problem = new LegacyResourceProblem(vi.fn());
|
||||
const issue = new LegacyResourceIssue();
|
||||
const hass = createHASS(undefined, createUser({ is_admin: true }));
|
||||
setupHASSResources(hass, [
|
||||
{
|
||||
@@ -42,13 +42,13 @@ describe('LegacyResourceProblem', () => {
|
||||
},
|
||||
]);
|
||||
|
||||
await problem.detectStatic(hass);
|
||||
await issue.detectStatic(hass);
|
||||
|
||||
expect(problem.hasResult()).toBe(true);
|
||||
expect(issue.hasIssue()).toBe(true);
|
||||
});
|
||||
|
||||
it('should not detect when only advanced-camera-card exists', async () => {
|
||||
const problem = new LegacyResourceProblem(vi.fn());
|
||||
const issue = new LegacyResourceIssue();
|
||||
const hass = createHASS(undefined, createUser({ is_admin: true }));
|
||||
setupHASSResources(hass, [
|
||||
{
|
||||
@@ -58,45 +58,45 @@ describe('LegacyResourceProblem', () => {
|
||||
},
|
||||
]);
|
||||
|
||||
await problem.detectStatic(hass);
|
||||
await issue.detectStatic(hass);
|
||||
|
||||
expect(problem.hasResult()).toBe(false);
|
||||
expect(issue.hasIssue()).toBe(false);
|
||||
});
|
||||
|
||||
it('should handle invalid resource data', async () => {
|
||||
const problem = new LegacyResourceProblem(vi.fn());
|
||||
const issue = new LegacyResourceIssue();
|
||||
const hass = createHASS(undefined, createUser({ is_admin: true }));
|
||||
vi.mocked(hass.callWS).mockResolvedValue('not-an-array');
|
||||
|
||||
await problem.detectStatic(hass);
|
||||
await issue.detectStatic(hass);
|
||||
|
||||
expect(problem.hasResult()).toBe(false);
|
||||
expect(issue.hasIssue()).toBe(false);
|
||||
});
|
||||
|
||||
it('should handle websocket failure', async () => {
|
||||
const problem = new LegacyResourceProblem(vi.fn());
|
||||
const issue = new LegacyResourceIssue();
|
||||
const hass = createHASS(undefined, createUser({ is_admin: true }));
|
||||
vi.mocked(hass.callWS).mockRejectedValue(new Error('connection lost'));
|
||||
|
||||
await problem.detectStatic(hass);
|
||||
await issue.detectStatic(hass);
|
||||
|
||||
expect(problem.hasResult()).toBe(false);
|
||||
expect(issue.hasIssue()).toBe(false);
|
||||
});
|
||||
|
||||
it('should handle missing user', async () => {
|
||||
const problem = new LegacyResourceProblem(vi.fn());
|
||||
const issue = new LegacyResourceIssue();
|
||||
const hass = createHASS();
|
||||
Object.defineProperty(hass, 'user', { value: undefined });
|
||||
|
||||
await problem.detectStatic(hass);
|
||||
await issue.detectStatic(hass);
|
||||
|
||||
expect(problem.hasResult()).toBe(false);
|
||||
expect(issue.hasIssue()).toBe(false);
|
||||
});
|
||||
});
|
||||
|
||||
describe('getResult', () => {
|
||||
describe('getIssue', () => {
|
||||
it('should return controls and link when both resources exist', async () => {
|
||||
const problem = new LegacyResourceProblem(vi.fn());
|
||||
const issue = new LegacyResourceIssue();
|
||||
const hass = createHASS(undefined, createUser({ is_admin: true }));
|
||||
setupHASSResources(hass, [
|
||||
{
|
||||
@@ -111,16 +111,16 @@ describe('LegacyResourceProblem', () => {
|
||||
},
|
||||
]);
|
||||
|
||||
await problem.detectStatic(hass);
|
||||
await issue.detectStatic(hass);
|
||||
|
||||
const result = problem.getResult();
|
||||
const result = issue.getIssue();
|
||||
expect(result).not.toBeNull();
|
||||
expect(result?.notification.controls).toHaveLength(1);
|
||||
expect(result?.notification.link).toBeDefined();
|
||||
});
|
||||
|
||||
it('should return link without controls when only legacy exists', async () => {
|
||||
const problem = new LegacyResourceProblem(vi.fn());
|
||||
const issue = new LegacyResourceIssue();
|
||||
const hass = createHASS(undefined, createUser({ is_admin: true }));
|
||||
setupHASSResources(hass, [
|
||||
{
|
||||
@@ -130,24 +130,24 @@ describe('LegacyResourceProblem', () => {
|
||||
},
|
||||
]);
|
||||
|
||||
await problem.detectStatic(hass);
|
||||
await issue.detectStatic(hass);
|
||||
|
||||
const result = problem.getResult();
|
||||
const result = issue.getIssue();
|
||||
expect(result).not.toBeNull();
|
||||
expect(result?.notification.link).toBeDefined();
|
||||
expect(result?.notification.controls).toBeUndefined();
|
||||
});
|
||||
|
||||
it('should return null when no result', () => {
|
||||
const problem = new LegacyResourceProblem(vi.fn());
|
||||
expect(problem.getResult()).toBeNull();
|
||||
const issue = new LegacyResourceIssue();
|
||||
expect(issue.getIssue()).toBeNull();
|
||||
});
|
||||
});
|
||||
|
||||
describe('fix', () => {
|
||||
it('should remove legacy resources when correct resource exists', async () => {
|
||||
const triggerUpdate = vi.fn();
|
||||
const problem = new LegacyResourceProblem(triggerUpdate);
|
||||
const onChange = vi.fn();
|
||||
const issue = new LegacyResourceIssue(onChange);
|
||||
const hass = createHASS(undefined, createUser({ is_admin: true }));
|
||||
vi.mocked(hass.hassUrl).mockReturnValue('http://homeassistant.local:8123');
|
||||
|
||||
@@ -163,7 +163,7 @@ describe('LegacyResourceProblem', () => {
|
||||
url: '/hacsfiles/advanced-camera-card/advanced-camera-card.js',
|
||||
},
|
||||
]);
|
||||
await problem.detectStatic(hass);
|
||||
await issue.detectStatic(hass);
|
||||
|
||||
vi.mocked(hass.callWS)
|
||||
.mockResolvedValueOnce(undefined)
|
||||
@@ -175,7 +175,7 @@ describe('LegacyResourceProblem', () => {
|
||||
},
|
||||
]);
|
||||
|
||||
const result = await problem.fix(hass);
|
||||
const result = await issue.fix(hass);
|
||||
|
||||
expect(result).toBe(true);
|
||||
expect(hass.callWS).toBeCalledWith(
|
||||
@@ -184,12 +184,12 @@ describe('LegacyResourceProblem', () => {
|
||||
resource_id: '1',
|
||||
}),
|
||||
);
|
||||
expect(problem.hasResult()).toBe(false);
|
||||
expect(triggerUpdate).toBeCalled();
|
||||
expect(issue.hasIssue()).toBe(false);
|
||||
expect(onChange).toBeCalled();
|
||||
});
|
||||
|
||||
it('should not fix when only legacy resource exists', async () => {
|
||||
const problem = new LegacyResourceProblem(vi.fn());
|
||||
const issue = new LegacyResourceIssue();
|
||||
const hass = createHASS(undefined, createUser({ is_admin: true }));
|
||||
setupHASSResources(hass, [
|
||||
{
|
||||
@@ -199,23 +199,23 @@ describe('LegacyResourceProblem', () => {
|
||||
},
|
||||
]);
|
||||
|
||||
await problem.detectStatic(hass);
|
||||
await issue.detectStatic(hass);
|
||||
|
||||
const result = await problem.fix(hass);
|
||||
const result = await issue.fix(hass);
|
||||
expect(result).toBe(false);
|
||||
});
|
||||
|
||||
it('should not fix for non-admin', async () => {
|
||||
const problem = new LegacyResourceProblem(vi.fn());
|
||||
const issue = new LegacyResourceIssue();
|
||||
const hass = createHASS(undefined, createUser({ is_admin: false }));
|
||||
|
||||
const result = await problem.fix(hass);
|
||||
const result = await issue.fix(hass);
|
||||
expect(result).toBe(false);
|
||||
});
|
||||
|
||||
it('should return false on websocket failure during fix', async () => {
|
||||
const triggerUpdate = vi.fn();
|
||||
const problem = new LegacyResourceProblem(triggerUpdate);
|
||||
const onChange = vi.fn();
|
||||
const issue = new LegacyResourceIssue(onChange);
|
||||
const hass = createHASS(undefined, createUser({ is_admin: true }));
|
||||
vi.mocked(hass.hassUrl).mockReturnValue('http://homeassistant.local:8123');
|
||||
vi.mocked(hass.callWS).mockResolvedValueOnce([
|
||||
@@ -231,18 +231,52 @@ describe('LegacyResourceProblem', () => {
|
||||
},
|
||||
]);
|
||||
|
||||
await problem.detectStatic(hass);
|
||||
await issue.detectStatic(hass);
|
||||
|
||||
vi.mocked(hass.callWS).mockRejectedValue(new Error('connection lost'));
|
||||
|
||||
const result = await problem.fix(hass);
|
||||
const result = await issue.fix(hass);
|
||||
expect(result).toBe(false);
|
||||
expect(triggerUpdate).not.toBeCalled();
|
||||
expect(onChange).not.toBeCalled();
|
||||
});
|
||||
|
||||
it('should return false when the verification fetch silently fails after a successful delete', async () => {
|
||||
const onChange = vi.fn();
|
||||
const issue = new LegacyResourceIssue(onChange);
|
||||
const hass = createHASS(undefined, createUser({ is_admin: true }));
|
||||
vi.mocked(hass.hassUrl).mockReturnValue('http://homeassistant.local:8123');
|
||||
|
||||
// Initial detection: finds one legacy resource + one correct resource.
|
||||
vi.mocked(hass.callWS).mockResolvedValueOnce([
|
||||
{
|
||||
id: '1',
|
||||
type: 'module',
|
||||
url: '/hacsfiles/frigate-hass-card/frigate-hass-card.js',
|
||||
},
|
||||
{
|
||||
id: '2',
|
||||
type: 'module',
|
||||
url: '/hacsfiles/advanced-camera-card/advanced-camera-card.js',
|
||||
},
|
||||
]);
|
||||
await issue.detectStatic(hass);
|
||||
|
||||
// Delete succeeds; verification fetch fails. detectStatic silently
|
||||
// swallows the WS error, so the fix path must not interpret the
|
||||
// absence of a positive signal as success.
|
||||
vi.mocked(hass.callWS)
|
||||
.mockResolvedValueOnce(undefined)
|
||||
.mockRejectedValueOnce(new Error('connection lost'));
|
||||
|
||||
const result = await issue.fix(hass);
|
||||
|
||||
expect(result).toBe(false);
|
||||
expect(onChange).not.toBeCalled();
|
||||
});
|
||||
|
||||
it('should return false when re-detection still finds legacy resource', async () => {
|
||||
const triggerUpdate = vi.fn();
|
||||
const problem = new LegacyResourceProblem(triggerUpdate);
|
||||
const onChange = vi.fn();
|
||||
const issue = new LegacyResourceIssue(onChange);
|
||||
const hass = createHASS(undefined, createUser({ is_admin: true }));
|
||||
vi.mocked(hass.hassUrl).mockReturnValue('http://homeassistant.local:8123');
|
||||
|
||||
@@ -258,7 +292,7 @@ describe('LegacyResourceProblem', () => {
|
||||
url: '/hacsfiles/advanced-camera-card/advanced-camera-card.js',
|
||||
},
|
||||
]);
|
||||
await problem.detectStatic(hass);
|
||||
await issue.detectStatic(hass);
|
||||
|
||||
// Delete succeeds, but re-detection still finds the legacy resource.
|
||||
vi.mocked(hass.callWS)
|
||||
@@ -276,14 +310,14 @@ describe('LegacyResourceProblem', () => {
|
||||
},
|
||||
]);
|
||||
|
||||
const result = await problem.fix(hass);
|
||||
const result = await issue.fix(hass);
|
||||
|
||||
expect(result).toBe(false);
|
||||
expect(triggerUpdate).not.toBeCalled();
|
||||
expect(onChange).not.toBeCalled();
|
||||
});
|
||||
|
||||
it('should fix multiple legacy resources', async () => {
|
||||
const problem = new LegacyResourceProblem(vi.fn());
|
||||
const issue = new LegacyResourceIssue();
|
||||
const hass = createHASS(undefined, createUser({ is_admin: true }));
|
||||
vi.mocked(hass.hassUrl).mockReturnValue('http://homeassistant.local:8123');
|
||||
vi.mocked(hass.callWS).mockResolvedValueOnce([
|
||||
@@ -300,7 +334,7 @@ describe('LegacyResourceProblem', () => {
|
||||
},
|
||||
]);
|
||||
|
||||
await problem.detectStatic(hass);
|
||||
await issue.detectStatic(hass);
|
||||
|
||||
vi.mocked(hass.callWS)
|
||||
.mockResolvedValueOnce(undefined)
|
||||
@@ -313,13 +347,13 @@ describe('LegacyResourceProblem', () => {
|
||||
},
|
||||
]);
|
||||
|
||||
expect(await problem.fix(hass)).toBe(true);
|
||||
expect(await issue.fix(hass)).toBe(true);
|
||||
});
|
||||
});
|
||||
|
||||
describe('getResourcePath fallback', () => {
|
||||
it('should handle invalid URLs by stripping query string', async () => {
|
||||
const problem = new LegacyResourceProblem(vi.fn());
|
||||
const issue = new LegacyResourceIssue();
|
||||
const hass = createHASS(undefined, createUser({ is_admin: true }));
|
||||
vi.mocked(hass.hassUrl).mockReturnValue('not-a-valid-url');
|
||||
vi.mocked(hass.callWS).mockResolvedValue([
|
||||
@@ -330,13 +364,13 @@ describe('LegacyResourceProblem', () => {
|
||||
},
|
||||
]);
|
||||
|
||||
await problem.detectStatic(hass);
|
||||
await issue.detectStatic(hass);
|
||||
|
||||
expect(problem.hasResult()).toBe(true);
|
||||
expect(issue.hasIssue()).toBe(true);
|
||||
});
|
||||
|
||||
it('should handle invalid URLs without query string', async () => {
|
||||
const problem = new LegacyResourceProblem(vi.fn());
|
||||
const issue = new LegacyResourceIssue();
|
||||
const hass = createHASS(undefined, createUser({ is_admin: true }));
|
||||
vi.mocked(hass.hassUrl).mockReturnValue('not-a-valid-url');
|
||||
vi.mocked(hass.callWS).mockResolvedValue([
|
||||
@@ -347,17 +381,17 @@ describe('LegacyResourceProblem', () => {
|
||||
},
|
||||
]);
|
||||
|
||||
await problem.detectStatic(hass);
|
||||
await issue.detectStatic(hass);
|
||||
|
||||
expect(problem.hasResult()).toBe(true);
|
||||
expect(issue.hasIssue()).toBe(true);
|
||||
});
|
||||
});
|
||||
|
||||
describe('callback action', () => {
|
||||
const getCallback = (
|
||||
problem: LegacyResourceProblem,
|
||||
issue: LegacyResourceIssue,
|
||||
): ((api: unknown) => Promise<void>) | null => {
|
||||
const result = problem.getResult();
|
||||
const result = issue.getIssue();
|
||||
const action = result?.notification.controls?.[0]?.actions?.tap_action;
|
||||
if (action && 'callback' in action) {
|
||||
return (action as { callback: (api: unknown) => Promise<void> }).callback;
|
||||
@@ -366,7 +400,7 @@ describe('LegacyResourceProblem', () => {
|
||||
};
|
||||
|
||||
it('should call fix via the notification control action', async () => {
|
||||
const problem = new LegacyResourceProblem(vi.fn());
|
||||
const issue = new LegacyResourceIssue();
|
||||
const hass = createHASS(undefined, createUser({ is_admin: true }));
|
||||
vi.mocked(hass.hassUrl).mockReturnValue('http://homeassistant.local:8123');
|
||||
vi.mocked(hass.callWS).mockResolvedValueOnce([
|
||||
@@ -382,9 +416,9 @@ describe('LegacyResourceProblem', () => {
|
||||
},
|
||||
]);
|
||||
|
||||
await problem.detectStatic(hass);
|
||||
await issue.detectStatic(hass);
|
||||
|
||||
const callback = getCallback(problem);
|
||||
const callback = getCallback(issue);
|
||||
expect(callback).toBeDefined();
|
||||
|
||||
const api = createCardAPI();
|
||||
@@ -410,7 +444,7 @@ describe('LegacyResourceProblem', () => {
|
||||
});
|
||||
|
||||
it('should handle missing hass in callback', async () => {
|
||||
const problem = new LegacyResourceProblem(vi.fn());
|
||||
const issue = new LegacyResourceIssue();
|
||||
const hass = createHASS(undefined, createUser({ is_admin: true }));
|
||||
vi.mocked(hass.hassUrl).mockReturnValue('http://homeassistant.local:8123');
|
||||
vi.mocked(hass.callWS).mockResolvedValueOnce([
|
||||
@@ -426,9 +460,9 @@ describe('LegacyResourceProblem', () => {
|
||||
},
|
||||
]);
|
||||
|
||||
await problem.detectStatic(hass);
|
||||
await issue.detectStatic(hass);
|
||||
|
||||
const callback = getCallback(problem);
|
||||
const callback = getCallback(issue);
|
||||
expect(callback).toBeDefined();
|
||||
|
||||
const api = createCardAPI();
|
||||
@@ -0,0 +1,623 @@
|
||||
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
|
||||
import { mock } from 'vitest-mock-extended';
|
||||
import { MediaLoadIssue } from '../../../../src/card-controller/issues/issues/media-load';
|
||||
import { InternalCallbackActionConfig } from '../../../../src/config/schema/actions/custom/internal';
|
||||
import { View } from '../../../../src/view/view';
|
||||
import { createCardAPI, createMediaLoadedInfo } from '../../../test-utils';
|
||||
import { IMAGE_VIEW_TARGET_ID_SENTINEL } from '../../../../src/view/target-id';
|
||||
|
||||
const createAPI = () => createCardAPI();
|
||||
|
||||
// @vitest-environment jsdom
|
||||
describe('MediaLoadIssue', () => {
|
||||
beforeEach(() => {
|
||||
vi.useFakeTimers();
|
||||
});
|
||||
|
||||
afterEach(() => {
|
||||
vi.useRealTimers();
|
||||
});
|
||||
|
||||
it('should have correct key', () => {
|
||||
const issue = new MediaLoadIssue(createAPI());
|
||||
expect(issue.key).toBe('media_load');
|
||||
});
|
||||
|
||||
describe('detectDynamic', () => {
|
||||
it.each([
|
||||
['live' as const],
|
||||
['clip' as const],
|
||||
['folder' as const],
|
||||
['media' as const],
|
||||
['snapshot' as const],
|
||||
['recording' as const],
|
||||
['review' as const],
|
||||
])('should start timer when view is %s and not loaded', (view) => {
|
||||
const onChange = vi.fn();
|
||||
const issue = new MediaLoadIssue(createAPI(), onChange);
|
||||
|
||||
issue.detectDynamic({ targetID: 'target-1', view });
|
||||
|
||||
expect(issue.hasIssue()).toBe(false);
|
||||
|
||||
vi.advanceTimersByTime(10000);
|
||||
|
||||
expect(issue.hasIssue()).toBe(true);
|
||||
expect(onChange).toBeCalled();
|
||||
});
|
||||
|
||||
it('should not start timer when targetID is null (no provider rendering)', () => {
|
||||
const issue = new MediaLoadIssue(createAPI());
|
||||
|
||||
// Media view but no targetID, e.g. viewer showing "No media to display"
|
||||
// instead of mounting a provider.
|
||||
issue.detectDynamic({ view: 'media' });
|
||||
|
||||
vi.advanceTimersByTime(10000);
|
||||
|
||||
expect(issue.hasIssue()).toBe(false);
|
||||
});
|
||||
|
||||
it('should deactivate when targetID becomes null', () => {
|
||||
const issue = new MediaLoadIssue(createAPI());
|
||||
|
||||
issue.detectDynamic({ targetID: 'camera-1', view: 'live' });
|
||||
vi.advanceTimersByTime(10000);
|
||||
expect(issue.hasIssue()).toBe(true);
|
||||
|
||||
// Target cleared (e.g. switched to a view with no media provider).
|
||||
issue.detectDynamic({ view: 'live' });
|
||||
expect(issue.hasIssue()).toBe(false);
|
||||
});
|
||||
|
||||
it('should not start timer when view is not a media view', () => {
|
||||
const issue = new MediaLoadIssue(createAPI());
|
||||
|
||||
issue.detectDynamic({ view: 'timeline' });
|
||||
|
||||
vi.advanceTimersByTime(10000);
|
||||
|
||||
expect(issue.hasIssue()).toBe(false);
|
||||
});
|
||||
|
||||
it('should not start timer when view is undefined', () => {
|
||||
const issue = new MediaLoadIssue(createAPI());
|
||||
|
||||
issue.detectDynamic({});
|
||||
|
||||
vi.advanceTimersByTime(10000);
|
||||
|
||||
expect(issue.hasIssue()).toBe(false);
|
||||
});
|
||||
|
||||
it('should not start timer when media is loaded', () => {
|
||||
const issue = new MediaLoadIssue(createAPI());
|
||||
|
||||
issue.detectDynamic({ view: 'live', mediaLoadedInfo: createMediaLoadedInfo() });
|
||||
|
||||
vi.advanceTimersByTime(10000);
|
||||
|
||||
expect(issue.hasIssue()).toBe(false);
|
||||
});
|
||||
|
||||
it('should clear timeout when media loads', () => {
|
||||
const issue = new MediaLoadIssue(createAPI());
|
||||
|
||||
issue.detectDynamic({ targetID: 'camera-1', view: 'live' });
|
||||
vi.advanceTimersByTime(5000);
|
||||
|
||||
issue.detectDynamic({ view: 'live', mediaLoadedInfo: createMediaLoadedInfo() });
|
||||
|
||||
vi.advanceTimersByTime(5000);
|
||||
|
||||
expect(issue.hasIssue()).toBe(false);
|
||||
});
|
||||
|
||||
it('should clear timeout when view changes to a non-media view', () => {
|
||||
const issue = new MediaLoadIssue(createAPI());
|
||||
|
||||
issue.detectDynamic({ targetID: 'camera-1', view: 'live' });
|
||||
vi.advanceTimersByTime(5000);
|
||||
|
||||
issue.detectDynamic({ view: 'timeline' });
|
||||
|
||||
vi.advanceTimersByTime(5000);
|
||||
|
||||
expect(issue.hasIssue()).toBe(false);
|
||||
});
|
||||
|
||||
it('should remain active across media views for the same target', () => {
|
||||
const issue = new MediaLoadIssue(createAPI());
|
||||
|
||||
issue.detectDynamic({ targetID: 'camera-1', view: 'live' });
|
||||
vi.advanceTimersByTime(10000);
|
||||
expect(issue.hasIssue()).toBe(true);
|
||||
|
||||
// Same target, different media view — issue stays active.
|
||||
issue.detectDynamic({ targetID: 'camera-1', view: 'clip' });
|
||||
expect(issue.hasIssue()).toBe(true);
|
||||
});
|
||||
|
||||
it('should deactivate when target changes to non-errored target', () => {
|
||||
const issue = new MediaLoadIssue(createAPI());
|
||||
|
||||
issue.detectDynamic({ targetID: 'camera-1', view: 'live' });
|
||||
vi.advanceTimersByTime(10000);
|
||||
expect(issue.hasIssue()).toBe(true);
|
||||
|
||||
// Switch to camera-2 which has no error — should deactivate and start
|
||||
// a fresh timer for the new target.
|
||||
issue.detectDynamic({ targetID: 'camera-2', view: 'live' });
|
||||
expect(issue.hasIssue()).toBe(false);
|
||||
|
||||
// camera-2 gets its own timeout window.
|
||||
vi.advanceTimersByTime(10000);
|
||||
expect(issue.hasIssue()).toBe(true);
|
||||
});
|
||||
|
||||
it('should stay active when target changes to errored target', () => {
|
||||
const issue = new MediaLoadIssue(createAPI());
|
||||
|
||||
issue.trigger({ targetID: 'camera-1' });
|
||||
issue.trigger({ targetID: 'camera-2' });
|
||||
|
||||
issue.detectDynamic({ targetID: 'camera-1', view: 'live' });
|
||||
expect(issue.hasIssue()).toBe(true);
|
||||
|
||||
// Switch to camera-2 which also has an error — should stay active.
|
||||
issue.detectDynamic({ targetID: 'camera-2', view: 'live' });
|
||||
expect(issue.hasIssue()).toBe(true);
|
||||
});
|
||||
|
||||
it('should clear timed-out state when media loads', () => {
|
||||
const issue = new MediaLoadIssue(createAPI());
|
||||
|
||||
issue.detectDynamic({ targetID: 'camera-1', view: 'live' });
|
||||
vi.advanceTimersByTime(10000);
|
||||
expect(issue.hasIssue()).toBe(true);
|
||||
|
||||
issue.detectDynamic({ view: 'live', mediaLoadedInfo: createMediaLoadedInfo() });
|
||||
expect(issue.hasIssue()).toBe(false);
|
||||
});
|
||||
|
||||
it('should restart timer when target changes', () => {
|
||||
const onChange = vi.fn();
|
||||
const issue = new MediaLoadIssue(createAPI(), onChange);
|
||||
|
||||
issue.detectDynamic({
|
||||
targetID: 'camera-1',
|
||||
view: 'live',
|
||||
});
|
||||
vi.advanceTimersByTime(5000);
|
||||
|
||||
// Switch to camera-2: timer restarts from 0 for the new target.
|
||||
issue.detectDynamic({
|
||||
targetID: 'camera-2',
|
||||
view: 'live',
|
||||
});
|
||||
|
||||
// 5 more seconds is not enough for the new 10s timer.
|
||||
vi.advanceTimersByTime(5000);
|
||||
expect(issue.hasIssue()).toBe(false);
|
||||
|
||||
// Full 10s from camera-2's timer start.
|
||||
vi.advanceTimersByTime(5000);
|
||||
expect(issue.hasIssue()).toBe(true);
|
||||
expect(onChange).toBeCalledTimes(1);
|
||||
});
|
||||
|
||||
it('should not restart timer for same target while running', () => {
|
||||
const onChange = vi.fn();
|
||||
const issue = new MediaLoadIssue(createAPI(), onChange);
|
||||
|
||||
issue.detectDynamic({
|
||||
targetID: 'camera-1',
|
||||
view: 'live',
|
||||
});
|
||||
vi.advanceTimersByTime(5000);
|
||||
|
||||
// Same target again: timer should continue, not restart.
|
||||
issue.detectDynamic({
|
||||
targetID: 'camera-1',
|
||||
view: 'live',
|
||||
});
|
||||
|
||||
// 5 more seconds completes the original 10s timer.
|
||||
vi.advanceTimersByTime(5000);
|
||||
expect(issue.hasIssue()).toBe(true);
|
||||
expect(onChange).toBeCalledTimes(1);
|
||||
});
|
||||
|
||||
it('should not restart timer when targetID is undefined and matches', () => {
|
||||
const onChange = vi.fn();
|
||||
const issue = new MediaLoadIssue(createAPI(), onChange);
|
||||
|
||||
issue.detectDynamic({ targetID: 'camera-1', view: 'live' });
|
||||
vi.advanceTimersByTime(5000);
|
||||
|
||||
// Same undefined target: timer should continue.
|
||||
issue.detectDynamic({ targetID: 'camera-1', view: 'live' });
|
||||
|
||||
vi.advanceTimersByTime(5000);
|
||||
expect(issue.hasIssue()).toBe(true);
|
||||
expect(onChange).toBeCalledTimes(1);
|
||||
});
|
||||
|
||||
it('should not restart timer if already timed out', () => {
|
||||
const onChange = vi.fn();
|
||||
const issue = new MediaLoadIssue(createAPI(), onChange);
|
||||
|
||||
issue.detectDynamic({ targetID: 'camera-1', view: 'live' });
|
||||
vi.advanceTimersByTime(10000);
|
||||
expect(onChange).toBeCalledTimes(1);
|
||||
|
||||
// Calling detectDynamic again should not restart timer.
|
||||
issue.detectDynamic({ targetID: 'camera-1', view: 'live' });
|
||||
vi.advanceTimersByTime(10000);
|
||||
expect(onChange).toBeCalledTimes(1);
|
||||
});
|
||||
});
|
||||
|
||||
describe('trigger', () => {
|
||||
it('should activate immediately when target has error and view is a media view', () => {
|
||||
const issue = new MediaLoadIssue(createAPI());
|
||||
|
||||
issue.trigger({ targetID: 'camera-1' });
|
||||
issue.detectDynamic({
|
||||
targetID: 'camera-1',
|
||||
view: 'live',
|
||||
});
|
||||
|
||||
expect(issue.hasIssue()).toBe(true);
|
||||
});
|
||||
|
||||
it('should not activate with only a trigger', () => {
|
||||
const issue = new MediaLoadIssue(createAPI());
|
||||
|
||||
issue.trigger({ targetID: 'camera-1' });
|
||||
|
||||
expect(issue.hasIssue()).toBe(false);
|
||||
});
|
||||
|
||||
it('should clear target error when media loads', () => {
|
||||
const issue = new MediaLoadIssue(createAPI());
|
||||
|
||||
issue.trigger({ targetID: 'camera-1' });
|
||||
issue.detectDynamic({
|
||||
targetID: 'camera-1',
|
||||
view: 'live',
|
||||
});
|
||||
|
||||
expect(issue.hasIssue()).toBe(true);
|
||||
|
||||
// Media loaded clears the error for this target.
|
||||
issue.detectDynamic({
|
||||
targetID: 'camera-1',
|
||||
view: 'live',
|
||||
mediaLoadedInfo: createMediaLoadedInfo(),
|
||||
});
|
||||
|
||||
// Target error was cleared by the successful load, so this unloaded state
|
||||
// falls back to the timer (issue would not activate until after the
|
||||
// timer is reached).
|
||||
issue.detectDynamic({
|
||||
targetID: 'camera-1',
|
||||
view: 'live',
|
||||
});
|
||||
|
||||
expect(issue.hasIssue()).toBe(false);
|
||||
});
|
||||
|
||||
it('should not activate for a different target', () => {
|
||||
const issue = new MediaLoadIssue(createAPI());
|
||||
|
||||
issue.trigger({ targetID: 'camera-1' });
|
||||
issue.detectDynamic({
|
||||
targetID: 'camera-2',
|
||||
view: 'live',
|
||||
});
|
||||
|
||||
// camera-2 has no error, so it falls back to timeout behavior.
|
||||
expect(issue.hasIssue()).toBe(false);
|
||||
});
|
||||
});
|
||||
|
||||
describe('getNotification', () => {
|
||||
it('should return notification regardless of active state', () => {
|
||||
const issue = new MediaLoadIssue(createAPI());
|
||||
|
||||
const notification = issue.getNotification();
|
||||
expect(notification).toEqual(
|
||||
expect.objectContaining({
|
||||
heading: expect.objectContaining({
|
||||
text: expect.any(String),
|
||||
}),
|
||||
link: expect.objectContaining({
|
||||
url: expect.any(String),
|
||||
}),
|
||||
}),
|
||||
);
|
||||
});
|
||||
|
||||
it('should include metadata for errored targets', () => {
|
||||
const issue = new MediaLoadIssue(createAPI());
|
||||
issue.trigger({ targetID: 'camera.office' });
|
||||
|
||||
const notification = issue.getNotification();
|
||||
expect(notification.metadata).toEqual([
|
||||
expect.objectContaining({ text: 'camera.office', icon: 'mdi:cctv' }),
|
||||
]);
|
||||
});
|
||||
|
||||
it('should include the pending timer target in metadata', () => {
|
||||
const issue = new MediaLoadIssue(createAPI());
|
||||
|
||||
// Start a load timer (no explicit error yet, just slow-loading).
|
||||
issue.detectDynamic({ targetID: 'camera.garden', view: 'live' });
|
||||
|
||||
const notification = issue.getNotification();
|
||||
expect(notification.metadata).toEqual([
|
||||
expect.objectContaining({ text: 'camera.garden', icon: 'mdi:cctv' }),
|
||||
]);
|
||||
});
|
||||
|
||||
it('should use camera title when available', () => {
|
||||
const api = createAPI();
|
||||
vi.mocked(api.getCameraManager().getCameraMetadata).mockReturnValue({
|
||||
title: 'Office',
|
||||
icon: { icon: 'mdi:cctv' },
|
||||
});
|
||||
const issue = new MediaLoadIssue(api);
|
||||
issue.trigger({ targetID: 'camera.office' });
|
||||
|
||||
const notification = issue.getNotification();
|
||||
expect(notification.metadata).toEqual([
|
||||
expect.objectContaining({ text: 'Office' }),
|
||||
]);
|
||||
});
|
||||
|
||||
it('should use localized label and image icon for the image-view sentinel', () => {
|
||||
const issue = new MediaLoadIssue(createAPI());
|
||||
issue.trigger({ targetID: IMAGE_VIEW_TARGET_ID_SENTINEL });
|
||||
|
||||
const notification = issue.getNotification();
|
||||
expect(notification.metadata).toEqual([
|
||||
expect.objectContaining({ text: 'Image', icon: 'mdi:image' }),
|
||||
]);
|
||||
});
|
||||
|
||||
it('should include a retry control with wired callback', async () => {
|
||||
const api = createCardAPI();
|
||||
const issue = new MediaLoadIssue(api);
|
||||
|
||||
const control = issue.getNotification().controls?.[0];
|
||||
expect(control).toMatchObject({ icon: 'mdi:refresh', dismiss: true });
|
||||
|
||||
const tapAction = control?.actions?.tap_action as InternalCallbackActionConfig;
|
||||
await tapAction.callback(api);
|
||||
|
||||
expect(api.getIssueManager().retry).toBeCalledWith('media_load', true);
|
||||
});
|
||||
});
|
||||
|
||||
describe('getIssue', () => {
|
||||
it('should return result when timed out', () => {
|
||||
const issue = new MediaLoadIssue(createAPI());
|
||||
|
||||
issue.detectDynamic({ targetID: 'camera-1', view: 'live' });
|
||||
vi.advanceTimersByTime(10000);
|
||||
|
||||
const result = issue.getIssue();
|
||||
expect(result).toEqual(
|
||||
expect.objectContaining({
|
||||
icon: 'mdi:cctv-off',
|
||||
severity: 'high',
|
||||
notification: expect.objectContaining({
|
||||
link: expect.objectContaining({
|
||||
url: expect.any(String),
|
||||
}),
|
||||
}),
|
||||
}),
|
||||
);
|
||||
});
|
||||
|
||||
it('should return null when not timed out', () => {
|
||||
const issue = new MediaLoadIssue(createAPI());
|
||||
|
||||
expect(issue.getIssue()).toBeNull();
|
||||
});
|
||||
});
|
||||
|
||||
describe('needsRetry', () => {
|
||||
it('should return true when issue is active', () => {
|
||||
const issue = new MediaLoadIssue(createAPI());
|
||||
|
||||
issue.detectDynamic({ targetID: 'camera-1', view: 'live' });
|
||||
vi.advanceTimersByTime(10000);
|
||||
|
||||
expect(issue.needsRetry()).toBe(true);
|
||||
});
|
||||
|
||||
it('should return false when issue is not active', () => {
|
||||
const issue = new MediaLoadIssue(createAPI());
|
||||
|
||||
expect(issue.needsRetry()).toBe(false);
|
||||
});
|
||||
});
|
||||
|
||||
describe('retry', () => {
|
||||
it('should keep issue active after retry so error stays visible', () => {
|
||||
const onChange = vi.fn();
|
||||
const issue = new MediaLoadIssue(createAPI(), onChange);
|
||||
|
||||
issue.detectDynamic({ targetID: 'camera-1', view: 'live' });
|
||||
vi.advanceTimersByTime(10000);
|
||||
expect(issue.hasIssue()).toBe(true);
|
||||
|
||||
issue.retry();
|
||||
|
||||
// Issue remains active — no new 10s grace period. The error stays
|
||||
// visible while the provider re-attempts loading underneath.
|
||||
expect(issue.hasIssue()).toBe(true);
|
||||
});
|
||||
|
||||
it('should return false when no targets have errors', () => {
|
||||
const api = createAPI();
|
||||
const issue = new MediaLoadIssue(api);
|
||||
|
||||
expect(issue.retry()).toBe(false);
|
||||
});
|
||||
|
||||
it('should bump mediaEpoch for targets with errors and call setViewWithMergedContext', () => {
|
||||
const api = createAPI();
|
||||
vi.mocked(api.getViewManager().getView).mockReturnValue(mock<View>());
|
||||
const issue = new MediaLoadIssue(api);
|
||||
|
||||
issue.trigger({ targetID: 'camera-1' });
|
||||
issue.trigger({ targetID: 'media-1' });
|
||||
|
||||
const result = issue.retry();
|
||||
|
||||
expect(result).toEqual(false);
|
||||
expect(api.getViewManager().setViewWithMergedContext).toBeCalledWith({
|
||||
mediaEpoch: { 'camera-1': 1, 'media-1': 1 },
|
||||
});
|
||||
});
|
||||
|
||||
it('should bump mediaEpoch for the image-view sentinel', () => {
|
||||
const api = createAPI();
|
||||
vi.mocked(api.getViewManager().getView).mockReturnValue(mock<View>());
|
||||
const issue = new MediaLoadIssue(api);
|
||||
|
||||
issue.trigger({ targetID: IMAGE_VIEW_TARGET_ID_SENTINEL });
|
||||
|
||||
const result = issue.retry();
|
||||
|
||||
expect(result).toEqual(false);
|
||||
expect(api.getViewManager().setViewWithMergedContext).toBeCalledWith({
|
||||
mediaEpoch: { [IMAGE_VIEW_TARGET_ID_SENTINEL]: 1 },
|
||||
});
|
||||
});
|
||||
|
||||
it('should increment existing epoch values from current view context', () => {
|
||||
const api = createAPI();
|
||||
vi.mocked(api.getViewManager().getView).mockReturnValue(
|
||||
mock<View>({ context: { mediaEpoch: { 'camera-1': 5, 'camera-2': 3 } } }),
|
||||
);
|
||||
const issue = new MediaLoadIssue(api);
|
||||
|
||||
issue.trigger({ targetID: 'camera-1' });
|
||||
|
||||
const result = issue.retry();
|
||||
|
||||
expect(result).toEqual(false);
|
||||
expect(api.getViewManager().setViewWithMergedContext).toBeCalledWith({
|
||||
mediaEpoch: { 'camera-1': 6, 'camera-2': 3 },
|
||||
});
|
||||
});
|
||||
|
||||
it('should include pending timer target in retry', () => {
|
||||
const api = createAPI();
|
||||
vi.mocked(api.getViewManager().getView).mockReturnValue(mock<View>());
|
||||
const issue = new MediaLoadIssue(api);
|
||||
|
||||
// Start the timer for camera-1 (not yet timed out).
|
||||
issue.detectDynamic({ targetID: 'camera-1', view: 'live' });
|
||||
|
||||
issue.retry();
|
||||
|
||||
expect(api.getViewManager().setViewWithMergedContext).toBeCalledWith({
|
||||
mediaEpoch: { 'camera-1': 1 },
|
||||
});
|
||||
});
|
||||
|
||||
it('should keep errored targets and issue state after retry', () => {
|
||||
const api = createAPI();
|
||||
vi.mocked(api.getViewManager().getView).mockReturnValue(mock<View>());
|
||||
const issue = new MediaLoadIssue(api);
|
||||
|
||||
issue.trigger({ targetID: 'camera-1' });
|
||||
issue.detectDynamic({ targetID: 'camera-1', view: 'live' });
|
||||
expect(issue.hasIssue()).toBe(true);
|
||||
|
||||
issue.retry();
|
||||
|
||||
// After retry, the issue stays active and the errored target is
|
||||
// preserved — no new 10s grace period. If media:loaded fires, the
|
||||
// existing _handleMediaLoaded path will clear everything.
|
||||
expect(issue.hasIssue()).toBe(true);
|
||||
issue.detectDynamic({ targetID: 'camera-1', view: 'live' });
|
||||
expect(issue.hasIssue()).toBe(true);
|
||||
});
|
||||
});
|
||||
|
||||
describe('reset', () => {
|
||||
it('should stop timer', () => {
|
||||
const onChange = vi.fn();
|
||||
const issue = new MediaLoadIssue(createAPI(), onChange);
|
||||
|
||||
issue.detectDynamic({ targetID: 'camera-1', view: 'live' });
|
||||
issue.reset();
|
||||
|
||||
vi.advanceTimersByTime(10000);
|
||||
|
||||
expect(issue.hasIssue()).toBe(false);
|
||||
expect(onChange).not.toBeCalled();
|
||||
});
|
||||
});
|
||||
|
||||
describe('suspend', () => {
|
||||
it('should stop the pending-load timer so it cannot mature offscreen', () => {
|
||||
const onChange = vi.fn();
|
||||
const issue = new MediaLoadIssue(createAPI(), onChange);
|
||||
|
||||
// Enter loading state. Timer arms but has not yet fired.
|
||||
issue.detectDynamic({ targetID: 'camera-1', view: 'live' });
|
||||
vi.advanceTimersByTime(5000);
|
||||
expect(issue.hasIssue()).toBe(false);
|
||||
|
||||
// Card detaches: timer must stop.
|
||||
issue.suspend();
|
||||
|
||||
// Full 10s later (plus margin) the timer has NOT matured — the user
|
||||
// was offscreen and that time does not count against them.
|
||||
vi.advanceTimersByTime(20000);
|
||||
expect(issue.hasIssue()).toBe(false);
|
||||
expect(onChange).not.toBeCalled();
|
||||
});
|
||||
|
||||
it('should preserve an already-active issue across suspend', () => {
|
||||
const issue = new MediaLoadIssue(createAPI());
|
||||
|
||||
// Issue activates (timeout fires).
|
||||
issue.detectDynamic({ targetID: 'camera-1', view: 'live' });
|
||||
vi.advanceTimersByTime(10000);
|
||||
expect(issue.hasIssue()).toBe(true);
|
||||
|
||||
// Card detaches — issue must remain visible on reattach.
|
||||
issue.suspend();
|
||||
|
||||
expect(issue.hasIssue()).toBe(true);
|
||||
});
|
||||
|
||||
it('should rearm a fresh timer window on resume via detectDynamic', () => {
|
||||
const onChange = vi.fn();
|
||||
const issue = new MediaLoadIssue(createAPI(), onChange);
|
||||
|
||||
issue.detectDynamic({ targetID: 'camera-1', view: 'live' });
|
||||
vi.advanceTimersByTime(5000);
|
||||
issue.suspend();
|
||||
|
||||
// Reattach: the manager's resume() triggers evaluate() → detectDynamic.
|
||||
// The target is still loading, so the timer arms with a fresh 10s
|
||||
// window — not whatever was left when we suspended.
|
||||
issue.detectDynamic({ targetID: 'camera-1', view: 'live' });
|
||||
|
||||
vi.advanceTimersByTime(9999);
|
||||
expect(issue.hasIssue()).toBe(false);
|
||||
vi.advanceTimersByTime(1);
|
||||
expect(issue.hasIssue()).toBe(true);
|
||||
expect(onChange).toBeCalled();
|
||||
});
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,150 @@
|
||||
import { describe, expect, it } from 'vitest';
|
||||
import { CardController } from '../../../../src/card-controller/controller';
|
||||
import { MediaQueryIssue } from '../../../../src/card-controller/issues/issues/media-query';
|
||||
import { InternalCallbackActionConfig } from '../../../../src/config/schema/actions/custom/internal';
|
||||
import { createCardAPI } from '../../../test-utils';
|
||||
|
||||
const createIssue = (): {
|
||||
issue: MediaQueryIssue;
|
||||
api: CardController;
|
||||
} => {
|
||||
const api = createCardAPI();
|
||||
const issue = new MediaQueryIssue(api);
|
||||
return { issue, api };
|
||||
};
|
||||
|
||||
describe('MediaQueryIssue', () => {
|
||||
it('should have correct key', () => {
|
||||
const { issue } = createIssue();
|
||||
expect(issue.key).toBe('media_query');
|
||||
});
|
||||
|
||||
it('should report no issue when untriggered', () => {
|
||||
const { issue } = createIssue();
|
||||
expect(issue.hasIssue()).toBe(false);
|
||||
expect(issue.getIssue()).toBeNull();
|
||||
});
|
||||
|
||||
it('should report an issue after trigger with an error', () => {
|
||||
const { issue } = createIssue();
|
||||
issue.trigger({ error: new Error('query failed') });
|
||||
|
||||
expect(issue.hasIssue()).toBe(true);
|
||||
});
|
||||
|
||||
it('should treat a triggered null/undefined error as no issue', () => {
|
||||
const { issue } = createIssue();
|
||||
issue.trigger({ error: undefined });
|
||||
|
||||
expect(issue.hasIssue()).toBe(false);
|
||||
expect(issue.getIssue()).toBeNull();
|
||||
expect(issue.needsRetry()).toBe(false);
|
||||
});
|
||||
|
||||
it('should return expected shape from getIssue when triggered with an error', () => {
|
||||
const { issue } = createIssue();
|
||||
issue.trigger({ error: new Error('media query failed') });
|
||||
|
||||
const result = issue.getIssue();
|
||||
expect(result).toEqual(
|
||||
expect.objectContaining({
|
||||
icon: 'mdi:alert',
|
||||
severity: 'high',
|
||||
notification: expect.objectContaining({
|
||||
body: expect.objectContaining({
|
||||
text: 'media query failed',
|
||||
}),
|
||||
}),
|
||||
}),
|
||||
);
|
||||
});
|
||||
|
||||
describe('getNotification', () => {
|
||||
it('should return null when no error is set', () => {
|
||||
const { issue } = createIssue();
|
||||
|
||||
expect(issue.getNotification()).toBeNull();
|
||||
});
|
||||
|
||||
it('should return notification with retry control when triggered with an error', () => {
|
||||
const { issue } = createIssue();
|
||||
issue.trigger({ error: new Error('query failed') });
|
||||
|
||||
const notification = issue.getNotification();
|
||||
expect(notification?.controls).toHaveLength(1);
|
||||
expect(notification?.controls?.[0]).toMatchObject({
|
||||
icon: 'mdi:refresh',
|
||||
dismiss: true,
|
||||
});
|
||||
});
|
||||
|
||||
it('should call manager.retry with the issue key from retry control callback', async () => {
|
||||
const { issue, api } = createIssue();
|
||||
issue.trigger({ error: new Error('query failed') });
|
||||
|
||||
const control = issue.getNotification()?.controls?.[0];
|
||||
const tapAction = control?.actions?.tap_action as InternalCallbackActionConfig;
|
||||
await tapAction.callback(api);
|
||||
|
||||
expect(api.getIssueManager().retry).toBeCalledWith('media_query', true);
|
||||
});
|
||||
});
|
||||
|
||||
describe('needsRetry', () => {
|
||||
it('should return true after trigger with an error', () => {
|
||||
const { issue } = createIssue();
|
||||
issue.trigger({ error: new Error('query failed') });
|
||||
|
||||
expect(issue.needsRetry()).toBe(true);
|
||||
});
|
||||
|
||||
it('should return false when not triggered', () => {
|
||||
const { issue } = createIssue();
|
||||
|
||||
expect(issue.needsRetry()).toBe(false);
|
||||
});
|
||||
});
|
||||
|
||||
describe('retry', () => {
|
||||
it('should return requery action and clear error and needsRetry', () => {
|
||||
const { issue, api } = createIssue();
|
||||
issue.trigger({ error: new Error('query failed') });
|
||||
|
||||
const result = issue.retry();
|
||||
|
||||
expect(result).toEqual(true);
|
||||
expect(api.getViewManager().setViewByParametersWithNewQuery).toBeCalled();
|
||||
expect(issue.needsRetry()).toBe(false);
|
||||
expect(issue.hasIssue()).toBe(false);
|
||||
});
|
||||
|
||||
it('should return null when needsRetry is false', () => {
|
||||
const { issue } = createIssue();
|
||||
|
||||
const result = issue.retry();
|
||||
|
||||
expect(result).toBe(false);
|
||||
});
|
||||
});
|
||||
|
||||
it('should clear the issue after reset', () => {
|
||||
const { issue } = createIssue();
|
||||
issue.trigger({ error: new Error('oops') });
|
||||
expect(issue.hasIssue()).toBe(true);
|
||||
|
||||
issue.reset();
|
||||
|
||||
expect(issue.hasIssue()).toBe(false);
|
||||
expect(issue.getIssue()).toBeNull();
|
||||
});
|
||||
|
||||
it('should clear needsRetry after reset', () => {
|
||||
const { issue } = createIssue();
|
||||
issue.trigger({ error: new Error('oops') });
|
||||
expect(issue.needsRetry()).toBe(true);
|
||||
|
||||
issue.reset();
|
||||
|
||||
expect(issue.needsRetry()).toBe(false);
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,109 @@
|
||||
import { describe, expect, it, vi } from 'vitest';
|
||||
import { mock } from 'vitest-mock-extended';
|
||||
import { CardController } from '../../../../src/card-controller/controller';
|
||||
import { ViewIncompatibleIssue } from '../../../../src/card-controller/issues/issues/view-incompatible';
|
||||
import { AdvancedCameraCardError } from '../../../../src/types';
|
||||
import { View } from '../../../../src/view/view';
|
||||
import { createCardAPI } from '../../../test-utils';
|
||||
|
||||
describe('ViewIncompatibleIssue', () => {
|
||||
const createAPI = (hasView = false): CardController => {
|
||||
const api = createCardAPI();
|
||||
vi.mocked(api.getViewManager().getView).mockReturnValue(
|
||||
hasView ? mock<View>() : null,
|
||||
);
|
||||
return api;
|
||||
};
|
||||
|
||||
it('should have correct key', () => {
|
||||
const issue = new ViewIncompatibleIssue(createAPI());
|
||||
expect(issue.key).toBe('view_incompatible');
|
||||
});
|
||||
|
||||
it('should report no issue when untriggered', () => {
|
||||
const issue = new ViewIncompatibleIssue(createAPI());
|
||||
expect(issue.hasIssue()).toBe(false);
|
||||
expect(issue.getIssue()).toBeNull();
|
||||
});
|
||||
|
||||
it('should report an issue after trigger', () => {
|
||||
const issue = new ViewIncompatibleIssue(createAPI());
|
||||
issue.trigger({ error: new Error('boom') });
|
||||
|
||||
expect(issue.hasIssue()).toBe(true);
|
||||
});
|
||||
|
||||
it('should treat a triggered null/undefined error as no issue', () => {
|
||||
const issue = new ViewIncompatibleIssue(createAPI());
|
||||
issue.trigger({ error: undefined });
|
||||
|
||||
expect(issue.hasIssue()).toBe(false);
|
||||
expect(issue.getIssue()).toBeNull();
|
||||
});
|
||||
|
||||
describe('isFullCardIssue', () => {
|
||||
it('should return true when no view is set', () => {
|
||||
const issue = new ViewIncompatibleIssue(createAPI(false));
|
||||
expect(issue.isFullCardIssue()).toBe(true);
|
||||
});
|
||||
|
||||
it('should return false when a view is set', () => {
|
||||
const issue = new ViewIncompatibleIssue(createAPI(true));
|
||||
expect(issue.isFullCardIssue()).toBe(false);
|
||||
});
|
||||
});
|
||||
|
||||
describe('getIssue', () => {
|
||||
it('should return a notification with heading, body, and no retry control', () => {
|
||||
const issue = new ViewIncompatibleIssue(createAPI());
|
||||
issue.trigger({ error: new Error('boom') });
|
||||
|
||||
expect(issue.getIssue()).toEqual({
|
||||
icon: 'mdi:video-off',
|
||||
severity: 'high',
|
||||
notification: {
|
||||
heading: {
|
||||
text: 'View not supported',
|
||||
icon: 'mdi:video-off',
|
||||
severity: 'high',
|
||||
},
|
||||
body: { text: 'The selected camera or media does not support this view' },
|
||||
},
|
||||
});
|
||||
});
|
||||
|
||||
it('should include error context on AdvancedCameraCardError', () => {
|
||||
const issue = new ViewIncompatibleIssue(createAPI());
|
||||
issue.trigger({
|
||||
error: new AdvancedCameraCardError('err', {
|
||||
view: 'snapshot',
|
||||
camera: 'cam.office',
|
||||
}),
|
||||
});
|
||||
|
||||
const result = issue.getIssue();
|
||||
expect(result?.notification.context).toEqual([
|
||||
expect.stringContaining('view: snapshot'),
|
||||
]);
|
||||
});
|
||||
|
||||
it('should omit context on plain errors', () => {
|
||||
const issue = new ViewIncompatibleIssue(createAPI());
|
||||
issue.trigger({ error: new Error('plain') });
|
||||
|
||||
const result = issue.getIssue();
|
||||
expect(result?.notification.context).toBeUndefined();
|
||||
});
|
||||
});
|
||||
|
||||
it('should clear the issue after reset', () => {
|
||||
const issue = new ViewIncompatibleIssue(createAPI());
|
||||
issue.trigger({ error: new Error('boom') });
|
||||
expect(issue.hasIssue()).toBe(true);
|
||||
|
||||
issue.reset();
|
||||
|
||||
expect(issue.hasIssue()).toBe(false);
|
||||
expect(issue.getIssue()).toBeNull();
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,25 @@
|
||||
// @vitest-environment jsdom
|
||||
import { describe, expect, it } from 'vitest';
|
||||
import { createRetryControl } from '../../../src/card-controller/issues/retry-control';
|
||||
import { InternalCallbackActionConfig } from '../../../src/config/schema/actions/custom/internal';
|
||||
import { createCardAPI } from '../../test-utils';
|
||||
|
||||
describe('createRetryControl', () => {
|
||||
it('should return a control with expected icon, tooltip, and dismiss', () => {
|
||||
const control = createRetryControl('media_load');
|
||||
|
||||
expect(control.icon).toBe('mdi:refresh');
|
||||
expect(control.tooltip).toBe('Retry');
|
||||
expect(control.dismiss).toBe(true);
|
||||
});
|
||||
|
||||
it('should call manager.retry with the issue key when the callback executes', async () => {
|
||||
const api = createCardAPI();
|
||||
const control = createRetryControl('media_query');
|
||||
|
||||
const tapAction = control.actions?.tap_action as InternalCallbackActionConfig;
|
||||
await tapAction.callback(api);
|
||||
|
||||
expect(api.getIssueManager().retry).toBeCalledWith('media_query', true);
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,555 @@
|
||||
import { assert, beforeEach, describe, expect, it, vi } from 'vitest';
|
||||
import { mock } from 'vitest-mock-extended';
|
||||
import { IssueStateManager } from '../../../src/card-controller/issues/state-manager';
|
||||
import { Issue, IssueDescription } from '../../../src/card-controller/issues/types';
|
||||
import { createHASS } from '../../test-utils';
|
||||
|
||||
const createIssueDescription = (
|
||||
overrides?: Partial<IssueDescription>,
|
||||
): IssueDescription => ({
|
||||
icon: 'mdi:test',
|
||||
severity: 'high',
|
||||
notification: {
|
||||
heading: {
|
||||
text: 'Test heading',
|
||||
icon: 'mdi:test',
|
||||
severity: 'high',
|
||||
},
|
||||
body: { text: 'Test text' },
|
||||
},
|
||||
...overrides,
|
||||
});
|
||||
|
||||
describe('IssueStateManager', () => {
|
||||
let mockConfigUpgrade: Issue;
|
||||
let mockLegacyResource: Issue;
|
||||
let mockMediaLoad: Issue;
|
||||
|
||||
const createManager = (issues?: Issue[]): IssueStateManager => {
|
||||
const manager = new IssueStateManager();
|
||||
for (const issue of issues ?? [
|
||||
mockConfigUpgrade,
|
||||
mockLegacyResource,
|
||||
mockMediaLoad,
|
||||
]) {
|
||||
manager.addIssue(issue);
|
||||
}
|
||||
return manager;
|
||||
};
|
||||
|
||||
beforeEach(() => {
|
||||
vi.resetAllMocks();
|
||||
|
||||
mockConfigUpgrade = mock<Issue>({ key: 'config_upgrade' });
|
||||
mockLegacyResource = mock<Issue>({ key: 'legacy_resource' });
|
||||
mockMediaLoad = mock<Issue>({ key: 'media_load' });
|
||||
});
|
||||
|
||||
it('should register all provided issues on construction', () => {
|
||||
const manager = createManager();
|
||||
const presence = manager.getIssuePresence();
|
||||
|
||||
expect(presence.has('config_upgrade')).toBe(false);
|
||||
expect(presence.has('legacy_resource')).toBe(false);
|
||||
expect(presence.has('media_load')).toBe(false);
|
||||
});
|
||||
|
||||
describe('detectStatic', () => {
|
||||
it('should call detectStatic on all issues', async () => {
|
||||
const manager = createManager();
|
||||
const hass = createHASS();
|
||||
|
||||
await manager.detectStatic(hass);
|
||||
|
||||
assert(mockConfigUpgrade.detectStatic);
|
||||
assert(mockLegacyResource.detectStatic);
|
||||
assert(mockMediaLoad.detectStatic);
|
||||
expect(mockConfigUpgrade.detectStatic).toBeCalledWith(hass);
|
||||
expect(mockLegacyResource.detectStatic).toBeCalledWith(hass);
|
||||
expect(mockMediaLoad.detectStatic).toBeCalledWith(hass);
|
||||
});
|
||||
});
|
||||
|
||||
describe('trigger', () => {
|
||||
it('should call trigger on the matching issue', () => {
|
||||
const manager = createManager();
|
||||
|
||||
manager.trigger('media_load', { targetID: 'cam1' });
|
||||
|
||||
assert(mockMediaLoad.trigger);
|
||||
expect(mockMediaLoad.trigger).toBeCalledWith({ targetID: 'cam1' });
|
||||
});
|
||||
|
||||
it('should do nothing for unknown key', () => {
|
||||
const manager = createManager();
|
||||
|
||||
manager.trigger('unknown' as never, {} as never);
|
||||
|
||||
assert(mockMediaLoad.trigger);
|
||||
expect(mockMediaLoad.trigger).not.toBeCalled();
|
||||
});
|
||||
});
|
||||
|
||||
describe('detectDynamic', () => {
|
||||
it('should call detectDynamic on issues with the given state', () => {
|
||||
const manager = createManager();
|
||||
|
||||
manager.detectDynamic({ view: 'live' });
|
||||
|
||||
assert(mockMediaLoad.detectDynamic);
|
||||
expect(mockMediaLoad.detectDynamic).toBeCalledWith({ view: 'live' });
|
||||
});
|
||||
});
|
||||
|
||||
describe('getFullCardIssue', () => {
|
||||
it('should return first full-card issue', () => {
|
||||
const result = createIssueDescription();
|
||||
vi.mocked(mockMediaLoad.hasIssue).mockReturnValue(true);
|
||||
assert(mockMediaLoad.isFullCardIssue);
|
||||
vi.mocked(mockMediaLoad.isFullCardIssue).mockReturnValue(true);
|
||||
vi.mocked(mockMediaLoad.getIssue).mockReturnValue(result);
|
||||
|
||||
const manager = createManager();
|
||||
|
||||
expect(manager.getFullCardIssue()).toBe(result);
|
||||
});
|
||||
|
||||
it('should return null when only popup issues exist', () => {
|
||||
vi.mocked(mockMediaLoad.hasIssue).mockReturnValue(true);
|
||||
assert(mockMediaLoad.isFullCardIssue);
|
||||
vi.mocked(mockMediaLoad.isFullCardIssue).mockReturnValue(false);
|
||||
|
||||
const manager = createManager();
|
||||
|
||||
expect(manager.getFullCardIssue()).toBeNull();
|
||||
});
|
||||
|
||||
it('should skip inactive full-card issues', () => {
|
||||
vi.mocked(mockMediaLoad.hasIssue).mockReturnValue(false);
|
||||
|
||||
const manager = createManager();
|
||||
|
||||
expect(manager.getFullCardIssue()).toBeNull();
|
||||
});
|
||||
});
|
||||
|
||||
describe('hasFullCardIssue', () => {
|
||||
it('should return true when full-card issue exists', () => {
|
||||
vi.mocked(mockMediaLoad.hasIssue).mockReturnValue(true);
|
||||
assert(mockMediaLoad.isFullCardIssue);
|
||||
vi.mocked(mockMediaLoad.isFullCardIssue).mockReturnValue(true);
|
||||
vi.mocked(mockMediaLoad.getIssue).mockReturnValue(createIssueDescription());
|
||||
|
||||
expect(createManager().hasFullCardIssue()).toBe(true);
|
||||
});
|
||||
|
||||
it('should return false when no full-card issues', () => {
|
||||
expect(createManager().hasFullCardIssue()).toBe(false);
|
||||
});
|
||||
});
|
||||
|
||||
describe('getIssueDescriptions', () => {
|
||||
it('should return results for active issues', () => {
|
||||
const result = createIssueDescription();
|
||||
vi.mocked(mockConfigUpgrade.getIssue).mockReturnValue(result);
|
||||
|
||||
const manager = createManager();
|
||||
|
||||
expect(manager.getIssueDescriptions()).toEqual([
|
||||
{ key: 'config_upgrade', issue: result },
|
||||
]);
|
||||
});
|
||||
|
||||
it('should return empty array when no issues active', () => {
|
||||
expect(createManager().getIssueDescriptions()).toEqual([]);
|
||||
});
|
||||
});
|
||||
|
||||
describe('getIssuePresence', () => {
|
||||
it('should return a map keyed by issue key with the current description as value', () => {
|
||||
const description = createIssueDescription();
|
||||
vi.mocked(mockConfigUpgrade.getIssue).mockReturnValue(description);
|
||||
vi.mocked(mockLegacyResource.getIssue).mockReturnValue(null);
|
||||
|
||||
const manager = createManager();
|
||||
|
||||
const presence = manager.getIssuePresence();
|
||||
expect(presence.has('config_upgrade')).toBe(true);
|
||||
expect(presence.get('config_upgrade')).toBe(description);
|
||||
expect(presence.has('legacy_resource')).toBe(false);
|
||||
});
|
||||
});
|
||||
|
||||
describe('getNotification', () => {
|
||||
it('should return notification for an issue', () => {
|
||||
const notification = { body: { text: 'test' } };
|
||||
mockMediaLoad.getNotification = vi.fn().mockReturnValue(notification);
|
||||
|
||||
const manager = createManager();
|
||||
|
||||
expect(manager.getNotification('media_load')).toBe(notification);
|
||||
});
|
||||
|
||||
it('should return null for unknown key', () => {
|
||||
expect(createManager().getNotification('unknown' as never)).toBeNull();
|
||||
});
|
||||
});
|
||||
|
||||
describe('retry', () => {
|
||||
it('should call retry on issues that want retry with non-exclusive result', () => {
|
||||
assert(mockMediaLoad.needsRetry);
|
||||
assert(mockMediaLoad.retry);
|
||||
vi.mocked(mockMediaLoad.needsRetry).mockReturnValue(true);
|
||||
vi.mocked(mockMediaLoad.retry).mockReturnValue(false);
|
||||
|
||||
const manager = createManager();
|
||||
manager.retry();
|
||||
|
||||
expect(mockMediaLoad.retry).toBeCalled();
|
||||
});
|
||||
|
||||
it('should call retry on issues that want retry with exclusive result', () => {
|
||||
assert(mockMediaLoad.needsRetry);
|
||||
assert(mockMediaLoad.retry);
|
||||
vi.mocked(mockMediaLoad.needsRetry).mockReturnValue(true);
|
||||
vi.mocked(mockMediaLoad.retry).mockReturnValue(true);
|
||||
|
||||
createManager().retry();
|
||||
|
||||
expect(mockMediaLoad.retry).toBeCalled();
|
||||
});
|
||||
|
||||
it('should not call retry on issues that do not want retry', () => {
|
||||
assert(mockMediaLoad.needsRetry);
|
||||
vi.mocked(mockMediaLoad.needsRetry).mockReturnValue(false);
|
||||
|
||||
const manager = createManager();
|
||||
manager.retry();
|
||||
|
||||
assert(mockMediaLoad.retry);
|
||||
expect(mockMediaLoad.retry).not.toBeCalled();
|
||||
});
|
||||
|
||||
it('should stop after exclusive result and not call retry on subsequent issues', () => {
|
||||
// configUpgrade returns exclusive (true) → loop should stop.
|
||||
// mediaLoad is registered after, so its retry should not be called.
|
||||
assert(mockConfigUpgrade.needsRetry);
|
||||
assert(mockConfigUpgrade.retry);
|
||||
vi.mocked(mockConfigUpgrade.needsRetry).mockReturnValue(true);
|
||||
vi.mocked(mockConfigUpgrade.retry).mockReturnValue(true);
|
||||
assert(mockMediaLoad.needsRetry);
|
||||
vi.mocked(mockMediaLoad.needsRetry).mockReturnValue(true);
|
||||
|
||||
const manager = createManager();
|
||||
manager.retry();
|
||||
|
||||
expect(mockConfigUpgrade.retry).toBeCalled();
|
||||
assert(mockMediaLoad.retry);
|
||||
expect(mockMediaLoad.retry).not.toBeCalled();
|
||||
});
|
||||
|
||||
it('should continue after non-exclusive result and call retry on subsequent issues', () => {
|
||||
// configUpgrade returns non-exclusive (false) → loop should continue.
|
||||
assert(mockConfigUpgrade.needsRetry);
|
||||
assert(mockConfigUpgrade.retry);
|
||||
vi.mocked(mockConfigUpgrade.needsRetry).mockReturnValue(true);
|
||||
vi.mocked(mockConfigUpgrade.retry).mockReturnValue(false);
|
||||
assert(mockMediaLoad.needsRetry);
|
||||
assert(mockMediaLoad.retry);
|
||||
vi.mocked(mockMediaLoad.needsRetry).mockReturnValue(true);
|
||||
vi.mocked(mockMediaLoad.retry).mockReturnValue(false);
|
||||
|
||||
const manager = createManager();
|
||||
manager.retry();
|
||||
|
||||
expect(mockConfigUpgrade.retry).toBeCalled();
|
||||
expect(mockMediaLoad.retry).toBeCalled();
|
||||
});
|
||||
});
|
||||
|
||||
describe('retry with key', () => {
|
||||
it('should call retry on the matching issue when needsRetry is true', () => {
|
||||
assert(mockMediaLoad.needsRetry);
|
||||
assert(mockMediaLoad.retry);
|
||||
vi.mocked(mockMediaLoad.needsRetry).mockReturnValue(true);
|
||||
vi.mocked(mockMediaLoad.retry).mockReturnValue(false);
|
||||
|
||||
createManager().retry('media_load');
|
||||
|
||||
expect(mockMediaLoad.retry).toBeCalled();
|
||||
});
|
||||
|
||||
it('should not call retry on the matching issue when needsRetry is false', () => {
|
||||
assert(mockMediaLoad.needsRetry);
|
||||
vi.mocked(mockMediaLoad.needsRetry).mockReturnValue(false);
|
||||
|
||||
createManager().retry('media_load');
|
||||
|
||||
assert(mockMediaLoad.retry);
|
||||
expect(mockMediaLoad.retry).not.toBeCalled();
|
||||
});
|
||||
|
||||
it('should call retry when force is true even if needsRetry is false', () => {
|
||||
assert(mockMediaLoad.needsRetry);
|
||||
assert(mockMediaLoad.retry);
|
||||
vi.mocked(mockMediaLoad.needsRetry).mockReturnValue(false);
|
||||
vi.mocked(mockMediaLoad.retry).mockReturnValue(false);
|
||||
|
||||
createManager().retry('media_load', true);
|
||||
|
||||
expect(mockMediaLoad.retry).toBeCalled();
|
||||
});
|
||||
|
||||
it('should do nothing for unknown key', () => {
|
||||
createManager().retry('unknown' as never);
|
||||
|
||||
assert(mockMediaLoad.retry);
|
||||
expect(mockMediaLoad.retry).not.toBeCalled();
|
||||
});
|
||||
});
|
||||
|
||||
describe('needsRetry', () => {
|
||||
it('should return true when issues want retry', () => {
|
||||
assert(mockMediaLoad.needsRetry);
|
||||
vi.mocked(mockMediaLoad.needsRetry).mockReturnValue(true);
|
||||
|
||||
expect(createManager().needsRetry()).toBe(true);
|
||||
});
|
||||
|
||||
it('should return false when no issues want retry', () => {
|
||||
expect(createManager().needsRetry()).toBe(false);
|
||||
});
|
||||
});
|
||||
|
||||
describe('logging', () => {
|
||||
it('should log on static detection when issue is active', async () => {
|
||||
const spy = vi.spyOn(console, 'warn').mockReturnValue();
|
||||
const result = createIssueDescription({
|
||||
notification: { body: { text: 'Legacy issue' } },
|
||||
});
|
||||
vi.mocked(mockLegacyResource.hasIssue).mockReturnValue(true);
|
||||
vi.mocked(mockLegacyResource.getIssue).mockReturnValue(result);
|
||||
|
||||
const manager = createManager();
|
||||
await manager.detectStatic(createHASS());
|
||||
|
||||
expect(spy).toBeCalledWith(
|
||||
'Advanced Camera Card [issue=legacy_resource]: Legacy issue',
|
||||
);
|
||||
spy.mockRestore();
|
||||
});
|
||||
|
||||
it('should log on dynamic evaluation when issue becomes active', () => {
|
||||
const spy = vi.spyOn(console, 'warn').mockReturnValue();
|
||||
const result = createIssueDescription({
|
||||
notification: { body: { text: 'Stream issue' } },
|
||||
});
|
||||
vi.mocked(mockMediaLoad.hasIssue).mockReturnValueOnce(false).mockReturnValue(true);
|
||||
vi.mocked(mockMediaLoad.getIssue).mockReturnValue(result);
|
||||
|
||||
const manager = createManager();
|
||||
manager.detectDynamic({ view: 'live' });
|
||||
|
||||
expect(spy).toBeCalledWith(
|
||||
'Advanced Camera Card [issue=media_load]: Stream issue',
|
||||
);
|
||||
spy.mockRestore();
|
||||
});
|
||||
|
||||
it('should log on trigger when the issue becomes active', () => {
|
||||
const spy = vi.spyOn(console, 'warn').mockReturnValue();
|
||||
const result = createIssueDescription({
|
||||
notification: { body: { text: 'Triggered' } },
|
||||
});
|
||||
vi.mocked(mockMediaLoad.getIssue).mockReturnValue(result);
|
||||
|
||||
const manager = createManager();
|
||||
manager.trigger('media_load', { targetID: 'cam1' });
|
||||
|
||||
expect(spy).toBeCalledWith('Advanced Camera Card [issue=media_load]: Triggered');
|
||||
spy.mockRestore();
|
||||
});
|
||||
|
||||
it('should not log on trigger when the issue stays inactive', () => {
|
||||
const spy = vi.spyOn(console, 'warn').mockReturnValue();
|
||||
vi.mocked(mockMediaLoad.getIssue).mockReturnValue(null);
|
||||
|
||||
const manager = createManager();
|
||||
manager.trigger('media_load', { targetID: 'cam1' });
|
||||
|
||||
expect(spy).not.toBeCalled();
|
||||
spy.mockRestore();
|
||||
});
|
||||
|
||||
it('should not log on trigger for an unknown key', () => {
|
||||
const spy = vi.spyOn(console, 'warn').mockReturnValue();
|
||||
|
||||
const manager = createManager();
|
||||
manager.trigger('unknown' as never, {} as never);
|
||||
|
||||
expect(spy).not.toBeCalled();
|
||||
spy.mockRestore();
|
||||
});
|
||||
|
||||
it('should only log once per issue key', async () => {
|
||||
const spy = vi.spyOn(console, 'warn').mockReturnValue();
|
||||
const result = createIssueDescription({
|
||||
notification: { body: { text: 'Repeated' } },
|
||||
});
|
||||
vi.mocked(mockLegacyResource.hasIssue).mockReturnValue(true);
|
||||
vi.mocked(mockLegacyResource.getIssue).mockReturnValue(result);
|
||||
|
||||
const manager = createManager();
|
||||
await manager.detectStatic(createHASS());
|
||||
await manager.detectStatic(createHASS());
|
||||
|
||||
expect(spy).toBeCalledTimes(1);
|
||||
spy.mockRestore();
|
||||
});
|
||||
|
||||
it('should not log when issue has no result', async () => {
|
||||
const spy = vi.spyOn(console, 'warn').mockReturnValue();
|
||||
vi.mocked(mockLegacyResource.hasIssue).mockReturnValue(false);
|
||||
|
||||
const manager = createManager();
|
||||
await manager.detectStatic(createHASS());
|
||||
|
||||
expect(spy).not.toBeCalled();
|
||||
spy.mockRestore();
|
||||
});
|
||||
|
||||
it('should not log when issue result has no summarizable text', async () => {
|
||||
const spy = vi.spyOn(console, 'warn').mockReturnValue();
|
||||
// Notification has neither body.text nor heading.text
|
||||
const result = createIssueDescription({
|
||||
notification: {},
|
||||
});
|
||||
vi.mocked(mockLegacyResource.hasIssue).mockReturnValue(true);
|
||||
vi.mocked(mockLegacyResource.getIssue).mockReturnValue(result);
|
||||
|
||||
const manager = createManager();
|
||||
await manager.detectStatic(createHASS());
|
||||
|
||||
expect(spy).not.toBeCalled();
|
||||
spy.mockRestore();
|
||||
});
|
||||
|
||||
it('should log again after the issue clears and re-activates', async () => {
|
||||
const spy = vi.spyOn(console, 'warn').mockReturnValue();
|
||||
const first = createIssueDescription({
|
||||
notification: { body: { text: 'First' } },
|
||||
});
|
||||
const second = createIssueDescription({
|
||||
notification: { body: { text: 'Second' } },
|
||||
});
|
||||
vi.mocked(mockLegacyResource.getIssue)
|
||||
.mockReturnValueOnce(first)
|
||||
.mockReturnValueOnce(null)
|
||||
.mockReturnValueOnce(second);
|
||||
|
||||
const manager = createManager();
|
||||
// Activate → log First.
|
||||
await manager.detectStatic(createHASS());
|
||||
// Clear → drop dedupe entry.
|
||||
await manager.detectStatic(createHASS());
|
||||
// Re-activate with a different payload → log Second.
|
||||
await manager.detectStatic(createHASS());
|
||||
|
||||
expect(spy).toBeCalledTimes(2);
|
||||
expect(spy).toHaveBeenNthCalledWith(
|
||||
1,
|
||||
'Advanced Camera Card [issue=legacy_resource]: First',
|
||||
);
|
||||
expect(spy).toHaveBeenNthCalledWith(
|
||||
2,
|
||||
'Advanced Camera Card [issue=legacy_resource]: Second',
|
||||
);
|
||||
spy.mockRestore();
|
||||
});
|
||||
|
||||
it('should log again after reset and re-activation', () => {
|
||||
const spy = vi.spyOn(console, 'warn').mockReturnValue();
|
||||
const description = createIssueDescription({
|
||||
notification: { body: { text: 'Repeat' } },
|
||||
});
|
||||
// Active → cleared-by-reset → active again on next eval.
|
||||
vi.mocked(mockMediaLoad.getIssue)
|
||||
.mockReturnValueOnce(description)
|
||||
.mockReturnValueOnce(null)
|
||||
.mockReturnValueOnce(description);
|
||||
|
||||
const manager = createManager();
|
||||
manager.detectDynamic({ view: 'live' });
|
||||
manager.reset('media_load');
|
||||
// After reset, the issue reports cleared on next detect, releasing the
|
||||
// dedupe.
|
||||
manager.detectDynamic({ view: 'live' });
|
||||
// Then it re-activates (e.g. new trigger arrives).
|
||||
manager.detectDynamic({ view: 'live' });
|
||||
|
||||
expect(spy).toBeCalledTimes(2);
|
||||
spy.mockRestore();
|
||||
});
|
||||
});
|
||||
|
||||
describe('reset', () => {
|
||||
it('should reset a specific issue by key', () => {
|
||||
const manager = createManager();
|
||||
manager.reset('media_load');
|
||||
|
||||
assert(mockMediaLoad.reset);
|
||||
expect(mockMediaLoad.reset).toBeCalled();
|
||||
assert(mockConfigUpgrade.reset);
|
||||
expect(mockConfigUpgrade.reset).not.toBeCalled();
|
||||
});
|
||||
|
||||
it('should reset all issues when no key is given', () => {
|
||||
const manager = createManager();
|
||||
manager.reset();
|
||||
|
||||
assert(mockConfigUpgrade.reset);
|
||||
assert(mockLegacyResource.reset);
|
||||
assert(mockMediaLoad.reset);
|
||||
expect(mockConfigUpgrade.reset).toBeCalled();
|
||||
expect(mockLegacyResource.reset).toBeCalled();
|
||||
expect(mockMediaLoad.reset).toBeCalled();
|
||||
});
|
||||
|
||||
it('should do nothing for unknown key', () => {
|
||||
const manager = createManager();
|
||||
manager.reset('unknown' as never);
|
||||
|
||||
assert(mockMediaLoad.reset);
|
||||
expect(mockMediaLoad.reset).not.toBeCalled();
|
||||
});
|
||||
});
|
||||
|
||||
describe('suspend', () => {
|
||||
it('should call suspend on all issues that implement it', () => {
|
||||
const manager = createManager();
|
||||
manager.suspend();
|
||||
|
||||
assert(mockConfigUpgrade.suspend);
|
||||
assert(mockLegacyResource.suspend);
|
||||
assert(mockMediaLoad.suspend);
|
||||
expect(mockConfigUpgrade.suspend).toBeCalled();
|
||||
expect(mockLegacyResource.suspend).toBeCalled();
|
||||
expect(mockMediaLoad.suspend).toBeCalled();
|
||||
});
|
||||
});
|
||||
|
||||
describe('destroy', () => {
|
||||
it('should destroy all issues and clear', () => {
|
||||
const manager = createManager();
|
||||
manager.destroy();
|
||||
|
||||
assert(mockConfigUpgrade.reset);
|
||||
assert(mockLegacyResource.reset);
|
||||
assert(mockMediaLoad.reset);
|
||||
expect(mockConfigUpgrade.reset).toBeCalled();
|
||||
expect(mockLegacyResource.reset).toBeCalled();
|
||||
expect(mockMediaLoad.reset).toBeCalled();
|
||||
expect(manager.getIssuePresence().size).toBe(0);
|
||||
});
|
||||
});
|
||||
});
|
||||
@@ -83,4 +83,30 @@ describe('KeyboardStateManager', () => {
|
||||
|
||||
expect(api.getConditionStateManager().setState).not.toBeCalled();
|
||||
});
|
||||
|
||||
it('should clear held keys on uninitialize', () => {
|
||||
const api = createCardAPI();
|
||||
const element = createLitElement();
|
||||
vi.mocked(api.getCardElementManager().getElement).mockReturnValue(element);
|
||||
const manager = new KeyboardStateManager(api);
|
||||
manager.initialize();
|
||||
|
||||
element.dispatchEvent(new KeyboardEvent('keydown', { key: 'a' }));
|
||||
vi.mocked(api.getConditionStateManager().setState).mockClear();
|
||||
|
||||
manager.uninitialize();
|
||||
|
||||
expect(api.getConditionStateManager().setState).toBeCalledWith({ keys: {} });
|
||||
});
|
||||
|
||||
it('should not set state on uninitialize when no keys held', () => {
|
||||
const api = createCardAPI();
|
||||
const element = createLitElement();
|
||||
vi.mocked(api.getCardElementManager().getElement).mockReturnValue(element);
|
||||
const manager = new KeyboardStateManager(api);
|
||||
manager.initialize();
|
||||
manager.uninitialize();
|
||||
|
||||
expect(api.getConditionStateManager().setState).not.toBeCalled();
|
||||
});
|
||||
});
|
||||
|
||||
@@ -69,7 +69,7 @@ describe('MediaPlayerManager', () => {
|
||||
});
|
||||
|
||||
describe('should initialize', () => {
|
||||
it('correctly', async () => {
|
||||
it('should initialize correctly', async () => {
|
||||
const entityRegistryManager = new EntityRegistryManagerMock([
|
||||
createRegistryEntity({
|
||||
entity_id: 'media_player.ok1',
|
||||
@@ -108,7 +108,7 @@ describe('MediaPlayerManager', () => {
|
||||
expect(manager.hasMediaPlayers()).toBeTruthy();
|
||||
});
|
||||
|
||||
it('without hass', async () => {
|
||||
it('should handle without hass', async () => {
|
||||
const api = createCardAPI();
|
||||
vi.mocked(api.getHASSManager().getHASS).mockReturnValue(null);
|
||||
const manager = new MediaPlayerManager(api);
|
||||
@@ -119,7 +119,7 @@ describe('MediaPlayerManager', () => {
|
||||
expect(manager.hasMediaPlayers()).toBeFalsy();
|
||||
});
|
||||
|
||||
it('even if entity registry call fails', async () => {
|
||||
it('should handle entity registry call failure', async () => {
|
||||
const spy = vi.spyOn(global.console, 'warn').mockImplementation(() => true);
|
||||
|
||||
const entityRegistryManager = mock<EntityRegistryManager>();
|
||||
@@ -273,7 +273,7 @@ describe('MediaPlayerManager', () => {
|
||||
|
||||
describe('should play', () => {
|
||||
describe('live', () => {
|
||||
it('without camera config', async () => {
|
||||
it('should handle without camera config', async () => {
|
||||
const api = createCardAPI();
|
||||
vi.mocked(api.getCameraManager).mockReturnValue(createCameraManager());
|
||||
vi.mocked(api.getHASSManager().getHASS).mockReturnValue(createHASS());
|
||||
@@ -285,7 +285,7 @@ describe('MediaPlayerManager', () => {
|
||||
});
|
||||
|
||||
describe('using standard method', () => {
|
||||
it('successfully', async () => {
|
||||
it('should succeed', async () => {
|
||||
const api = createCardAPI();
|
||||
vi.mocked(api.getCameraManager).mockReturnValue(createCameraManager());
|
||||
vi.mocked(api.getCameraManager().getStore).mockReturnValue(
|
||||
@@ -330,7 +330,7 @@ describe('MediaPlayerManager', () => {
|
||||
);
|
||||
});
|
||||
|
||||
it('without camera_entity', async () => {
|
||||
it('should handle without camera_entity', async () => {
|
||||
const api = createCardAPI();
|
||||
vi.mocked(api.getCameraManager).mockReturnValue(createCameraManager());
|
||||
|
||||
@@ -350,7 +350,7 @@ describe('MediaPlayerManager', () => {
|
||||
expect(api.getHASSManager().getHASS()?.callService).not.toBeCalled();
|
||||
});
|
||||
|
||||
it('without title and thumbnail', async () => {
|
||||
it('should handle without title and thumbnail', async () => {
|
||||
const api = createCardAPI();
|
||||
vi.mocked(api.getCameraManager).mockReturnValue(createCameraManager());
|
||||
vi.mocked(api.getCameraManager().getStore).mockReturnValue(
|
||||
@@ -382,7 +382,7 @@ describe('MediaPlayerManager', () => {
|
||||
});
|
||||
|
||||
describe('using dashboard method', () => {
|
||||
it('successfully', async () => {
|
||||
it('should succeed', async () => {
|
||||
const api = createCardAPI();
|
||||
vi.mocked(api.getCameraManager).mockReturnValue(createCameraManager());
|
||||
vi.mocked(api.getCameraManager().getStore).mockReturnValue(
|
||||
@@ -418,7 +418,7 @@ describe('MediaPlayerManager', () => {
|
||||
);
|
||||
});
|
||||
|
||||
it('without hass', async () => {
|
||||
it('should handle without hass', async () => {
|
||||
const api = createCardAPI();
|
||||
vi.mocked(api.getCameraManager).mockReturnValue(createCameraManager());
|
||||
vi.mocked(api.getCameraManager().getStore).mockReturnValue(
|
||||
@@ -446,38 +446,36 @@ describe('MediaPlayerManager', () => {
|
||||
// No actual test can be performed here as nothing observable happens.
|
||||
// This test serves only as code-coverage long-tail.
|
||||
});
|
||||
});
|
||||
|
||||
it('without required configuration', async () => {
|
||||
const api = createCardAPI();
|
||||
vi.mocked(api.getCameraManager).mockReturnValue(createCameraManager());
|
||||
vi.mocked(api.getCameraManager().getStore).mockReturnValue(
|
||||
createStore([
|
||||
{
|
||||
cameraID: 'camera.foo',
|
||||
config: createCameraConfig({
|
||||
camera_entity: 'camera.foo',
|
||||
cast: {
|
||||
method: 'dashboard',
|
||||
},
|
||||
}),
|
||||
},
|
||||
]),
|
||||
);
|
||||
vi.mocked(api.getHASSManager().getHASS).mockReturnValue(createHASS());
|
||||
it('should handle without dashboard_path or view_path', async () => {
|
||||
const api = createCardAPI();
|
||||
vi.mocked(api.getCameraManager).mockReturnValue(createCameraManager());
|
||||
|
||||
const manager = new MediaPlayerManager(api);
|
||||
// Bypass schema validation — the code has a runtime guard (TypeScript
|
||||
// narrowing) for the case where dashboard config is present but
|
||||
// dashboard_path / view_path are missing.
|
||||
const configWithNoDashboardPaths = createCameraConfig({
|
||||
camera_entity: 'camera.foo',
|
||||
});
|
||||
(configWithNoDashboardPaths as Record<string, unknown>).cast = {
|
||||
method: 'dashboard',
|
||||
dashboard: { dashboard_path: undefined, view_path: undefined },
|
||||
};
|
||||
|
||||
await manager.playLive('media_player.foo', 'camera.foo');
|
||||
vi.mocked(api.getCameraManager().getStore).mockReturnValue(
|
||||
createStore([
|
||||
{
|
||||
cameraID: 'camera.foo',
|
||||
config: configWithNoDashboardPaths,
|
||||
},
|
||||
]),
|
||||
);
|
||||
vi.mocked(api.getHASSManager().getHASS).mockReturnValue(createHASS());
|
||||
const manager = new MediaPlayerManager(api);
|
||||
|
||||
expect(
|
||||
vi.mocked(api.getMessageManager().setMessageIfHigherPriority),
|
||||
).toBeCalledWith({
|
||||
type: 'error',
|
||||
icon: 'mdi:cast',
|
||||
message:
|
||||
"Both 'dashboard_path' and 'view_path' parameters are required " +
|
||||
"for the 'dashboard' cast method",
|
||||
await manager.playLive('media_player.foo', 'camera.foo');
|
||||
|
||||
expect(api.getHASSManager().getHASS()?.callService).not.toBeCalled();
|
||||
});
|
||||
});
|
||||
});
|
||||
@@ -516,7 +514,7 @@ describe('MediaPlayerManager', () => {
|
||||
});
|
||||
});
|
||||
|
||||
it('without hass', async () => {
|
||||
it('should handle without hass', async () => {
|
||||
const api = createCardAPI();
|
||||
vi.mocked(api.getHASSManager().getHASS).mockReturnValue(null);
|
||||
const manager = new MediaPlayerManager(api);
|
||||
|
||||
@@ -1,176 +0,0 @@
|
||||
import { afterAll, describe, expect, it, vi } from 'vitest';
|
||||
import { MessageManager } from '../../src/card-controller/message-manager';
|
||||
import { AdvancedCameraCardError, Message } from '../../src/types';
|
||||
import { createCardAPI } from '../test-utils';
|
||||
|
||||
const createMessage = (options?: Partial<Message>): Message => {
|
||||
return {
|
||||
message: options?.message ?? 'message',
|
||||
...(!!options?.type && { type: options.type }),
|
||||
...(!!options?.icon && { icon: options.icon }),
|
||||
...(!!options?.context && { context: options.context }),
|
||||
...(!!options?.dotdotdot && { dotdotdot: options.dotdotdot }),
|
||||
};
|
||||
};
|
||||
|
||||
describe('MessageManager', () => {
|
||||
afterAll(() => {
|
||||
vi.restoreAllMocks();
|
||||
});
|
||||
|
||||
it('should construct', () => {
|
||||
const manager = new MessageManager(createCardAPI());
|
||||
expect(manager.hasMessage()).toBeFalsy();
|
||||
expect(manager.getMessage()).toBeNull();
|
||||
expect(manager.hasErrorMessage()).toBeFalsy();
|
||||
});
|
||||
|
||||
it('should set info message', () => {
|
||||
const api = createCardAPI();
|
||||
const manager = new MessageManager(api);
|
||||
const message = createMessage();
|
||||
manager.setMessageIfHigherPriority(message);
|
||||
expect(manager.hasMessage()).toBeTruthy();
|
||||
expect(manager.getMessage()).toBe(message);
|
||||
expect(manager.hasErrorMessage()).toBeFalsy();
|
||||
|
||||
expect(api.getMediaLoadedInfoManager().clear).toBeCalled();
|
||||
expect(api.getCardElementManager().scrollReset).toBeCalled();
|
||||
expect(api.getCardElementManager().update).toBeCalled();
|
||||
});
|
||||
|
||||
it('should set error message', () => {
|
||||
const api = createCardAPI();
|
||||
const manager = new MessageManager(api);
|
||||
const message = createMessage({ type: 'error' });
|
||||
manager.setMessageIfHigherPriority(message);
|
||||
expect(manager.hasMessage()).toBeTruthy();
|
||||
expect(manager.getMessage()).toBe(message);
|
||||
expect(manager.hasErrorMessage()).toBeTruthy();
|
||||
|
||||
expect(api.getMediaLoadedInfoManager().clear).toBeCalled();
|
||||
expect(api.getCardElementManager().scrollReset).toBeCalled();
|
||||
expect(api.getCardElementManager().update).toBeCalled();
|
||||
});
|
||||
|
||||
it('should reset message', () => {
|
||||
const api = createCardAPI();
|
||||
const manager = new MessageManager(api);
|
||||
|
||||
manager.reset();
|
||||
expect(manager.hasMessage()).toBeFalsy();
|
||||
|
||||
const message = createMessage({ type: 'error' });
|
||||
manager.setMessageIfHigherPriority(message);
|
||||
expect(manager.hasMessage()).toBeTruthy();
|
||||
|
||||
vi.mocked(api.getCardElementManager().update).mockClear();
|
||||
manager.reset();
|
||||
|
||||
expect(manager.hasMessage()).toBeFalsy();
|
||||
expect(api.getCardElementManager().update).toBeCalled();
|
||||
});
|
||||
|
||||
it('should reset message that matches type', () => {
|
||||
const api = createCardAPI();
|
||||
const manager = new MessageManager(api);
|
||||
|
||||
const message = createMessage({ type: 'connection' });
|
||||
manager.setMessageIfHigherPriority(message);
|
||||
expect(manager.getMessage()).toBe(message);
|
||||
|
||||
manager.resetType('error');
|
||||
expect(manager.getMessage()).toBe(message);
|
||||
|
||||
manager.resetType('connection');
|
||||
expect(manager.getMessage()).toBeNull();
|
||||
expect(manager.hasMessage()).toBeFalsy();
|
||||
});
|
||||
|
||||
it('should respect priority', () => {
|
||||
const api = createCardAPI();
|
||||
const manager = new MessageManager(api);
|
||||
|
||||
manager.reset();
|
||||
expect(manager.hasMessage()).toBeFalsy();
|
||||
|
||||
const errorMessage = createMessage({ type: 'error' });
|
||||
manager.setMessageIfHigherPriority(errorMessage);
|
||||
|
||||
const explicitInfoMessage = createMessage({ type: 'info' });
|
||||
manager.setMessageIfHigherPriority(explicitInfoMessage);
|
||||
|
||||
const implicitInfoMessage = createMessage();
|
||||
manager.setMessageIfHigherPriority(implicitInfoMessage);
|
||||
|
||||
expect(manager.getMessage()).toBe(errorMessage);
|
||||
|
||||
const connectionMessage = createMessage({ type: 'connection' });
|
||||
manager.setMessageIfHigherPriority(connectionMessage);
|
||||
|
||||
expect(manager.getMessage()).toBe(connectionMessage);
|
||||
});
|
||||
|
||||
it('should set AdvancedCameraCardError object', () => {
|
||||
const consoleSpy = vi.spyOn(global.console, 'warn').mockReturnValue(undefined);
|
||||
|
||||
const api = createCardAPI();
|
||||
const manager = new MessageManager(api);
|
||||
const context = { foo: 'bar' };
|
||||
|
||||
manager.setErrorIfHigherPriority(
|
||||
new AdvancedCameraCardError('advanced camera card message', context),
|
||||
);
|
||||
expect(manager.hasMessage()).toBeTruthy();
|
||||
expect(manager.getMessage()).toEqual({
|
||||
message: 'advanced camera card message',
|
||||
type: 'error',
|
||||
context: context,
|
||||
});
|
||||
|
||||
expect(consoleSpy).toBeCalled();
|
||||
});
|
||||
|
||||
it('should set Error object', () => {
|
||||
const consoleSpy = vi.spyOn(global.console, 'warn').mockReturnValue(undefined);
|
||||
|
||||
const api = createCardAPI();
|
||||
const manager = new MessageManager(api);
|
||||
|
||||
manager.setErrorIfHigherPriority(new Error('generic error message'));
|
||||
expect(manager.hasMessage()).toBeTruthy();
|
||||
expect(manager.getMessage()).toEqual({
|
||||
message: 'generic error message',
|
||||
type: 'error',
|
||||
});
|
||||
|
||||
expect(consoleSpy).toBeCalled();
|
||||
});
|
||||
|
||||
it('should set error with prefix', () => {
|
||||
const consoleSpy = vi.spyOn(global.console, 'warn').mockReturnValue(undefined);
|
||||
|
||||
const api = createCardAPI();
|
||||
const manager = new MessageManager(api);
|
||||
|
||||
manager.setErrorIfHigherPriority(new Error('generic error message'), 'PREFIX');
|
||||
expect(manager.hasMessage()).toBeTruthy();
|
||||
expect(manager.getMessage()).toEqual({
|
||||
message: 'PREFIX: generic error message',
|
||||
type: 'error',
|
||||
});
|
||||
|
||||
expect(consoleSpy).toBeCalled();
|
||||
});
|
||||
|
||||
it('should not set unknown error type', () => {
|
||||
const consoleSpy = vi.spyOn(global.console, 'warn').mockReturnValue(undefined);
|
||||
|
||||
const api = createCardAPI();
|
||||
const manager = new MessageManager(api);
|
||||
|
||||
manager.setErrorIfHigherPriority('not_an_error_object');
|
||||
expect(manager.hasMessage()).toBeFalsy();
|
||||
expect(consoleSpy).not.toBeCalled();
|
||||
});
|
||||
});
|
||||
@@ -1,6 +1,9 @@
|
||||
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
|
||||
import { mock } from 'vitest-mock-extended';
|
||||
import { MicrophoneManager } from '../../src/card-controller/microphone-manager';
|
||||
import {
|
||||
MicrophoneManager,
|
||||
MicrophoneNotSupportedError,
|
||||
} from '../../src/card-controller/microphone-manager';
|
||||
import { MicrophoneState } from '../../src/card-controller/types';
|
||||
import { createCardAPI, createConfig } from '../test-utils';
|
||||
|
||||
@@ -82,20 +85,17 @@ describe('MicrophoneManager', () => {
|
||||
const stream = createMockStream();
|
||||
vi.mocked(navigatorMock.mediaDevices.getUserMedia).mockResolvedValue(stream);
|
||||
|
||||
await manager.connect();
|
||||
await expect(manager.connect()).rejects.toThrow(MicrophoneNotSupportedError);
|
||||
|
||||
expect(manager.isConnected()).toBeFalsy();
|
||||
});
|
||||
|
||||
it('should be forbidden when permission denied', async () => {
|
||||
// Don't actually log messages to the console during the test.
|
||||
vi.spyOn(global.console, 'warn').mockReturnValue(undefined);
|
||||
|
||||
const api = createCardAPI();
|
||||
const manager = new MicrophoneManager(api);
|
||||
vi.mocked(navigatorMock.mediaDevices.getUserMedia).mockRejectedValue(new Error());
|
||||
|
||||
expect(await manager.connect()).toBeFalsy();
|
||||
await expect(manager.connect()).rejects.toThrow(Error);
|
||||
|
||||
expect(manager.isConnected()).toBeFalsy();
|
||||
expect(manager.isForbidden()).toBeTruthy();
|
||||
@@ -127,7 +127,7 @@ describe('MicrophoneManager', () => {
|
||||
const manager = new MicrophoneManager(api);
|
||||
vi.mocked(navigatorMock.mediaDevices.getUserMedia).mockRejectedValue(new Error());
|
||||
|
||||
await manager.connect();
|
||||
await expect(manager.connect()).rejects.toThrow(Error);
|
||||
|
||||
expect(manager.isMuted()).toBeTruthy();
|
||||
expect(api.getCardElementManager().update).toBeCalledTimes(1);
|
||||
@@ -245,7 +245,7 @@ describe('MicrophoneManager', () => {
|
||||
});
|
||||
|
||||
describe('should require initialization', async () => {
|
||||
it('when configured and supported', async () => {
|
||||
it('should require when configured and supported', async () => {
|
||||
const api = createCardAPI();
|
||||
const manager = new MicrophoneManager(api);
|
||||
vi.mocked(api.getConfigManager().getConfig).mockReturnValue(
|
||||
@@ -263,7 +263,7 @@ describe('MicrophoneManager', () => {
|
||||
expect(manager.shouldConnectOnInitialization()).toBeTruthy();
|
||||
});
|
||||
|
||||
it('when configured but not supported', async () => {
|
||||
it('should not require when configured but not supported', async () => {
|
||||
vi.stubGlobal('navigator', medialessNavigatorMock);
|
||||
|
||||
const api = createCardAPI();
|
||||
@@ -278,19 +278,19 @@ describe('MicrophoneManager', () => {
|
||||
}),
|
||||
);
|
||||
|
||||
await manager.connect();
|
||||
await expect(manager.connect()).rejects.toThrow(MicrophoneNotSupportedError);
|
||||
|
||||
expect(manager.shouldConnectOnInitialization()).toBeFalsy();
|
||||
});
|
||||
|
||||
it('when neither configured nor supported', async () => {
|
||||
it('should not require when neither configured nor supported', async () => {
|
||||
vi.stubGlobal('navigator', medialessNavigatorMock);
|
||||
|
||||
const api = createCardAPI();
|
||||
const manager = new MicrophoneManager(api);
|
||||
vi.mocked(api.getConfigManager().getConfig).mockReturnValue(createConfig());
|
||||
|
||||
await manager.connect();
|
||||
await expect(manager.connect()).rejects.toThrow(MicrophoneNotSupportedError);
|
||||
|
||||
expect(manager.shouldConnectOnInitialization()).toBeFalsy();
|
||||
});
|
||||
|
||||
@@ -22,7 +22,7 @@ describe('NotificationManager', () => {
|
||||
|
||||
it('should set and get notification', () => {
|
||||
const manager = new NotificationManager(api);
|
||||
const notification = { text: 'foo' };
|
||||
const notification = { body: { text: 'foo' } };
|
||||
manager.setNotification(notification);
|
||||
|
||||
expect(manager.getNotification()).toBe(notification);
|
||||
@@ -32,7 +32,7 @@ describe('NotificationManager', () => {
|
||||
|
||||
it('should reset notification', () => {
|
||||
const manager = new NotificationManager(api);
|
||||
manager.setNotification({ text: 'foo' });
|
||||
manager.setNotification({ body: { text: 'foo' } });
|
||||
vi.clearAllMocks();
|
||||
|
||||
manager.reset();
|
||||
|
||||
@@ -1,365 +0,0 @@
|
||||
import { beforeEach, describe, expect, it, vi } from 'vitest';
|
||||
import { mock } from 'vitest-mock-extended';
|
||||
import { ProblemManager } from '../../../src/card-controller/problems/manager';
|
||||
import { ConfigUpgradeProblem } from '../../../src/card-controller/problems/problems/config-upgrade';
|
||||
import { LegacyResourceProblem } from '../../../src/card-controller/problems/problems/legacy-resource';
|
||||
import { StreamNotLoadingProblem } from '../../../src/card-controller/problems/problems/stream-not-loading';
|
||||
import { Problem, ProblemResult } from '../../../src/card-controller/problems/types';
|
||||
import { ConditionStateManager } from '../../../src/conditions/state-manager';
|
||||
import { createCardAPI, createHASS } from '../../test-utils';
|
||||
|
||||
vi.mock('../../../src/card-controller/problems/problems/config-upgrade');
|
||||
vi.mock('../../../src/card-controller/problems/problems/legacy-resource');
|
||||
vi.mock('../../../src/card-controller/problems/problems/stream-not-loading');
|
||||
|
||||
const createProblemResult = (overrides?: Partial<ProblemResult>): ProblemResult => ({
|
||||
icon: 'mdi:test',
|
||||
severity: 'high',
|
||||
notification: {
|
||||
heading: {
|
||||
text: 'Test heading',
|
||||
icon: 'mdi:test',
|
||||
severity: 'high',
|
||||
},
|
||||
text: 'Test text',
|
||||
},
|
||||
...overrides,
|
||||
});
|
||||
|
||||
// @vitest-environment jsdom
|
||||
describe('ProblemManager', () => {
|
||||
let mockConfigUpgrade: Problem;
|
||||
let mockLegacyResource: Problem;
|
||||
let mockStreamNotLoading: Problem;
|
||||
|
||||
beforeEach(() => {
|
||||
vi.resetAllMocks();
|
||||
|
||||
mockConfigUpgrade = mock<Problem>({ key: 'config_upgrade' });
|
||||
mockLegacyResource = mock<Problem>({ key: 'legacy_resource' });
|
||||
mockStreamNotLoading = mock<Problem>({ key: 'stream_not_loading' });
|
||||
|
||||
vi.mocked(ConfigUpgradeProblem).mockImplementation(
|
||||
() => mockConfigUpgrade as unknown as ConfigUpgradeProblem,
|
||||
);
|
||||
vi.mocked(LegacyResourceProblem).mockImplementation(
|
||||
() => mockLegacyResource as unknown as LegacyResourceProblem,
|
||||
);
|
||||
vi.mocked(StreamNotLoadingProblem).mockImplementation(
|
||||
() => mockStreamNotLoading as unknown as StreamNotLoadingProblem,
|
||||
);
|
||||
});
|
||||
|
||||
it('should pass config getter to ConfigUpgradeProblem', () => {
|
||||
const api = createCardAPI();
|
||||
new ProblemManager(api);
|
||||
|
||||
const callback = vi.mocked(ConfigUpgradeProblem).mock.calls[0][0];
|
||||
callback();
|
||||
|
||||
expect(api.getConfigManager().getRawConfig).toBeCalled();
|
||||
});
|
||||
|
||||
it('should pass update callback to LegacyResourceProblem', () => {
|
||||
const api = createCardAPI();
|
||||
new ProblemManager(api);
|
||||
|
||||
const callback = vi.mocked(LegacyResourceProblem).mock.calls[0][0];
|
||||
callback();
|
||||
|
||||
expect(api.getCardElementManager().update).toBeCalled();
|
||||
});
|
||||
|
||||
it('should pass update callback to StreamNotLoadingProblem', () => {
|
||||
const api = createCardAPI();
|
||||
new ProblemManager(api);
|
||||
|
||||
const callback = vi.mocked(StreamNotLoadingProblem).mock.calls[0][0];
|
||||
callback();
|
||||
|
||||
expect(api.getCardElementManager().update).toBeCalled();
|
||||
});
|
||||
|
||||
it('should register all built-in problems on construction', () => {
|
||||
const api = createCardAPI();
|
||||
const manager = new ProblemManager(api);
|
||||
const presence = manager.getProblemPresence();
|
||||
|
||||
expect('config_upgrade' in presence).toBe(true);
|
||||
expect('legacy_resource' in presence).toBe(true);
|
||||
expect('stream_not_loading' in presence).toBe(true);
|
||||
});
|
||||
|
||||
describe('detectStatic', () => {
|
||||
it('should call detectStatic on all problems', async () => {
|
||||
const api = createCardAPI();
|
||||
const manager = new ProblemManager(api);
|
||||
const hass = createHASS();
|
||||
|
||||
await manager.detectStatic(hass);
|
||||
|
||||
expect(mockConfigUpgrade.detectStatic).toBeCalledWith(hass);
|
||||
expect(mockLegacyResource.detectStatic).toBeCalledWith(hass);
|
||||
expect(mockStreamNotLoading.detectStatic).toBeCalledWith(hass);
|
||||
expect(api.getCardElementManager().update).toBeCalled();
|
||||
});
|
||||
});
|
||||
|
||||
describe('trigger', () => {
|
||||
it('should trigger a problem and update when state changes', () => {
|
||||
const api = createCardAPI();
|
||||
vi.mocked(api.getConditionStateManager().getState).mockReturnValue({});
|
||||
const manager = new ProblemManager(api);
|
||||
vi.mocked(mockStreamNotLoading.hasResult)
|
||||
.mockReturnValueOnce(false)
|
||||
.mockReturnValue(true);
|
||||
|
||||
manager.trigger('stream_not_loading');
|
||||
|
||||
expect(mockStreamNotLoading.trigger).toBeCalled();
|
||||
expect(api.getCardElementManager().update).toBeCalled();
|
||||
});
|
||||
|
||||
it('should do nothing for unknown key', () => {
|
||||
const api = createCardAPI();
|
||||
const manager = new ProblemManager(api);
|
||||
|
||||
manager.trigger(('stream_not_loading' + '_unknown') as never);
|
||||
|
||||
expect(mockStreamNotLoading.trigger).not.toBeCalled();
|
||||
});
|
||||
|
||||
it('should not update when trigger does not change state', () => {
|
||||
const api = createCardAPI();
|
||||
vi.mocked(api.getConditionStateManager().getState).mockReturnValue({});
|
||||
const manager = new ProblemManager(api);
|
||||
vi.mocked(mockStreamNotLoading.hasResult).mockReturnValue(false);
|
||||
|
||||
manager.trigger('stream_not_loading');
|
||||
|
||||
expect(mockStreamNotLoading.trigger).toBeCalled();
|
||||
expect(api.getCardElementManager().update).not.toBeCalled();
|
||||
});
|
||||
});
|
||||
|
||||
describe('forceNotify', () => {
|
||||
it('should show notification from getNotification', () => {
|
||||
const api = createCardAPI();
|
||||
const manager = new ProblemManager(api);
|
||||
const notification = { text: 'from getNotification' };
|
||||
mockStreamNotLoading.getNotification = vi.fn().mockReturnValue(notification);
|
||||
|
||||
manager.forceNotify('stream_not_loading');
|
||||
|
||||
expect(api.getNotificationManager().setNotification).toBeCalledWith(notification);
|
||||
});
|
||||
|
||||
it('should not show notification when getNotification returns null', () => {
|
||||
const api = createCardAPI();
|
||||
const manager = new ProblemManager(api);
|
||||
|
||||
manager.forceNotify('config_upgrade');
|
||||
|
||||
expect(api.getNotificationManager().setNotification).not.toBeCalled();
|
||||
});
|
||||
});
|
||||
|
||||
describe('getProblemResults', () => {
|
||||
it('should return results for active problems', () => {
|
||||
const api = createCardAPI();
|
||||
const result = createProblemResult();
|
||||
vi.mocked(mockConfigUpgrade.getResult).mockReturnValue(result);
|
||||
|
||||
const manager = new ProblemManager(api);
|
||||
|
||||
expect(manager.getProblemResults()).toEqual([
|
||||
{ key: 'config_upgrade', problem: result },
|
||||
]);
|
||||
});
|
||||
|
||||
it('should return empty array when no problems active', () => {
|
||||
const api = createCardAPI();
|
||||
const manager = new ProblemManager(api);
|
||||
|
||||
expect(manager.getProblemResults()).toEqual([]);
|
||||
});
|
||||
});
|
||||
|
||||
describe('getProblemPresence', () => {
|
||||
it('should return presence map', () => {
|
||||
const api = createCardAPI();
|
||||
vi.mocked(mockConfigUpgrade.hasResult).mockReturnValue(true);
|
||||
vi.mocked(mockLegacyResource.hasResult).mockReturnValue(false);
|
||||
|
||||
const manager = new ProblemManager(api);
|
||||
|
||||
expect(manager.getProblemPresence()).toMatchObject({
|
||||
['config_upgrade']: true,
|
||||
['legacy_resource']: false,
|
||||
});
|
||||
});
|
||||
});
|
||||
|
||||
describe('state change handling', () => {
|
||||
it('should detect dynamic problems on view change', () => {
|
||||
const api = createCardAPI();
|
||||
const stateManager = new ConditionStateManager();
|
||||
vi.mocked(api.getConditionStateManager).mockReturnValue(stateManager);
|
||||
|
||||
const manager = new ProblemManager(api);
|
||||
vi.mocked(mockStreamNotLoading.hasResult)
|
||||
.mockReturnValueOnce(false)
|
||||
.mockReturnValue(true);
|
||||
|
||||
manager.initialize();
|
||||
|
||||
stateManager.setState({ view: 'live' });
|
||||
|
||||
expect(mockStreamNotLoading.detectDynamic).toBeCalledWith({
|
||||
view: 'live',
|
||||
mediaLoaded: false,
|
||||
});
|
||||
expect(api.getCardElementManager().update).toBeCalled();
|
||||
});
|
||||
|
||||
it('should detect dynamic problems on mediaLoadedInfo change', () => {
|
||||
const api = createCardAPI();
|
||||
const stateManager = new ConditionStateManager();
|
||||
vi.mocked(api.getConditionStateManager).mockReturnValue(stateManager);
|
||||
|
||||
const manager = new ProblemManager(api);
|
||||
|
||||
manager.initialize();
|
||||
|
||||
stateManager.setState({
|
||||
mediaLoadedInfo: { width: 1920, height: 1080 },
|
||||
});
|
||||
|
||||
expect(mockStreamNotLoading.detectDynamic).toBeCalledWith(
|
||||
expect.objectContaining({ mediaLoaded: true }),
|
||||
);
|
||||
});
|
||||
|
||||
it('should not update when dynamic detection does not change state', () => {
|
||||
const api = createCardAPI();
|
||||
const stateManager = new ConditionStateManager();
|
||||
vi.mocked(api.getConditionStateManager).mockReturnValue(stateManager);
|
||||
|
||||
const manager = new ProblemManager(api);
|
||||
vi.mocked(mockStreamNotLoading.hasResult).mockReturnValue(false);
|
||||
|
||||
manager.initialize();
|
||||
|
||||
stateManager.setState({ view: 'live' });
|
||||
|
||||
expect(mockStreamNotLoading.detectDynamic).toBeCalled();
|
||||
expect(api.getCardElementManager().update).not.toBeCalled();
|
||||
});
|
||||
});
|
||||
|
||||
describe('uninitialize', () => {
|
||||
it('should remove state listener', () => {
|
||||
const api = createCardAPI();
|
||||
const stateManager = new ConditionStateManager();
|
||||
vi.mocked(api.getConditionStateManager).mockReturnValue(stateManager);
|
||||
|
||||
const manager = new ProblemManager(api);
|
||||
|
||||
manager.initialize();
|
||||
manager.uninitialize();
|
||||
|
||||
stateManager.setState({ view: 'live' });
|
||||
|
||||
expect(mockStreamNotLoading.detectDynamic).not.toBeCalled();
|
||||
});
|
||||
});
|
||||
|
||||
describe('logging', () => {
|
||||
it('should log on static detection when problem is active', async () => {
|
||||
const spy = vi.spyOn(console, 'warn').mockReturnValue();
|
||||
const api = createCardAPI();
|
||||
const result = createProblemResult({ notification: { text: 'Legacy problem' } });
|
||||
vi.mocked(mockLegacyResource.hasResult).mockReturnValue(true);
|
||||
vi.mocked(mockLegacyResource.getResult).mockReturnValue(result);
|
||||
|
||||
const manager = new ProblemManager(api);
|
||||
await manager.detectStatic(createHASS());
|
||||
|
||||
expect(spy).toBeCalledWith('Advanced Camera Card: Legacy problem');
|
||||
spy.mockRestore();
|
||||
});
|
||||
|
||||
it('should log on dynamic detection when problem becomes active', () => {
|
||||
const spy = vi.spyOn(console, 'warn').mockReturnValue();
|
||||
const api = createCardAPI();
|
||||
const stateManager = new ConditionStateManager();
|
||||
vi.mocked(api.getConditionStateManager).mockReturnValue(stateManager);
|
||||
|
||||
const result = createProblemResult({
|
||||
notification: { text: 'Stream problem' },
|
||||
});
|
||||
vi.mocked(mockStreamNotLoading.hasResult)
|
||||
.mockReturnValueOnce(false)
|
||||
.mockReturnValue(true);
|
||||
vi.mocked(mockStreamNotLoading.getResult).mockReturnValue(result);
|
||||
|
||||
const manager = new ProblemManager(api);
|
||||
manager.initialize();
|
||||
|
||||
stateManager.setState({ view: 'live' });
|
||||
|
||||
expect(spy).toBeCalledWith('Advanced Camera Card: Stream problem');
|
||||
spy.mockRestore();
|
||||
});
|
||||
|
||||
it('should only log once per problem key', async () => {
|
||||
const spy = vi.spyOn(console, 'warn').mockReturnValue();
|
||||
const api = createCardAPI();
|
||||
const result = createProblemResult({ notification: { text: 'Repeated' } });
|
||||
vi.mocked(mockLegacyResource.hasResult).mockReturnValue(true);
|
||||
vi.mocked(mockLegacyResource.getResult).mockReturnValue(result);
|
||||
|
||||
const manager = new ProblemManager(api);
|
||||
await manager.detectStatic(createHASS());
|
||||
await manager.detectStatic(createHASS());
|
||||
|
||||
expect(spy).toBeCalledTimes(1);
|
||||
spy.mockRestore();
|
||||
});
|
||||
|
||||
it('should not log when problem has no result', async () => {
|
||||
const spy = vi.spyOn(console, 'warn').mockReturnValue();
|
||||
const api = createCardAPI();
|
||||
vi.mocked(mockLegacyResource.hasResult).mockReturnValue(false);
|
||||
|
||||
const manager = new ProblemManager(api);
|
||||
await manager.detectStatic(createHASS());
|
||||
|
||||
expect(spy).not.toBeCalled();
|
||||
spy.mockRestore();
|
||||
});
|
||||
});
|
||||
|
||||
describe('destroy', () => {
|
||||
it('should destroy all problems and clear', () => {
|
||||
const api = createCardAPI();
|
||||
const stateManager = new ConditionStateManager();
|
||||
vi.mocked(api.getConditionStateManager).mockReturnValue(stateManager);
|
||||
|
||||
const manager = new ProblemManager(api);
|
||||
|
||||
manager.initialize();
|
||||
manager.destroy();
|
||||
|
||||
expect(mockConfigUpgrade.destroy).toBeCalled();
|
||||
expect(mockLegacyResource.destroy).toBeCalled();
|
||||
expect(mockStreamNotLoading.destroy).toBeCalled();
|
||||
expect(manager.getProblemPresence()).toEqual({});
|
||||
|
||||
// State changes after destroy should not trigger detection.
|
||||
stateManager.setState({ view: 'live' });
|
||||
|
||||
expect(mockStreamNotLoading.detectDynamic).not.toBeCalled();
|
||||
});
|
||||
});
|
||||
});
|
||||
@@ -1,63 +0,0 @@
|
||||
import { describe, expect, it, vi } from 'vitest';
|
||||
import { ConfigUpgradeProblem } from '../../../../src/card-controller/problems/problems/config-upgrade';
|
||||
import { isConfigUpgradeable } from '../../../../src/config/management';
|
||||
|
||||
vi.mock('../../../../src/config/management.js');
|
||||
|
||||
describe('ConfigUpgradeProblem', () => {
|
||||
it('should have correct key', () => {
|
||||
const problem = new ConfigUpgradeProblem(() => null);
|
||||
expect(problem.key).toBe('config_upgrade');
|
||||
});
|
||||
|
||||
it('should detect upgradeable config', async () => {
|
||||
vi.mocked(isConfigUpgradeable).mockReturnValue(true);
|
||||
const rawConfig = { type: 'custom:frigate-card' };
|
||||
const problem = new ConfigUpgradeProblem(() => rawConfig);
|
||||
|
||||
await problem.detectStatic();
|
||||
|
||||
expect(problem.hasResult()).toBe(true);
|
||||
expect(isConfigUpgradeable).toBeCalledWith(rawConfig);
|
||||
});
|
||||
|
||||
it('should detect non-upgradeable config', async () => {
|
||||
vi.mocked(isConfigUpgradeable).mockReturnValue(false);
|
||||
const rawConfig = { type: 'custom:advanced-camera-card' };
|
||||
const problem = new ConfigUpgradeProblem(() => rawConfig);
|
||||
|
||||
await problem.detectStatic();
|
||||
|
||||
expect(problem.hasResult()).toBe(false);
|
||||
});
|
||||
|
||||
it('should handle null raw config', async () => {
|
||||
const problem = new ConfigUpgradeProblem(() => null);
|
||||
|
||||
await problem.detectStatic();
|
||||
|
||||
expect(problem.hasResult()).toBe(false);
|
||||
expect(problem.getResult()).toBeNull();
|
||||
});
|
||||
|
||||
it('should return result when upgradeable', async () => {
|
||||
vi.mocked(isConfigUpgradeable).mockReturnValue(true);
|
||||
const problem = new ConfigUpgradeProblem(() => ({ type: 'custom:frigate-card' }));
|
||||
|
||||
await problem.detectStatic();
|
||||
|
||||
const result = problem.getResult();
|
||||
expect(result).toEqual(
|
||||
expect.objectContaining({
|
||||
icon: 'mdi:update',
|
||||
severity: 'medium',
|
||||
notification: expect.objectContaining({
|
||||
heading: expect.objectContaining({
|
||||
icon: 'mdi:update',
|
||||
severity: 'medium',
|
||||
}),
|
||||
}),
|
||||
}),
|
||||
);
|
||||
});
|
||||
});
|
||||
@@ -1,311 +0,0 @@
|
||||
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
|
||||
import { StreamNotLoadingProblem } from '../../../../src/card-controller/problems/problems/stream-not-loading';
|
||||
|
||||
// @vitest-environment jsdom
|
||||
describe('StreamNotLoadingProblem', () => {
|
||||
beforeEach(() => {
|
||||
vi.useFakeTimers();
|
||||
});
|
||||
|
||||
afterEach(() => {
|
||||
vi.useRealTimers();
|
||||
});
|
||||
|
||||
it('should have correct key', () => {
|
||||
const problem = new StreamNotLoadingProblem(vi.fn());
|
||||
expect(problem.key).toBe('stream_not_loading');
|
||||
});
|
||||
|
||||
describe('detectDynamic', () => {
|
||||
it('should start timer when live and not loaded', () => {
|
||||
const triggerUpdate = vi.fn();
|
||||
const problem = new StreamNotLoadingProblem(triggerUpdate);
|
||||
|
||||
problem.detectDynamic({ view: 'live', mediaLoaded: false });
|
||||
|
||||
expect(problem.hasResult()).toBe(false);
|
||||
|
||||
vi.advanceTimersByTime(10000);
|
||||
|
||||
expect(problem.hasResult()).toBe(true);
|
||||
expect(triggerUpdate).toBeCalled();
|
||||
});
|
||||
|
||||
it('should not start timer when not live', () => {
|
||||
const problem = new StreamNotLoadingProblem(vi.fn());
|
||||
|
||||
problem.detectDynamic({ view: 'media', mediaLoaded: false });
|
||||
|
||||
vi.advanceTimersByTime(10000);
|
||||
|
||||
expect(problem.hasResult()).toBe(false);
|
||||
});
|
||||
|
||||
it('should not start timer when media is loaded', () => {
|
||||
const problem = new StreamNotLoadingProblem(vi.fn());
|
||||
|
||||
problem.detectDynamic({ view: 'live', mediaLoaded: true });
|
||||
|
||||
vi.advanceTimersByTime(10000);
|
||||
|
||||
expect(problem.hasResult()).toBe(false);
|
||||
});
|
||||
|
||||
it('should clear timeout when media loads', () => {
|
||||
const problem = new StreamNotLoadingProblem(vi.fn());
|
||||
|
||||
problem.detectDynamic({ view: 'live', mediaLoaded: false });
|
||||
vi.advanceTimersByTime(5000);
|
||||
|
||||
problem.detectDynamic({ view: 'live', mediaLoaded: true });
|
||||
|
||||
vi.advanceTimersByTime(5000);
|
||||
|
||||
expect(problem.hasResult()).toBe(false);
|
||||
});
|
||||
|
||||
it('should clear timeout when view changes away from live', () => {
|
||||
const problem = new StreamNotLoadingProblem(vi.fn());
|
||||
|
||||
problem.detectDynamic({ view: 'live', mediaLoaded: false });
|
||||
vi.advanceTimersByTime(5000);
|
||||
|
||||
problem.detectDynamic({ view: 'media', mediaLoaded: false });
|
||||
|
||||
vi.advanceTimersByTime(5000);
|
||||
|
||||
expect(problem.hasResult()).toBe(false);
|
||||
});
|
||||
|
||||
it('should clear timed-out state when media loads', () => {
|
||||
const problem = new StreamNotLoadingProblem(vi.fn());
|
||||
|
||||
problem.detectDynamic({ view: 'live', mediaLoaded: false });
|
||||
vi.advanceTimersByTime(10000);
|
||||
expect(problem.hasResult()).toBe(true);
|
||||
|
||||
problem.detectDynamic({ view: 'live', mediaLoaded: true });
|
||||
expect(problem.hasResult()).toBe(false);
|
||||
});
|
||||
|
||||
it('should restart timer when camera changes', () => {
|
||||
const triggerUpdate = vi.fn();
|
||||
const problem = new StreamNotLoadingProblem(triggerUpdate);
|
||||
|
||||
problem.detectDynamic({
|
||||
cameraID: 'camera-1',
|
||||
view: 'live',
|
||||
mediaLoaded: false,
|
||||
});
|
||||
vi.advanceTimersByTime(5000);
|
||||
|
||||
// Switch to camera-2: timer restarts from 0 for the new camera.
|
||||
problem.detectDynamic({
|
||||
cameraID: 'camera-2',
|
||||
view: 'live',
|
||||
mediaLoaded: false,
|
||||
});
|
||||
|
||||
// 5 more seconds is not enough for the new 10s timer.
|
||||
vi.advanceTimersByTime(5000);
|
||||
expect(problem.hasResult()).toBe(false);
|
||||
|
||||
// Full 10s from camera-2's timer start.
|
||||
vi.advanceTimersByTime(5000);
|
||||
expect(problem.hasResult()).toBe(true);
|
||||
expect(triggerUpdate).toBeCalledTimes(1);
|
||||
});
|
||||
|
||||
it('should not restart timer for same camera while running', () => {
|
||||
const triggerUpdate = vi.fn();
|
||||
const problem = new StreamNotLoadingProblem(triggerUpdate);
|
||||
|
||||
problem.detectDynamic({
|
||||
cameraID: 'camera-1',
|
||||
view: 'live',
|
||||
mediaLoaded: false,
|
||||
});
|
||||
vi.advanceTimersByTime(5000);
|
||||
|
||||
// Same camera again: timer should continue, not restart.
|
||||
problem.detectDynamic({
|
||||
cameraID: 'camera-1',
|
||||
view: 'live',
|
||||
mediaLoaded: false,
|
||||
});
|
||||
|
||||
// 5 more seconds completes the original 10s timer.
|
||||
vi.advanceTimersByTime(5000);
|
||||
expect(problem.hasResult()).toBe(true);
|
||||
expect(triggerUpdate).toBeCalledTimes(1);
|
||||
});
|
||||
|
||||
it('should not restart timer when cameraID is undefined and matches', () => {
|
||||
const triggerUpdate = vi.fn();
|
||||
const problem = new StreamNotLoadingProblem(triggerUpdate);
|
||||
|
||||
problem.detectDynamic({ view: 'live', mediaLoaded: false });
|
||||
vi.advanceTimersByTime(5000);
|
||||
|
||||
// Same undefined cameraID: timer should continue.
|
||||
problem.detectDynamic({ view: 'live', mediaLoaded: false });
|
||||
|
||||
vi.advanceTimersByTime(5000);
|
||||
expect(problem.hasResult()).toBe(true);
|
||||
expect(triggerUpdate).toBeCalledTimes(1);
|
||||
});
|
||||
|
||||
it('should not restart timer if already timed out', () => {
|
||||
const triggerUpdate = vi.fn();
|
||||
const problem = new StreamNotLoadingProblem(triggerUpdate);
|
||||
|
||||
problem.detectDynamic({ view: 'live', mediaLoaded: false });
|
||||
vi.advanceTimersByTime(10000);
|
||||
expect(triggerUpdate).toBeCalledTimes(1);
|
||||
|
||||
// Calling detectDynamic again should not restart timer.
|
||||
problem.detectDynamic({ view: 'live', mediaLoaded: false });
|
||||
vi.advanceTimersByTime(10000);
|
||||
expect(triggerUpdate).toBeCalledTimes(1);
|
||||
});
|
||||
});
|
||||
|
||||
describe('trigger', () => {
|
||||
it('should activate immediately when camera has error and view is live', () => {
|
||||
const problem = new StreamNotLoadingProblem(vi.fn());
|
||||
|
||||
problem.trigger({ cameraID: 'camera-1' });
|
||||
problem.detectDynamic({
|
||||
cameraID: 'camera-1',
|
||||
view: 'live',
|
||||
mediaLoaded: false,
|
||||
});
|
||||
|
||||
expect(problem.hasResult()).toBe(true);
|
||||
});
|
||||
|
||||
it('should not activate with only a trigger', () => {
|
||||
const problem = new StreamNotLoadingProblem(vi.fn());
|
||||
|
||||
problem.trigger({ cameraID: 'camera-1' });
|
||||
|
||||
expect(problem.hasResult()).toBe(false);
|
||||
});
|
||||
|
||||
it('should ignore trigger without cameraID', () => {
|
||||
const problem = new StreamNotLoadingProblem(vi.fn());
|
||||
|
||||
problem.trigger();
|
||||
problem.detectDynamic({ view: 'live', mediaLoaded: false });
|
||||
|
||||
// No camera error recorded, so falls back to timeout behavior.
|
||||
expect(problem.hasResult()).toBe(false);
|
||||
});
|
||||
|
||||
it('should clear camera error when stream loads', () => {
|
||||
const problem = new StreamNotLoadingProblem(vi.fn());
|
||||
|
||||
problem.trigger({ cameraID: 'camera-1' });
|
||||
problem.detectDynamic({
|
||||
cameraID: 'camera-1',
|
||||
view: 'live',
|
||||
mediaLoaded: false,
|
||||
});
|
||||
|
||||
expect(problem.hasResult()).toBe(true);
|
||||
|
||||
// Stream loaded clears the error for this camera.
|
||||
problem.detectDynamic({
|
||||
cameraID: 'camera-1',
|
||||
view: 'live',
|
||||
mediaLoaded: true,
|
||||
});
|
||||
|
||||
// Camera error was cleared by the successful load, so this unloaded state
|
||||
// falls back to the timer (problem would not activate until after the
|
||||
// timer is reached).
|
||||
problem.detectDynamic({
|
||||
cameraID: 'camera-1',
|
||||
view: 'live',
|
||||
mediaLoaded: false,
|
||||
});
|
||||
|
||||
expect(problem.hasResult()).toBe(false);
|
||||
});
|
||||
|
||||
it('should not activate for a different camera', () => {
|
||||
const problem = new StreamNotLoadingProblem(vi.fn());
|
||||
|
||||
problem.trigger({ cameraID: 'camera-1' });
|
||||
problem.detectDynamic({
|
||||
cameraID: 'camera-2',
|
||||
view: 'live',
|
||||
mediaLoaded: false,
|
||||
});
|
||||
|
||||
// camera-2 has no error, so it falls back to timeout behavior.
|
||||
expect(problem.hasResult()).toBe(false);
|
||||
});
|
||||
});
|
||||
|
||||
describe('getNotification', () => {
|
||||
it('should return notification regardless of active state', () => {
|
||||
const problem = new StreamNotLoadingProblem(vi.fn());
|
||||
|
||||
const notification = problem.getNotification();
|
||||
expect(notification).toEqual(
|
||||
expect.objectContaining({
|
||||
heading: expect.objectContaining({
|
||||
text: expect.any(String),
|
||||
}),
|
||||
link: expect.objectContaining({
|
||||
url: expect.any(String),
|
||||
}),
|
||||
}),
|
||||
);
|
||||
});
|
||||
});
|
||||
|
||||
describe('getResult', () => {
|
||||
it('should return result when timed out', () => {
|
||||
const problem = new StreamNotLoadingProblem(vi.fn());
|
||||
|
||||
problem.detectDynamic({ view: 'live', mediaLoaded: false });
|
||||
vi.advanceTimersByTime(10000);
|
||||
|
||||
const result = problem.getResult();
|
||||
expect(result).toEqual(
|
||||
expect.objectContaining({
|
||||
icon: 'mdi:cctv-off',
|
||||
severity: 'high',
|
||||
notification: expect.objectContaining({
|
||||
link: expect.objectContaining({
|
||||
url: expect.any(String),
|
||||
}),
|
||||
}),
|
||||
}),
|
||||
);
|
||||
});
|
||||
|
||||
it('should return null when not timed out', () => {
|
||||
const problem = new StreamNotLoadingProblem(vi.fn());
|
||||
|
||||
expect(problem.getResult()).toBeNull();
|
||||
});
|
||||
});
|
||||
|
||||
describe('destroy', () => {
|
||||
it('should stop timer', () => {
|
||||
const triggerUpdate = vi.fn();
|
||||
const problem = new StreamNotLoadingProblem(triggerUpdate);
|
||||
|
||||
problem.detectDynamic({ view: 'live', mediaLoaded: false });
|
||||
problem.destroy();
|
||||
|
||||
vi.advanceTimersByTime(10000);
|
||||
|
||||
expect(problem.hasResult()).toBe(false);
|
||||
expect(triggerUpdate).not.toBeCalled();
|
||||
});
|
||||
});
|
||||
});
|
||||
@@ -29,7 +29,9 @@ describe('QueryStringManager', () => {
|
||||
it('should reject malformed query string', async () => {
|
||||
setQueryString('BOGUS_KEY=BOGUS_VALUE');
|
||||
const api = createCardAPI();
|
||||
vi.mocked(api.getMessageManager().hasMessage).mockReturnValue(true);
|
||||
vi.mocked(api.getIssueManager().getStateManager().hasFullCardIssue).mockReturnValue(
|
||||
true,
|
||||
);
|
||||
const manager = new QueryStringManager(api);
|
||||
|
||||
expect(manager.hasViewRelatedActionsToRun()).toBeFalsy();
|
||||
@@ -230,7 +232,7 @@ describe('QueryStringManager', () => {
|
||||
});
|
||||
|
||||
describe('should handle conflicting but valid actions', () => {
|
||||
it('view and default with camera and substream specified', async () => {
|
||||
it('should handle view and default with camera and substream specified', async () => {
|
||||
setQueryString(
|
||||
'?advanced-camera-card-action.id.clips=' +
|
||||
'&advanced-camera-card-action.id.live_substream_select=camera.kitchen_hd' +
|
||||
@@ -253,7 +255,7 @@ describe('QueryStringManager', () => {
|
||||
expect(api.getViewManager().setViewByParametersWithNewQuery).not.toBeCalled();
|
||||
});
|
||||
|
||||
it('multiple cameras specified', async () => {
|
||||
it('should handle multiple cameras specified', async () => {
|
||||
setQueryString(
|
||||
'?advanced-camera-card-action.id.camera_select=camera.kitchen' +
|
||||
'&advanced-camera-card-action.id.camera_select=camera.office',
|
||||
|
||||
@@ -48,7 +48,7 @@ describe('StatusBarItemManager', () => {
|
||||
describe('should have standard status bar items', () => {
|
||||
describe('should have title', () => {
|
||||
describe('live', () => {
|
||||
it('with metadata', () => {
|
||||
it('should show with metadata', () => {
|
||||
const manager = new StatusBarItemManager(createCardAPI());
|
||||
const store = createStore([
|
||||
{
|
||||
@@ -74,7 +74,7 @@ describe('StatusBarItemManager', () => {
|
||||
});
|
||||
});
|
||||
|
||||
it('without metadata', () => {
|
||||
it('should handle without metadata', () => {
|
||||
const manager = new StatusBarItemManager(createCardAPI());
|
||||
const cameraManager = createCameraManager();
|
||||
expect(
|
||||
@@ -87,7 +87,7 @@ describe('StatusBarItemManager', () => {
|
||||
});
|
||||
|
||||
describe('media', () => {
|
||||
it('with a title', () => {
|
||||
it('should show with a title', () => {
|
||||
const manager = new StatusBarItemManager(createCardAPI());
|
||||
const cameraManager = createCameraManager();
|
||||
|
||||
@@ -114,7 +114,7 @@ describe('StatusBarItemManager', () => {
|
||||
});
|
||||
});
|
||||
|
||||
it('without a title', () => {
|
||||
it('should handle without a title', () => {
|
||||
const manager = new StatusBarItemManager(createCardAPI());
|
||||
const cameraManager = createCameraManager();
|
||||
|
||||
@@ -187,7 +187,7 @@ describe('StatusBarItemManager', () => {
|
||||
});
|
||||
|
||||
describe('should have technology', () => {
|
||||
it('webrtc', () => {
|
||||
it('should show webrtc icon', () => {
|
||||
const manager = new StatusBarItemManager(createCardAPI());
|
||||
|
||||
expect(
|
||||
@@ -200,7 +200,7 @@ describe('StatusBarItemManager', () => {
|
||||
});
|
||||
});
|
||||
|
||||
it('non-webrtc', () => {
|
||||
it('should show non-webrtc string', () => {
|
||||
const manager = new StatusBarItemManager(createCardAPI());
|
||||
|
||||
expect(
|
||||
@@ -241,15 +241,15 @@ describe('StatusBarItemManager', () => {
|
||||
});
|
||||
});
|
||||
|
||||
describe('problems', () => {
|
||||
it('should show problem items', () => {
|
||||
describe('issues', () => {
|
||||
it('should show issue items', () => {
|
||||
const manager = new StatusBarItemManager(createCardAPI());
|
||||
|
||||
const items = manager.calculateItems({
|
||||
problems: [
|
||||
issues: [
|
||||
{
|
||||
key: 'config_upgrade',
|
||||
problem: {
|
||||
issue: {
|
||||
icon: 'mdi:update',
|
||||
severity: 'medium',
|
||||
notification: {
|
||||
@@ -258,7 +258,7 @@ describe('StatusBarItemManager', () => {
|
||||
icon: 'mdi:update',
|
||||
severity: 'medium',
|
||||
},
|
||||
text: 'Upgrade text',
|
||||
body: { text: 'Upgrade text' },
|
||||
},
|
||||
},
|
||||
},
|
||||
@@ -281,11 +281,11 @@ describe('StatusBarItemManager', () => {
|
||||
);
|
||||
});
|
||||
|
||||
it('should not show problem items when empty', () => {
|
||||
it('should not show issue items when empty', () => {
|
||||
const manager = new StatusBarItemManager(createCardAPI());
|
||||
|
||||
const items = manager.calculateItems({
|
||||
problems: [],
|
||||
issues: [],
|
||||
});
|
||||
|
||||
expect(items).not.toContainEqual(
|
||||
@@ -295,7 +295,7 @@ describe('StatusBarItemManager', () => {
|
||||
);
|
||||
});
|
||||
|
||||
it('should not show problem items by default', () => {
|
||||
it('should not show issue items by default', () => {
|
||||
const manager = new StatusBarItemManager(createCardAPI());
|
||||
|
||||
const items = manager.calculateItems();
|
||||
@@ -307,7 +307,7 @@ describe('StatusBarItemManager', () => {
|
||||
);
|
||||
});
|
||||
|
||||
it('should filter out disabled problems', () => {
|
||||
it('should filter out all issues when disabled', () => {
|
||||
const manager = new StatusBarItemManager(createCardAPI());
|
||||
|
||||
const items = manager.calculateItems({
|
||||
@@ -318,19 +318,17 @@ describe('StatusBarItemManager', () => {
|
||||
height: 40,
|
||||
items: {
|
||||
engine: { enabled: true, priority: 50 },
|
||||
issues: { enabled: false, priority: 50 },
|
||||
resolution: { enabled: true, priority: 50 },
|
||||
severity: { enabled: true, priority: 50 },
|
||||
technology: { enabled: true, priority: 50 },
|
||||
title: { enabled: true, priority: 50 },
|
||||
problem_config_upgrade: { enabled: false, priority: 50 },
|
||||
problem_legacy_resource: { enabled: true, priority: 50 },
|
||||
problem_stream_not_loading: { enabled: true, priority: 50 },
|
||||
},
|
||||
},
|
||||
problems: [
|
||||
issues: [
|
||||
{
|
||||
key: 'config_upgrade',
|
||||
problem: {
|
||||
issue: {
|
||||
icon: 'mdi:update',
|
||||
severity: 'medium',
|
||||
notification: {
|
||||
@@ -339,7 +337,7 @@ describe('StatusBarItemManager', () => {
|
||||
icon: 'mdi:update',
|
||||
severity: 'medium',
|
||||
},
|
||||
text: 'Upgrade text',
|
||||
body: { text: 'Upgrade text' },
|
||||
},
|
||||
},
|
||||
},
|
||||
@@ -353,7 +351,7 @@ describe('StatusBarItemManager', () => {
|
||||
);
|
||||
});
|
||||
|
||||
it('should apply config overrides to problem items', () => {
|
||||
it('should apply config overrides to issue items', () => {
|
||||
const manager = new StatusBarItemManager(createCardAPI());
|
||||
|
||||
const items = manager.calculateItems({
|
||||
@@ -364,19 +362,17 @@ describe('StatusBarItemManager', () => {
|
||||
height: 40,
|
||||
items: {
|
||||
engine: { enabled: true, priority: 50 },
|
||||
issues: { enabled: true, priority: 90 },
|
||||
resolution: { enabled: true, priority: 50 },
|
||||
severity: { enabled: true, priority: 50 },
|
||||
technology: { enabled: true, priority: 50 },
|
||||
title: { enabled: true, priority: 50 },
|
||||
problem_config_upgrade: { enabled: true, priority: 90 },
|
||||
problem_legacy_resource: { enabled: true, priority: 50 },
|
||||
problem_stream_not_loading: { enabled: true, priority: 50 },
|
||||
},
|
||||
},
|
||||
problems: [
|
||||
issues: [
|
||||
{
|
||||
key: 'config_upgrade',
|
||||
problem: {
|
||||
issue: {
|
||||
icon: 'mdi:update',
|
||||
severity: 'medium',
|
||||
notification: {
|
||||
@@ -385,7 +381,7 @@ describe('StatusBarItemManager', () => {
|
||||
icon: 'mdi:update',
|
||||
severity: 'medium',
|
||||
},
|
||||
text: 'Upgrade text',
|
||||
body: { text: 'Upgrade text' },
|
||||
},
|
||||
},
|
||||
},
|
||||
|
||||
@@ -19,7 +19,7 @@ import {
|
||||
|
||||
vi.mock('lodash-es', async () => ({
|
||||
...(await vi.importActual('lodash-es')),
|
||||
throttle: vi.fn((fn) => fn),
|
||||
throttle: vi.fn((fn) => Object.assign(fn, { cancel: vi.fn() })),
|
||||
}));
|
||||
|
||||
const baseTriggersConfig: TriggersOptions = {
|
||||
@@ -542,6 +542,56 @@ describe('TriggersManager', () => {
|
||||
expect(manager.isTriggered()).toBe(false);
|
||||
});
|
||||
|
||||
it('should stop timers on reset while untrigger delay is pending', async () => {
|
||||
const api = createTriggerAPI({
|
||||
config: {
|
||||
untrigger_delay_seconds: 10,
|
||||
},
|
||||
});
|
||||
const manager = new TriggersManager(api);
|
||||
|
||||
// Trigger then end to start the untrigger delay timer.
|
||||
await manager.handleCameraEvent({ cameraID: 'camera_1', id: 'e1', type: 'new' });
|
||||
await manager.handleCameraEvent({ cameraID: 'camera_1', id: 'e1', type: 'end' });
|
||||
expect(manager.isTriggered()).toBe(true);
|
||||
|
||||
// Reset clears all states and timers.
|
||||
manager.reset();
|
||||
expect(manager.isTriggered()).toBe(false);
|
||||
|
||||
// Advancing past the delay should not cause errors or state changes.
|
||||
vi.setSystemTime(add(start, { seconds: 15 }));
|
||||
vi.runOnlyPendingTimers();
|
||||
await flushPromises();
|
||||
|
||||
expect(manager.isTriggered()).toBe(false);
|
||||
});
|
||||
|
||||
it('should stop force untrigger timer on reset', async () => {
|
||||
const api = createTriggerAPI({
|
||||
config: {
|
||||
untrigger_delay_seconds: 0,
|
||||
untrigger_force_seconds: 10,
|
||||
},
|
||||
});
|
||||
const manager = new TriggersManager(api);
|
||||
|
||||
// Trigger to start the force untrigger timer.
|
||||
await manager.handleCameraEvent({ cameraID: 'camera_1', id: 'e1', type: 'new' });
|
||||
expect(manager.isTriggered()).toBe(true);
|
||||
|
||||
// Reset clears all states and timers.
|
||||
manager.reset();
|
||||
expect(manager.isTriggered()).toBe(false);
|
||||
|
||||
// Advancing past the force timer should not cause errors.
|
||||
vi.setSystemTime(add(start, { seconds: 15 }));
|
||||
vi.runOnlyPendingTimers();
|
||||
await flushPromises();
|
||||
|
||||
expect(manager.isTriggered()).toBe(false);
|
||||
});
|
||||
|
||||
it('should untrigger immediately when untrigger_delay_seconds is 0', async () => {
|
||||
const api = createTriggerAPI({
|
||||
config: {
|
||||
|
||||
@@ -2,7 +2,7 @@ import { describe, expect, it, vi } from 'vitest';
|
||||
import { mock } from 'vitest-mock-extended';
|
||||
import { FoldersManager } from '../../../src/card-controller/folders/manager';
|
||||
import { ViewFactory } from '../../../src/card-controller/view/factory';
|
||||
import { ViewModifier } from '../../../src/card-controller/view/types';
|
||||
import { ViewIncompatible, ViewModifier } from '../../../src/card-controller/view/types';
|
||||
import { AdvancedCameraCardView } from '../../../src/config/schema/common/const';
|
||||
import { ViewDisplayMode } from '../../../src/config/schema/common/display';
|
||||
import { View } from '../../../src/view/view';
|
||||
@@ -47,7 +47,7 @@ describe('getViewDefault', () => {
|
||||
);
|
||||
|
||||
const factory = new ViewFactory(api);
|
||||
expect(() => factory.getViewDefault()).toThrowError(/No cameras support this view/);
|
||||
expect(() => factory.getViewDefault()).toThrowError(ViewIncompatible);
|
||||
});
|
||||
|
||||
it('should use folders view as default when folders exist without cameras', () => {
|
||||
@@ -241,7 +241,7 @@ describe('getViewByParameters', () => {
|
||||
view: 'snapshots',
|
||||
},
|
||||
}),
|
||||
).toThrowError(/No cameras support this view/);
|
||||
).toThrowError(ViewIncompatible);
|
||||
});
|
||||
|
||||
describe('should handle no camera for view with failsafe', () => {
|
||||
@@ -321,7 +321,7 @@ describe('getViewByParameters', () => {
|
||||
view: 'snapshots',
|
||||
},
|
||||
}),
|
||||
).toThrowError(/The selected camera or media does not support this view/);
|
||||
).toThrowError(ViewIncompatible);
|
||||
});
|
||||
|
||||
it('should choose live view with failsafe', () => {
|
||||
@@ -369,7 +369,7 @@ describe('getViewByParameters', () => {
|
||||
view: 'snapshots',
|
||||
},
|
||||
}),
|
||||
).toThrowError(/The selected camera or media does not support this view/);
|
||||
).toThrowError(ViewIncompatible);
|
||||
});
|
||||
});
|
||||
|
||||
|
||||
@@ -94,9 +94,15 @@ describe('ViewItemManager', () => {
|
||||
vi.mocked(homeAssistantGetSignedURLIfNecessary).mockRejectedValue(signError);
|
||||
|
||||
expect(await manager.download(item)).toBe(false);
|
||||
expect(api.getMessageManager().setErrorIfHigherPriority).toHaveBeenCalledWith(
|
||||
expect(api.getNotificationManager().setNotification).toBeCalledWith(
|
||||
expect.objectContaining({
|
||||
message: 'Could not sign media URL for download',
|
||||
heading: expect.objectContaining({
|
||||
text: 'Download failed',
|
||||
icon: 'mdi:download-off',
|
||||
}),
|
||||
body: expect.objectContaining({
|
||||
text: 'Could not sign media URL for download',
|
||||
}),
|
||||
}),
|
||||
);
|
||||
expect(consoleSpy).toHaveBeenCalledWith('sign-error');
|
||||
@@ -169,9 +175,15 @@ describe('ViewItemManager', () => {
|
||||
const item = new TestViewMedia({ cameraID: null, folder: null });
|
||||
|
||||
expect(await manager.download(item)).toBe(false);
|
||||
expect(api.getMessageManager().setErrorIfHigherPriority).toHaveBeenCalledWith(
|
||||
expect(api.getNotificationManager().setNotification).toBeCalledWith(
|
||||
expect.objectContaining({
|
||||
message: 'No media to download',
|
||||
heading: expect.objectContaining({
|
||||
text: 'Download failed',
|
||||
icon: 'mdi:download-off',
|
||||
}),
|
||||
body: expect.objectContaining({
|
||||
text: 'No media to download',
|
||||
}),
|
||||
}),
|
||||
);
|
||||
});
|
||||
|
||||
@@ -26,7 +26,7 @@ const createInitializedCardAPI = (initialized?: boolean): CardController => {
|
||||
};
|
||||
|
||||
describe('should act correctly when view is set', () => {
|
||||
it('basic view', () => {
|
||||
it('should set basic view', () => {
|
||||
const view = createView({
|
||||
view: 'live',
|
||||
camera: 'camera',
|
||||
@@ -45,17 +45,17 @@ describe('should act correctly when view is set', () => {
|
||||
expect(manager.hasView()).toBeTruthy();
|
||||
expect(api.getMediaLoadedInfoManager().clear).toBeCalled();
|
||||
expect(api.getCardElementManager().scrollReset).toBeCalled();
|
||||
expect(api.getMessageManager().reset).toBeCalled();
|
||||
expect(api.getStyleManager().setExpandedMode).toBeCalled();
|
||||
expect(api.getConditionStateManager()?.setState).toBeCalledWith({
|
||||
view: 'live',
|
||||
camera: 'camera',
|
||||
displayMode: 'grid',
|
||||
targetID: 'camera',
|
||||
});
|
||||
expect(api.getCardElementManager().update).toBeCalled();
|
||||
});
|
||||
|
||||
it('view with minor changes without media clearing or scroll', () => {
|
||||
it('should set view with minor changes without media clearing or scroll', () => {
|
||||
const view_1 = createView({
|
||||
view: 'live',
|
||||
camera: 'camera',
|
||||
@@ -89,7 +89,7 @@ describe('should act correctly when view is set', () => {
|
||||
});
|
||||
});
|
||||
|
||||
it('setViewWithMergedContext', () => {
|
||||
it('should set view with merged context', () => {
|
||||
const api = createInitializedCardAPI();
|
||||
const factory = mock<ViewFactory>();
|
||||
|
||||
@@ -113,14 +113,14 @@ it('setViewWithMergedContext', () => {
|
||||
expect(manager.getView()?.context).toEqual(context);
|
||||
});
|
||||
|
||||
it('getEpoch', () => {
|
||||
it('should return epoch', () => {
|
||||
const factory = mock<ViewFactory>();
|
||||
const manager = new ViewManager(createCardAPI(), { viewFactory: factory });
|
||||
expect(manager.getEpoch()).toBeTruthy();
|
||||
expect(manager.getEpoch().manager).toBe(manager);
|
||||
});
|
||||
|
||||
it('reset', () => {
|
||||
it('should reset view', () => {
|
||||
const factory = mock<ViewFactory>();
|
||||
const manager = new ViewManager(createInitializedCardAPI(), { viewFactory: factory });
|
||||
|
||||
@@ -166,7 +166,7 @@ describe('should not set view without cameras being initialized', () => {
|
||||
});
|
||||
});
|
||||
|
||||
it('setViewDefault', () => {
|
||||
it('should set view default', () => {
|
||||
const factory = mock<ViewFactory>();
|
||||
factory.getViewDefault.mockReturnValue(createView());
|
||||
|
||||
@@ -177,7 +177,7 @@ it('setViewDefault', () => {
|
||||
expect(manager.getView()?.camera).toBe('camera');
|
||||
});
|
||||
|
||||
it('setViewByParameters', () => {
|
||||
it('should set view by parameters', () => {
|
||||
const factory = mock<ViewFactory>();
|
||||
factory.getViewByParameters.mockReturnValue(createView());
|
||||
|
||||
@@ -188,7 +188,7 @@ it('setViewByParameters', () => {
|
||||
expect(manager.getView()?.camera).toBe('camera');
|
||||
});
|
||||
|
||||
it('setViewDefaultWithNewQuery', async () => {
|
||||
it('should set view default with new query', async () => {
|
||||
const viewFactory = mock<ViewFactory>();
|
||||
viewFactory.getViewDefault.mockReturnValue(createView());
|
||||
|
||||
@@ -205,7 +205,7 @@ it('setViewDefaultWithNewQuery', async () => {
|
||||
expect(manager.getView()?.camera).toBe('camera');
|
||||
});
|
||||
|
||||
it('setViewByParametersWithNewQuery', async () => {
|
||||
it('should set view by parameters with new query', async () => {
|
||||
const viewFactory = mock<ViewFactory>();
|
||||
viewFactory.getViewByParameters.mockReturnValue(createView());
|
||||
|
||||
@@ -222,7 +222,7 @@ it('setViewByParametersWithNewQuery', async () => {
|
||||
expect(manager.getView()?.camera).toBe('camera');
|
||||
});
|
||||
|
||||
it('setViewByParametersWithExistingQuery', async () => {
|
||||
it('should set view by parameters with existing query', async () => {
|
||||
const viewFactory = mock<ViewFactory>();
|
||||
viewFactory.getViewByParameters.mockReturnValue(createView());
|
||||
|
||||
@@ -241,34 +241,122 @@ it('setViewByParametersWithExistingQuery', async () => {
|
||||
});
|
||||
|
||||
describe('should handle exceptions', () => {
|
||||
it('should handle exceptions in sync calls', () => {
|
||||
const error = new Error();
|
||||
it('should retry with failSafe when no existing view in sync calls', () => {
|
||||
const viewFactory = mock<ViewFactory>();
|
||||
viewFactory.getViewDefault.mockImplementation(() => {
|
||||
throw error;
|
||||
});
|
||||
const failSafeView = createView();
|
||||
const error = new Error('message');
|
||||
viewFactory.getViewDefault
|
||||
.mockImplementationOnce(() => {
|
||||
throw error;
|
||||
})
|
||||
.mockReturnValueOnce(failSafeView);
|
||||
|
||||
const api = createInitializedCardAPI();
|
||||
const manager = new ViewManager(api, { viewFactory: viewFactory });
|
||||
manager.setViewDefault();
|
||||
|
||||
expect(manager.hasView()).toBeFalsy();
|
||||
expect(api.getMessageManager().setErrorIfHigherPriority).toBeCalledWith(error);
|
||||
expect(manager.hasView()).toBeTruthy();
|
||||
expect(manager.getView()).toBe(failSafeView);
|
||||
expect(viewFactory.getViewDefault).toBeCalledWith(
|
||||
expect.objectContaining({ baseView: null, failSafe: true }),
|
||||
);
|
||||
expect(api.getIssueManager().trigger).toBeCalledWith('view_incompatible', {
|
||||
error,
|
||||
});
|
||||
expect(api.getNotificationManager().setNotification).not.toBeCalled();
|
||||
});
|
||||
|
||||
it('should handle viewFactory exceptions in async calls', async () => {
|
||||
const error = new Error();
|
||||
it('should not retry with failSafe when existing view in sync calls', () => {
|
||||
const viewFactory = mock<ViewFactory>();
|
||||
viewFactory.getViewDefault.mockImplementation(() => {
|
||||
throw error;
|
||||
const existingView = createView();
|
||||
const error = new Error('message');
|
||||
viewFactory.getViewDefault
|
||||
.mockReturnValueOnce(existingView)
|
||||
.mockImplementationOnce(() => {
|
||||
throw error;
|
||||
});
|
||||
|
||||
const api = createInitializedCardAPI();
|
||||
const manager = new ViewManager(api, { viewFactory: viewFactory });
|
||||
manager.setViewDefault();
|
||||
manager.setViewDefault();
|
||||
|
||||
expect(manager.getView()).toBe(existingView);
|
||||
expect(viewFactory.getViewDefault).toBeCalledTimes(2);
|
||||
expect(api.getIssueManager().trigger).toBeCalledWith('view_incompatible', {
|
||||
error,
|
||||
});
|
||||
});
|
||||
|
||||
it('should retry with failSafe when no existing view in async calls', async () => {
|
||||
const viewFactory = mock<ViewFactory>();
|
||||
const failSafeView = createView();
|
||||
const error = new Error('message');
|
||||
viewFactory.getViewDefault
|
||||
.mockImplementationOnce(() => {
|
||||
throw error;
|
||||
})
|
||||
.mockReturnValueOnce(failSafeView);
|
||||
|
||||
const api = createInitializedCardAPI();
|
||||
const manager = new ViewManager(api, { viewFactory: viewFactory });
|
||||
await manager.setViewDefaultWithNewQuery();
|
||||
|
||||
expect(manager.hasView()).toBeTruthy();
|
||||
expect(viewFactory.getViewDefault).toBeCalledWith(
|
||||
expect.objectContaining({ baseView: null, failSafe: true }),
|
||||
);
|
||||
expect(api.getIssueManager().trigger).toBeCalledWith('view_incompatible', {
|
||||
error,
|
||||
});
|
||||
expect(api.getNotificationManager().setNotification).not.toBeCalled();
|
||||
});
|
||||
|
||||
it('should not retry with failSafe when existing view in async calls', async () => {
|
||||
const viewFactory = mock<ViewFactory>();
|
||||
const existingView = createView();
|
||||
const error = new Error('message');
|
||||
viewFactory.getViewDefault
|
||||
.mockReturnValueOnce(existingView)
|
||||
.mockImplementationOnce(() => {
|
||||
throw error;
|
||||
});
|
||||
|
||||
const api = createInitializedCardAPI();
|
||||
const manager = new ViewManager(api, { viewFactory: viewFactory });
|
||||
manager.setViewDefault();
|
||||
await manager.setViewDefaultWithNewQuery();
|
||||
|
||||
expect(manager.getView()).not.toBeNull();
|
||||
expect(viewFactory.getViewDefault).toBeCalledTimes(2);
|
||||
expect(api.getIssueManager().trigger).toBeCalledWith('view_incompatible', {
|
||||
error,
|
||||
});
|
||||
});
|
||||
|
||||
it('should reset view_incompatible on successful view set', () => {
|
||||
const viewFactory = mock<ViewFactory>();
|
||||
viewFactory.getViewDefault.mockReturnValue(createView());
|
||||
|
||||
const api = createInitializedCardAPI();
|
||||
const manager = new ViewManager(api, { viewFactory });
|
||||
manager.setViewDefault();
|
||||
|
||||
expect(api.getIssueManager().reset).toBeCalledWith('view_incompatible');
|
||||
});
|
||||
|
||||
it('should return null when failSafe view factory also throws', () => {
|
||||
const viewFactory = mock<ViewFactory>();
|
||||
viewFactory.getViewDefault.mockImplementation(() => {
|
||||
throw new Error('message');
|
||||
});
|
||||
|
||||
const api = createInitializedCardAPI();
|
||||
const manager = new ViewManager(api, { viewFactory });
|
||||
manager.setViewDefault();
|
||||
|
||||
expect(manager.hasView()).toBeFalsy();
|
||||
expect(api.getMessageManager().setErrorIfHigherPriority).toBeCalledWith(error);
|
||||
expect(viewFactory.getViewDefault).toBeCalledTimes(2);
|
||||
});
|
||||
|
||||
it('should handle viewQueryExecutor exceptions in async calls', async () => {
|
||||
@@ -290,7 +378,79 @@ describe('should handle exceptions', () => {
|
||||
expect(manager.hasView()).toBeTruthy();
|
||||
|
||||
// But an error will also be generated.
|
||||
expect(api.getMessageManager().setErrorIfHigherPriority).toBeCalledWith(error);
|
||||
expect(api.getIssueManager().trigger).toBeCalledWith(
|
||||
'media_query',
|
||||
expect.objectContaining({ error }),
|
||||
);
|
||||
|
||||
// The loading flag must be cleared on error — otherwise gallery/viewer
|
||||
// components render "Awaiting media" indefinitely on top of the error
|
||||
// notification.
|
||||
expect(manager.getView()?.context?.loading?.query).toBeUndefined();
|
||||
});
|
||||
|
||||
it('should reset media_query when navigating via the sync path', () => {
|
||||
const viewFactory = mock<ViewFactory>();
|
||||
viewFactory.getViewByParameters.mockReturnValue(createView({ view: 'live' }));
|
||||
|
||||
const api = createInitializedCardAPI();
|
||||
const manager = new ViewManager(api, { viewFactory });
|
||||
manager.setViewByParameters();
|
||||
|
||||
expect(api.getIssueManager().reset).toBeCalledWith('media_query');
|
||||
});
|
||||
|
||||
it('should tolerate the view being reset during a failing async query', async () => {
|
||||
const error = new Error();
|
||||
const viewFactory = mock<ViewFactory>();
|
||||
viewFactory.getViewDefault.mockReturnValue(createView());
|
||||
const viewQueryExecutor = mock<ViewQueryExecutor>();
|
||||
|
||||
const api = createInitializedCardAPI();
|
||||
const manager = new ViewManager(api, {
|
||||
viewFactory: viewFactory,
|
||||
viewQueryExecutor: viewQueryExecutor,
|
||||
});
|
||||
|
||||
// Concurrent reset during the await — clears `_view` before the
|
||||
// rejection is processed. The error path must not crash on the null
|
||||
// view when attempting to clear the loading flag.
|
||||
viewQueryExecutor.getNewQueryModifiers.mockImplementation(async () => {
|
||||
manager.reset();
|
||||
throw error;
|
||||
});
|
||||
|
||||
await manager.setViewDefaultWithNewQuery();
|
||||
|
||||
expect(manager.getView()).toBeNull();
|
||||
expect(api.getIssueManager().trigger).toBeCalledWith(
|
||||
'media_query',
|
||||
expect.objectContaining({ error }),
|
||||
);
|
||||
});
|
||||
|
||||
it('should reset media_query at the start of a new async query', async () => {
|
||||
const viewFactory = mock<ViewFactory>();
|
||||
viewFactory.getViewDefault.mockReturnValue(createView());
|
||||
const viewQueryExecutor = mock<ViewQueryExecutor>();
|
||||
viewQueryExecutor.getNewQueryModifiers.mockResolvedValue(null);
|
||||
|
||||
const api = createInitializedCardAPI();
|
||||
const manager = new ViewManager(api, {
|
||||
viewFactory: viewFactory,
|
||||
viewQueryExecutor: viewQueryExecutor,
|
||||
});
|
||||
|
||||
await manager.setViewDefaultWithNewQuery();
|
||||
|
||||
// Reset is called twice: once at dispatch (supersedes any prior error)
|
||||
// and once after success (clears on confirmed success).
|
||||
expect(api.getIssueManager().reset).toBeCalledWith('media_query');
|
||||
expect(
|
||||
vi
|
||||
.mocked(api.getIssueManager().reset)
|
||||
.mock.calls.filter(([key]) => key === 'media_query').length,
|
||||
).toBe(2);
|
||||
});
|
||||
});
|
||||
|
||||
@@ -431,7 +591,7 @@ describe('hasMajorMediaChange', () => {
|
||||
});
|
||||
|
||||
describe('should initialize', () => {
|
||||
it('without querystring', async () => {
|
||||
it('should initialize without querystring', async () => {
|
||||
const view = createView({
|
||||
view: 'live',
|
||||
camera: 'camera',
|
||||
@@ -445,12 +605,12 @@ describe('should initialize', () => {
|
||||
viewFactory: viewFactory,
|
||||
});
|
||||
|
||||
expect(await manager.initialize()).toBeTruthy();
|
||||
await manager.initialize();
|
||||
|
||||
expect(manager.getView()).toBe(view);
|
||||
});
|
||||
|
||||
it('with querystring', async () => {
|
||||
it('should initialize with querystring', async () => {
|
||||
const api = createCardAPI();
|
||||
const factory = mock<ViewFactory>();
|
||||
const manager = new ViewManager(api, { viewFactory: factory });
|
||||
@@ -458,7 +618,7 @@ describe('should initialize', () => {
|
||||
true,
|
||||
);
|
||||
|
||||
expect(await manager.initialize()).toBeTruthy();
|
||||
await manager.initialize();
|
||||
|
||||
expect(manager.hasView()).toBeFalsy();
|
||||
});
|
||||
@@ -480,7 +640,8 @@ describe('should apply async view modifications', () => {
|
||||
}),
|
||||
]);
|
||||
|
||||
const manager = new ViewManager(createInitializedCardAPI(), {
|
||||
const api = createInitializedCardAPI();
|
||||
const manager = new ViewManager(api, {
|
||||
viewFactory: viewFactory,
|
||||
viewQueryExecutor: viewQueryExecutor,
|
||||
});
|
||||
@@ -490,6 +651,7 @@ describe('should apply async view modifications', () => {
|
||||
expect(manager.getView()?.query).toBe(query);
|
||||
expect(manager.getView()?.queryResults).toBe(queryResults);
|
||||
expect(manager.getView()?.context?.loading?.query).toBeUndefined();
|
||||
expect(api.getIssueManager().reset).toBeCalledWith('media_query');
|
||||
});
|
||||
|
||||
it('should not apply modifications if there is a major media change', async () => {
|
||||
|
||||
+52
-52
@@ -7,9 +7,9 @@ import { CardController } from '../../../src/card-controller/controller';
|
||||
import { ViewItemManager } from '../../../src/card-controller/view/item-manager';
|
||||
import { ViewManagerEpoch } from '../../../src/card-controller/view/types';
|
||||
import {
|
||||
MediaDetailsController,
|
||||
MediaNotificationController,
|
||||
NotificationControlsContext,
|
||||
} from '../../../src/components-lib/media/details-controller';
|
||||
} from '../../../src/components-lib/media/notification-controller';
|
||||
import { NotificationControl } from '../../../src/config/schema/actions/types';
|
||||
import { formatDateAndTime } from '../../../src/utils/basic';
|
||||
import { downloadMedia, navigateToTimeline } from '../../../src/utils/media-actions';
|
||||
@@ -34,7 +34,7 @@ async function executeControlAction(
|
||||
await action?.execute(api);
|
||||
}
|
||||
|
||||
describe('MediaDetailsController', () => {
|
||||
describe('MediaNotificationController', () => {
|
||||
describe('should set heading', () => {
|
||||
it('should set heading on event with what, tags and score', () => {
|
||||
const item = new TestViewMedia({
|
||||
@@ -43,7 +43,7 @@ describe('MediaDetailsController', () => {
|
||||
score: 0.5,
|
||||
});
|
||||
|
||||
const controller = new MediaDetailsController();
|
||||
const controller = new MediaNotificationController();
|
||||
controller.calculate(null, item);
|
||||
expect(controller.getHeading()?.text).toBe('Person, Car: Tag1, Tag2 50.00%');
|
||||
});
|
||||
@@ -53,7 +53,7 @@ describe('MediaDetailsController', () => {
|
||||
tags: ['tag1', 'tag2'],
|
||||
});
|
||||
|
||||
const controller = new MediaDetailsController();
|
||||
const controller = new MediaNotificationController();
|
||||
controller.calculate(null, item);
|
||||
expect(controller.getHeading()?.text).toBe('Tag1, Tag2');
|
||||
});
|
||||
@@ -63,7 +63,7 @@ describe('MediaDetailsController', () => {
|
||||
what: ['person', 'car'],
|
||||
});
|
||||
|
||||
const controller = new MediaDetailsController();
|
||||
const controller = new MediaNotificationController();
|
||||
controller.calculate(null, item);
|
||||
expect(controller.getHeading()?.text).toBe('Person, Car');
|
||||
});
|
||||
@@ -76,7 +76,7 @@ describe('MediaDetailsController', () => {
|
||||
score: null,
|
||||
});
|
||||
|
||||
const controller = new MediaDetailsController();
|
||||
const controller = new MediaNotificationController();
|
||||
controller.calculate(null, item);
|
||||
expect(controller.getHeading()).toBeNull();
|
||||
});
|
||||
@@ -92,7 +92,7 @@ describe('MediaDetailsController', () => {
|
||||
mediaType: ViewMediaType.Recording,
|
||||
});
|
||||
|
||||
const controller = new MediaDetailsController();
|
||||
const controller = new MediaNotificationController();
|
||||
controller.calculate(cameraManager, item);
|
||||
expect(controller.getHeading()?.text).toBe('Camera Title');
|
||||
});
|
||||
@@ -102,7 +102,7 @@ describe('MediaDetailsController', () => {
|
||||
mediaType: ViewMediaType.Recording,
|
||||
});
|
||||
|
||||
const controller = new MediaDetailsController();
|
||||
const controller = new MediaNotificationController();
|
||||
controller.calculate(null, item);
|
||||
expect(controller.getHeading()).toBeNull();
|
||||
});
|
||||
@@ -110,7 +110,7 @@ describe('MediaDetailsController', () => {
|
||||
it('should set no heading on folder', () => {
|
||||
const item = new ViewFolder(createFolder(), []);
|
||||
|
||||
const controller = new MediaDetailsController();
|
||||
const controller = new MediaNotificationController();
|
||||
controller.calculate(null, item);
|
||||
expect(controller.getHeading()).toBeNull();
|
||||
});
|
||||
@@ -124,9 +124,9 @@ describe('MediaDetailsController', () => {
|
||||
where: ['where1', 'where2'],
|
||||
});
|
||||
|
||||
const controller = new MediaDetailsController();
|
||||
const controller = new MediaNotificationController();
|
||||
controller.calculate(null, item);
|
||||
expect(controller.getDetails()).toContainEqual({
|
||||
expect(controller.getMetadata()).toContainEqual({
|
||||
text: 'Test Event',
|
||||
icon: 'mdi:rename',
|
||||
tooltip: 'Title',
|
||||
@@ -138,9 +138,9 @@ describe('MediaDetailsController', () => {
|
||||
title: 'Test Event',
|
||||
});
|
||||
|
||||
const controller = new MediaDetailsController();
|
||||
const controller = new MediaNotificationController();
|
||||
controller.calculate(null, item);
|
||||
expect(controller.getDetails()).toEqual([
|
||||
expect(controller.getMetadata()).toEqual([
|
||||
{
|
||||
text: 'Test Event',
|
||||
},
|
||||
@@ -153,9 +153,9 @@ describe('MediaDetailsController', () => {
|
||||
startTime: new Date('2025-05-22T21:12:00Z'),
|
||||
});
|
||||
|
||||
const controller = new MediaDetailsController();
|
||||
const controller = new MediaNotificationController();
|
||||
controller.calculate(null, item);
|
||||
expect(controller.getDetails()).not.toContainEqual(
|
||||
expect(controller.getMetadata()).not.toContainEqual(
|
||||
expect.objectContaining({
|
||||
text: 'Test Event',
|
||||
}),
|
||||
@@ -169,11 +169,11 @@ describe('MediaDetailsController', () => {
|
||||
startTime,
|
||||
});
|
||||
|
||||
const controller = new MediaDetailsController();
|
||||
const controller = new MediaNotificationController();
|
||||
controller.calculate(null, item);
|
||||
|
||||
// Use formatDateAndTime to generate expected value (formats in local time with seconds)
|
||||
expect(controller.getDetails()).toContainEqual({
|
||||
expect(controller.getMetadata()).toContainEqual({
|
||||
text: formatDateAndTime(startTime, true),
|
||||
tooltip: 'Start',
|
||||
icon: 'mdi:calendar-clock-outline',
|
||||
@@ -187,9 +187,9 @@ describe('MediaDetailsController', () => {
|
||||
endTime: new Date('2025-05-18T17:04:00Z'),
|
||||
});
|
||||
|
||||
const controller = new MediaDetailsController();
|
||||
const controller = new MediaNotificationController();
|
||||
controller.calculate(null, item);
|
||||
expect(controller.getDetails()).toContainEqual({
|
||||
expect(controller.getMetadata()).toContainEqual({
|
||||
text: '1m 0s',
|
||||
tooltip: 'Duration',
|
||||
icon: 'mdi:clock-outline',
|
||||
@@ -203,10 +203,10 @@ describe('MediaDetailsController', () => {
|
||||
inProgress: true,
|
||||
});
|
||||
|
||||
const controller = new MediaDetailsController();
|
||||
const controller = new MediaNotificationController();
|
||||
controller.calculate(null, item);
|
||||
expect(controller.getDetails()).toContainEqual({
|
||||
text: 'In Progress',
|
||||
expect(controller.getMetadata()).toContainEqual({
|
||||
text: 'In progress...',
|
||||
tooltip: 'Duration',
|
||||
icon: 'mdi:clock-outline',
|
||||
});
|
||||
@@ -219,10 +219,10 @@ describe('MediaDetailsController', () => {
|
||||
inProgress: true,
|
||||
});
|
||||
|
||||
const controller = new MediaDetailsController();
|
||||
const controller = new MediaNotificationController();
|
||||
controller.calculate(null, item);
|
||||
expect(controller.getDetails()).toContainEqual({
|
||||
text: '1m 0s In Progress',
|
||||
expect(controller.getMetadata()).toContainEqual({
|
||||
text: '1m 0s In progress...',
|
||||
tooltip: 'Duration',
|
||||
icon: 'mdi:clock-outline',
|
||||
});
|
||||
@@ -240,9 +240,9 @@ describe('MediaDetailsController', () => {
|
||||
cameraID: 'camera_1',
|
||||
});
|
||||
|
||||
const controller = new MediaDetailsController();
|
||||
const controller = new MediaNotificationController();
|
||||
controller.calculate(cameraManager, item);
|
||||
expect(controller.getDetails()).toContainEqual({
|
||||
expect(controller.getMetadata()).toContainEqual({
|
||||
text: 'Camera Title',
|
||||
tooltip: 'Camera',
|
||||
icon: 'mdi:cctv',
|
||||
@@ -255,9 +255,9 @@ describe('MediaDetailsController', () => {
|
||||
where: ['where1', 'where2'],
|
||||
});
|
||||
|
||||
const controller = new MediaDetailsController();
|
||||
const controller = new MediaNotificationController();
|
||||
controller.calculate(null, item);
|
||||
expect(controller.getDetails()).toContainEqual({
|
||||
expect(controller.getMetadata()).toContainEqual({
|
||||
text: 'Where1, Where2',
|
||||
tooltip: 'Where',
|
||||
icon: 'mdi:map-marker-outline',
|
||||
@@ -270,9 +270,9 @@ describe('MediaDetailsController', () => {
|
||||
tags: ['tag1', 'tag2'],
|
||||
});
|
||||
|
||||
const controller = new MediaDetailsController();
|
||||
const controller = new MediaNotificationController();
|
||||
controller.calculate(null, item);
|
||||
expect(controller.getDetails()).toContainEqual({
|
||||
expect(controller.getMetadata()).toContainEqual({
|
||||
text: 'Tag1, Tag2',
|
||||
tooltip: 'Tag',
|
||||
icon: 'mdi:tag',
|
||||
@@ -283,11 +283,11 @@ describe('MediaDetailsController', () => {
|
||||
const item = new TestViewMedia();
|
||||
const seekTime = new Date('2025-05-20T07:14:57Z');
|
||||
|
||||
const controller = new MediaDetailsController();
|
||||
const controller = new MediaNotificationController();
|
||||
controller.calculate(null, item, seekTime);
|
||||
|
||||
// Use format() to generate expected value (formats in local time)
|
||||
expect(controller.getDetails()).toContainEqual({
|
||||
expect(controller.getMetadata()).toContainEqual({
|
||||
text: format(seekTime, 'HH:mm:ss'),
|
||||
tooltip: 'Seek',
|
||||
icon: 'mdi:clock-fast',
|
||||
@@ -300,7 +300,7 @@ describe('MediaDetailsController', () => {
|
||||
severity: 'high',
|
||||
});
|
||||
|
||||
const controller = new MediaDetailsController();
|
||||
const controller = new MediaNotificationController();
|
||||
controller.calculate(null, item);
|
||||
const heading = controller.getHeading();
|
||||
expect(heading?.text).toBe('Review Title');
|
||||
@@ -316,7 +316,7 @@ describe('MediaDetailsController', () => {
|
||||
severity: null,
|
||||
});
|
||||
|
||||
const controller = new MediaDetailsController();
|
||||
const controller = new MediaNotificationController();
|
||||
controller.calculate(null, item);
|
||||
const heading = controller.getHeading();
|
||||
expect(heading?.text).toBe('Review Title');
|
||||
@@ -329,16 +329,16 @@ describe('MediaDetailsController', () => {
|
||||
title: null,
|
||||
});
|
||||
|
||||
const controller = new MediaDetailsController();
|
||||
const controller = new MediaNotificationController();
|
||||
controller.calculate(null, item);
|
||||
expect(controller.getHeading()).toBeNull();
|
||||
});
|
||||
|
||||
it('should calculate with null item', () => {
|
||||
const controller = new MediaDetailsController();
|
||||
const controller = new MediaNotificationController();
|
||||
controller.calculate(null, undefined);
|
||||
expect(controller.getHeading()).toBeNull();
|
||||
expect(controller.getDetails()).toEqual([]);
|
||||
expect(controller.getMetadata()).toEqual([]);
|
||||
});
|
||||
});
|
||||
|
||||
@@ -354,25 +354,25 @@ describe('MediaDetailsController', () => {
|
||||
description: 'Test Description',
|
||||
});
|
||||
|
||||
const controller = new MediaDetailsController();
|
||||
const controller = new MediaNotificationController();
|
||||
controller.calculate(null, item);
|
||||
|
||||
const notification = controller.getNotification();
|
||||
expect(notification.heading?.text).toBe('Person');
|
||||
expect(notification.details).toContainEqual({
|
||||
expect(notification.metadata).toContainEqual({
|
||||
text: 'Test Title',
|
||||
});
|
||||
expect(notification.text).toBe('Test Description');
|
||||
expect(notification.body).toEqual({ text: 'Test Description' });
|
||||
});
|
||||
|
||||
it('should get notification without media', () => {
|
||||
const item = new ViewFolder(createFolder(), []);
|
||||
|
||||
const controller = new MediaDetailsController();
|
||||
const controller = new MediaNotificationController();
|
||||
controller.calculate(null, item);
|
||||
|
||||
const notification = controller.getNotification();
|
||||
expect(notification.text).toBeUndefined();
|
||||
expect(notification.body).toBeUndefined();
|
||||
});
|
||||
|
||||
it('should get notification with null description', () => {
|
||||
@@ -380,11 +380,11 @@ describe('MediaDetailsController', () => {
|
||||
description: null,
|
||||
});
|
||||
|
||||
const controller = new MediaDetailsController();
|
||||
const controller = new MediaNotificationController();
|
||||
controller.calculate(null, item);
|
||||
|
||||
const notification = controller.getNotification();
|
||||
expect(notification.text).toBeUndefined();
|
||||
expect(notification.body).toBeUndefined();
|
||||
});
|
||||
|
||||
it('should get notification with controls', async () => {
|
||||
@@ -408,7 +408,7 @@ describe('MediaDetailsController', () => {
|
||||
viewManagerEpoch: viewManagerEpoch,
|
||||
};
|
||||
|
||||
const controller = new MediaDetailsController();
|
||||
const controller = new MediaNotificationController();
|
||||
controller.calculate(null, item);
|
||||
|
||||
const notification = controller.getNotification(context);
|
||||
@@ -469,7 +469,7 @@ describe('MediaDetailsController', () => {
|
||||
},
|
||||
};
|
||||
|
||||
const controller = new MediaDetailsController();
|
||||
const controller = new MediaNotificationController();
|
||||
controller.calculate(null, item);
|
||||
|
||||
const notification = controller.getNotification(context);
|
||||
@@ -494,7 +494,7 @@ describe('MediaDetailsController', () => {
|
||||
},
|
||||
};
|
||||
|
||||
const controller = new MediaDetailsController();
|
||||
const controller = new MediaNotificationController();
|
||||
controller.calculate(null, item);
|
||||
|
||||
const notification = controller.getNotification(context);
|
||||
@@ -507,7 +507,7 @@ describe('MediaDetailsController', () => {
|
||||
});
|
||||
const context = {};
|
||||
|
||||
const controller = new MediaDetailsController();
|
||||
const controller = new MediaNotificationController();
|
||||
controller.calculate(null, item);
|
||||
|
||||
const notification = controller.getNotification(context);
|
||||
@@ -515,11 +515,11 @@ describe('MediaDetailsController', () => {
|
||||
});
|
||||
|
||||
it('should get empty controls when item is null', () => {
|
||||
const controller = new MediaDetailsController();
|
||||
const ctrl = new MediaNotificationController();
|
||||
// Directly call protected method via casting to test the null item branch.
|
||||
// Use cast to unknown first to avoid any-related lint errors.
|
||||
const controls = (
|
||||
controller as unknown as {
|
||||
ctrl as unknown as {
|
||||
_getControls: (context: NotificationControlsContext) => NotificationControl[];
|
||||
}
|
||||
)._getControls({});
|
||||
@@ -1,157 +0,0 @@
|
||||
import yaml from 'js-yaml';
|
||||
import { describe, expect, it } from 'vitest';
|
||||
import { MessageController } from '../../../src/components-lib/message/controller';
|
||||
import { Link } from '../../../src/config/schema/common/link';
|
||||
import { TROUBLESHOOTING_URL } from '../../../src/const';
|
||||
import { localize } from '../../../src/localize/localize';
|
||||
import { Message, MessageType } from '../../../src/types';
|
||||
|
||||
describe('MessageController', () => {
|
||||
describe('should return the correct message string', () => {
|
||||
it('should return simple message string', () => {
|
||||
const controller = new MessageController();
|
||||
const message: Message = {
|
||||
message: 'Message',
|
||||
type: 'info',
|
||||
};
|
||||
expect(controller.getMessageString(message)).toBe('Message');
|
||||
});
|
||||
|
||||
it('should embed simple string context', () => {
|
||||
const controller = new MessageController();
|
||||
const message: Message = {
|
||||
message: 'Message',
|
||||
context: 'Context',
|
||||
type: 'info',
|
||||
};
|
||||
expect(controller.getMessageString(message)).toBe('Message: Context');
|
||||
});
|
||||
});
|
||||
|
||||
describe('should return the correct icon', () => {
|
||||
describe('when icon is specified', () => {
|
||||
it.each([['info' as const], ['error' as const], ['connection' as const]])(
|
||||
'%s',
|
||||
(type: MessageType) => {
|
||||
const controller = new MessageController();
|
||||
const message: Message = {
|
||||
message: 'Message',
|
||||
icon: 'mdi:car',
|
||||
type,
|
||||
};
|
||||
expect(controller.getIcon(message)).toBe('mdi:car');
|
||||
},
|
||||
);
|
||||
});
|
||||
|
||||
it('when type is an error', () => {
|
||||
const controller = new MessageController();
|
||||
const message: Message = {
|
||||
message: 'Message',
|
||||
type: 'error',
|
||||
};
|
||||
expect(controller.getIcon(message)).toBe('mdi:alert-circle');
|
||||
});
|
||||
|
||||
it('by default', () => {
|
||||
const controller = new MessageController();
|
||||
const message: Message = {
|
||||
message: 'Message',
|
||||
};
|
||||
expect(controller.getIcon(message)).toBe('mdi:information-outline');
|
||||
});
|
||||
});
|
||||
|
||||
describe('should show troubleshooting link', () => {
|
||||
it('should show for errors', () => {
|
||||
const controller = new MessageController();
|
||||
const message: Message = { message: 'Error message', type: 'error' };
|
||||
expect(controller.getLink(message)).toEqual({
|
||||
url: TROUBLESHOOTING_URL,
|
||||
title: localize('error.troubleshooting'),
|
||||
});
|
||||
});
|
||||
|
||||
describe('should not show for other types', () => {
|
||||
it.each([['info' as const], ['connection' as const]])(
|
||||
'%s',
|
||||
(type: MessageType) => {
|
||||
const controller = new MessageController();
|
||||
const message: Message = {
|
||||
message: 'Message',
|
||||
icon: 'mdi:car',
|
||||
type,
|
||||
};
|
||||
expect(controller.getLink(message)).toBeNull();
|
||||
},
|
||||
);
|
||||
});
|
||||
|
||||
describe('should show correct URL', () => {
|
||||
it('by default', () => {
|
||||
const controller = new MessageController();
|
||||
const message: Message = { message: 'Error message', type: 'error' };
|
||||
expect(controller.getLink(message)?.url).toBe(TROUBLESHOOTING_URL);
|
||||
});
|
||||
|
||||
it('when specified', () => {
|
||||
const controller = new MessageController();
|
||||
const url: Link = {
|
||||
url: 'link',
|
||||
title: 'title',
|
||||
};
|
||||
const message: Message = {
|
||||
message: 'Error message',
|
||||
type: 'error',
|
||||
link: url,
|
||||
};
|
||||
expect(controller.getLink(message)).toBe(url);
|
||||
});
|
||||
});
|
||||
});
|
||||
|
||||
describe('should get context strings', () => {
|
||||
it('for no context', () => {
|
||||
const controller = new MessageController();
|
||||
const message: Message = {
|
||||
message: 'Message',
|
||||
type: 'info',
|
||||
};
|
||||
expect(controller.getContextStrings(message)).toEqual([]);
|
||||
});
|
||||
|
||||
it('for simple string', () => {
|
||||
const controller = new MessageController();
|
||||
const message: Message = {
|
||||
message: 'Message',
|
||||
context: 'Context',
|
||||
type: 'info',
|
||||
};
|
||||
expect(controller.getContextStrings(message)).toEqual(['Context']);
|
||||
});
|
||||
|
||||
it('for object', () => {
|
||||
const controller = new MessageController();
|
||||
const obj = { one: 1, two: 2 };
|
||||
const message: Message = {
|
||||
message: 'Message',
|
||||
context: obj,
|
||||
type: 'info',
|
||||
};
|
||||
expect(controller.getContextStrings(message)).toEqual([yaml.dump(obj)]);
|
||||
});
|
||||
|
||||
it('for array', () => {
|
||||
const controller = new MessageController();
|
||||
const array = ['one', 'two'];
|
||||
const message: Message = {
|
||||
message: 'Message',
|
||||
context: array,
|
||||
type: 'info',
|
||||
};
|
||||
expect(controller.getContextStrings(message)).toEqual(
|
||||
array.map((item) => yaml.dump(item)),
|
||||
);
|
||||
});
|
||||
});
|
||||
});
|
||||
@@ -1,50 +0,0 @@
|
||||
import { expect, it, vi } from 'vitest';
|
||||
import { dispatchAdvancedCameraCardErrorEvent } from '../../../src/components-lib/message/dispatch';
|
||||
import { AdvancedCameraCardError } from '../../../src/types';
|
||||
|
||||
// @vitest-environment jsdom
|
||||
it('should ignore non-error', () => {
|
||||
const element = document.createElement('div');
|
||||
const handler = vi.fn();
|
||||
element.addEventListener('advanced-camera-card:message', handler);
|
||||
|
||||
dispatchAdvancedCameraCardErrorEvent(element, 'NOT_ADVANCED_CAMERA_CARD_EVENT');
|
||||
|
||||
expect(handler).not.toBeCalled();
|
||||
});
|
||||
|
||||
it('should dispatch error', () => {
|
||||
const element = document.createElement('div');
|
||||
const handler = vi.fn();
|
||||
element.addEventListener('advanced-camera-card:message', handler);
|
||||
|
||||
dispatchAdvancedCameraCardErrorEvent(element, new Error('ERROR'));
|
||||
|
||||
expect(handler).toBeCalledWith(
|
||||
expect.objectContaining({
|
||||
detail: expect.objectContaining({
|
||||
message: 'ERROR',
|
||||
}),
|
||||
}),
|
||||
);
|
||||
});
|
||||
|
||||
it('should dispatch error with context', () => {
|
||||
const element = document.createElement('div');
|
||||
const handler = vi.fn();
|
||||
element.addEventListener('advanced-camera-card:message', handler);
|
||||
|
||||
dispatchAdvancedCameraCardErrorEvent(
|
||||
element,
|
||||
new AdvancedCameraCardError('ERROR', 'CONTEXT'),
|
||||
);
|
||||
|
||||
expect(handler).toBeCalledWith(
|
||||
expect.objectContaining({
|
||||
detail: expect.objectContaining({
|
||||
message: 'ERROR',
|
||||
context: 'CONTEXT',
|
||||
}),
|
||||
}),
|
||||
);
|
||||
});
|
||||
@@ -0,0 +1,93 @@
|
||||
// @vitest-environment jsdom
|
||||
import { beforeEach, describe, expect, it, vi } from 'vitest';
|
||||
import { dispatchActionExecutionRequest } from '../../../src/card-controller/actions/utils/execution-request';
|
||||
import { handleControlAction } from '../../../src/components-lib/notification/action';
|
||||
import { NotificationControl } from '../../../src/config/schema/actions/types';
|
||||
import {
|
||||
getActionConfigGivenAction,
|
||||
stopEventFromActivatingCardWideActions,
|
||||
} from '../../../src/utils/action';
|
||||
|
||||
vi.mock('../../../src/card-controller/actions/utils/execution-request.js');
|
||||
vi.mock('../../../src/utils/action.js');
|
||||
|
||||
describe('handleControlAction', () => {
|
||||
beforeEach(() => {
|
||||
vi.resetAllMocks();
|
||||
});
|
||||
|
||||
const createControl = (
|
||||
overrides?: Partial<NotificationControl>,
|
||||
): NotificationControl => ({
|
||||
dismiss: true,
|
||||
...overrides,
|
||||
});
|
||||
|
||||
it('should stop the event from activating card-wide actions', () => {
|
||||
const ev = new CustomEvent('action', { detail: { action: 'tap' } });
|
||||
const host = document.createElement('div');
|
||||
handleControlAction(ev, createControl(), host);
|
||||
|
||||
expect(stopEventFromActivatingCardWideActions).toBeCalledWith(ev);
|
||||
});
|
||||
|
||||
it('should dispatch action when getActionConfigGivenAction returns an action', () => {
|
||||
const action = { action: 'navigate' as const, navigation_path: '/foo' };
|
||||
vi.mocked(getActionConfigGivenAction).mockReturnValue(action);
|
||||
|
||||
const ev = new CustomEvent('action', { detail: { action: 'tap' } });
|
||||
const control = createControl({ actions: { tap_action: action } });
|
||||
const host = document.createElement('div');
|
||||
|
||||
handleControlAction(ev, control, host);
|
||||
|
||||
expect(dispatchActionExecutionRequest).toBeCalledWith(host, {
|
||||
actions: [action],
|
||||
});
|
||||
});
|
||||
|
||||
it('should not dispatch when getActionConfigGivenAction returns null', () => {
|
||||
vi.mocked(getActionConfigGivenAction).mockReturnValue(null);
|
||||
|
||||
const ev = new CustomEvent('action', { detail: { action: 'tap' } });
|
||||
const host = document.createElement('div');
|
||||
|
||||
handleControlAction(ev, createControl(), host);
|
||||
|
||||
expect(dispatchActionExecutionRequest).not.toBeCalled();
|
||||
});
|
||||
|
||||
it('should call onDismiss when dismiss is not false', () => {
|
||||
vi.mocked(getActionConfigGivenAction).mockReturnValue(null);
|
||||
|
||||
const ev = new CustomEvent('action', { detail: { action: 'tap' } });
|
||||
const host = document.createElement('div');
|
||||
const onDismiss = vi.fn();
|
||||
|
||||
handleControlAction(ev, createControl({ dismiss: true }), host, onDismiss);
|
||||
|
||||
expect(onDismiss).toBeCalled();
|
||||
});
|
||||
|
||||
it('should not call onDismiss when dismiss is false', () => {
|
||||
vi.mocked(getActionConfigGivenAction).mockReturnValue(null);
|
||||
|
||||
const ev = new CustomEvent('action', { detail: { action: 'tap' } });
|
||||
const host = document.createElement('div');
|
||||
const onDismiss = vi.fn();
|
||||
|
||||
handleControlAction(ev, createControl({ dismiss: false }), host, onDismiss);
|
||||
|
||||
expect(onDismiss).not.toBeCalled();
|
||||
});
|
||||
|
||||
it('should not call onDismiss when no onDismiss is provided', () => {
|
||||
vi.mocked(getActionConfigGivenAction).mockReturnValue(null);
|
||||
|
||||
const ev = new CustomEvent('action', { detail: { action: 'tap' } });
|
||||
const host = document.createElement('div');
|
||||
|
||||
// Should not throw when onDismiss is undefined
|
||||
expect(() => handleControlAction(ev, createControl(), host)).not.toThrow();
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,32 @@
|
||||
import { describe, expect, it } from 'vitest';
|
||||
import { dataToContext } from '../../../src/components-lib/notification/data-to-context';
|
||||
|
||||
describe('dataToContext', () => {
|
||||
it('should return an array of string items unchanged when input is an array of strings', () => {
|
||||
expect(dataToContext(['line one', 'line two'])).toEqual(['line one', 'line two']);
|
||||
});
|
||||
|
||||
it('should YAML-dump object items when input is an array containing objects', () => {
|
||||
const result = dataToContext([{ key: 'value' }]);
|
||||
expect(result).toHaveLength(1);
|
||||
expect(result[0]).toContain('key: value');
|
||||
});
|
||||
|
||||
it('should handle a mixed array of strings and objects', () => {
|
||||
const result = dataToContext(['plain string', { foo: 'bar' }]);
|
||||
expect(result).toHaveLength(2);
|
||||
expect(result[0]).toBe('plain string');
|
||||
expect(result[1]).toContain('foo: bar');
|
||||
});
|
||||
|
||||
it('should return a single YAML-dumped string for a plain object', () => {
|
||||
const result = dataToContext({ error: 'something went wrong', code: 42 });
|
||||
expect(result).toHaveLength(1);
|
||||
expect(result[0]).toContain('error: something went wrong');
|
||||
expect(result[0]).toContain('code: 42');
|
||||
});
|
||||
|
||||
it('should return an empty array for an empty array input', () => {
|
||||
expect(dataToContext([])).toEqual([]);
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,165 @@
|
||||
import { assert, describe, expect, it } from 'vitest';
|
||||
import {
|
||||
createNotificationFromError,
|
||||
createNotificationFromText,
|
||||
} from '../../../src/components-lib/notification/factory';
|
||||
import { AdvancedCameraCardError } from '../../../src/types';
|
||||
|
||||
describe('createNotificationFromText', () => {
|
||||
it('should create a notification with body text', () => {
|
||||
const notification = createNotificationFromText('Something failed');
|
||||
expect(notification.body?.text).toBe('Something failed');
|
||||
});
|
||||
|
||||
it('should add the default error icon to body when no heading and no icon provided', () => {
|
||||
const notification = createNotificationFromText('oops');
|
||||
expect(notification.body?.icon).toBe('mdi:alert');
|
||||
});
|
||||
|
||||
it('should add a custom icon to body when specified', () => {
|
||||
const notification = createNotificationFromText('oops', { icon: 'mdi:wifi-off' });
|
||||
expect(notification.body?.icon).toBe('mdi:wifi-off');
|
||||
});
|
||||
|
||||
it('should include the heading when provided', () => {
|
||||
const notification = createNotificationFromText('oops', {
|
||||
heading: { text: 'Error heading' },
|
||||
});
|
||||
expect(notification.heading?.text).toBe('Error heading');
|
||||
});
|
||||
|
||||
it('should omit icon from body when heading is provided and no icon is specified', () => {
|
||||
const notification = createNotificationFromText('oops', {
|
||||
heading: { text: 'Error heading' },
|
||||
});
|
||||
expect(notification.body?.icon).toBeUndefined();
|
||||
});
|
||||
|
||||
it('should add icon to body when heading is provided but icon is also specified', () => {
|
||||
const notification = createNotificationFromText('oops', {
|
||||
heading: { text: 'Error heading' },
|
||||
icon: 'mdi:alert-circle',
|
||||
});
|
||||
expect(notification.body?.icon).toBe('mdi:alert-circle');
|
||||
});
|
||||
|
||||
it('should include metadata when provided', () => {
|
||||
const notification = createNotificationFromText('oops', {
|
||||
metadata: [{ text: 'meta line' }],
|
||||
});
|
||||
expect(notification.metadata).toEqual([{ text: 'meta line' }]);
|
||||
});
|
||||
|
||||
it('should omit metadata when not provided', () => {
|
||||
const notification = createNotificationFromText('oops');
|
||||
expect(notification.metadata).toBeUndefined();
|
||||
});
|
||||
|
||||
it('should include link when provided', () => {
|
||||
const notification = createNotificationFromText('oops', {
|
||||
link: { url: 'https://example.com', title: 'Docs' },
|
||||
});
|
||||
expect(notification.link?.url).toBe('https://example.com');
|
||||
});
|
||||
|
||||
it('should include context when provided', () => {
|
||||
const notification = createNotificationFromText('oops', {
|
||||
context: { detail: 'extra info' },
|
||||
});
|
||||
expect(notification.context).toBeDefined();
|
||||
expect(notification.context?.join(' ')).toContain('detail: extra info');
|
||||
});
|
||||
|
||||
it('should omit context when not provided', () => {
|
||||
const notification = createNotificationFromText('oops');
|
||||
expect(notification.context).toBeUndefined();
|
||||
});
|
||||
|
||||
it('should include in_progress when true', () => {
|
||||
const notification = createNotificationFromText('oops', { in_progress: true });
|
||||
expect(notification.in_progress).toBe(true);
|
||||
});
|
||||
|
||||
it('should include in_progress when false', () => {
|
||||
const notification = createNotificationFromText('oops', { in_progress: false });
|
||||
expect(notification.in_progress).toBe(false);
|
||||
});
|
||||
|
||||
it('should omit in_progress when not provided', () => {
|
||||
const notification = createNotificationFromText('oops');
|
||||
expect(notification.in_progress).toBeUndefined();
|
||||
});
|
||||
});
|
||||
|
||||
describe('createNotificationFromError', () => {
|
||||
it('should create a notification from an Error object', () => {
|
||||
const notification = createNotificationFromError(new Error('something failed'));
|
||||
assert(notification);
|
||||
expect(notification.body?.text).toBe('something failed');
|
||||
});
|
||||
|
||||
it('should create a notification from a string error', () => {
|
||||
const notification = createNotificationFromError('plain string error');
|
||||
assert(notification);
|
||||
expect(notification.body?.text).toBe('plain string error');
|
||||
});
|
||||
|
||||
it('should create a notification from a non-error object', () => {
|
||||
const notification = createNotificationFromError({ code: 404 });
|
||||
assert(notification);
|
||||
expect(notification.body?.text).toBe('{"code":404}');
|
||||
});
|
||||
|
||||
it('should merge the default error icon into heading when heading is provided', () => {
|
||||
const notification = createNotificationFromError(new Error('failed'), {
|
||||
heading: { text: 'Init Error' },
|
||||
});
|
||||
assert(notification);
|
||||
expect(notification.heading?.text).toBe('Init Error');
|
||||
expect(notification.heading?.icon).toBe('mdi:alert');
|
||||
expect(notification.heading?.severity).toBe('high');
|
||||
});
|
||||
|
||||
it('should preserve custom heading properties alongside defaults', () => {
|
||||
const notification = createNotificationFromError(new Error('failed'), {
|
||||
heading: { text: 'My Heading', icon: 'mdi:custom', severity: 'medium' },
|
||||
});
|
||||
assert(notification);
|
||||
// Spread order: { icon: DEFAULT, severity: 'high', ...options.heading }
|
||||
// so custom values win
|
||||
expect(notification.heading?.icon).toBe('mdi:custom');
|
||||
expect(notification.heading?.severity).toBe('medium');
|
||||
});
|
||||
|
||||
it('should use context from AdvancedCameraCardError when no explicit context is provided', () => {
|
||||
const error = new AdvancedCameraCardError('boom', { reason: 'network' });
|
||||
const notification = createNotificationFromError(error);
|
||||
assert(notification);
|
||||
expect(notification.context).toBeDefined();
|
||||
expect(notification.context?.join(' ')).toContain('reason: network');
|
||||
});
|
||||
|
||||
it('should use explicit context option over AdvancedCameraCardError context', () => {
|
||||
const error = new AdvancedCameraCardError('boom', { reason: 'network' });
|
||||
const notification = createNotificationFromError(error, {
|
||||
context: { override: 'explicit' },
|
||||
});
|
||||
assert(notification);
|
||||
expect(notification.context?.join(' ')).toContain('override: explicit');
|
||||
expect(notification.context?.join(' ')).not.toContain('reason: network');
|
||||
});
|
||||
|
||||
it('should not include context when AdvancedCameraCardError has a non-object context', () => {
|
||||
const error = new AdvancedCameraCardError('boom', 'not an object');
|
||||
const notification = createNotificationFromError(error);
|
||||
assert(notification);
|
||||
expect(notification.context).toBeUndefined();
|
||||
});
|
||||
|
||||
it('should not include context when AdvancedCameraCardError context is null', () => {
|
||||
const error = new AdvancedCameraCardError('boom', null);
|
||||
const notification = createNotificationFromError(error);
|
||||
assert(notification);
|
||||
expect(notification.context).toBeUndefined();
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,48 @@
|
||||
import { describe, expect, it } from 'vitest';
|
||||
import { summarizeNotification } from '../../../src/components-lib/notification/summarize';
|
||||
import { Notification } from '../../../src/config/schema/actions/types';
|
||||
|
||||
describe('summarizeNotification', () => {
|
||||
it('should return the body text when present', () => {
|
||||
const notification: Notification = { body: { text: 'Body text' } };
|
||||
expect(summarizeNotification(notification)).toBe('Body text');
|
||||
});
|
||||
|
||||
it('should return the heading text when body is absent', () => {
|
||||
const notification: Notification = {
|
||||
heading: { text: 'Heading text' },
|
||||
};
|
||||
expect(summarizeNotification(notification)).toBe('Heading text');
|
||||
});
|
||||
|
||||
it('should return the body text even when heading is also present', () => {
|
||||
const notification: Notification = {
|
||||
heading: { text: 'Heading text' },
|
||||
body: { text: 'Body text' },
|
||||
};
|
||||
expect(summarizeNotification(notification)).toBe('Body text');
|
||||
});
|
||||
|
||||
it('should return null when neither body nor heading has text', () => {
|
||||
const notification: Notification = {};
|
||||
expect(summarizeNotification(notification)).toBeNull();
|
||||
});
|
||||
|
||||
it('should append metadata text in brackets', () => {
|
||||
const notification: Notification = {
|
||||
body: { text: 'Media not loading' },
|
||||
metadata: [{ text: 'camera.office' }, { text: 'camera.garden' }],
|
||||
};
|
||||
expect(summarizeNotification(notification)).toBe(
|
||||
'Media not loading [camera.office, camera.garden]',
|
||||
);
|
||||
});
|
||||
|
||||
it('should not append brackets when metadata is empty', () => {
|
||||
const notification: Notification = {
|
||||
body: { text: 'Body text' },
|
||||
metadata: [],
|
||||
};
|
||||
expect(summarizeNotification(notification)).toBe('Body text');
|
||||
});
|
||||
});
|
||||
@@ -267,6 +267,105 @@ describe('StatusBarController', () => {
|
||||
expect(host.getAttribute('hide')).toBe(null);
|
||||
});
|
||||
|
||||
it('should not start popup timer when permanent items are present', () => {
|
||||
const host = createLitElement();
|
||||
setOrRemoveAttribute(host, true, 'hide');
|
||||
|
||||
const controller = new StatusBarController(host);
|
||||
controller.setConfig(
|
||||
createConfig({
|
||||
style: 'popup',
|
||||
}),
|
||||
);
|
||||
|
||||
const permanentItem = {
|
||||
type: 'custom:advanced-camera-card-status-bar-icon' as const,
|
||||
icon: 'mdi:alert',
|
||||
sufficient: true,
|
||||
permanent: true,
|
||||
};
|
||||
|
||||
controller.setItems([permanentItem]);
|
||||
expect(host.getAttribute('hide')).toBe(null);
|
||||
|
||||
// Timer should not hide the bar.
|
||||
vi.advanceTimersByTime(10000);
|
||||
expect(host.getAttribute('hide')).toBe(null);
|
||||
});
|
||||
|
||||
it('should start popup timer when permanent items are removed', () => {
|
||||
const host = createLitElement();
|
||||
|
||||
const controller = new StatusBarController(host);
|
||||
controller.setConfig(
|
||||
createConfig({
|
||||
style: 'popup',
|
||||
}),
|
||||
);
|
||||
|
||||
const permanentItem = {
|
||||
type: 'custom:advanced-camera-card-status-bar-icon' as const,
|
||||
icon: 'mdi:alert',
|
||||
sufficient: true,
|
||||
permanent: true,
|
||||
};
|
||||
const nonPermanentItem = {
|
||||
type: 'custom:advanced-camera-card-status-bar-string' as const,
|
||||
string: 'Title',
|
||||
sufficient: true,
|
||||
};
|
||||
|
||||
// Start with permanent item — bar stays visible.
|
||||
controller.setItems([permanentItem, nonPermanentItem]);
|
||||
vi.advanceTimersByTime(10000);
|
||||
expect(host.getAttribute('hide')).toBe(null);
|
||||
|
||||
// Remove permanent item — popup timer starts.
|
||||
controller.setItems([nonPermanentItem]);
|
||||
expect(host.getAttribute('hide')).toBe(null);
|
||||
|
||||
vi.advanceTimersByTime(3000);
|
||||
expect(host.getAttribute('hide')).not.toBe(null);
|
||||
});
|
||||
|
||||
it('should start popup timer when permanent item is removed without changing sufficient items', () => {
|
||||
const host = createLitElement();
|
||||
|
||||
const controller = new StatusBarController(host);
|
||||
controller.setConfig(
|
||||
createConfig({
|
||||
style: 'popup',
|
||||
}),
|
||||
);
|
||||
|
||||
const sufficientItem = {
|
||||
type: 'custom:advanced-camera-card-status-bar-string' as const,
|
||||
string: 'Title',
|
||||
sufficient: true,
|
||||
};
|
||||
// A permanent item that is NOT sufficient — removing it does not
|
||||
// change the sufficient-values set, so the popup timer takes the
|
||||
// dedicated permanent-removal branch.
|
||||
const permanentInsufficientItem = {
|
||||
type: 'custom:advanced-camera-card-status-bar-icon' as const,
|
||||
icon: 'mdi:alert',
|
||||
sufficient: false,
|
||||
permanent: true,
|
||||
};
|
||||
|
||||
controller.setItems([sufficientItem, permanentInsufficientItem]);
|
||||
vi.advanceTimersByTime(10000);
|
||||
expect(host.getAttribute('hide')).toBe(null);
|
||||
|
||||
// Remove the permanent (insufficient) item — sufficient values are
|
||||
// unchanged, but the popup timer must still start.
|
||||
controller.setItems([sufficientItem]);
|
||||
expect(host.getAttribute('hide')).toBe(null);
|
||||
|
||||
vi.advanceTimersByTime(3000);
|
||||
expect(host.getAttribute('hide')).not.toBe(null);
|
||||
});
|
||||
|
||||
it('should hide popup after expiry', () => {
|
||||
const host = createLitElement();
|
||||
|
||||
|
||||
@@ -0,0 +1,74 @@
|
||||
import { describe, expect, it, vi } from 'vitest';
|
||||
import { renderNoMedia } from '../../../src/components/notification/no-media';
|
||||
import { createCameraManager, createStore } from '../../test-utils';
|
||||
|
||||
// @vitest-environment jsdom
|
||||
describe('renderNoMedia', () => {
|
||||
it('should render "No media" heading when not loading', () => {
|
||||
const result = renderNoMedia({
|
||||
cameraID: null,
|
||||
cameraManager: null,
|
||||
});
|
||||
expect(result).toBeTruthy();
|
||||
});
|
||||
|
||||
it('should render "Awaiting media" heading when loading', () => {
|
||||
const result = renderNoMedia({
|
||||
cameraID: null,
|
||||
cameraManager: null,
|
||||
loading: true,
|
||||
});
|
||||
expect(result).toBeTruthy();
|
||||
});
|
||||
|
||||
it('should include camera title as metadata when camera resolves', () => {
|
||||
const cameraManager = createCameraManager();
|
||||
vi.mocked(cameraManager.getCameraMetadata).mockReturnValue({
|
||||
title: 'Office',
|
||||
icon: { icon: 'mdi:cctv' },
|
||||
});
|
||||
|
||||
const result = renderNoMedia({
|
||||
cameraID: 'camera.office',
|
||||
cameraManager,
|
||||
});
|
||||
expect(result).toBeTruthy();
|
||||
expect(cameraManager.getCameraMetadata).toBeCalledWith('camera.office');
|
||||
});
|
||||
|
||||
it('should fall back to raw camera ID when metadata has no title', () => {
|
||||
const cameraManager = createCameraManager();
|
||||
vi.mocked(cameraManager.getCameraMetadata).mockReturnValue(null);
|
||||
|
||||
const result = renderNoMedia({
|
||||
cameraID: 'camera.office',
|
||||
cameraManager,
|
||||
});
|
||||
expect(result).toBeTruthy();
|
||||
});
|
||||
|
||||
it('should fall back to default camera ID when cameraID is null', () => {
|
||||
const store = createStore([{ cameraID: 'camera.default' }]);
|
||||
const cameraManager = createCameraManager(store);
|
||||
vi.mocked(cameraManager.getCameraMetadata).mockReturnValue(null);
|
||||
|
||||
const result = renderNoMedia({
|
||||
cameraID: null,
|
||||
cameraManager,
|
||||
});
|
||||
expect(result).toBeTruthy();
|
||||
expect(cameraManager.getCameraMetadata).toBeCalledWith('camera.default');
|
||||
});
|
||||
|
||||
it('should not include metadata when no camera is resolvable', () => {
|
||||
// Empty store — no default camera.
|
||||
const cameraManager = createCameraManager(createStore());
|
||||
|
||||
const result = renderNoMedia({
|
||||
cameraID: null,
|
||||
cameraManager,
|
||||
});
|
||||
expect(result).toBeTruthy();
|
||||
expect(cameraManager.getCameraMetadata).not.toBeCalled();
|
||||
});
|
||||
});
|
||||
@@ -36,43 +36,49 @@ describe('ConditionStateManager', () => {
|
||||
fullscreen: true,
|
||||
};
|
||||
|
||||
manager.setState(state);
|
||||
expect(manager.setState(state)).toBe(true);
|
||||
expect(listener).toBeCalledTimes(1);
|
||||
|
||||
manager.setState(state);
|
||||
expect(manager.setState(state)).toBe(false);
|
||||
expect(listener).toBeCalledTimes(1);
|
||||
|
||||
manager.setState({ ...state });
|
||||
expect(manager.setState({ ...state })).toBe(false);
|
||||
expect(listener).toBeCalledTimes(1);
|
||||
|
||||
manager.setState({
|
||||
hass: createHASS({
|
||||
'binary_sensor.foo': createStateEntity(),
|
||||
expect(
|
||||
manager.setState({
|
||||
hass: createHASS({
|
||||
'binary_sensor.foo': createStateEntity(),
|
||||
}),
|
||||
}),
|
||||
});
|
||||
).toBe(true);
|
||||
expect(listener).toBeCalledTimes(2);
|
||||
|
||||
manager.setState({ fullscreen: true });
|
||||
expect(manager.setState({ fullscreen: true })).toBe(false);
|
||||
expect(listener).toBeCalledTimes(2);
|
||||
|
||||
manager.setState({
|
||||
hass: createHASS({
|
||||
'binary_sensor.foo': createStateEntity(),
|
||||
expect(
|
||||
manager.setState({
|
||||
hass: createHASS({
|
||||
'binary_sensor.foo': createStateEntity(),
|
||||
}),
|
||||
}),
|
||||
});
|
||||
).toBe(true);
|
||||
expect(listener).toBeCalledTimes(3);
|
||||
|
||||
manager.setState({ fullscreen: false });
|
||||
expect(manager.setState({ fullscreen: false })).toBe(true);
|
||||
expect(listener).toBeCalledTimes(4);
|
||||
|
||||
manager.setState({ fullscreen: false });
|
||||
expect(manager.setState({ fullscreen: false })).toBe(false);
|
||||
expect(listener).toBeCalledTimes(4);
|
||||
|
||||
manager.setState({
|
||||
hass: createHASS({
|
||||
'binary_sensor.foo': createStateEntity({ state: 'off' }),
|
||||
expect(
|
||||
manager.setState({
|
||||
hass: createHASS({
|
||||
'binary_sensor.foo': createStateEntity({ state: 'off' }),
|
||||
}),
|
||||
}),
|
||||
});
|
||||
).toBe(true);
|
||||
expect(listener).toBeCalledTimes(5);
|
||||
});
|
||||
});
|
||||
|
||||
+35
-23
@@ -429,34 +429,32 @@ describe('config defaults', () => {
|
||||
items: {
|
||||
engine: {
|
||||
enabled: true,
|
||||
permanent: false,
|
||||
priority: 50,
|
||||
},
|
||||
issues: {
|
||||
enabled: true,
|
||||
permanent: true,
|
||||
priority: 50,
|
||||
},
|
||||
resolution: {
|
||||
enabled: true,
|
||||
permanent: false,
|
||||
priority: 50,
|
||||
},
|
||||
severity: {
|
||||
enabled: true,
|
||||
permanent: false,
|
||||
priority: 50,
|
||||
},
|
||||
technology: {
|
||||
enabled: true,
|
||||
permanent: false,
|
||||
priority: 50,
|
||||
},
|
||||
title: {
|
||||
enabled: true,
|
||||
priority: 50,
|
||||
},
|
||||
problem_config_upgrade: {
|
||||
enabled: true,
|
||||
priority: 50,
|
||||
},
|
||||
problem_legacy_resource: {
|
||||
enabled: true,
|
||||
priority: 50,
|
||||
},
|
||||
problem_stream_not_loading: {
|
||||
enabled: true,
|
||||
permanent: false,
|
||||
priority: 50,
|
||||
},
|
||||
},
|
||||
@@ -537,6 +535,10 @@ describe('config defaults', () => {
|
||||
untrigger_delay_seconds: 0,
|
||||
untrigger_force_seconds: 0,
|
||||
},
|
||||
issues: {
|
||||
interaction_mode: 'all',
|
||||
retry_seconds: 'auto',
|
||||
},
|
||||
},
|
||||
});
|
||||
});
|
||||
@@ -828,6 +830,7 @@ describe('config defaults', () => {
|
||||
enabled: true,
|
||||
exclusive: false,
|
||||
expand: false,
|
||||
permanent: false,
|
||||
string: 'Intruder alert!',
|
||||
priority: 50,
|
||||
sufficient: false,
|
||||
@@ -838,6 +841,7 @@ describe('config defaults', () => {
|
||||
exclusive: false,
|
||||
expand: false,
|
||||
icon: 'mdi:cow',
|
||||
permanent: false,
|
||||
priority: 50,
|
||||
sufficient: false,
|
||||
},
|
||||
@@ -847,6 +851,7 @@ describe('config defaults', () => {
|
||||
exclusive: false,
|
||||
expand: false,
|
||||
image: 'https://my.site.com/status.png',
|
||||
permanent: false,
|
||||
priority: 50,
|
||||
sufficient: false,
|
||||
},
|
||||
@@ -1093,8 +1098,8 @@ describe('config defaults', () => {
|
||||
icon: 'mdi:alert',
|
||||
severity: 'high',
|
||||
},
|
||||
text: 'Something happened.',
|
||||
details: [{ text: 'Detail 1', icon: 'mdi:info' }],
|
||||
body: { text: 'Something happened.' },
|
||||
metadata: [{ text: 'Detail 1', icon: 'mdi:info' }],
|
||||
controls: [
|
||||
{
|
||||
icon: 'mdi:check',
|
||||
@@ -1191,6 +1196,7 @@ describe('config defaults', () => {
|
||||
enabled: true,
|
||||
exclusive: false,
|
||||
expand: false,
|
||||
permanent: false,
|
||||
string: 'Intruder alert!',
|
||||
priority: 50,
|
||||
sufficient: false,
|
||||
@@ -1201,6 +1207,7 @@ describe('config defaults', () => {
|
||||
exclusive: false,
|
||||
expand: false,
|
||||
icon: 'mdi:cow',
|
||||
permanent: false,
|
||||
priority: 50,
|
||||
sufficient: false,
|
||||
},
|
||||
@@ -1210,6 +1217,7 @@ describe('config defaults', () => {
|
||||
exclusive: false,
|
||||
expand: false,
|
||||
image: 'https://my.site.com/status.png',
|
||||
permanent: false,
|
||||
priority: 50,
|
||||
sufficient: false,
|
||||
},
|
||||
@@ -1225,6 +1233,7 @@ describe('config defaults', () => {
|
||||
enabled: true,
|
||||
exclusive: false,
|
||||
expand: false,
|
||||
permanent: false,
|
||||
string: 'Intruder alert!',
|
||||
priority: 50,
|
||||
sufficient: false,
|
||||
@@ -1235,6 +1244,7 @@ describe('config defaults', () => {
|
||||
exclusive: false,
|
||||
expand: false,
|
||||
icon: 'mdi:cow',
|
||||
permanent: false,
|
||||
priority: 50,
|
||||
sufficient: false,
|
||||
},
|
||||
@@ -1244,6 +1254,7 @@ describe('config defaults', () => {
|
||||
exclusive: false,
|
||||
expand: false,
|
||||
image: 'https://my.site.com/status.png',
|
||||
permanent: false,
|
||||
priority: 50,
|
||||
sufficient: false,
|
||||
},
|
||||
@@ -1413,7 +1424,7 @@ describe('should convert webrtc card PTZ to Advanced Camera Card PTZ', () => {
|
||||
});
|
||||
});
|
||||
|
||||
it('presets via presets sub-object', () => {
|
||||
it('should parse presets via presets sub-object', () => {
|
||||
expect(
|
||||
cameraConfigSchema.parse({
|
||||
ptz: {
|
||||
@@ -1457,7 +1468,7 @@ describe('should convert webrtc card PTZ to Advanced Camera Card PTZ', () => {
|
||||
);
|
||||
});
|
||||
|
||||
it('actions_left takes priority over data_left', () => {
|
||||
it('should prioritize actions_left over data_left', () => {
|
||||
const result = cameraConfigSchema.parse({
|
||||
ptz: {
|
||||
service: 'foo',
|
||||
@@ -1482,7 +1493,7 @@ describe('should convert webrtc card PTZ to Advanced Camera Card PTZ', () => {
|
||||
);
|
||||
});
|
||||
|
||||
it('data_home creates a home preset', () => {
|
||||
it('should create a home preset from data_home', () => {
|
||||
expect(
|
||||
cameraConfigSchema.parse({
|
||||
ptz: {
|
||||
@@ -1511,7 +1522,7 @@ describe('should convert webrtc card PTZ to Advanced Camera Card PTZ', () => {
|
||||
);
|
||||
});
|
||||
|
||||
it('data_home does not overwrite existing home preset', () => {
|
||||
it('should not overwrite existing home preset from data_home', () => {
|
||||
expect(
|
||||
cameraConfigSchema.parse({
|
||||
ptz: {
|
||||
@@ -1546,7 +1557,7 @@ describe('should convert webrtc card PTZ to Advanced Camera Card PTZ', () => {
|
||||
});
|
||||
|
||||
describe('should lazy evaluate schemas', () => {
|
||||
it('conditional picture element', () => {
|
||||
it('should parse conditional picture element', () => {
|
||||
expect(
|
||||
conditionalSchema.parse({
|
||||
type: 'conditional',
|
||||
@@ -1594,7 +1605,7 @@ describe('should lazy evaluate schemas', () => {
|
||||
});
|
||||
});
|
||||
|
||||
it('status bar actions', () => {
|
||||
it('should parse status bar actions', () => {
|
||||
const input = {
|
||||
action: 'fire-dom-event',
|
||||
advanced_camera_card_action: 'status_bar',
|
||||
@@ -1604,6 +1615,7 @@ describe('should lazy evaluate schemas', () => {
|
||||
enabled: true,
|
||||
exclusive: false,
|
||||
expand: false,
|
||||
permanent: false,
|
||||
priority: 50,
|
||||
sufficient: false,
|
||||
type: 'custom:advanced-camera-card-status-bar-string',
|
||||
@@ -1688,7 +1700,7 @@ it('media viewer should not support microphone based conditions', () => {
|
||||
});
|
||||
|
||||
describe('automations should require at least one action', () => {
|
||||
it('no action', () => {
|
||||
it('should handle no action', () => {
|
||||
expect(() =>
|
||||
createConfig({
|
||||
cameras: [{}],
|
||||
@@ -1697,7 +1709,7 @@ describe('automations should require at least one action', () => {
|
||||
).toThrowError(/Automations must include at least one action/);
|
||||
});
|
||||
|
||||
it('empty actions', () => {
|
||||
it('should handle empty actions', () => {
|
||||
expect(() =>
|
||||
createConfig({
|
||||
cameras: [{}],
|
||||
@@ -1706,7 +1718,7 @@ describe('automations should require at least one action', () => {
|
||||
).toThrowError(/Automations must include at least one action/);
|
||||
});
|
||||
|
||||
it('at least one action', () => {
|
||||
it('should handle at least one action', () => {
|
||||
expect(() =>
|
||||
createConfig({
|
||||
cameras: [{}],
|
||||
|
||||
@@ -1,34 +0,0 @@
|
||||
import { describe, expect, it } from 'vitest';
|
||||
import { hasHAConnectionStateChanged } from '../../src/ha/has-hass-connection-changed';
|
||||
import { createHASS } from '../test-utils';
|
||||
|
||||
describe('hasHAConnectionStateChanged', () => {
|
||||
it('returns false if both oldHass and newHass are undefined', () => {
|
||||
expect(hasHAConnectionStateChanged()).toBe(false);
|
||||
});
|
||||
|
||||
it('returns false if both oldHass and newHass are null', () => {
|
||||
expect(hasHAConnectionStateChanged(null, null)).toBe(false);
|
||||
});
|
||||
|
||||
it('returns false if both oldHass and newHass are the same object', () => {
|
||||
const hass = createHASS();
|
||||
expect(hasHAConnectionStateChanged(hass, hass)).toBe(false);
|
||||
});
|
||||
|
||||
it('returns false if both oldHass.connected and newHass.connected are the same', () => {
|
||||
const oldHass = createHASS();
|
||||
const newHass = createHASS();
|
||||
oldHass.connected = true;
|
||||
newHass.connected = true;
|
||||
expect(hasHAConnectionStateChanged(oldHass, newHass)).toBe(false);
|
||||
});
|
||||
|
||||
it('returns true if oldHass.connected and newHass.connected are different', () => {
|
||||
const oldHass = createHASS();
|
||||
const newHass = createHASS();
|
||||
oldHass.connected = true;
|
||||
newHass.connected = false;
|
||||
expect(hasHAConnectionStateChanged(oldHass, newHass)).toBe(true);
|
||||
});
|
||||
});
|
||||
@@ -14,12 +14,12 @@ describe('sideLoadHomeAssistantElements', () => {
|
||||
vi.unstubAllGlobals();
|
||||
});
|
||||
|
||||
it('returns true if all elements already registered', async () => {
|
||||
it('should return if all elements already registered', async () => {
|
||||
vi.mocked(customElements.get).mockResolvedValue(LitElement);
|
||||
expect(await sideLoadHomeAssistantElements()).toBe(true);
|
||||
await sideLoadHomeAssistantElements();
|
||||
});
|
||||
|
||||
it('returns false when the picture glance card cannot be found', async () => {
|
||||
it('should throw when the picture glance card cannot be found', async () => {
|
||||
vi.mocked(customElements.get).mockReturnValue(undefined);
|
||||
|
||||
const createCardElement = vi.fn();
|
||||
@@ -29,10 +29,10 @@ describe('sideLoadHomeAssistantElements', () => {
|
||||
}),
|
||||
});
|
||||
|
||||
expect(await sideLoadHomeAssistantElements()).toBe(false);
|
||||
await expect(sideLoadHomeAssistantElements()).rejects.toThrow();
|
||||
});
|
||||
|
||||
it('returns true when elements are loaded', async () => {
|
||||
it('should return when elements are loaded', async () => {
|
||||
vi.mocked(customElements.get).mockImplementation((name: string) => {
|
||||
if (name === 'hui-picture-glance-card') {
|
||||
const result = LitElement;
|
||||
@@ -50,7 +50,7 @@ describe('sideLoadHomeAssistantElements', () => {
|
||||
}),
|
||||
});
|
||||
|
||||
expect(await sideLoadHomeAssistantElements()).toBe(true);
|
||||
await sideLoadHomeAssistantElements();
|
||||
|
||||
expect(customElements.whenDefined).toHaveBeenCalledWith('hui-picture-glance-card');
|
||||
expect(createCardElement).toHaveBeenCalledWith({
|
||||
|
||||
+12
-5
@@ -1,4 +1,4 @@
|
||||
import { HassEntities, HassEntity } from 'home-assistant-js-websocket';
|
||||
import { HassEntities, HassEntity, STATE_RUNNING } from 'home-assistant-js-websocket';
|
||||
import { LitElement } from 'lit';
|
||||
import screenfull from 'screenfull';
|
||||
import { expect, vi } from 'vitest';
|
||||
@@ -40,14 +40,14 @@ import { HASSManager } from '../src/card-controller/hass/hass-manager';
|
||||
import { StateWatcherSubscriptionInterface } from '../src/card-controller/hass/state-watcher';
|
||||
import { InitializationManager } from '../src/card-controller/initialization-manager';
|
||||
import { InteractionManager } from '../src/card-controller/interaction-manager';
|
||||
import { IssueManager } from '../src/card-controller/issues/issue-manager';
|
||||
import { IssueStateManager } from '../src/card-controller/issues/state-manager';
|
||||
import { KeyboardStateManager } from '../src/card-controller/keyboard-state-manager';
|
||||
import { MediaLoadedInfoManager } from '../src/card-controller/media-info-manager';
|
||||
import { MediaPlayerManager } from '../src/card-controller/media-player-manager';
|
||||
import { MessageManager } from '../src/card-controller/message-manager';
|
||||
import { MicrophoneManager } from '../src/card-controller/microphone-manager';
|
||||
import { NotificationManager } from '../src/card-controller/notification-manager';
|
||||
import { PIPManager } from '../src/card-controller/pip-manager';
|
||||
import { ProblemManager } from '../src/card-controller/problems/manager';
|
||||
import { QueryStringManager } from '../src/card-controller/query-string-manager';
|
||||
import { StatusBarItemManager } from '../src/card-controller/status-bar-item-manager';
|
||||
import { StyleManager } from '../src/card-controller/style-manager';
|
||||
@@ -131,6 +131,10 @@ export const createHASS = (states?: HassEntities, user?: CurrentUser): HomeAssis
|
||||
hass.user = user;
|
||||
}
|
||||
hass.config.components = [];
|
||||
|
||||
// Default to a fully-started HA so existing tests that don't care about
|
||||
// startup state still represent a "ready" instance.
|
||||
hass.config.state = STATE_RUNNING;
|
||||
hass.connection.subscribeMessage = vi.fn();
|
||||
|
||||
// ha-nunjucks calls sendMessagePromise to fetch label registry; return empty array to prevent crash.
|
||||
@@ -678,11 +682,14 @@ export const createCardAPI = (): CardController => {
|
||||
api.getKeyboardStateManager.mockReturnValue(mock<KeyboardStateManager>());
|
||||
api.getMediaLoadedInfoManager.mockReturnValue(mock<MediaLoadedInfoManager>());
|
||||
api.getMediaPlayerManager.mockReturnValue(mock<MediaPlayerManager>());
|
||||
api.getMessageManager.mockReturnValue(mock<MessageManager>());
|
||||
api.getMicrophoneManager.mockReturnValue(mock<MicrophoneManager>());
|
||||
api.getNotificationManager.mockReturnValue(mock<NotificationManager>());
|
||||
api.getPIPManager.mockReturnValue(mock<PIPManager>());
|
||||
api.getProblemManager.mockReturnValue(mock<ProblemManager>());
|
||||
|
||||
const issueManager = mock<IssueManager>();
|
||||
issueManager.getStateManager.mockReturnValue(mock<IssueStateManager>());
|
||||
api.getIssueManager.mockReturnValue(issueManager);
|
||||
|
||||
api.getQueryStringManager.mockReturnValue(mock<QueryStringManager>());
|
||||
api.getStatusBarItemManager.mockReturnValue(mock<StatusBarItemManager>());
|
||||
api.getStyleManager.mockReturnValue(mock<StyleManager>());
|
||||
|
||||
@@ -360,7 +360,7 @@ describe('createSetReviewAction', () => {
|
||||
|
||||
describe('createNotificationAction', () => {
|
||||
it('should create notification action', () => {
|
||||
const notification = { text: 'test' };
|
||||
const notification = { body: { text: 'test' } };
|
||||
expect(createNotificationAction(notification)).toEqual({
|
||||
action: 'fire-dom-event',
|
||||
advanced_camera_card_action: 'notification',
|
||||
@@ -369,7 +369,7 @@ describe('createNotificationAction', () => {
|
||||
});
|
||||
|
||||
it('should create notification action with cardID', () => {
|
||||
const notification = { text: 'test' };
|
||||
const notification = { body: { text: 'test' } };
|
||||
expect(createNotificationAction(notification, { cardID: 'card_id' })).toEqual({
|
||||
action: 'fire-dom-event',
|
||||
advanced_camera_card_action: 'notification',
|
||||
|
||||
@@ -104,6 +104,7 @@ describe('getDiagnostics', () => {
|
||||
lang: 'en',
|
||||
ha_version: '2023.9.0',
|
||||
timezone: expect.anything(),
|
||||
issues: [],
|
||||
});
|
||||
});
|
||||
|
||||
@@ -148,26 +149,33 @@ describe('getDiagnostics', () => {
|
||||
date: now,
|
||||
lang: 'en',
|
||||
timezone: expect.anything(),
|
||||
issues: [],
|
||||
});
|
||||
});
|
||||
|
||||
it('should include problems in diagnostics', async () => {
|
||||
it('should include issues in diagnostics', async () => {
|
||||
const deviceRegistryManager = mock<DeviceRegistryManager>();
|
||||
deviceRegistryManager.getMatchingDevices.mockResolvedValue([]);
|
||||
|
||||
const problems = {
|
||||
config_upgrade: true,
|
||||
legacy_resource: false,
|
||||
};
|
||||
const issues = new Map([
|
||||
[
|
||||
'config_upgrade' as const,
|
||||
{
|
||||
icon: 'mdi:update',
|
||||
severity: 'medium' as const,
|
||||
notification: { body: { text: 'test' } },
|
||||
},
|
||||
],
|
||||
]);
|
||||
|
||||
const result = await getDiagnostics(
|
||||
hass,
|
||||
deviceRegistryManager,
|
||||
{ cameras: [{ camera_entity: 'camera.office' }] },
|
||||
problems,
|
||||
issues,
|
||||
);
|
||||
|
||||
expect(result.problems).toEqual(problems);
|
||||
expect(result.issues).toEqual(['config_upgrade']);
|
||||
});
|
||||
|
||||
it('should fetch diagnostics without device model', async () => {
|
||||
@@ -194,6 +202,7 @@ describe('getDiagnostics', () => {
|
||||
date: now,
|
||||
lang: 'en',
|
||||
timezone: expect.anything(),
|
||||
issues: [],
|
||||
});
|
||||
});
|
||||
});
|
||||
|
||||
@@ -0,0 +1,37 @@
|
||||
import { describe, expect, it } from 'vitest';
|
||||
import { AdvancedCameraCardError } from '../../src/types';
|
||||
import { getContextFromError } from '../../src/utils/error-context';
|
||||
|
||||
describe('getContextFromError', () => {
|
||||
it('should return the context for an AdvancedCameraCardError with an object context', () => {
|
||||
const error = new AdvancedCameraCardError('boom', { foo: 'bar' });
|
||||
expect(getContextFromError(error)).toEqual({ foo: 'bar' });
|
||||
});
|
||||
|
||||
it('should return null for an AdvancedCameraCardError without context', () => {
|
||||
const error = new AdvancedCameraCardError('boom');
|
||||
expect(getContextFromError(error)).toBeNull();
|
||||
});
|
||||
|
||||
it('should return null for an AdvancedCameraCardError with null context', () => {
|
||||
const error = new AdvancedCameraCardError('boom', null);
|
||||
expect(getContextFromError(error)).toBeNull();
|
||||
});
|
||||
|
||||
it('should return null for an AdvancedCameraCardError with non-object context', () => {
|
||||
const error = new AdvancedCameraCardError('boom', 'string context');
|
||||
expect(getContextFromError(error)).toBeNull();
|
||||
});
|
||||
|
||||
it('should return null for a plain Error', () => {
|
||||
expect(getContextFromError(new Error('plain'))).toBeNull();
|
||||
});
|
||||
|
||||
it('should return null for non-error values', () => {
|
||||
expect(getContextFromError('string')).toBeNull();
|
||||
expect(getContextFromError(42)).toBeNull();
|
||||
expect(getContextFromError(null)).toBeNull();
|
||||
expect(getContextFromError(undefined)).toBeNull();
|
||||
expect(getContextFromError({})).toBeNull();
|
||||
});
|
||||
});
|
||||
@@ -6,9 +6,8 @@ describe('Initializer', () => {
|
||||
const initializer = new Initializer();
|
||||
|
||||
expect(initializer.isInitialized('foo')).toBeFalsy();
|
||||
expect(
|
||||
await initializer.initializeIfNecessary('foo', async () => true),
|
||||
).toBeTruthy();
|
||||
|
||||
await initializer.initializeIfNecessary('foo', async () => {});
|
||||
expect(initializer.isInitialized('foo')).toBeTruthy();
|
||||
});
|
||||
|
||||
@@ -16,9 +15,7 @@ describe('Initializer', () => {
|
||||
const initializer = new Initializer();
|
||||
|
||||
expect(initializer.isInitialized('foo')).toBeFalsy();
|
||||
expect(
|
||||
await initializer.initializeIfNecessary('foo', async () => true),
|
||||
).toBeTruthy();
|
||||
await initializer.initializeIfNecessary('foo');
|
||||
expect(initializer.isInitialized('foo')).toBeTruthy();
|
||||
});
|
||||
|
||||
@@ -26,12 +23,8 @@ describe('Initializer', () => {
|
||||
const initializer = new Initializer();
|
||||
|
||||
expect(initializer.isInitialized('foo')).toBeFalsy();
|
||||
expect(
|
||||
await initializer.initializeIfNecessary('foo', async () => true),
|
||||
).toBeTruthy();
|
||||
expect(
|
||||
await initializer.initializeIfNecessary('foo', async () => true),
|
||||
).toBeTruthy();
|
||||
await initializer.initializeIfNecessary('foo', async () => {});
|
||||
await initializer.initializeIfNecessary('foo', async () => {});
|
||||
expect(initializer.isInitialized('foo')).toBeTruthy();
|
||||
});
|
||||
|
||||
@@ -39,9 +32,11 @@ describe('Initializer', () => {
|
||||
const initializer = new Initializer();
|
||||
|
||||
expect(initializer.isInitialized('foo')).toBeFalsy();
|
||||
expect(
|
||||
await initializer.initializeIfNecessary('foo', async () => false),
|
||||
).toBeFalsy();
|
||||
await expect(
|
||||
initializer.initializeIfNecessary('foo', async () => {
|
||||
throw new Error('test');
|
||||
}),
|
||||
).rejects.toThrow('test');
|
||||
expect(initializer.isInitialized('foo')).toBeFalsy();
|
||||
});
|
||||
|
||||
@@ -49,20 +44,20 @@ describe('Initializer', () => {
|
||||
const initializer = new Initializer();
|
||||
|
||||
expect(initializer.isInitializedMultiple(['foo', 'bar'])).toBeFalsy();
|
||||
expect(
|
||||
await initializer.initializeMultipleIfNecessary({
|
||||
foo: async () => true,
|
||||
bar: async () => false,
|
||||
await expect(
|
||||
initializer.initializeMultipleIfNecessary({
|
||||
foo: async () => {},
|
||||
bar: async () => {
|
||||
throw new Error('test');
|
||||
},
|
||||
}),
|
||||
).toBeFalsy();
|
||||
).rejects.toThrow('test');
|
||||
|
||||
expect(initializer.isInitializedMultiple(['foo', 'bar'])).toBeFalsy();
|
||||
|
||||
expect(
|
||||
await initializer.initializeMultipleIfNecessary({
|
||||
bar: async () => true,
|
||||
}),
|
||||
).toBeTruthy();
|
||||
await initializer.initializeMultipleIfNecessary({
|
||||
bar: async () => {},
|
||||
});
|
||||
|
||||
expect(initializer.isInitializedMultiple(['foo', 'bar'])).toBeTruthy();
|
||||
});
|
||||
|
||||
+28
-15
@@ -1,7 +1,6 @@
|
||||
import { describe, expect, it } from 'vitest';
|
||||
import { describe, expect, it, vi } from 'vitest';
|
||||
import { Capabilities } from '../../src/camera-manager/capabilities';
|
||||
import { AdvancedCameraCardView } from '../../src/config/schema/common/const';
|
||||
import { IMAGE_VIEW_ZOOM_TARGET_SENTINEL } from '../../src/const';
|
||||
import { PTZMovementType } from '../../src/types';
|
||||
import {
|
||||
getPTZTarget,
|
||||
@@ -9,6 +8,8 @@ import {
|
||||
ptzActionToCapabilityKey,
|
||||
} from '../../src/utils/ptz';
|
||||
import { QueryResults } from '../../src/view/query-results';
|
||||
import { IMAGE_VIEW_TARGET_ID_SENTINEL } from '../../src/view/target-id';
|
||||
import * as targetId from '../../src/view/target-id';
|
||||
import {
|
||||
TestViewMedia,
|
||||
createCameraManager,
|
||||
@@ -18,7 +19,7 @@ import {
|
||||
|
||||
describe('getPTZTarget', () => {
|
||||
describe('in a viewer view', () => {
|
||||
it('with media', () => {
|
||||
it('should return target with media', () => {
|
||||
const media = [new TestViewMedia({ id: 'media-id' })];
|
||||
const view = createView({
|
||||
view: 'media',
|
||||
@@ -30,14 +31,14 @@ describe('getPTZTarget', () => {
|
||||
});
|
||||
});
|
||||
|
||||
it('without media', () => {
|
||||
it('should return null without media', () => {
|
||||
const view = createView({
|
||||
view: 'media',
|
||||
});
|
||||
expect(getPTZTarget(view, { cameraManager: createCameraManager() })).toBeNull();
|
||||
});
|
||||
|
||||
it('with true PTZ restriction', () => {
|
||||
it('should return null with true PTZ restriction', () => {
|
||||
const media = [new TestViewMedia({ id: 'media-id' })];
|
||||
const view = createView({
|
||||
view: 'media',
|
||||
@@ -49,15 +50,15 @@ describe('getPTZTarget', () => {
|
||||
});
|
||||
});
|
||||
|
||||
it('in image view', () => {
|
||||
it('should return target in image view', () => {
|
||||
expect(getPTZTarget(createView({ view: 'image' }))).toEqual({
|
||||
targetID: IMAGE_VIEW_ZOOM_TARGET_SENTINEL,
|
||||
targetID: IMAGE_VIEW_TARGET_ID_SENTINEL,
|
||||
type: 'digital',
|
||||
});
|
||||
});
|
||||
|
||||
describe('in live view', () => {
|
||||
it('without restriction with true PTZ capability', () => {
|
||||
it('should return PTZ target without restriction with true PTZ capability', () => {
|
||||
const view = createView({
|
||||
view: 'live',
|
||||
camera: 'camera-1',
|
||||
@@ -75,7 +76,7 @@ describe('getPTZTarget', () => {
|
||||
});
|
||||
});
|
||||
|
||||
it('without restriction without true PTZ capability', () => {
|
||||
it('should return digital target without restriction without true PTZ capability', () => {
|
||||
const view = createView({
|
||||
view: 'live',
|
||||
camera: 'camera-1',
|
||||
@@ -87,7 +88,7 @@ describe('getPTZTarget', () => {
|
||||
});
|
||||
});
|
||||
|
||||
it('with truePTZ restriction without true PTZ capability', () => {
|
||||
it('should return null with truePTZ restriction without true PTZ capability', () => {
|
||||
const view = createView({
|
||||
view: 'live',
|
||||
camera: 'camera-1',
|
||||
@@ -98,7 +99,7 @@ describe('getPTZTarget', () => {
|
||||
).toBeNull();
|
||||
});
|
||||
|
||||
it('with digitalPTZ restriction with true PTZ capability', () => {
|
||||
it('should return digital target with digitalPTZ restriction with true PTZ capability', () => {
|
||||
const view = createView({
|
||||
view: 'live',
|
||||
camera: 'camera-1',
|
||||
@@ -121,7 +122,7 @@ describe('getPTZTarget', () => {
|
||||
});
|
||||
});
|
||||
|
||||
it('without cameraID', () => {
|
||||
it('should return null without cameraID', () => {
|
||||
const view = createView({
|
||||
view: 'live',
|
||||
camera: null,
|
||||
@@ -141,10 +142,22 @@ describe('getPTZTarget', () => {
|
||||
},
|
||||
);
|
||||
});
|
||||
|
||||
it('should return null for a view with a targetID that is not viewer, image, or live', () => {
|
||||
// Force getViewTargetID to return a non-null value so that the early-return
|
||||
// guard passes, then present a view that is none of viewer/image/live to
|
||||
// exercise the final return null branch at the end of getPTZTarget.
|
||||
vi.spyOn(targetId, 'getViewTargetID').mockReturnValue('some-target');
|
||||
const view = createView({ view: 'timeline' });
|
||||
|
||||
expect(getPTZTarget(view)).toBeNull();
|
||||
|
||||
vi.restoreAllMocks();
|
||||
});
|
||||
});
|
||||
|
||||
describe('hasCameraTruePTZ', () => {
|
||||
it('with true PTZ', () => {
|
||||
it('should return true with true PTZ', () => {
|
||||
const store = createStore([
|
||||
{
|
||||
cameraID: 'camera-1',
|
||||
@@ -155,12 +168,12 @@ describe('hasCameraTruePTZ', () => {
|
||||
expect(hasCameraTruePTZ(createCameraManager(store), 'camera-1')).toBeTruthy();
|
||||
});
|
||||
|
||||
it('without true PTZ', () => {
|
||||
it('should return false without true PTZ', () => {
|
||||
expect(hasCameraTruePTZ(createCameraManager(createStore()), 'camera-1')).toBeFalsy();
|
||||
});
|
||||
});
|
||||
|
||||
it('ptzActionToCapabilityKey', () => {
|
||||
it('should map ptzActionToCapabilityKey correctly', () => {
|
||||
expect(ptzActionToCapabilityKey('left')).toBe('left');
|
||||
expect(ptzActionToCapabilityKey('right')).toBe('right');
|
||||
expect(ptzActionToCapabilityKey('up')).toBe('up');
|
||||
|
||||
Reference in New Issue
Block a user