feat: Add hardened error handling and retries (#2451)
- Closes #1830 - Closes #2099
This commit is contained in:
committed by
dermotduffy
parent
4bc787e2b7
commit
47bcce93d3
@@ -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 () => {
|
||||
|
||||
Reference in New Issue
Block a user