From a36f75da40b2c8ac6f9dce25eb0d07992287ba0f Mon Sep 17 00:00:00 2001 From: Alex Sorafumo Date: Fri, 13 Nov 2026 19:10:31 +1100 Subject: [PATCH 1/5] test(common): cover cascade failures, settings saves, uploads and access races Replace mock-only locale, hotkey and interface tests with tests of the real services. Wait for locale strings in the cascade locale spec. Co-Authored-By: Claude Opus 5.5 --- src/tests/common/actions.spec.ts | 115 ++++------ src/tests/common/cascade-delete.spec.ts | 40 ++++ src/tests/common/cascade-locale.spec.ts | 4 +- src/tests/common/hotkeys.service.spec.ts | 26 +-- src/tests/common/item-group-switch.spec.ts | 48 ++++ src/tests/common/item.service.spec.ts | 249 +++++++++++++++++++++ src/tests/common/locale.service.spec.ts | 91 ++++---- src/tests/common/placeos.spec.ts | 37 --- src/tests/common/settings.spec.ts | 67 +++++- src/tests/common/support-access.spec.ts | 56 +++++ src/tests/common/uploads.spec.ts | 118 ++++++++++ 11 files changed, 684 insertions(+), 167 deletions(-) create mode 100644 src/tests/common/item.service.spec.ts create mode 100644 src/tests/common/uploads.spec.ts diff --git a/src/tests/common/actions.spec.ts b/src/tests/common/actions.spec.ts index 5bd9b83e2..aa5effaea 100644 --- a/src/tests/common/actions.spec.ts +++ b/src/tests/common/actions.spec.ts @@ -338,46 +338,50 @@ describe('actions.ts', () => { expect(client.addSystem).toHaveBeenCalled(); }); - it('should create modules for logic driver ids when adding systems', async () => { - vi.mocked(client.addSystem).mockReturnValueOnce( - Promise.resolve({ id: 'sys-new' } as any), - ); - vi.mocked(client.showDriver).mockImplementation((id: string) => - Promise.resolve({ - id, - name: `${id} name`, - module_name: `${id} module`, - role: - id === 'driver-logic' - ? client.PlaceDriverRole.Logic - : client.PlaceDriverRole.Device, - default_uri: '', - default_port: 1, - alert_level: 'medium', - ignore_connected: false, - } as any), - ); - - await ACTIONS.systems.save({ - name: 'New System', - support_url: '', - modules: ['mod-123', 'driver-logic', 'driver-device'], - } as any); - - expect(client.addSystem).toHaveBeenCalledWith( - expect.objectContaining({ modules: ['mod-123'] }), - ); - expect(client.showDriver).toHaveBeenCalledWith('driver-logic'); - expect(client.showDriver).toHaveBeenCalledWith('driver-device'); - expect(client.addModule).toHaveBeenCalledTimes(1); - expect(client.addModule).toHaveBeenCalledWith( - expect.objectContaining({ - driver_id: 'driver-logic', - control_system_id: 'sys-new', - role: client.PlaceDriverRole.Logic, - }), - ); - }); + it.each([ + ['an array', ['mod-123', 'driver-logic', 'driver-device']], + ['a JSON string', '["mod-123","driver-logic","driver-device"]'], + ['a CSV cell', "['mod-123', driver-logic driver-device]"], + ])( + 'should create modules for logic driver ids in %s when adding systems', + async (_, modules) => { + vi.mocked(client.addSystem).mockResolvedValueOnce({ + id: 'sys-new', + } as client.PlaceSystem); + vi.mocked(client.showDriver).mockImplementation( + async (id: string) => + ({ + id, + name: `${id} name`, + role: + id === 'driver-logic' + ? client.PlaceDriverRole.Logic + : client.PlaceDriverRole.Device, + default_port: 1, + }) as client.PlaceDriver, + ); + + await ACTIONS.systems.save({ + name: 'New System', + support_url: '', + modules, + } as unknown as client.PlaceSystem); + + expect(client.addSystem).toHaveBeenCalledWith( + expect.objectContaining({ modules: ['mod-123'] }), + ); + expect(client.showDriver).toHaveBeenCalledWith('driver-logic'); + expect(client.showDriver).toHaveBeenCalledWith('driver-device'); + expect(client.addModule).toHaveBeenCalledTimes(1); + expect(client.addModule).toHaveBeenCalledWith( + expect.objectContaining({ + driver_id: 'driver-logic', + control_system_id: 'sys-new', + role: client.PlaceDriverRole.Logic, + }), + ); + }, + ); it('should start systems after bulk add when requested', async () => { vi.mocked(client.addSystem).mockReturnValueOnce( @@ -623,39 +627,18 @@ describe('actions.ts', () => { ); }); - it('should process origin placeholder', () => { - const item = { + it('should process the page origin, host and pathname', () => { + ACTIONS.systems.save({ id: 'sys-123', - support_url: '{{origin}}/support', - } as any; - ACTIONS.systems.save(item); + support_url: '{{origin}}/help?host={{host}}&path={{pathname}}', + } as client.PlaceSystem); expect(client.updateSystem).toHaveBeenCalledWith( 'sys-123', expect.objectContaining({ - support_url: expect.stringContaining('/support'), + support_url: `${location.origin}/help?host=${location.host}&path=${location.pathname}`, }), ); }); - - it('should process host placeholder', () => { - const item = { - id: 'sys-123', - support_url: 'https://{{host}}/api', - } as any; - ACTIONS.systems.save(item); - - expect(client.updateSystem).toHaveBeenCalled(); - }); - - it('should process pathname placeholder', () => { - const item = { - id: 'sys-123', - support_url: 'path={{pathname}}', - } as any; - ACTIONS.systems.save(item); - - expect(client.updateSystem).toHaveBeenCalled(); - }); }); }); diff --git a/src/tests/common/cascade-delete.spec.ts b/src/tests/common/cascade-delete.spec.ts index 05e8c4a5e..6632dc5a8 100644 --- a/src/tests/common/cascade-delete.spec.ts +++ b/src/tests/common/cascade-delete.spec.ts @@ -664,5 +664,45 @@ describe('cascade-delete', () => { expect(outcome.failures[0].resource.id).toBe('sys-broken'); expect(outcome.skipped.map((_) => _.id)).toEqual(['zone-after']); }); + + it('lets running system removals finish after one fails and starts no more', async () => { + const removals = new Map< + string, + { resolve: () => void; reject: (error: Error) => void } + >(); + const systems = ['s1', 's2', 's3', 's4', 's5'].map((id) => ({ + resource: { type: 'system' as const, id, name: id }, + run: vi.fn( + () => + new Promise((resolve, reject) => + removals.set(id, { resolve, reject }), + ), + ), + })); + const zone = { + resource: { type: 'zone' as const, id: 'zone-1', name: 'zone' }, + run: vi.fn(() => Promise.resolve()), + }; + const running = runCascade({ + scope: [], + summary: [], + warnings: [], + steps: [...systems, zone], + }); + expect([...removals.keys()]).toEqual(['s1', 's2', 's3', 's4']); + removals.get('s1').reject(new Error('In use')); + await new Promise((resolve) => setTimeout(resolve)); + expect(systems[4].run).not.toHaveBeenCalled(); + for (const id of ['s2', 's3', 's4']) removals.get(id).resolve(); + const outcome = await running; + expect(zone.run).not.toHaveBeenCalled(); + expect(outcome.removed.map((_) => _.id)).toEqual([ + 's2', + 's3', + 's4', + ]); + expect(outcome.failures.map((_) => _.resource.id)).toEqual(['s1']); + expect(outcome.skipped.map((_) => _.id)).toEqual(['s5', 'zone-1']); + }); }); }); diff --git a/src/tests/common/cascade-locale.spec.ts b/src/tests/common/cascade-locale.spec.ts index c1af27dbf..163a8fca0 100644 --- a/src/tests/common/cascade-locale.spec.ts +++ b/src/tests/common/cascade-locale.spec.ts @@ -1,4 +1,4 @@ -import { describe, expect, it, vi } from 'vitest'; +import { beforeAll, describe, expect, it, vi } from 'vitest'; vi.mock('@placeos/ts-client', () => ({ showMetadata: vi.fn(() => ({ @@ -19,6 +19,8 @@ describe('cascade locale strings', () => { const locale = new LocaleService(); const get = (key: string, count: number) => locale.get(key, { count }, count); + // The fallback translations load lazily + beforeAll(() => locale.ready); it.each([ ['CASCADE.SCOPE_ZONES', 1, 'Scope: this zone and 1 zone beneath it.'], diff --git a/src/tests/common/hotkeys.service.spec.ts b/src/tests/common/hotkeys.service.spec.ts index 6501bd5d8..883811c48 100644 --- a/src/tests/common/hotkeys.service.spec.ts +++ b/src/tests/common/hotkeys.service.spec.ts @@ -94,25 +94,15 @@ describe('HotkeysService', () => { }); describe('key mapping', () => { - it('should map AltLeft to alt', () => { + it('fires a combination registered in upper case with a left modifier when the right one is held', () => { const callback = vi.fn(); - // Both should work as they map to the same key - const sub1 = service.listen(['altleft', 'keyk'], callback); - const sub2 = service.listen(['alt', 'keyk'], callback); - expect(sub1).toBeTruthy(); - expect(sub2).toBeTruthy(); - sub1?.unsubscribe(); - sub2?.unsubscribe(); - }); - - it('should handle case insensitivity', () => { - const callback = vi.fn(); - const sub1 = service.listen('ALT+KEYK', callback); - const sub2 = service.listen('alt+keyk', callback); - expect(sub1).toBeTruthy(); - expect(sub2).toBeTruthy(); - sub1?.unsubscribe(); - sub2?.unsubscribe(); + const subscription = service.listen('ALTLEFT+KEYK', callback); + keyEvent('keydown', 'AltRight', { altKey: true }); + keyEvent('keydown', 'KeyK', { altKey: true }); + keyEvent('keyup', 'KeyK', { altKey: true }); + keyEvent('keyup', 'AltRight'); + expect(callback).toHaveBeenCalledTimes(1); + subscription?.unsubscribe(); }); }); diff --git a/src/tests/common/item-group-switch.spec.ts b/src/tests/common/item-group-switch.spec.ts index 5e2caa115..7daed6851 100644 --- a/src/tests/common/item-group-switch.spec.ts +++ b/src/tests/common/item-group-switch.spec.ts @@ -243,3 +243,51 @@ it('shows a saved item with its current settings', async () => { expect(settingsValue()).toBe('a: 2'); service.ngOnDestroy(); }); + +it('keeps the latest item when an older detail response arrives last', async () => { + vi.useFakeTimers(); + mocks.query.mockResolvedValue({ data: [], total: 0, next: null }); + const responses = new Map< + string, + (item: { id: string; name: string }) => void + >(); + mocks.show.mockImplementation( + (id: string) => new Promise((resolve) => responses.set(id, resolve)), + ); + const user = signal({ sys_admin: false, support: false }); + TestBed.configureTestingModule({ + providers: [ + ActiveItemService, + { + provide: Router, + useValue: { + url: '/systems/-', + events: new Subject(), + parseUrl: (url: string) => + new DefaultUrlSerializer().parse(url), + }, + }, + { provide: Dialog, useValue: {} }, + { provide: SettingsService, useValue: {} }, + { + provide: HotkeysService, + useValue: { listen: () => () => undefined }, + }, + { + provide: BackofficeUsersService, + useValue: { user, current: user }, + }, + ], + }); + const service = TestBed.inject(ActiveItemService); + await vi.advanceTimersByTimeAsync(350); + const first = service.setItem('sys-1'); + const second = service.setItem('sys-2'); + await vi.advanceTimersByTimeAsync(1); + responses.get('sys-2')({ id: 'sys-2', name: 'Second' }); + await second; + responses.get('sys-1')({ id: 'sys-1', name: 'First' }); + await first; + expect(service.active_item?.id).toBe('sys-2'); + service.ngOnDestroy(); +}); diff --git a/src/tests/common/item.service.spec.ts b/src/tests/common/item.service.spec.ts new file mode 100644 index 000000000..6c7978658 --- /dev/null +++ b/src/tests/common/item.service.spec.ts @@ -0,0 +1,249 @@ +import { Dialog } from '@angular/cdk/dialog'; +import { signal } from '@angular/core'; +import { TestBed } from '@angular/core/testing'; +import { DefaultUrlSerializer, NavigationEnd, Router } from '@angular/router'; +import { PlaceDomain, PlaceGroup, PlaceUser } from '@placeos/ts-client'; +import { Subject } from 'rxjs'; +import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'; +import { CascadePlan } from '../../app/common/cascade-delete'; +import { HotkeysService } from '../../app/common/hotkeys.service'; +import { ActiveItemService } from '../../app/common/item.service'; +import { notifyError } from '../../app/common/notifications'; +import { SettingsService } from '../../app/common/settings.service'; +import { loadSupportAccess } from '../../app/common/support-access'; +import { DialogEvent } from '../../app/common/types'; +import type { + ConfirmModalData, + ConfirmModalResult, +} from '../../app/overlays/confirm-modal.component'; +import { BackofficeUsersService } from '../../app/users/users.service'; + +const mocks = vi.hoisted(() => ({ + remove: vi.fn(), + plan: vi.fn(), + current_groups: vi.fn(), + query_groups: vi.fn(), +})); +vi.mock('@placeos/ts-client', async () => ({ + ...(await vi.importActual( + '@placeos/ts-client/dist/index.es.js', + )), + currentGroups: mocks.current_groups, + queryGroups: mocks.query_groups, +})); +vi.mock('../../app/common/actions', () => { + const query = () => Promise.resolve({ data: [], total: 0, next: null }); + return { + ACTIONS: { + systems: { name: 'SYSTEMS', query }, + domains: { + name: 'DOMAINS', + query, + remove: mocks.remove, + cascade: { + label: 'DOMAINS.DELETE_CASCADE', + description: 'DOMAINS.DELETE_CASCADE_DESC', + resource_type: 'domain', + plan: mocks.plan, + }, + }, + }, + }; +}); +vi.mock('../../app/users/users.service', () => ({ + BackofficeUsersService: class {}, +})); +vi.mock('../../app/common/hotkeys.service', () => ({ + HotkeysService: class {}, +})); +vi.mock('../../app/common/settings.service', () => ({ + SettingsService: class {}, +})); +vi.mock('../../app/common/notifications', () => ({ + notifyError: vi.fn(), + notifySuccess: vi.fn(), +})); + +/** Confirm modal reference with the fields the delete flow writes to */ +const confirmRef = () => ({ + componentInstance: { + event: new Subject(), + loading: signal(''), + result: signal(null), + disableClose: vi.fn(), + enableClose: vi.fn(), + }, + close: vi.fn(), +}); + +const item = new PlaceDomain({ id: 'domain-1', name: 'Campus' }); +const user = signal>({ sys_admin: true }); +const router_events = new Subject(); +const router = { + url: '/domains/-', + events: router_events, + parseUrl: (url: string) => new DefaultUrlSerializer().parse(url), + navigate: vi.fn(async () => true), +}; +let ref = confirmRef(); +const dialog = { + open: vi.fn( + (_component: unknown, _config: { data: ConfirmModalData }) => ref, + ), +}; +let service: ActiveItemService; + +/** Open the list of a section, as a router navigation does */ +const openSection = (section: string) => { + router.url = `/${section}/-`; + router_events.next(new NavigationEnd(1, router.url, router.url)); +}; + +beforeEach(async () => { + vi.useFakeTimers(); + vi.clearAllMocks(); + ref = confirmRef(); + user.set({ sys_admin: true }); + router.url = '/domains/-'; + TestBed.configureTestingModule({ + providers: [ + ActiveItemService, + { provide: Router, useValue: router }, + { provide: Dialog, useValue: dialog }, + { provide: SettingsService, useValue: {} }, + { + provide: HotkeysService, + useValue: { listen: () => () => undefined }, + }, + { + provide: BackofficeUsersService, + useValue: { user, current: user }, + }, + ], + }); + service = TestBed.inject(ActiveItemService); + await vi.advanceTimersByTimeAsync(350); +}); + +afterEach(() => { + service.ngOnDestroy(); + vi.clearAllTimers(); + vi.useRealTimers(); +}); + +describe('cascade delete', () => { + /** Cascade step that removes `id`, or fails with `error` */ + const step = (type: 'system' | 'zone', id: string, error?: Error) => ({ + resource: { type, id, name: id }, + run: async () => { + if (error) throw error; + }, + }); + const confirm = () => + ref.componentInstance.event.next({ + reason: 'done', + metadata: { options: { cascade: true } }, + }); + + beforeEach(() => service.replaceItem(item)); + + it('keeps the item and lists removed, failed and skipped resources when a step fails', async () => { + mocks.plan.mockResolvedValue({ + scope: [], + summary: [], + warnings: [], + steps: [ + step('system', 'sys-1'), + step('zone', 'zone-1', new Error('In use')), + step('zone', 'zone-2'), + ], + } satisfies CascadePlan); + await service.delete(); + await dialog.open.mock.calls[0][1].data.options[0].details(); + confirm(); + await vi.advanceTimersByTimeAsync(0); + expect(mocks.remove).not.toHaveBeenCalled(); + expect(service.active_item).toBe(item); + expect(ref.componentInstance.result()).toEqual({ + title: 'CASCADE.RECEIPT_PARTIAL_TITLE', + items: [ + { type: 'CASCADE.TYPE_SYSTEM', id: 'sys-1', name: 'sys-1' }, + ], + failed: [ + { type: 'CASCADE.TYPE_ZONE', id: 'zone-1', name: 'zone-1' }, + ], + skipped: [ + { type: 'CASCADE.TYPE_ZONE', id: 'zone-2', name: 'zone-2' }, + ], + note: 'CASCADE.RECEIPT_PARTIAL_NOTE', + }); + expect(notifyError).toHaveBeenCalledExactlyOnceWith('CASCADE.FAILED'); + }); + + it('removes nothing when the cascade is confirmed before its plan resolves', async () => { + await service.delete(); + confirm(); + await vi.advanceTimersByTimeAsync(0); + expect(mocks.remove).not.toHaveBeenCalled(); + expect(service.active_item).toBe(item); + expect(notifyError).toHaveBeenCalledExactlyOnceWith( + 'CASCADE.PLAN_UNAVAILABLE', + ); + }); +}); + +describe('edit permissions', () => { + const support_group = (permissions: number) => ({ + group: new PlaceGroup({ + id: 'group-1', + name: 'Support', + subsystems: ['support'], + }), + permissions, + }); + + // `allowed` is whether each can change systems, then domains + it.each([ + { + role: 'admins', + account: { sys_admin: true }, + groups: [], + allowed: [true, true], + }, + { + role: 'support users', + account: { support: true }, + groups: [support_group(2)], + allowed: [false, false], + }, + { + role: 'subsystem users', + account: {}, + groups: [support_group(2)], + allowed: [true, false], + }, + { + role: 'read-only subsystem users', + account: {}, + groups: [support_group(1)], + allowed: [false, false], + }, + ])( + 'limits $role to the sections they can change', + async ({ account, groups, allowed }) => { + mocks.current_groups.mockResolvedValue(groups); + mocks.query_groups.mockResolvedValue({ + data: [], + total: 0, + next: null, + }); + await loadSupportAccess(new PlaceUser(account)); + user.set(account); + const result = ['systems', 'domains'].map((section) => { + openSection(section); + return service.canMutate(2); + }); + expect(result).toEqual(allowed); + }, + ); +}); diff --git a/src/tests/common/locale.service.spec.ts b/src/tests/common/locale.service.spec.ts index 57a48e011..86502b2ab 100644 --- a/src/tests/common/locale.service.spec.ts +++ b/src/tests/common/locale.service.spec.ts @@ -1,4 +1,6 @@ -import { afterEach, describe, expect, it, vi } from 'vitest'; +import type { PlaceMetadata } from '@placeos/ts-client'; +import { showMetadata } from '@placeos/ts-client'; +import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'; // Mock @placeos/ts-client vi.mock('@placeos/ts-client', () => ({ @@ -163,52 +165,53 @@ describe('setTranslationService', () => { }); }); -describe('LocaleService behavior patterns', () => { - it('should handle translation with variable replacement', () => { - const mock_service = { - get: vi.fn((key, args) => { - let value = 'Welcome {{ name }}'; - for (const id in args) { - value = value.replace(`{{ ${id} }}`, `${args[id]}`); - } - return value; - }), - }; - setTranslationService(mock_service as any); - - const result = i18n('welcome', { name: 'Alice' }); - expect(result).toBe('Welcome Alice'); - }); - - it('should handle multiple variable replacements', () => { - const mock_service = { - get: vi.fn((key, args) => { - let value = '{{ user }} has {{ count }} messages'; - for (const id in args) { - value = value.replace(`{{ ${id} }}`, `${args[id]}`); - } - return value; - }), - }; - setTranslationService(mock_service as any); +describe('LocaleService translations', () => { + /** Serve `data` as the locale file */ + const stubLocaleFile = (data: object) => + vi.stubGlobal( + 'fetch', + vi.fn(() => + Promise.resolve({ + ok: true, + json: () => Promise.resolve(data), + }), + ), + ); - const result = i18n('messages', { user: 'Bob', count: 5 }); - expect(result).toBe('Bob has 5 messages'); + beforeEach(() => localStorage.clear()); + afterEach(() => { + vi.unstubAllGlobals(); + localStorage.clear(); + }); + + it('fills in arguments and picks plural forms from the locale file', async () => { + stubLocaleFile({ + INBOX: { + WELCOME: 'Bonjour {{ name }}', + ITEMS_1: '{{ count }} élément', + ITEMS_N: '{{ count }} éléments', + }, + }); + const service = new LocaleService(); + await service.setLocale('fr'); + expect(service.get('INBOX.WELCOME', { name: 'Alex' })).toBe( + 'Bonjour Alex', + ); + expect(service.get('INBOX.ITEMS', { count: 1 }, 1)).toBe('1 élément'); + expect(service.get('INBOX.ITEMS', { count: 5 }, 5)).toBe('5 éléments'); }); - it('should handle plural forms', () => { - const mock_service = { - get: vi.fn((key, args, plural) => { - if (plural === 1) return '1 item'; - if (plural > 1) return `${plural} items`; - return '0 items'; - }), - }; - setTranslationService(mock_service as any); - - expect(i18n('items', {}, 0)).toBe('0 items'); - expect(i18n('items', {}, 1)).toBe('1 item'); - expect(i18n('items', {}, 5)).toBe('5 items'); + it('lets zone metadata replace matching strings and keeps the others', async () => { + stubLocaleFile({ INBOX: { WELCOME: 'Bonjour', LEAVE: 'Au revoir' } }); + vi.mocked(showMetadata).mockResolvedValueOnce({ + details: { INBOX: { WELCOME: 'Salut' } }, + } as Partial as PlaceMetadata); + const service = new LocaleService(); + service.zone_id = 'zone-1'; + await service.setLocale('fr'); + expect(showMetadata).toHaveBeenCalledWith('zone-1', 'locale_fr'); + expect(service.get('INBOX.WELCOME')).toBe('Salut'); + expect(service.get('INBOX.LEAVE')).toBe('Au revoir'); }); }); diff --git a/src/tests/common/placeos.spec.ts b/src/tests/common/placeos.spec.ts index 5a6b02279..ec9ee7361 100644 --- a/src/tests/common/placeos.spec.ts +++ b/src/tests/common/placeos.spec.ts @@ -229,41 +229,4 @@ describe('placeos.ts', () => { expect(typeof result.then).toBe('function'); }); }); - - describe('PlaceSettings interface', () => { - it('should accept all required properties', () => { - const settings: PlaceSettings = { - protocol: 'https:', - domain: 'example.com', - port: 443, - route: '/app', - use_domain: true, - local_login: false, - mock: false, - }; - - expect(settings.protocol).toBe('https:'); - expect(settings.domain).toBe('example.com'); - expect(settings.port).toBe(443); - expect(settings.route).toBe('/app'); - expect(settings.use_domain).toBe(true); - expect(settings.local_login).toBe(false); - expect(settings.mock).toBe(false); - }); - - it('should accept optional ignore_api_key', () => { - const settings: PlaceSettings = { - protocol: 'http:', - domain: 'localhost', - port: 4200, - route: '', - use_domain: false, - local_login: true, - mock: true, - ignore_api_key: true, - }; - - expect(settings.ignore_api_key).toBe(true); - }); - }); }); diff --git a/src/tests/common/settings.spec.ts b/src/tests/common/settings.spec.ts index 639b8c20d..902e073e2 100644 --- a/src/tests/common/settings.spec.ts +++ b/src/tests/common/settings.spec.ts @@ -41,7 +41,8 @@ vi.mock('../../app/common/general', () => ({ log: vi.fn(), })); -import { showMetadata } from '@placeos/ts-client'; +import type { PlaceMetadata } from '@placeos/ts-client'; +import { showMetadata, updateMetadata } from '@placeos/ts-client'; import { log } from '../../app/common/general'; import { DEFAULT_SETTINGS } from '../../app/common/settings'; @@ -340,3 +341,67 @@ describe('SettingsService', () => { }); }); }); + +describe('SettingsService saving', () => { + let service: SettingsService; + + beforeEach(async () => { + vi.useFakeTimers(); + // A saved theme stops `init()` saving the OS theme as a change + vi.mocked(showMetadata).mockResolvedValueOnce({ + details: { theme: 'dark', columns: 3 }, + } as Partial as PlaceMetadata); + TestBed.configureTestingModule({ + providers: [ + SettingsService, + { + provide: Title, + useValue: { getTitle: () => '', setTitle: vi.fn() }, + }, + ], + }); + service = TestBed.inject(SettingsService); + await vi.advanceTimersByTimeAsync(0); + }); + + afterEach(() => { + service.ngOnDestroy(); + vi.clearAllMocks(); + vi.useRealTimers(); + }); + + it('saves every change with the loaded settings after the delay', async () => { + service.saveUserSetting('compact', true); + service.saveUserSetting('page_size', 50); + await vi.advanceTimersByTimeAsync(4999); + expect(updateMetadata).not.toHaveBeenCalled(); + await vi.advanceTimersByTimeAsync(1); + expect(updateMetadata).toHaveBeenCalledExactlyOnceWith('user-123', { + name: 'settings', + description: '', + details: { + theme: 'dark', + columns: 3, + compact: true, + page_size: 50, + }, + }); + }); + + it('saves the newer value of a setting after a failed save', async () => { + let failSave: (error: Error) => void; + vi.mocked(updateMetadata).mockReturnValueOnce( + new Promise((_, reject) => (failSave = reject)), + ); + service.saveUserSetting('columns', 4); + await vi.advanceTimersByTimeAsync(5000); + service.saveUserSetting('columns', 5); + failSave(new Error('Offline')); + await vi.advanceTimersByTimeAsync(5000); + expect(updateMetadata).toHaveBeenCalledTimes(2); + expect(updateMetadata).toHaveBeenLastCalledWith( + 'user-123', + expect.objectContaining({ details: { theme: 'dark', columns: 5 } }), + ); + }); +}); diff --git a/src/tests/common/support-access.spec.ts b/src/tests/common/support-access.spec.ts index 30a4cdae9..3efc4e964 100644 --- a/src/tests/common/support-access.spec.ts +++ b/src/tests/common/support-access.spec.ts @@ -4,6 +4,7 @@ import { canAccessSection, canUseSupportAction, clearSupportModuleCache, + hasSupportRole, hasSupportSubsystem, isSubsystemUser, loadSupportAccess, @@ -121,6 +122,35 @@ describe('support subsystem access', () => { }); }); + it('keeps the latest user access when an earlier admin group list arrives late', async () => { + let resolveAdminGroups: (page: { + data: PlaceGroup[]; + total: number; + next: null; + }) => void; + api.queryGroups.mockReturnValueOnce( + new Promise((resolve) => (resolveAdminGroups = resolve)), + ); + await loadSupportAccess( + new PlaceUser({ id: 'admin', sys_admin: true }), + ); + api.currentGroups.mockResolvedValue([ + membership(1, 'support', 'group-2'), + ]); + await loadSupportAccess(new PlaceUser({ id: 'user-2' })); + resolveAdminGroups({ + data: [membership(1).group], + total: 1, + next: null, + }); + await new Promise((resolve) => setTimeout(resolve)); + expect(hasSupportRole()).toBe(false); + expect(support_groups().map(({ group }) => group.id)).toEqual([ + 'group-2', + ]); + expect(selected_support_group_id()).toBe('group-2'); + }); + it('returns an empty zone list without an unscoped request when there are no readable groups', async () => { api.currentGroups.mockResolvedValue([membership(64)]); await loadSupportAccess(new PlaceUser()); @@ -240,6 +270,32 @@ describe('selected support group', () => { }); }); + it('lists modules from readable systems when another system has no read grant', async () => { + api.currentGroups.mockResolvedValue([membership(1)]); + await loadSupportAccess(new PlaceUser()); + api.querySystems.mockResolvedValue({ + data: [{ id: 'sys-1' }, { id: 'sys-2' }], + total: 2, + next: null, + }); + api.queryModules.mockImplementation( + async ({ control_system_id }: { control_system_id: string }) => { + if (control_system_id === 'sys-1') { + throw Object.assign(new Error('Forbidden'), { + status: 403, + }); + } + return { + data: [{ id: 'mod-2', name: 'Light' }], + total: 1, + next: null, + }; + }, + ); + const result = await querySupportModules({}); + expect(result.data.map(({ id }) => id)).toEqual(['mod-2']); + }); + it('walks the group systems once for every search on the same group', async () => { api.currentGroups.mockResolvedValue([membership(1)]); await loadSupportAccess(new PlaceUser()); diff --git a/src/tests/common/uploads.spec.ts b/src/tests/common/uploads.spec.ts new file mode 100644 index 000000000..dc960a7f0 --- /dev/null +++ b/src/tests/common/uploads.spec.ts @@ -0,0 +1,118 @@ +import { Dialog } from '@angular/cdk/dialog'; +import { TestBed } from '@angular/core/testing'; +import type { + ChunkedUpload, + ChunkedUploadOptions, + ChunkedUploadState, +} from '@placeos/cloud-uploads'; +import { BehaviorSubject, of } from 'rxjs'; +import { beforeEach, describe, expect, it, vi } from 'vitest'; +import { uploadFile } from '../../app/common/uploads'; +import { UploadsService } from '../../app/common/uploads.service'; + +const mocks = vi.hoisted(() => ({ + token: vi.fn(() => 'token-0'), + initUploads: vi.fn(), + uploadNewFile: + vi.fn< + ( + file: File, + options?: ChunkedUploadOptions, + ) => Promise + >(), +})); +vi.mock('@placeos/cloud-uploads', () => ({ + humanReadableByteCount: (size: number) => `${size} B`, + initUploads: mocks.initUploads, + uploadFile: mocks.uploadNewFile, +})); +vi.mock('@placeos/ts-client', async () => ({ + ...(await vi.importActual( + '@placeos/ts-client/dist/index.es.js', + )), + token: mocks.token, +})); +vi.mock('../../app/ui/upload-permissions-modal.component', () => ({ + UploadPermissionsModalComponent: class {}, +})); + +const file = new File(['floor plan'], 'plan.svg'); +const uploading: ChunkedUploadState = { + status: 'UPLOADING', + completed: [], + pending_complete: [], + working: [], + progress: 10, +}; + +/** Upload whose state the test drives */ +const fakeUpload = () => { + const state = new BehaviorSubject(uploading); + return { id: 'upload-1', state } as Partial as ChunkedUpload; +}; + +beforeEach(() => { + vi.clearAllMocks(); + localStorage.clear(); +}); + +describe('uploadFile', () => { + it.each([ + { + status: 'FAILED', + errors: [[expect.objectContaining({ error: 'Upload failed' })]], + completions: 0, + }, + { status: 'COMPLETED', errors: [], completions: 1 }, + ] as const)( + 'stops listening once the upload is $status', + async ({ status, errors, completions }) => { + const upload = fakeUpload(); + mocks.uploadNewFile.mockResolvedValue(upload); + const next = vi.fn(); + const error = vi.fn(); + const complete = vi.fn(); + uploadFile(file).subscribe(next, error, complete); + await vi.waitFor(() => expect(next).toHaveBeenCalled()); + upload.state.next({ ...uploading, status, progress: 100 }); + expect(error.mock.calls).toEqual(errors); + expect(complete).toHaveBeenCalledTimes(completions); + expect(upload.state.observed).toBe(false); + }, + ); + + it('starts the upload service again when the PlaceOS token changes', async () => { + mocks.uploadNewFile.mockResolvedValue(fakeUpload()); + for (const token of ['token-1', 'token-1', 'token-2']) { + mocks.token.mockReturnValue(token); + uploadFile(file).subscribe(vi.fn()); + } + await vi.waitFor(() => + expect(mocks.uploadNewFile).toHaveBeenCalledTimes(3), + ); + expect(mocks.initUploads.mock.calls.map(([_]) => _.token)).toEqual([ + 'token-1', + 'token-2', + ]); + }); +}); + +describe('UploadsService', () => { + it('rejects without uploading when the permissions dialog closes without a choice', async () => { + TestBed.configureTestingModule({ + providers: [ + UploadsService, + { + provide: Dialog, + useValue: { open: () => ({ closed: of(undefined) }) }, + }, + ], + }); + const service = TestBed.inject(UploadsService); + await expect(service.uploadFileWithPermissions(file)).rejects.toThrow( + 'Upload cancelled', + ); + expect(mocks.uploadNewFile).not.toHaveBeenCalled(); + expect(service.upload_list()).toEqual([]); + }); +}); From d6f5f3021e530865b1e63f1e520cd0f6e78d9ba4 Mon Sep 17 00:00:00 2001 From: Alex Sorafumo Date: Fri, 13 Nov 2026 19:10:31 +1100 Subject: [PATCH 2/5] test(admin): cover imports, stored secrets, embed messages and upload polling Co-Authored-By: Claude Opus 5.5 --- src/tests/admin/admin-data.service.spec.ts | 31 +++++ .../admin/api-key-modal.component.spec.ts | 61 ++++++++++ .../admin/cluster-task-list.component.spec.ts | 55 +++++++++ .../admin/database-details.component.spec.ts | 95 ++++++++++++++- src/tests/admin/edge.component.spec.ts | 42 +++++++ src/tests/admin/extensions.component.spec.ts | 109 ++++++++++++++++++ .../admin/resource-imports.component.spec.ts | 78 +++++++++++++ ...ignage-ai-provider-modal.component.spec.ts | 24 ++++ src/tests/admin/signage-ai.component.spec.ts | 5 +- src/tests/admin/signage-ai.fn.spec.ts | 5 - .../signage-plugin-embed.component.spec.ts | 38 +++++- ...nage-plugin-import-modal.component.spec.ts | 46 ++++++++ .../staff-tenant-modal.component.spec.ts | 47 +++++++- .../storage-provider-modal.component.spec.ts | 53 +++++++++ src/tests/admin/storage.fn.spec.ts | 6 - .../admin/upload-library.component.spec.ts | 80 +++++++++++++ 16 files changed, 760 insertions(+), 15 deletions(-) create mode 100644 src/tests/admin/admin-data.service.spec.ts create mode 100644 src/tests/admin/api-key-modal.component.spec.ts create mode 100644 src/tests/admin/cluster-task-list.component.spec.ts create mode 100644 src/tests/admin/edge.component.spec.ts create mode 100644 src/tests/admin/extensions.component.spec.ts create mode 100644 src/tests/admin/resource-imports.component.spec.ts create mode 100644 src/tests/admin/signage-plugin-import-modal.component.spec.ts create mode 100644 src/tests/admin/storage-provider-modal.component.spec.ts create mode 100644 src/tests/admin/upload-library.component.spec.ts diff --git a/src/tests/admin/admin-data.service.spec.ts b/src/tests/admin/admin-data.service.spec.ts new file mode 100644 index 000000000..7c0e6d199 --- /dev/null +++ b/src/tests/admin/admin-data.service.spec.ts @@ -0,0 +1,31 @@ +import { PlaceDomain, authority, queryDomains } from '@placeos/ts-client'; +import { describe, expect, it, vi } from 'vitest'; +import { AdminDataService } from '../../app/admin/admin-data.service'; + +vi.mock('@placeos/ts-client', () => ({ + authority: vi.fn(), + queryDomains: vi.fn(), +})); + +describe('AdminDataService', () => { + it('keeps a domain picked while the domain list is loading', async () => { + type DomainPage = Awaited>; + const current = { id: 'domain-1' } as PlaceDomain; + const picked = { id: 'domain-2' } as PlaceDomain; + let resolveDomains: (page: DomainPage) => void; + vi.mocked(queryDomains).mockReturnValue( + new Promise((resolve) => (resolveDomains = resolve)), + ); + vi.mocked(authority).mockReturnValue({ id: 'domain-1' } as ReturnType< + typeof authority + >); + const service = new AdminDataService(); + + const result = service.selectDefaultDomain('zones'); + service.setDomain('zones', picked); + resolveDomains({ data: [current, picked] } as DomainPage); + + expect(await result).toBe(picked); + expect(service.selectedDomain('zones')()).toBe(picked); + }); +}); diff --git a/src/tests/admin/api-key-modal.component.spec.ts b/src/tests/admin/api-key-modal.component.spec.ts new file mode 100644 index 000000000..4849a4748 --- /dev/null +++ b/src/tests/admin/api-key-modal.component.spec.ts @@ -0,0 +1,61 @@ +import { DIALOG_DATA } from '@angular/cdk/dialog'; +import { signal } from '@angular/core'; +import { TestBed } from '@angular/core/testing'; +import { describe, expect, it, vi } from 'vitest'; +import { PlaceAPIKeyDetails } from '../../app/admin/api-keys/api-key-details.class'; +import { APIKeyModalComponent } from '../../app/admin/api-keys/api-key-modal.component'; +import { APIKeyService } from '../../app/admin/api-keys/api-keys.service'; +import { DialogEvent } from '../../app/common/types'; + +vi.mock('@placeos/ts-client', () => ({ + queryUsers: vi.fn(() => Promise.resolve({ data: [] })), + showMetadata: vi.fn(() => Promise.resolve({})), + showUser: vi.fn(() => Promise.resolve(null)), +})); +// The real service loads scopes and the current user, which this test does not use +vi.mock('../../app/admin/api-keys/api-keys.service', () => ({ + APIKeyService: class {}, +})); +vi.mock('../../app/common/notifications', () => ({ + notifyError: vi.fn(), +})); + +describe('APIKeyModalComponent', () => { + it('drops the TTL but keeps the expiry when a key is edited', async () => { + const key = new PlaceAPIKeyDetails({ + id: 'key-1', + name: 'Kiosk', + user_id: 'user-1', + scopes: ['public'], + expires_at: 1_900_000_000, + }); + await TestBed.configureTestingModule({ + imports: [APIKeyModalComponent], + providers: [ + { provide: DIALOG_DATA, useValue: { domain: null, key } }, + { + provide: APIKeyService, + useValue: { available_scopes: signal([]) }, + }, + ], + }) + .overrideComponent(APIKeyModalComponent, { + set: { template: '' }, + }) + .compileComponents(); + const fixture = TestBed.createComponent(APIKeyModalComponent); + fixture.detectChanges(); + const component = fixture.componentInstance; + const events: DialogEvent[] = []; + component.event.subscribe((event) => events.push(event)); + + component.setTTL(3600); + await component.save(); + + expect(events).toHaveLength(1); + expect(events[0].metadata).toEqual( + expect.objectContaining({ id: 'key-1', expires_at: 1_900_000_000 }), + ); + expect(events[0].metadata).not.toHaveProperty('ttl'); + }); +}); diff --git a/src/tests/admin/cluster-task-list.component.spec.ts b/src/tests/admin/cluster-task-list.component.spec.ts new file mode 100644 index 000000000..34f39d97f --- /dev/null +++ b/src/tests/admin/cluster-task-list.component.spec.ts @@ -0,0 +1,55 @@ +import { Dialog } from '@angular/cdk/dialog'; +import { TestBed } from '@angular/core/testing'; +import { ActivatedRoute, convertToParamMap } from '@angular/router'; +import { + PlaceCluster, + queryClusters, + queryProcesses, +} from '@placeos/ts-client'; +import { of } from 'rxjs'; +import { describe, expect, it, vi } from 'vitest'; +import { PlaceClusterTaskListComponent } from '../../app/admin/cluster-details/cluster-task-list.component'; + +vi.mock('@placeos/ts-client', () => ({ + queryClusters: vi.fn(), + queryProcesses: vi.fn(), + showMetadata: vi.fn(() => Promise.resolve({})), + terminateProcess: vi.fn(), +})); + +describe('PlaceClusterTaskListComponent', () => { + it('clears the cluster when the search has no exact id match', async () => { + const param_map = convertToParamMap({}); + await TestBed.configureTestingModule({ + imports: [PlaceClusterTaskListComponent], + providers: [ + { provide: Dialog, useValue: { open: vi.fn() } }, + { + provide: ActivatedRoute, + useValue: { + paramMap: of(param_map), + snapshot: { paramMap: param_map }, + }, + }, + ], + }) + .overrideComponent(PlaceClusterTaskListComponent, { + set: { template: '' }, + }) + .compileComponents(); + const component = TestBed.createComponent( + PlaceClusterTaskListComponent, + ).componentInstance; + component.cluster.set({ id: 'cluster-1' } as PlaceCluster); + component.process_list.set([{ id: 'driver_1' }]); + vi.mocked(queryClusters).mockResolvedValue({ + data: [{ id: 'cluster-10' } as PlaceCluster], + } as Awaited>); + + await component.loadCluster('cluster-1'); + + expect(component.cluster()).toBeNull(); + expect(component.process_list()).toEqual([]); + expect(queryProcesses).not.toHaveBeenCalled(); + }); +}); diff --git a/src/tests/admin/database-details.component.spec.ts b/src/tests/admin/database-details.component.spec.ts index 054a0e46f..668a8e6f9 100644 --- a/src/tests/admin/database-details.component.spec.ts +++ b/src/tests/admin/database-details.component.spec.ts @@ -1,9 +1,17 @@ import { TestBed } from '@angular/core/testing'; -import { sourceResync, sourceResyncStatus } from '@placeos/ts-client'; +import { + addZone, + PlaceZone, + queryZones, + sourceResync, + sourceResyncStatus, +} from '@placeos/ts-client'; +import { of } from 'rxjs'; import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'; import { Dialog } from '@angular/cdk/dialog'; import { PlaceDatabaseDetailsComponent } from '../../app/admin/database-details.component'; +import { downloadFile, parseCSV } from '../../app/common/general'; import { notifyError, notifySuccess, @@ -18,6 +26,10 @@ vi.mock('@placeos/ts-client', () => ({ sourceResync: vi.fn(), sourceResyncStatus: vi.fn(), })); +vi.mock('../../app/common/general', async (importOriginal) => ({ + ...(await importOriginal()), + downloadFile: vi.fn(), +})); vi.mock('../../app/common/notifications', () => ({ notifyError: vi.fn(), notifySuccess: vi.fn(), @@ -166,3 +178,84 @@ describe('Database details: MQTT re-sync', () => { expect(buttons(fixture).resync.disabled).toBe(false); }); }); + +describe('Database details: zone tree', () => { + beforeEach(() => vi.clearAllMocks()); + + afterEach(() => TestBed.resetTestingModule()); + + /** Creates the component with an export modal that picks `selected` */ + async function createComponent(selected: PlaceZone[] = []) { + await TestBed.configureTestingModule({ + imports: [PlaceDatabaseDetailsComponent], + providers: [ + { + provide: Dialog, + useValue: { open: () => ({ closed: of(selected) }) }, + }, + ], + }) + .overrideComponent(PlaceDatabaseDetailsComponent, { + set: { template: '' }, + }) + .compileComponents(); + return TestBed.createComponent(PlaceDatabaseDetailsComponent) + .componentInstance; + } + + it('gives imported children the new id of a parent listed after them', async () => { + const component = await createComponent(); + vi.mocked(openConfirmModal).mockResolvedValue({ + reason: 'done', + loading: vi.fn(), + close: vi.fn(), + }); + vi.mocked(addZone).mockImplementation((zone) => + Promise.resolve({ id: `new-${zone.name}` } as PlaceZone), + ); + const csv = [ + 'id,parent_id,name', + 'old-child,old-parent,Child', + 'old-parent,,Parent', + ].join('\n'); + // jsdom files have no text() + const file = { name: 'zones.csv', text: () => Promise.resolve(csv) }; + const event = { + target: { files: [file], value: '' }, + } as unknown as Event; + + await component.importZoneTreeFile(event); + + expect(addZone).toHaveBeenCalledTimes(2); + expect(addZone).toHaveBeenCalledWith( + expect.objectContaining({ name: 'Child', parent_id: 'new-Parent' }), + ); + }); + + it('exports each zone once when roots overlap and parents loop', async () => { + const zone_a = { id: 'zone-a', name: 'A' } as PlaceZone; + const zone_b = { id: 'zone-b', parent_id: 'zone-a' } as PlaceZone; + const zone_c = { id: 'zone-c', parent_id: 'zone-b' } as PlaceZone; + const children: Record = { + 'zone-a,zone-b': [zone_b, zone_c], + 'zone-c': [zone_a], + }; + vi.mocked(queryZones).mockImplementation( + ({ parent_id }) => + Promise.resolve({ + data: children[parent_id] || [], + }) as ReturnType, + ); + const component = await createComponent([zone_a, zone_b]); + + component.exportZoneTree(); + await vi.waitFor(() => expect(downloadFile).toHaveBeenCalled()); + + const csv = vi.mocked(downloadFile).mock.calls[0][1]; + expect(parseCSV(csv).map(({ id }) => id)).toEqual([ + 'zone-a', + 'zone-b', + 'zone-c', + ]); + }); +}); diff --git a/src/tests/admin/edge.component.spec.ts b/src/tests/admin/edge.component.spec.ts new file mode 100644 index 000000000..b40d5c9f5 --- /dev/null +++ b/src/tests/admin/edge.component.spec.ts @@ -0,0 +1,42 @@ +import { Dialog } from '@angular/cdk/dialog'; +import { TestBed } from '@angular/core/testing'; +import { PlaceEdge, queryEdges } from '@placeos/ts-client'; +import { of } from 'rxjs'; +import { afterEach, describe, expect, it, vi } from 'vitest'; +import { PlaceEdgeComponent } from '../../app/admin/edge.component'; + +vi.mock('@placeos/ts-client', () => ({ + queryEdges: vi.fn(() => Promise.resolve({ data: [] })), + removeEdge: vi.fn(), + showMetadata: vi.fn(() => Promise.resolve({})), +})); + +describe('PlaceEdgeComponent', () => { + afterEach(() => sessionStorage.clear()); + + it('keeps the last API key when an edit returns no key', async () => { + const created = JSON.stringify({ id: 'edge-1', x_api_key: 'key-1' }); + sessionStorage.setItem('BACKOFFICE.last_edge', created); + const closed = of({ id: 'edge-1', name: 'Renamed' } as PlaceEdge); + await TestBed.configureTestingModule({ + imports: [PlaceEdgeComponent], + providers: [ + { provide: Dialog, useValue: { open: () => ({ closed }) } }, + ], + }) + .overrideComponent(PlaceEdgeComponent, { + set: { template: '' }, + }) + .compileComponents(); + const fixture = TestBed.createComponent(PlaceEdgeComponent); + fixture.detectChanges(); + const component = fixture.componentInstance; + + await component.edit({ id: 'edge-1' } as PlaceEdge); + + // Once on open, and again after the edit + expect(queryEdges).toHaveBeenCalledTimes(2); + expect(component.last_change().x_api_key).toBe('key-1'); + expect(sessionStorage.getItem('BACKOFFICE.last_edge')).toBe(created); + }); +}); diff --git a/src/tests/admin/extensions.component.spec.ts b/src/tests/admin/extensions.component.spec.ts new file mode 100644 index 000000000..f81b0bc31 --- /dev/null +++ b/src/tests/admin/extensions.component.spec.ts @@ -0,0 +1,109 @@ +import { Dialog } from '@angular/cdk/dialog'; +import { signal } from '@angular/core'; +import { TestBed } from '@angular/core/testing'; +import { PlaceDomain, updateDomain } from '@placeos/ts-client'; +import { Subject } from 'rxjs'; +import { describe, expect, it, vi } from 'vitest'; +import { AdminDataService } from '../../app/admin/admin-data.service'; +import { PlaceExtensionsComponent } from '../../app/admin/extensions.component'; +import { DialogEvent } from '../../app/common/types'; + +vi.mock('@placeos/ts-client', () => ({ + PlaceDomain: class { + constructor(data: object) { + Object.assign(this, data); + } + }, + showMetadata: vi.fn(() => Promise.resolve({})), + updateDomain: vi.fn((_id: string, domain: unknown) => + Promise.resolve(domain), + ), +})); + +describe('PlaceExtensionsComponent', () => { + it('keeps other domain settings when an extension is edited', async () => { + const domain = signal( + new PlaceDomain({ + id: 'domain-1', + config: { + theme: 'dark', + backoffice: { + logo: 'logo.svg', + extend: { + systems: { + Docs: { + url: 'https://old.example', + conditions: [], + }, + Help: { + url: 'https://help.example', + conditions: [], + }, + }, + }, + }, + }, + }), + ); + const ref = { + componentInstance: { + event: new Subject(), + loading: signal(''), + }, + close: vi.fn(), + }; + await TestBed.configureTestingModule({ + imports: [PlaceExtensionsComponent], + providers: [ + { provide: Dialog, useValue: { open: () => ref } }, + { + provide: AdminDataService, + useValue: { + selectedDomain: () => domain, + selectDefaultDomain: () => Promise.resolve(domain()), + replaceDomain: vi.fn(), + }, + }, + ], + }) + .overrideComponent(PlaceExtensionsComponent, { + set: { template: '' }, + }) + .compileComponents(); + const component = TestBed.createComponent( + PlaceExtensionsComponent, + ).componentInstance; + const docs = component.extensions().find(({ name }) => name === 'Docs'); + + component.editExtension(docs); + ref.componentInstance.event.next({ + reason: 'done', + metadata: { ...docs, url: 'https://new.example' }, + }); + await vi.waitFor(() => expect(ref.close).toHaveBeenCalled()); + + expect(updateDomain).toHaveBeenCalledWith( + 'domain-1', + expect.objectContaining({ + config: { + theme: 'dark', + backoffice: { + logo: 'logo.svg', + extend: { + systems: { + Docs: { + url: 'https://new.example', + conditions: [], + }, + Help: { + url: 'https://help.example', + conditions: [], + }, + }, + }, + }, + }, + }), + ); + }); +}); diff --git a/src/tests/admin/resource-imports.component.spec.ts b/src/tests/admin/resource-imports.component.spec.ts new file mode 100644 index 000000000..dab6c7a0f --- /dev/null +++ b/src/tests/admin/resource-imports.component.spec.ts @@ -0,0 +1,78 @@ +import { Dialog } from '@angular/cdk/dialog'; +import { signal } from '@angular/core'; +import { TestBed } from '@angular/core/testing'; +import { PlaceSystem, query, querySystemsWithEmails } from '@placeos/ts-client'; +import { describe, expect, it, vi } from 'vitest'; +import { AdminDataService } from '../../app/admin/admin-data.service'; +import { ResourceImportsComponent } from '../../app/admin/resource-imports.component'; + +vi.mock('@placeos/ts-client', () => ({ + addSystem: vi.fn(), + query: vi.fn(), + querySystemsWithEmails: vi.fn(), + showMetadata: vi.fn(() => Promise.resolve({})), +})); + +describe('ResourceImportsComponent', () => { + it('marks a resource imported when a later page has its system', async () => { + const domain = signal({ id: 'domain-1', name: 'Place' }); + vi.mocked(query).mockResolvedValue({ + data: [ + { + id: 'room-1', + displayName: 'Room 1', + emailAddress: 'Room.1@Place.tech', + }, + { + id: 'room-2', + displayName: 'Room 2', + emailAddress: 'room.2@place.tech', + }, + ], + } as Awaited>); + const page = (data: Partial[], next?: () => unknown) => + ({ data, next }) as Awaited< + ReturnType + >; + vi.mocked(querySystemsWithEmails).mockResolvedValue( + page([{ id: 'sys-other', email: 'other@place.tech' }], () => + Promise.resolve( + page([{ id: 'sys-1', email: 'ROOM.1@place.tech' }]), + ), + ), + ); + await TestBed.configureTestingModule({ + imports: [ResourceImportsComponent], + providers: [ + { provide: Dialog, useValue: { open: vi.fn() } }, + { + provide: AdminDataService, + useValue: { + selectedDomain: () => domain, + selectDefaultDomain: () => Promise.resolve(null), + }, + }, + ], + }) + .overrideComponent(ResourceImportsComponent, { + set: { template: '' }, + }) + .compileComponents(); + const component = TestBed.createComponent( + ResourceImportsComponent, + ).componentInstance; + + await component.loadResourceList(); + + expect( + component.resource_list().map(({ id, imported, system_id }) => ({ + id, + imported, + system_id, + })), + ).toEqual([ + { id: 'room-1', imported: true, system_id: 'sys-1' }, + { id: 'room-2', imported: false, system_id: '' }, + ]); + }); +}); diff --git a/src/tests/admin/signage-ai-provider-modal.component.spec.ts b/src/tests/admin/signage-ai-provider-modal.component.spec.ts index 81d9be3a4..2b68625ff 100644 --- a/src/tests/admin/signage-ai-provider-modal.component.spec.ts +++ b/src/tests/admin/signage-ai-provider-modal.component.spec.ts @@ -1,5 +1,6 @@ import { DIALOG_DATA, DialogRef } from '@angular/cdk/dialog'; import { TestBed } from '@angular/core/testing'; +import { patch } from '@placeos/ts-client'; import { EMPTY } from 'rxjs'; import { beforeEach, describe, expect, it, vi } from 'vitest'; import { SignageAIProviderModalComponent } from '../../app/admin/signage-ai/signage-ai-provider-modal.component'; @@ -12,9 +13,14 @@ vi.mock('@placeos/ts-client', () => ({ post: vi.fn(() => Promise.resolve({})), showMetadata: vi.fn(() => Promise.resolve({})), })); +vi.mock('../../app/common/notifications', () => ({ + notifyError: vi.fn(), + notifySuccess: vi.fn(), +})); describe('SignageAIProviderModalComponent', () => { beforeEach(async () => { + vi.clearAllMocks(); await TestBed.configureTestingModule({ imports: [SignageAIProviderModalComponent], providers: [ @@ -62,4 +68,22 @@ describe('SignageAIProviderModalComponent', () => { })); expect(component.form.location().valid()).toBe(true); }); + + it('keeps the stored credentials when an edit leaves them empty', async () => { + TestBed.overrideProvider(DIALOG_DATA, { + useValue: { + item: { id: 'provider-1', name: 'OpenAI', provider: 'OPENAI' }, + }, + }); + const component = TestBed.createComponent( + SignageAIProviderModalComponent, + ).componentInstance; + + await component.save(); + + expect(patch).toHaveBeenCalledWith( + '/api/engine/v2/signage/ai/providers/provider-1', + expect.not.objectContaining({ credentials: expect.anything() }), + ); + }); }); diff --git a/src/tests/admin/signage-ai.component.spec.ts b/src/tests/admin/signage-ai.component.spec.ts index 908db7b74..b92ad82ce 100644 --- a/src/tests/admin/signage-ai.component.spec.ts +++ b/src/tests/admin/signage-ai.component.spec.ts @@ -57,7 +57,7 @@ describe('SignageAIComponent', () => { get_mock.mockImplementation((url) => url.endsWith('/usage') ? Promise.reject(new Error('usage failed')) - : Promise.resolve([]), + : Promise.resolve([{ id: 'provider-1', name: 'OpenAI' }]), ); const fixture = TestBed.createComponent(SignageAIComponent); @@ -65,5 +65,8 @@ describe('SignageAIComponent', () => { expect(fixture.componentInstance.provider_error()).toBe(''); expect(fixture.componentInstance.usage_error()).not.toBe(''); + expect( + fixture.componentInstance.providers().map(({ name }) => name), + ).toEqual(['OpenAI']); }); }); diff --git a/src/tests/admin/signage-ai.fn.spec.ts b/src/tests/admin/signage-ai.fn.spec.ts index 7ce0f560a..11fb908aa 100644 --- a/src/tests/admin/signage-ai.fn.spec.ts +++ b/src/tests/admin/signage-ai.fn.spec.ts @@ -47,11 +47,6 @@ describe('signage-ai.fn', () => { expect(provider.enabled).toBe(true); expect(provider.is_default).toBe(true); }); - - it('should never carry credentials, which the API does not return', () => { - const provider = new SignageAIProvider({ id: 'provider-1' }); - expect('credentials' in provider).toBe(false); - }); }); describe('querySignageAIProviders', () => { diff --git a/src/tests/admin/signage-plugin-embed.component.spec.ts b/src/tests/admin/signage-plugin-embed.component.spec.ts index dce0a2344..eb74604c8 100644 --- a/src/tests/admin/signage-plugin-embed.component.spec.ts +++ b/src/tests/admin/signage-plugin-embed.component.spec.ts @@ -1,6 +1,42 @@ -import { resolveSignagePluginUrl } from '../../app/admin/signage-plugins/signage-plugin-embed.component'; +import { TestBed } from '@angular/core/testing'; +import { SignagePlugin } from '@placeos/ts-client'; +import { describe, expect, it } from 'vitest'; +import { + resolveSignagePluginUrl, + SIGNAGE_PLUGIN_API_VERSION, + SignagePluginEmbedComponent, +} from '../../app/admin/signage-plugins/signage-plugin-embed.component'; describe('SignagePluginEmbedComponent', () => { + it('only reads messages from its frame that use the plugin API', () => { + const fixture = TestBed.createComponent(SignagePluginEmbedComponent); + fixture.componentRef.setInput('plugin', { + uri: 'https://plugin.example/news.html', + } as SignagePlugin); + fixture.detectChanges(); + const frame = (fixture.nativeElement as HTMLElement).querySelector( + 'iframe', + ); + const loaded = (source: Window, api: string) => + window.dispatchEvent( + new MessageEvent('message', { + source, + data: { + api, + type: 'loaded', + payload: { config_schema: { title: 'News' } }, + }, + }), + ); + + loaded(window, SIGNAGE_PLUGIN_API_VERSION); + loaded(frame.contentWindow, 'signage-plugin/v0'); + expect(fixture.componentInstance.schema()).toEqual({}); + + loaded(frame.contentWindow, SIGNAGE_PLUGIN_API_VERSION); + expect(fixture.componentInstance.schema()).toEqual({ title: 'News' }); + }); + describe('resolveSignagePluginUrl', () => { const base_uri = 'https://backoffice.example/admin/signage-plugins/'; diff --git a/src/tests/admin/signage-plugin-import-modal.component.spec.ts b/src/tests/admin/signage-plugin-import-modal.component.spec.ts new file mode 100644 index 000000000..1ff51892e --- /dev/null +++ b/src/tests/admin/signage-plugin-import-modal.component.spec.ts @@ -0,0 +1,46 @@ +import { DialogRef } from '@angular/cdk/dialog'; +import { TestBed } from '@angular/core/testing'; +import { listRepositoryFiles } from '@placeos/ts-client'; +import { describe, expect, it, vi } from 'vitest'; +import { SignagePluginImportModalComponent } from '../../app/admin/signage-plugins/signage-plugin-import-modal.component'; + +vi.mock('@placeos/ts-client', () => ({ + listRepositoryFiles: vi.fn(), + PlaceRepositoryType: { Interface: 'interface' }, + queryRepositories: vi.fn(() => Promise.resolve({ data: [] })), + showMetadata: vi.fn(() => Promise.resolve({})), + SignagePlugin: class {}, +})); +vi.mock('../../app/admin/signage-plugins/signage-plugins.utilities', () => ({ + probeSignagePlugin: vi.fn(() => Promise.resolve(null)), +})); + +describe('SignagePluginImportModalComponent', () => { + it('drops the files of a repository that is no longer selected', async () => { + const file_lists: Record void> = {}; + vi.mocked(listRepositoryFiles).mockImplementation( + (id) => new Promise((resolve) => (file_lists[id] = resolve)), + ); + await TestBed.configureTestingModule({ + imports: [SignagePluginImportModalComponent], + providers: [{ provide: DialogRef, useValue: { close: vi.fn() } }], + }) + .overrideComponent(SignagePluginImportModalComponent, { + set: { template: '' }, + }) + .compileComponents(); + const component = TestBed.createComponent( + SignagePluginImportModalComponent, + ).componentInstance; + + const first = component.selectRepository('repo-a'); + const second = component.selectRepository('repo-b'); + file_lists['repo-b'](['b.html']); + await second; + file_lists['repo-a'](['a.html']); + await first; + + expect(component.repository_id()).toBe('repo-b'); + expect(component.probes().map(({ uri }) => uri)).toEqual(['b.html']); + }); +}); diff --git a/src/tests/admin/staff-tenant-modal.component.spec.ts b/src/tests/admin/staff-tenant-modal.component.spec.ts index e7ade9c9a..2c1b6139d 100644 --- a/src/tests/admin/staff-tenant-modal.component.spec.ts +++ b/src/tests/admin/staff-tenant-modal.component.spec.ts @@ -18,7 +18,7 @@ vi.mock('../../app/common/notifications', () => ({ notifySuccess: vi.fn(), })); -describe('Staff tenant advance booking limits', () => { +describe('StaffTenantModalComponent', () => { const tenant = { id: 'tenant-test', name: 'Test Tenant', @@ -57,6 +57,51 @@ describe('Staff tenant advance booking limits', () => { .componentInstance; } + it('blocks a new Office 365 tenant until the client secret is set', async () => { + const component = await createComponent(); + component.formModel.update((model) => ({ + ...model, + name: 'New Tenant', + platform: 'office365', + delegated: false, + })); + component.updateCredential('tenant', 'tenant-id'); + component.updateCredential('client_id', 'client-id'); + + await component.save(); + expect(post).not.toHaveBeenCalled(); + + component.updateCredential('client_secret', 'secret'); + await component.save(); + expect(post).toHaveBeenCalledWith( + '/api/staff/v1/tenants', + expect.objectContaining({ + credentials: { + tenant: 'tenant-id', + client_id: 'client-id', + client_secret: 'secret', + }, + }), + ); + }); + + it('sends an empty Outlook config to clear a saved one', async () => { + const outlook_tenant = { + ...tenant, + outlook_config: { app_id: 'outlook-app' }, + }; + const component = await createComponent({ tenant: outlook_tenant }); + expect(component.show_outlook()).toBe(true); + + component.show_outlook.set(false); + await component.save(); + + expect(put).toHaveBeenCalledWith( + '/api/staff/v1/tenants/tenant-test', + expect.objectContaining({ outlook_config: {} }), + ); + }); + it('loads and updates ranges without changing booking count limits', async () => { const component = await createComponent({ tenant }); expect(component.formModel().booking_range).toEqual([ diff --git a/src/tests/admin/storage-provider-modal.component.spec.ts b/src/tests/admin/storage-provider-modal.component.spec.ts new file mode 100644 index 000000000..76782a75c --- /dev/null +++ b/src/tests/admin/storage-provider-modal.component.spec.ts @@ -0,0 +1,53 @@ +import { DIALOG_DATA, DialogRef } from '@angular/cdk/dialog'; +import { TestBed } from '@angular/core/testing'; +import { beforeEach, describe, expect, it, vi } from 'vitest'; +import { StorageProviderModalComponent } from '../../app/admin/storage/storage-provider-modal.component'; +import { PlaceStorage, saveStorage } from '../../app/admin/storage/storage.fn'; + +vi.mock('@placeos/ts-client', () => ({ + showMetadata: vi.fn(() => Promise.resolve({})), +})); +vi.mock('../../app/admin/storage/storage.fn', () => ({ + saveStorage: vi.fn(() => Promise.resolve({})), +})); +vi.mock('../../app/common/notifications', () => ({ + notifyError: vi.fn(), + notifySuccess: vi.fn(), +})); + +describe('StorageProviderModalComponent', () => { + beforeEach(() => vi.clearAllMocks()); + + it('keeps the stored secret when an edit leaves it empty', async () => { + const item = { + id: 'storage-1', + storage_type: 's3', + bucket_name: 'media', + region: 'ap-southeast-2', + access_key: 'AKIA-KEY', + } as PlaceStorage; + await TestBed.configureTestingModule({ + imports: [StorageProviderModalComponent], + providers: [ + { provide: DIALOG_DATA, useValue: { item } }, + { provide: DialogRef, useValue: { close: vi.fn() } }, + ], + }) + .overrideComponent(StorageProviderModalComponent, { + set: { template: '' }, + }) + .compileComponents(); + const component = TestBed.createComponent( + StorageProviderModalComponent, + ).componentInstance; + + await component.save(); + + expect(saveStorage).toHaveBeenCalledWith( + expect.objectContaining({ id: 'storage-1' }), + ); + expect(vi.mocked(saveStorage).mock.calls[0][0]).not.toHaveProperty( + 'access_secret', + ); + }); +}); diff --git a/src/tests/admin/storage.fn.spec.ts b/src/tests/admin/storage.fn.spec.ts index ea486feee..2ebb5fd88 100644 --- a/src/tests/admin/storage.fn.spec.ts +++ b/src/tests/admin/storage.fn.spec.ts @@ -73,12 +73,6 @@ describe('storage.fn', () => { expect(storage.mime_filter).toEqual(['application/x-msdownload']); expect(storage.is_default).toBe(true); }); - - it('should have readonly properties', () => { - const storage = new PlaceStorage({ id: 'storage-123' }); - // TypeScript would prevent assignment, but at runtime it won't throw - expect(storage.id).toBe('storage-123'); - }); }); describe('queryStorage', () => { diff --git a/src/tests/admin/upload-library.component.spec.ts b/src/tests/admin/upload-library.component.spec.ts new file mode 100644 index 000000000..c497b6722 --- /dev/null +++ b/src/tests/admin/upload-library.component.spec.ts @@ -0,0 +1,80 @@ +import { Dialog } from '@angular/cdk/dialog'; +import { signal } from '@angular/core'; +import { TestBed } from '@angular/core/testing'; +import { afterEach, describe, expect, it, vi } from 'vitest'; +import { AdminDataService } from '../../app/admin/admin-data.service'; +import { UploadLibraryComponent } from '../../app/admin/upload-library.component'; +import { UploadsService } from '../../app/common/uploads.service'; + +vi.mock('@placeos/ts-client', () => ({ + apiKey: vi.fn(), + cleanObject: vi.fn(), + query: vi.fn(), + remove: vi.fn(), + showMetadata: vi.fn(() => Promise.resolve({})), + token: vi.fn(), +})); +// The real service imports @placeos/cloud-uploads, which does not load here +vi.mock('../../app/common/uploads.service', () => ({ + UploadsService: class {}, +})); +vi.mock('../../app/common/notifications', () => ({ + notifyError: vi.fn(), + notifyInfo: vi.fn(), + notifySuccess: vi.fn(), +})); + +describe('UploadLibraryComponent', () => { + afterEach(() => vi.useRealTimers()); + + it('stops waiting for a stalled upload after an hour', async () => { + vi.useFakeTimers(); + const upload_list = vi.fn(() => [{ id: 1, progress: 50 }]); + await TestBed.configureTestingModule({ + imports: [UploadLibraryComponent], + providers: [ + { provide: Dialog, useValue: { open: vi.fn() } }, + { + provide: UploadsService, + useValue: { + upload_list, + uploadFileWithPermissions: () => Promise.resolve(1), + }, + }, + { + provide: AdminDataService, + useValue: { + filter: () => signal(''), + selectedDomain: () => signal(null), + selectDefaultDomain: () => Promise.resolve(null), + sort: () => signal(null), + }, + }, + ], + }) + .overrideComponent(UploadLibraryComponent, { + set: { template: '' }, + }) + .compileComponents(); + const component = TestBed.createComponent( + UploadLibraryComponent, + ).componentInstance; + const event = { + target: { files: [new File(['data'], 'stalled.png')] }, + } as unknown as Event; + + component.handleFileEvent(event); + await vi.advanceTimersByTimeAsync(300); + expect(component.loading()).toBe(true); + + vi.advanceTimersByTime(59 * 60 * 1000); + expect(component.loading()).toBe(true); + + vi.advanceTimersByTime(2 * 60 * 1000); + expect(component.loading()).toBe(false); + + const checks = upload_list.mock.calls.length; + vi.advanceTimersByTime(1000); + expect(upload_list).toHaveBeenCalledTimes(checks); + }); +}); From f581d12ecf1e1e1ddeb56cdb0d3006017bd5ab1e Mon Sep 17 00:00:00 2001 From: Alex Sorafumo Date: Fri, 13 Nov 2026 19:10:31 +1100 Subject: [PATCH 3/5] test(ui): cover markdown sanitising, extension origins, settings permissions and controls Co-Authored-By: Claude Opus 5.5 --- src/tests/ui/app.component.spec.ts | 74 +++++++++++++++++++ .../authenticated-image.directive.spec.ts | 64 ++++++++++++++++ .../fullscreen-modal-shell.component.spec.ts | 16 ++++ .../ui/components/icon.component.spec.ts | 10 --- .../metadata-display.component.spec.ts | 62 ++++++++++++++++ .../settings-form.component.spec.ts | 25 +++++++ .../trigger-action-modal.component.spec.ts | 53 +++++++++++++ .../trigger-condition-modal.component.spec.ts | 67 +++++++++++++++++ .../controls/autocomplete.component.spec.ts | 56 ++++++++++++++ .../ui/controls/form-field.component.spec.ts | 41 +++++++++- .../ui/controls/select.component.spec.ts | 18 +++++ .../cron-input-field.component.spec.ts | 47 ++++++++++++ .../date-calendar.component.spec.ts | 38 ++++++++++ .../execute-method-field.component.spec.ts | 56 ++++++++++++++ .../item-search-field.component.spec.ts | 24 ++++++ .../ui/extension-outlet.component.spec.ts | 10 ++- src/tests/ui/pipes/markdown.pipe.spec.ts | 23 ++++++ src/tests/ui/pipes/safe.pipe.spec.ts | 15 ++-- src/tests/ui/pipes/user.pipe.spec.ts | 11 +++ 19 files changed, 690 insertions(+), 20 deletions(-) create mode 100644 src/tests/ui/app.component.spec.ts create mode 100644 src/tests/ui/components/authenticated-image.directive.spec.ts create mode 100644 src/tests/ui/components/metadata-display.component.spec.ts create mode 100644 src/tests/ui/components/trigger-action-modal.component.spec.ts create mode 100644 src/tests/ui/components/trigger-condition-modal.component.spec.ts create mode 100644 src/tests/ui/controls/autocomplete.component.spec.ts create mode 100644 src/tests/ui/custom-fields/cron-input-field.component.spec.ts create mode 100644 src/tests/ui/custom-fields/date-calendar.component.spec.ts create mode 100644 src/tests/ui/custom-fields/execute-method-field.component.spec.ts diff --git a/src/tests/ui/app.component.spec.ts b/src/tests/ui/app.component.spec.ts new file mode 100644 index 000000000..b089c4d32 --- /dev/null +++ b/src/tests/ui/app.component.spec.ts @@ -0,0 +1,74 @@ +import { provideZonelessChangeDetection, signal } from '@angular/core'; +import { TestBed } from '@angular/core/testing'; +import { provideRouter } from '@angular/router'; +import { SwUpdate } from '@angular/service-worker'; +import { afterEach, describe, expect, it, vi } from 'vitest'; +import { AppComponent } from '../../app/app'; +import { LocaleService } from '../../app/common/locale.service'; +import { SettingsService } from '../../app/common/settings.service'; +import { BackofficeUsersService } from '../../app/users/users.service'; + +vi.mock('@placeos/ts-client', async () => ({ + ...(await vi.importActual('@placeos/ts-client/dist/index.es.js')), + isMock: () => true, + onlineState: () => ({ + value: true, + subscribe: (next: (value: boolean) => void) => { + next(true); + return () => undefined; + }, + }), +})); + +vi.mock('@placeos/cloud-uploads', () => + vi.importActual('@placeos/cloud-uploads/dist/index.es.js'), +); + +vi.mock('../../app/common/placeos', () => ({ + setLoadingMessage: vi.fn(), + setupPlace: vi.fn(() => Promise.resolve()), +})); + +vi.mock('../../app/common/sentry', async () => ({ + ...(await vi.importActual('../../app/common/sentry')), + initSentry: vi.fn(() => Promise.resolve()), +})); + +describe('AppComponent', () => { + afterEach(() => { + vi.useRealTimers(); + localStorage.clear(); + }); + + it('stops loading after five seconds when translations never load', async () => { + vi.useFakeTimers(); + const never = () => new Promise(() => undefined); + TestBed.configureTestingModule({ + providers: [ + provideZonelessChangeDetection(), + provideRouter([]), + { provide: SwUpdate, useValue: { isEnabled: false } }, + { + provide: SettingsService, + useValue: { initialised: signal(true), get: () => null }, + }, + { + provide: BackofficeUsersService, + useValue: { initialised: signal(true) }, + }, + { + provide: LocaleService, + useValue: { ready: never(), setLocale: never }, + }, + ], + }); + const app = TestBed.runInInjectionContext(() => new AppComponent()); + + const init = app.ngOnInit(); + await vi.advanceTimersByTimeAsync(4_999); + expect(app.loading()).toBe(true); + await vi.advanceTimersByTimeAsync(1); + expect(app.loading()).toBe(false); + await init; + }); +}); diff --git a/src/tests/ui/components/authenticated-image.directive.spec.ts b/src/tests/ui/components/authenticated-image.directive.spec.ts new file mode 100644 index 000000000..ab51bf87e --- /dev/null +++ b/src/tests/ui/components/authenticated-image.directive.spec.ts @@ -0,0 +1,64 @@ +import { + Component, + provideZonelessChangeDetection, + signal, +} from '@angular/core'; +import { TestBed } from '@angular/core/testing'; +import { afterEach, describe, expect, it, vi } from 'vitest'; +import { AuthenticatedImageDirective } from '../../../app/ui/authenticated-image.directive'; + +vi.mock('@placeos/ts-client', () => ({ + apiKey: () => '', + authority: () => ({}), + token: () => 'token', +})); + +const OLD_SOURCE = '/api/engine/v2/uploads/old/url'; +const NEW_SOURCE = '/api/engine/v2/uploads/new/url'; + +@Component({ + template: ``, + imports: [AuthenticatedImageDirective], +}) +class HostComponent { + public readonly source = signal(OLD_SOURCE); +} + +describe('AuthenticatedImageDirective', () => { + afterEach(() => vi.unstubAllGlobals()); + + it('keeps the newer source when an older request finishes last', async () => { + const responses = new Map void>(); + vi.stubGlobal( + 'fetch', + vi.fn( + (url: string) => + new Promise((resolve) => responses.set(url, resolve)), + ), + ); + // jsdom has no object URLs. The blob holds the source to show here. + URL.createObjectURL = (blob: Blob & { source?: string }) => + `blob:${blob.source}`; + const respond = async (url: string) => { + responses.get(url)({ + ok: true, + blob: () => Promise.resolve({ source: url }), + } as unknown as Response); + await new Promise((resolve) => setTimeout(resolve)); + }; + TestBed.configureTestingModule({ + providers: [provideZonelessChangeDetection()], + }); + const fixture = TestBed.createComponent(HostComponent); + await fixture.whenStable(); + fixture.componentInstance.source.set(NEW_SOURCE); + await fixture.whenStable(); + const image: HTMLImageElement = + fixture.nativeElement.querySelector('img'); + + await respond(NEW_SOURCE); + expect(image.getAttribute('src')).toBe(`blob:${NEW_SOURCE}`); + await respond(OLD_SOURCE); + expect(image.getAttribute('src')).toBe(`blob:${NEW_SOURCE}`); + }); +}); diff --git a/src/tests/ui/components/fullscreen-modal-shell.component.spec.ts b/src/tests/ui/components/fullscreen-modal-shell.component.spec.ts index 108b1a14d..351b30d05 100644 --- a/src/tests/ui/components/fullscreen-modal-shell.component.spec.ts +++ b/src/tests/ui/components/fullscreen-modal-shell.component.spec.ts @@ -109,6 +109,22 @@ describe('FullscreenModalShellComponent', () => { expect(ref.close).not.toHaveBeenCalled(); }); + it('closes both dialogs once discarding is confirmed', async () => { + const confirm = { + reason: 'done' as const, + loading: vi.fn(), + close: vi.fn(), + }; + vi.mocked(openConfirmModal).mockResolvedValue(confirm); + const { element, shell } = createForm(); + element + .querySelector('main') + .dispatchEvent(new Event('input', { bubbles: true })); + await shell.close(); + expect(confirm.close).toHaveBeenCalled(); + expect(ref.close).toHaveBeenCalled(); + }); + it('asks before closing after a chip was removed', async () => { const { element, shell } = createForm(); element.querySelector('.chip-action').click(); diff --git a/src/tests/ui/components/icon.component.spec.ts b/src/tests/ui/components/icon.component.spec.ts index b7cd14d4a..90dd7a148 100644 --- a/src/tests/ui/components/icon.component.spec.ts +++ b/src/tests/ui/components/icon.component.spec.ts @@ -116,16 +116,6 @@ describe('IconComponent', () => { }); }); - describe('ng-content projection', () => { - it('should render wrapper div with correct classes', () => { - const wrapper = fixture.nativeElement.querySelector('div'); - expect(wrapper).toBeTruthy(); - expect(wrapper.className).toContain('flex'); - expect(wrapper.className).toContain('items-center'); - expect(wrapper.className).toContain('justify-center'); - }); - }); - describe('inside buttons', () => { @Component({ imports: [IconComponent, TooltipDirective], diff --git a/src/tests/ui/components/metadata-display.component.spec.ts b/src/tests/ui/components/metadata-display.component.spec.ts new file mode 100644 index 000000000..bd0c6d4a7 --- /dev/null +++ b/src/tests/ui/components/metadata-display.component.spec.ts @@ -0,0 +1,62 @@ +import { provideZonelessChangeDetection } from '@angular/core'; +import { TestBed } from '@angular/core/testing'; +import { beforeEach, describe, expect, it, vi } from 'vitest'; + +const mocks = vi.hoisted(() => ({ + listMetadata: vi.fn(), + updateMetadata: vi.fn(), + removeMetadata: vi.fn(), + notifyError: vi.fn(), +})); + +vi.mock('@placeos/ts-client', async () => ({ + ...(await vi.importActual('@placeos/ts-client/dist/index.es.js')), + listMetadata: mocks.listMetadata, + updateMetadata: mocks.updateMetadata, + removeMetadata: mocks.removeMetadata, +})); + +vi.mock('../../../app/common/notifications', () => ({ + notifyError: mocks.notifyError, + notifySuccess: vi.fn(), +})); + +import { MetadataDisplayComponent } from '../../../app/ui/metadata-display.component'; + +describe('MetadataDisplayComponent', () => { + beforeEach(() => { + vi.resetAllMocks(); + mocks.listMetadata.mockResolvedValue({ + config: { name: 'config', description: '', details: { a: 1 } }, + }); + mocks.removeMetadata.mockResolvedValue(undefined); + TestBed.configureTestingModule({ + providers: [provideZonelessChangeDetection()], + }); + }); + + it('keeps the original block when saving a rename fails', async () => { + mocks.updateMetadata.mockRejectedValue(new Error('500')); + const fixture = TestBed.createComponent(MetadataDisplayComponent); + fixture.componentRef.setInput('item', { id: 'zone-1' }); + await fixture.whenStable(); + const component = fixture.componentInstance; + const [block] = component.metadata(); + + component.updateMetadataField('config', 'name', 'renamed'); + component.saveMetadata(block); + await new Promise((resolve) => setTimeout(resolve)); + + expect(mocks.updateMetadata).toHaveBeenCalledWith( + 'zone-1', + expect.objectContaining({ name: 'renamed' }), + ); + expect(mocks.removeMetadata).not.toHaveBeenCalled(); + expect(component.metadata().map(({ name }) => name)).toEqual([ + 'config', + ]); + expect(mocks.notifyError).toHaveBeenCalledWith( + expect.stringContaining('Error saving "renamed"'), + ); + }); +}); diff --git a/src/tests/ui/components/settings-form.component.spec.ts b/src/tests/ui/components/settings-form.component.spec.ts index 3b5edae87..068d33d8f 100644 --- a/src/tests/ui/components/settings-form.component.spec.ts +++ b/src/tests/ui/components/settings-form.component.spec.ts @@ -110,6 +110,31 @@ describe('SettingsFormComponent', () => { expect(component.settingDirty(1)).toBe(true); }); + it('keeps a failed save dirty and reports the error', async () => { + mocks.updateSettings.mockRejectedValueOnce(new Error('500')); + const component = createForm(); + component.updateSetting(0, 'level0: changed'); + component.save(0); + expect(component.saving()[0]).toBe(true); + await new Promise((resolve) => setTimeout(resolve)); + + expect(component.saving()[0]).toBe(false); + expect(component.settingDirty(0)).toBe(true); + expect(component.settingValue(0)).toBe('level0: changed'); + expect(mocks.notifyError).toHaveBeenCalledWith( + 'COMMON.SETTINGS_SAVE_ERROR', + ); + }); + + it('never saves admin settings for support users', () => { + mocks.user = { sys_admin: false, support: true }; + const component = createForm(); + component.updateSetting(2, 'level2: replaced'); + component.save(2); + component.saveAll(); + expect(mocks.updateSettings).not.toHaveBeenCalled(); + }); + it('masks admin settings for support users', () => { mocks.user = { sys_admin: false, support: true }; const component = createForm(); diff --git a/src/tests/ui/components/trigger-action-modal.component.spec.ts b/src/tests/ui/components/trigger-action-modal.component.spec.ts new file mode 100644 index 000000000..935c91055 --- /dev/null +++ b/src/tests/ui/components/trigger-action-modal.component.spec.ts @@ -0,0 +1,53 @@ +import { DIALOG_DATA, DialogRef } from '@angular/cdk/dialog'; +import { provideZonelessChangeDetection } from '@angular/core'; +import { TestBed } from '@angular/core/testing'; +import { PlaceTrigger, updateTrigger } from '@placeos/ts-client'; +import { describe, expect, it, vi } from 'vitest'; +import { notifyError } from '../../../app/common/notifications'; +import { TriggerActionModalComponent } from '../../../app/ui/forms/trigger-action-modal.component'; + +vi.mock('@placeos/ts-client', async () => ({ + ...(await vi.importActual('@placeos/ts-client/dist/index.es.js')), + updateTrigger: vi.fn(), +})); + +vi.mock('../../../app/common/notifications', () => ({ + notifyError: vi.fn(), + notifySuccess: vi.fn(), +})); + +describe('TriggerActionModalComponent', () => { + it('does not save an edited mailer that was removed elsewhere', async () => { + const trigger = { + id: 'trigger-1', + actions: { + functions: [], + mailers: [{ emails: ['other@example.com'], content: 'Other' }], + }, + } as unknown as PlaceTrigger; + TestBed.configureTestingModule({ + providers: [ + provideZonelessChangeDetection(), + { provide: DialogRef, useValue: { close: vi.fn() } }, + { + provide: DIALOG_DATA, + useValue: { + trigger, + action: { emails: ['old@example.com'], content: 'Old' }, + }, + }, + ], + }); + const modal = TestBed.runInInjectionContext( + () => new TriggerActionModalComponent(), + ); + modal.formModel.update((model) => ({ ...model, content: 'New' })); + + await modal.save(); + + expect(updateTrigger).not.toHaveBeenCalled(); + expect(notifyError).toHaveBeenCalledWith( + expect.stringContaining('changed or removed elsewhere'), + ); + }); +}); diff --git a/src/tests/ui/components/trigger-condition-modal.component.spec.ts b/src/tests/ui/components/trigger-condition-modal.component.spec.ts new file mode 100644 index 000000000..1a311a70f --- /dev/null +++ b/src/tests/ui/components/trigger-condition-modal.component.spec.ts @@ -0,0 +1,67 @@ +import { DIALOG_DATA, DialogRef } from '@angular/cdk/dialog'; +import { provideZonelessChangeDetection } from '@angular/core'; +import { TestBed } from '@angular/core/testing'; +import { PlaceTrigger, updateTrigger } from '@placeos/ts-client'; +import { describe, expect, it, vi } from 'vitest'; +import { TriggerConditionModalComponent } from '../../../app/ui/forms/trigger-condition-modal.component'; + +vi.mock('@placeos/ts-client', async () => ({ + ...(await vi.importActual('@placeos/ts-client/dist/index.es.js')), + updateTrigger: vi.fn((_: string, trigger: PlaceTrigger) => + Promise.resolve(trigger), + ), +})); + +vi.mock('../../../app/common/notifications', () => ({ + notifyError: vi.fn(), + notifySuccess: vi.fn(), +})); + +describe('TriggerConditionModalComponent', () => { + it('saves an edited time condition in seconds without CRON fields', async () => { + const comparison = { left: true, operator: 'equal', right: true }; + const cron = { type: 'cron', cron: '0 9 * * *', timezone: 'UTC' }; + const at_time = { type: 'at', time: 1_700_000_000 }; + const trigger = { + id: 'trigger-1', + conditions: { + comparisons: [comparison], + time_dependents: [cron, at_time], + }, + } as unknown as PlaceTrigger; + TestBed.configureTestingModule({ + providers: [ + provideZonelessChangeDetection(), + { provide: DialogRef, useValue: { close: vi.fn() } }, + { + provide: DIALOG_DATA, + useValue: { trigger, condition: at_time }, + }, + ], + }); + const modal = TestBed.runInInjectionContext( + () => new TriggerConditionModalComponent(), + ); + modal.formModel.update((model) => ({ + ...model, + time: 1_800_000_000_400, + cron: '* * * * *', + timezone: 'Australia/Sydney', + })); + + await modal.save(); + + expect(updateTrigger).toHaveBeenCalledWith( + 'trigger-1', + expect.objectContaining({ + conditions: { + comparisons: [comparison], + time_dependents: [ + cron, + { type: 'at', time: 1_800_000_000 }, + ], + }, + }), + ); + }); +}); diff --git a/src/tests/ui/controls/autocomplete.component.spec.ts b/src/tests/ui/controls/autocomplete.component.spec.ts new file mode 100644 index 000000000..c9d146b48 --- /dev/null +++ b/src/tests/ui/controls/autocomplete.component.spec.ts @@ -0,0 +1,56 @@ +import { Component, provideZonelessChangeDetection } from '@angular/core'; +import { TestBed } from '@angular/core/testing'; +import { FormsModule } from '@angular/forms'; +import { describe, expect, it, vi } from 'vitest'; +import { + AutocompleteComponent, + AutocompleteTriggerDirective, +} from '../../../app/ui/controls/autocomplete.component'; +import { OptionComponent } from '../../../app/ui/controls/option.component'; + +vi.mock('@placeos/ts-client', () => + vi.importActual('@placeos/ts-client/dist/index.es.js'), +); + +@Component({ + template: ` + + + Ten + Twenty + + `, + imports: [ + FormsModule, + AutocompleteComponent, + AutocompleteTriggerDirective, + OptionComponent, + ], +}) +class HostComponent { + public value = ''; +} + +describe('AutocompleteComponent', () => { + it('writes a suggestion picked with the keyboard into the input', async () => { + TestBed.configureTestingModule({ + providers: [provideZonelessChangeDetection()], + }); + const fixture = TestBed.createComponent(HostComponent); + await fixture.whenStable(); + const input: HTMLInputElement = + fixture.nativeElement.querySelector('input'); + // The CDK key manager reads the key code + const press = async (key: string, keyCode: number) => { + input.dispatchEvent(new KeyboardEvent('keydown', { key, keyCode })); + await fixture.whenStable(); + }; + + await press('ArrowDown', 40); + await press('Enter', 13); + + expect(input.value).toBe('10'); + expect(fixture.componentInstance.value).toBe('10'); + expect(input.getAttribute('aria-expanded')).toBe('false'); + }); +}); diff --git a/src/tests/ui/controls/form-field.component.spec.ts b/src/tests/ui/controls/form-field.component.spec.ts index d2b0a6869..ed79d03a5 100644 --- a/src/tests/ui/controls/form-field.component.spec.ts +++ b/src/tests/ui/controls/form-field.component.spec.ts @@ -1,5 +1,10 @@ -import { Component, provideZonelessChangeDetection } from '@angular/core'; +import { + Component, + provideZonelessChangeDetection, + signal, +} from '@angular/core'; import { TestBed } from '@angular/core/testing'; +import { form, FormField, required } from '@angular/forms/signals'; import { describe, expect, it } from 'vitest'; import { FormFieldComponent } from '../../../app/ui/controls/form-field.component'; @@ -14,6 +19,19 @@ import { FormFieldComponent } from '../../../app/ui/controls/form-field.componen }) class HostComponent {} +@Component({ + template: ` + + + + `, + imports: [FormFieldComponent, FormField], +}) +class SignalFormHostComponent { + public readonly model = signal({ name: '' }); + public readonly form = form(this.model, (path) => required(path.name)); +} + describe('FormFieldComponent', () => { it('describes the control by its error and hint, keeping other ids', async () => { TestBed.configureTestingModule({ @@ -31,4 +49,25 @@ describe('FormFieldComponent', () => { 'Name is required', ); }); + + it('shows the invalid state only while a touched control is invalid', async () => { + TestBed.configureTestingModule({ + providers: [provideZonelessChangeDetection()], + }); + const fixture = TestBed.createComponent(SignalFormHostComponent); + await fixture.whenStable(); + const field: HTMLElement = + fixture.nativeElement.querySelector('app-form-field'); + const input: HTMLInputElement = field.querySelector('input'); + expect(field.classList).not.toContain('field-invalid'); + + input.dispatchEvent(new Event('blur')); + await fixture.whenStable(); + expect(field.classList).toContain('field-invalid'); + + input.value = 'Ada'; + input.dispatchEvent(new Event('input')); + await fixture.whenStable(); + expect(field.classList).not.toContain('field-invalid'); + }); }); diff --git a/src/tests/ui/controls/select.component.spec.ts b/src/tests/ui/controls/select.component.spec.ts index e32a8562e..1989dcc51 100644 --- a/src/tests/ui/controls/select.component.spec.ts +++ b/src/tests/ui/controls/select.component.spec.ts @@ -98,6 +98,24 @@ describe('SelectComponent', () => { expect(select.getAttribute('aria-expanded')).toBe('false'); }); + it('picks an option with the arrow keys and Enter, skipping a disabled one', async () => { + const { fixture, select } = await setup(false, 'b'); + // The CDK key manager reads the key code + const press = async (key: string, keyCode: number) => { + select.dispatchEvent( + new KeyboardEvent('keydown', { key, keyCode }), + ); + await fixture.whenStable(); + }; + await press('ArrowDown', 40); + await new Promise((done) => requestAnimationFrame(done)); + // Gamma after Beta is disabled, so the active option wraps to Alpha + await press('ArrowDown', 40); + await press('Enter', 13); + expect(fixture.componentInstance.value).toBe('a'); + expect(select.getAttribute('aria-expanded')).toBe('false'); + }); + it('marks the control touched when the panel closes', async () => { const { fixture, select, open } = await setup(); await open(); diff --git a/src/tests/ui/custom-fields/cron-input-field.component.spec.ts b/src/tests/ui/custom-fields/cron-input-field.component.spec.ts new file mode 100644 index 000000000..2c574c40c --- /dev/null +++ b/src/tests/ui/custom-fields/cron-input-field.component.spec.ts @@ -0,0 +1,47 @@ +import { provideZonelessChangeDetection } from '@angular/core'; +import { TestBed } from '@angular/core/testing'; +import { describe, expect, it, vi } from 'vitest'; +import { CronInputFieldComponent } from '../../../app/ui/custom-fields/cron-input-field.component'; + +const SEGMENTS = ['minute', 'hour', 'day', 'month', 'day_of_week'] as const; + +describe('CronInputFieldComponent', () => { + it.each([ + ['minute', '60', '59'], + ['hour', '24', '23'], + ['day', '0', '1'], + ['day', '32', '31'], + ['month', '0', '1'], + ['month', '13', '12'], + ['day_of_week', '7', '6'], + ] as const)( + 'sends only a valid %s value (%s rejected, %s sent)', + (segment, invalid, valid) => { + TestBed.configureTestingModule({ + providers: [provideZonelessChangeDetection()], + }); + const field = TestBed.runInInjectionContext( + () => new CronInputFieldComponent(), + ); + const changed = vi.fn(); + field.registerOnChange(changed); + TestBed.tick(); + changed.mockClear(); + + field.formModel.update((model) => ({ + ...model, + [segment]: invalid, + })); + TestBed.tick(); + expect(changed).not.toHaveBeenCalled(); + + field.formModel.update((model) => ({ ...model, [segment]: valid })); + TestBed.tick(); + expect(changed).toHaveBeenCalledExactlyOnceWith( + SEGMENTS.map((key) => (key === segment ? valid : '*')).join( + ' ', + ), + ); + }, + ); +}); diff --git a/src/tests/ui/custom-fields/date-calendar.component.spec.ts b/src/tests/ui/custom-fields/date-calendar.component.spec.ts new file mode 100644 index 000000000..a33eafaa0 --- /dev/null +++ b/src/tests/ui/custom-fields/date-calendar.component.spec.ts @@ -0,0 +1,38 @@ +import { provideZonelessChangeDetection } from '@angular/core'; +import { ComponentFixtureAutoDetect, TestBed } from '@angular/core/testing'; +import { describe, expect, it, vi } from 'vitest'; +import { DateCalendarComponent } from '../../../app/ui/custom-fields/date-calendar.component'; + +vi.mock('@placeos/ts-client', () => + vi.importActual('@placeos/ts-client/dist/index.es.js'), +); + +const FROM = new Date(2026, 0, 10).valueOf(); +const TO = new Date(2026, 0, 20).valueOf(); + +describe('DateCalendarComponent', () => { + it('accepts dates from the start up to but not including the end', () => { + TestBed.configureTestingModule({ + providers: [ + provideZonelessChangeDetection(), + { provide: ComponentFixtureAutoDetect, useValue: false }, + ], + }); + const fixture = TestBed.createComponent(DateCalendarComponent); + fixture.componentRef.setInput('from', FROM); + fixture.componentRef.setInput('to', TO); + const calendar = fixture.componentInstance; + const changed = vi.fn(); + calendar.registerOnChange(changed); + + calendar.setValue(FROM - 1); + calendar.setValue(TO); + expect(changed).not.toHaveBeenCalled(); + expect(calendar.active_date()).toBe(calendar.today); + + calendar.setValue(FROM); + calendar.setValue(TO - 1); + expect(changed.mock.calls).toEqual([[FROM], [TO - 1]]); + expect(calendar.active_date()).toBe(new Date(2026, 0, 19).valueOf()); + }); +}); diff --git a/src/tests/ui/custom-fields/execute-method-field.component.spec.ts b/src/tests/ui/custom-fields/execute-method-field.component.spec.ts new file mode 100644 index 000000000..f226184d5 --- /dev/null +++ b/src/tests/ui/custom-fields/execute-method-field.component.spec.ts @@ -0,0 +1,56 @@ +import { provideZonelessChangeDetection } from '@angular/core'; +import { ComponentFixtureAutoDetect, TestBed } from '@angular/core/testing'; +import { + executeOnSystem, + PlaceModuleFunction, + PlaceSystem, +} from '@placeos/ts-client'; +import { describe, expect, it, vi } from 'vitest'; +import { ExecuteMethodFieldComponent } from '../../../app/ui/custom-fields/system-exec/execute-method-field.component'; + +vi.mock('@placeos/ts-client', async () => ({ + ...(await vi.importActual('@placeos/ts-client/dist/index.es.js')), + executeOnSystem: vi.fn(() => Promise.resolve('ok')), +})); + +vi.mock('../../../app/common/notifications', () => ({ + notifyError: vi.fn(), + notifySuccess: vi.fn(), +})); + +describe('ExecuteMethodFieldComponent', () => { + it('sends arguments in method order with JSON values and defaults', async () => { + TestBed.configureTestingModule({ + providers: [ + provideZonelessChangeDetection(), + // The template loads modules from the API, so do not render it + { provide: ComponentFixtureAutoDetect, useValue: false }, + ], + }); + const fixture = TestBed.createComponent(ExecuteMethodFieldComponent); + fixture.componentRef.setInput('system', { id: 'sys-1' } as PlaceSystem); + const field = fixture.componentInstance; + field.module.set({ module: 'Display', index: 2 } as never); + field.fn.set({ + name: 'power', + order: ['level', 'enabled', 'label', 'mode'], + params: { mode: { default: 'auto' } }, + } as unknown as PlaceModuleFunction); + field.arguments.set({ + mode: '', + label: 'hello', + enabled: 'false', + level: '0', + }); + + await field.execute(); + + expect(executeOnSystem).toHaveBeenCalledWith( + 'sys-1', + 'power', + 'Display', + 2, + [0, false, 'hello', 'auto'], + ); + }); +}); diff --git a/src/tests/ui/custom-fields/item-search-field.component.spec.ts b/src/tests/ui/custom-fields/item-search-field.component.spec.ts index 7d30a3ace..b99d4c796 100644 --- a/src/tests/ui/custom-fields/item-search-field.component.spec.ts +++ b/src/tests/ui/custom-fields/item-search-field.component.spec.ts @@ -86,4 +86,28 @@ describe('ItemSearchFieldComponent', () => { ); expect(names['sys-1']).toBe('<Unnamed>'); }); + + it('should query only once the trimmed search reaches the minimum length', async () => { + const query_fn = vi.fn(() => + Promise.resolve([ + { id: 'sys-1', name: 'Lobby' }, + { id: 'sys-2', name: 'Board room' }, + ]), + ); + const field = TestBed.createComponent(ItemSearchFieldComponent); + field.componentRef.setInput('minLength', 3); + field.componentRef.setInput('query_fn', query_fn); + field.detectChanges(); + + field.componentInstance.search_str.set(' lo '); + await sleep(450); + expect(query_fn).not.toHaveBeenCalled(); + + field.componentInstance.search_str.set(' lob '); + await sleep(450); + expect(query_fn).toHaveBeenCalledExactlyOnceWith('lob'); + expect(field.componentInstance.item_list()).toEqual([ + { id: 'sys-1', name: 'Lobby' }, + ]); + }); }); diff --git a/src/tests/ui/extension-outlet.component.spec.ts b/src/tests/ui/extension-outlet.component.spec.ts index a10f7eea5..86adbdb15 100644 --- a/src/tests/ui/extension-outlet.component.spec.ts +++ b/src/tests/ui/extension-outlet.component.spec.ts @@ -63,10 +63,11 @@ describe('ExtensionOutletComponent', () => { const send = async ( message: Partial, source = frame_window, + origin = new URL(EXTENSION_URL).origin, ) => { fixture.componentInstance.onMessage({ source, - origin: new URL(EXTENSION_URL).origin, + origin, data: JSON.stringify({ id: '1', type: 'backoffice', ...message }), } as MessageEvent); // Let the mocked API promises settle @@ -157,8 +158,13 @@ describe('ExtensionOutletComponent', () => { expect(no_name).toMatchObject({ id: '2', status: 'error' }); }); - it('ignores messages from other windows and unknown actions', async () => { + it('ignores messages from other windows, other origins and unknown actions', async () => { await send({ action: 'update', content: {} }, window); + await send( + { action: 'update', content: {} }, + frame_window, + 'https://evil.example', + ); await send({ action: 'result' }); expect(replies).toEqual([]); expect(save).not.toHaveBeenCalled(); diff --git a/src/tests/ui/pipes/markdown.pipe.spec.ts b/src/tests/ui/pipes/markdown.pipe.spec.ts index c3b9715d5..149308fe7 100644 --- a/src/tests/ui/pipes/markdown.pipe.spec.ts +++ b/src/tests/ui/pipes/markdown.pipe.spec.ts @@ -22,4 +22,27 @@ describe('Markdown highlighting', () => { '', ); }); + + it('keeps raw HTML and unsafe URLs inactive and renders safe links', async () => { + const pipe = TestBed.runInInjectionContext(() => new MarkdownPipe()); + const value = await pipe.transform( + '\n\n' + + 'Text inline\n\n' + + '[bad](javascript:alert(3)) ![pic](javascript:alert(4)) ' + + '[docs](https://example.com/docs)', + ); + const html = TestBed.inject(DomSanitizer).sanitize( + SecurityContext.HTML, + value, + ); + const document = new DOMParser().parseFromString(html, 'text/html'); + + expect(document.querySelector('[onerror], [onclick]')).toBeNull(); + expect(document.querySelector('img')).toBeNull(); + expect(html).not.toContain('javascript:'); + const links = document.querySelectorAll('a'); + expect(links).toHaveLength(1); + expect(links[0].getAttribute('href')).toBe('https://example.com/docs'); + expect(links[0].textContent).toBe('docs'); + }); }); diff --git a/src/tests/ui/pipes/safe.pipe.spec.ts b/src/tests/ui/pipes/safe.pipe.spec.ts index 36686da06..3949efced 100644 --- a/src/tests/ui/pipes/safe.pipe.spec.ts +++ b/src/tests/ui/pipes/safe.pipe.spec.ts @@ -1,3 +1,4 @@ +import { SecurityContext } from '@angular/core'; import { TestBed } from '@angular/core/testing'; import { DomSanitizer } from '@angular/platform-browser'; import { beforeEach, describe, expect, it } from 'vitest'; @@ -29,18 +30,18 @@ describe('SafePipe', () => { 'https://example.com/video.mp4', 'resource', ); - expect(result).toBeTruthy(); - expect((result as any).changingThisBreaksApplicationSecurity).toBe( - 'https://example.com/video.mp4', - ); + // Throws unless the value is trusted as a resource URL + expect( + sanitizer.sanitize(SecurityContext.RESOURCE_URL, result), + ).toBe('https://example.com/video.mp4'); }); it('should handle blob URLs for resources', () => { const url = 'blob:https://example.com/12345'; const result = pipe.transform(url, 'resource'); - expect((result as any).changingThisBreaksApplicationSecurity).toBe( - url, - ); + expect( + sanitizer.sanitize(SecurityContext.RESOURCE_URL, result), + ).toBe(url); }); it('should handle data URLs', () => { diff --git a/src/tests/ui/pipes/user.pipe.spec.ts b/src/tests/ui/pipes/user.pipe.spec.ts index 51868dbd4..10e370334 100644 --- a/src/tests/ui/pipes/user.pipe.spec.ts +++ b/src/tests/ui/pipes/user.pipe.spec.ts @@ -70,6 +70,17 @@ describe('UserPipe', () => { expect(showUser).toHaveBeenCalledTimes(1); }); + it('should retry a lookup that failed', async () => { + const { showUser } = await import('@placeos/ts-client'); + vi.mocked(showUser).mockRejectedValueOnce(new Error('offline')); + + expect(await pipe.transform('user-retry')).toEqual({}); + const result = await pipe.transform('user-retry'); + + expect(result.id).toBe('user-retry'); + expect(showUser).toHaveBeenCalledTimes(2); + }); + it('should return user with expected properties', async () => { const result = await pipe.transform('test-user'); expect(result).toHaveProperty('id'); From 2cea5fecf32c1c02a7ed381babaa77843a44c34d Mon Sep 17 00:00:00 2001 From: Alex Sorafumo Date: Fri, 13 Nov 2026 19:10:31 +1100 Subject: [PATCH 4/5] test(systems): cover module races, driver updates and repository branch selection Co-Authored-By: Claude Opus 5.5 --- .../drivers/driver-form.component.spec.ts | 141 ++++++++++++++++++ ...driver-update-list-modal.component.spec.ts | 96 ++++++++++++ .../modules/module-state.service.spec.ts | 59 ++++++++ .../repositories-state.service.spec.ts | 8 +- .../repository-form.component.spec.ts | 40 +++++ .../systems/system-form.component.spec.ts | 68 +++++++++ .../systems/system-state.service.spec.ts | 128 +++++++++++++++- .../systems/system-zones.component.spec.ts | 54 +++++++ src/tests/systems/systems.utilities.spec.ts | 37 ++++- 9 files changed, 625 insertions(+), 6 deletions(-) create mode 100644 src/tests/drivers/driver-form.component.spec.ts create mode 100644 src/tests/drivers/driver-update-list-modal.component.spec.ts create mode 100644 src/tests/modules/module-state.service.spec.ts create mode 100644 src/tests/systems/system-form.component.spec.ts create mode 100644 src/tests/systems/system-zones.component.spec.ts diff --git a/src/tests/drivers/driver-form.component.spec.ts b/src/tests/drivers/driver-form.component.spec.ts new file mode 100644 index 000000000..f013c5f2a --- /dev/null +++ b/src/tests/drivers/driver-form.component.spec.ts @@ -0,0 +1,141 @@ +import { DIALOG_DATA, DialogRef } from '@angular/cdk/dialog'; +import { provideZonelessChangeDetection } from '@angular/core'; +import { ComponentFixture, TestBed } from '@angular/core/testing'; +import { + EncryptionLevel, + PlaceDriver, + PlaceDriverDetails, + PlaceDriverRole, + PlaceRepository, +} from '@placeos/ts-client'; +import { EMPTY } from 'rxjs'; +import { beforeEach, describe, expect, it, vi } from 'vitest'; +import { DriverFormComponent } from '../../app/drivers/driver-form.component'; + +const mocks = vi.hoisted(() => ({ + addDriver: vi.fn(), + addSettings: vi.fn(), + listRepositoryCommits: vi.fn(), + listRepositoryDriverDetails: vi.fn(), + listRepositoryDrivers: vi.fn(), + queryRepositories: vi.fn(), +})); +vi.mock('@placeos/ts-client', async () => ({ + ...(await vi.importActual( + '@placeos/ts-client/dist/index.es.js', + )), + ...mocks, +})); +vi.mock('../../app/common/notifications', async (importOriginal) => ({ + ...(await importOriginal()), + notifyError: vi.fn(), + notifySuccess: vi.fn(), +})); + +const commit = (id: string) => ({ id, name: id, extra: null }); +const details = (values: Partial) => + ({ default_settings: '{}', ...values }) as PlaceDriverDetails; + +describe('DriverFormComponent', () => { + let fixture: ComponentFixture; + let component: DriverFormComponent; + + beforeEach(async () => { + vi.resetAllMocks(); + mocks.listRepositoryCommits.mockResolvedValue([]); + mocks.listRepositoryDrivers.mockResolvedValue([]); + mocks.queryRepositories.mockResolvedValue({ data: [] }); + TestBed.configureTestingModule({ + imports: [DriverFormComponent], + providers: [ + provideZonelessChangeDetection(), + { + provide: DialogRef, + useValue: { + close: vi.fn(), + backdropClick: EMPTY, + keydownEvents: EMPTY, + }, + }, + { provide: DIALOG_DATA, useValue: { item: new PlaceDriver() } }, + ], + }); + fixture = TestBed.createComponent(DriverFormComponent); + component = fixture.componentInstance; + await fixture.whenStable(); + component.repo.set(new PlaceRepository({ id: 'repo-1' })); + component.driver.set({ id: 'display.cr', name: 'display.cr' }); + }); + + it('keeps the latest commit when an older details request finishes last', async () => { + let resolve_first: (value: PlaceDriverDetails) => void; + mocks.listRepositoryDriverDetails + .mockReturnValueOnce( + new Promise((resolve) => (resolve_first = resolve)), + ) + .mockResolvedValueOnce(details({ descriptive_name: 'Second' })); + + const first = component.applyDriverCommit(commit('commit-1')); + await component.applyDriverCommit(commit('commit-2')); + resolve_first(details({ descriptive_name: 'First' })); + await first; + + expect(component.commit()?.id).toBe('commit-2'); + expect(component.formModel()).toMatchObject({ + commit: 'commit-2', + name: 'Second', + }); + }); + + it.each([ + ['port 22', { tcp_port: 22 }, PlaceDriverRole.SSH], + ['another port', { udp_port: 4999 }, PlaceDriverRole.Device], + [ + 'a WebSocket URI', + { uri_base: 'wss://example.com' }, + PlaceDriverRole.Websocket, + ], + [ + 'a service URI', + { uri_base: 'https://example.com' }, + PlaceDriverRole.Service, + ], + ['no connection details', {}, PlaceDriverRole.Logic], + ])('sets the role from %s', async (_, connection, role) => { + // Start from another role so each case must set it + component.formModel.update((model) => ({ + ...model, + role: + role === PlaceDriverRole.Logic + ? PlaceDriverRole.Device + : PlaceDriverRole.Logic, + })); + mocks.listRepositoryDriverDetails.mockResolvedValue( + details(connection), + ); + + await component.applyDriverCommit(commit('commit-1')); + + expect(component.formModel().role).toBe(role); + }); + + it('saves the initial settings of a new driver', async () => { + mocks.addDriver.mockResolvedValue(new PlaceDriver({ id: 'driver-1' })); + mocks.addSettings.mockResolvedValue({}); + component.formModel.update((model) => ({ + ...model, + name: 'Display', + module_name: 'Display', + settings: 'volume: 10\n', + })); + + await component.submit(); + + expect(mocks.addSettings).toHaveBeenCalledOnce(); + expect(mocks.addSettings.mock.calls[0][0]).toMatchObject({ + parent_id: 'driver-1', + settings_string: 'volume: 10\n', + encryption_level: EncryptionLevel.Support, + }); + }); +}); diff --git a/src/tests/drivers/driver-update-list-modal.component.spec.ts b/src/tests/drivers/driver-update-list-modal.component.spec.ts new file mode 100644 index 000000000..214a36eca --- /dev/null +++ b/src/tests/drivers/driver-update-list-modal.component.spec.ts @@ -0,0 +1,96 @@ +import { DialogRef } from '@angular/cdk/dialog'; +import { provideZonelessChangeDetection } from '@angular/core'; +import { ComponentFixture, TestBed } from '@angular/core/testing'; +import { PlaceDriver } from '@placeos/ts-client'; +import { beforeEach, describe, expect, it, vi } from 'vitest'; +import { notifyError, notifySuccess } from '../../app/common/notifications'; +import { DriverUpdateListModalComponent } from '../../app/drivers/driver-update-list-modal.component'; + +const mocks = vi.hoisted(() => ({ + queryDrivers: vi.fn(), + updateDriver: vi.fn(), +})); +vi.mock('@placeos/ts-client', async () => ({ + ...(await vi.importActual( + '@placeos/ts-client/dist/index.es.js', + )), + ...mocks, +})); +vi.mock('../../app/common/notifications', () => ({ + notifyError: vi.fn(), + notifySuccess: vi.fn(), +})); + +/** Driver with an update from `-old` to `-new` */ +const driver = (id: string) => + new PlaceDriver({ + id, + name: id, + commit: `${id}-old`, + update_info: { + commit: `${id}-new`, + message: '', + author: '', + date: '2026-01-01T00:00:00Z', + }, + }); + +describe('DriverUpdateListModalComponent', () => { + let fixture: ComponentFixture; + let dialog_ref: { close: () => void; disableClose: boolean }; + + beforeEach(async () => { + vi.resetAllMocks(); + mocks.queryDrivers.mockResolvedValue({ + data: ['drv-1', 'drv-2', 'drv-3'].map(driver), + total: 3, + }); + dialog_ref = { close: vi.fn(), disableClose: false }; + TestBed.configureTestingModule({ + imports: [DriverUpdateListModalComponent], + providers: [ + provideZonelessChangeDetection(), + { provide: DialogRef, useValue: dialog_ref }, + ], + }); + fixture = TestBed.createComponent(DriverUpdateListModalComponent); + await fixture.whenStable(); + }); + + it('updates only the selected drivers to their advertised commit', async () => { + mocks.updateDriver.mockResolvedValue({}); + const component = fixture.componentInstance; + component.toggleDriver('drv-1', true); + component.toggleDriver('drv-3', true); + + await component.updateDrivers(); + + expect( + mocks.updateDriver.mock.calls.map(([id, item]) => [ + id, + item.commit, + ]), + ).toEqual([ + ['drv-1', 'drv-1-new'], + ['drv-3', 'drv-3-new'], + ]); + }); + + it('reports failed updates and keeps the dialog open', async () => { + mocks.updateDriver.mockImplementation(async (id: string) => { + if (id === 'drv-2') throw new Error('Build failed'); + return {}; + }); + const component = fixture.componentInstance; + component.toggleAll(true); + + await component.updateDrivers(); + + expect(notifyError).toHaveBeenCalledWith( + expect.stringContaining('Failed to update 1 of 3 drivers'), + ); + expect(notifySuccess).not.toHaveBeenCalled(); + expect(dialog_ref.disableClose).toBe(false); + expect(dialog_ref.close).not.toHaveBeenCalled(); + }); +}); diff --git a/src/tests/modules/module-state.service.spec.ts b/src/tests/modules/module-state.service.spec.ts new file mode 100644 index 000000000..92929610b --- /dev/null +++ b/src/tests/modules/module-state.service.spec.ts @@ -0,0 +1,59 @@ +import { Dialog } from '@angular/cdk/dialog'; +import { provideZonelessChangeDetection, signal } from '@angular/core'; +import { TestBed } from '@angular/core/testing'; +import { PlaceModule } from '@placeos/ts-client'; +import { describe, expect, it, vi } from 'vitest'; +import { ActiveItemService } from '../../app/common/item.service'; +import { ModuleStateService } from '../../app/modules/module-state.service'; + +const mocks = vi.hoisted(() => ({ + startModule: vi.fn(), +})); +vi.mock('@placeos/ts-client', async () => ({ + ...(await vi.importActual( + '@placeos/ts-client/dist/index.es.js', + )), + ...mocks, +})); +vi.mock('../../app/common/item.service', () => ({ + ActiveItemService: class {}, +})); +vi.mock('../../app/common/notifications', () => ({ + notifyError: vi.fn(), + notifySuccess: vi.fn(), +})); +vi.mock('../../app/common/support-access', () => ({ + querySupportSystems: vi.fn(), +})); +vi.mock('../../app/overlays/view-response-modal.component', () => ({ + ViewResponseModalComponent: class {}, +})); + +describe('ModuleStateService', () => { + it('changes the power state of the module the request started for', async () => { + const module_a = new PlaceModule({ id: 'mod-a' }); + const module_b = new PlaceModule({ id: 'mod-b' }); + const state = { item: signal(null), active_item: module_a }; + TestBed.configureTestingModule({ + providers: [ + provideZonelessChangeDetection(), + ModuleStateService, + { provide: ActiveItemService, useValue: state }, + { provide: Dialog, useValue: {} }, + ], + }); + let resolve_power: () => void; + mocks.startModule.mockReturnValue( + new Promise((resolve) => (resolve_power = resolve)), + ); + + const request = TestBed.inject(ModuleStateService).toggleModuleState(); + state.active_item = module_b; + resolve_power(); + await request; + + expect(mocks.startModule).toHaveBeenCalledWith('mod-a'); + expect(module_a.running).toBe(true); + expect(module_b.running).toBe(false); + }); +}); diff --git a/src/tests/repositories/repositories-state.service.spec.ts b/src/tests/repositories/repositories-state.service.spec.ts index c2ea03b50..ddd72af9b 100644 --- a/src/tests/repositories/repositories-state.service.spec.ts +++ b/src/tests/repositories/repositories-state.service.spec.ts @@ -1,5 +1,9 @@ import { Dialog } from '@angular/cdk/dialog'; -import { provideZonelessChangeDetection, signal } from '@angular/core'; +import { + ApplicationRef, + provideZonelessChangeDetection, + signal, +} from '@angular/core'; import { TestBed } from '@angular/core/testing'; import { PlaceRepository, PlaceRepositoryType } from '@placeos/ts-client'; import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'; @@ -133,7 +137,7 @@ describe('RepositoriesStateService', () => { const service = TestBed.inject(RepositoriesStateService); - await Promise.resolve(); + await TestBed.inject(ApplicationRef).whenStable(); expect(service.has_changelog()).toBe(false); expect(fetch_mock).not.toHaveBeenCalled(); }); diff --git a/src/tests/repositories/repository-form.component.spec.ts b/src/tests/repositories/repository-form.component.spec.ts index 16251acde..ad0e41151 100644 --- a/src/tests/repositories/repository-form.component.spec.ts +++ b/src/tests/repositories/repository-form.component.spec.ts @@ -114,4 +114,44 @@ describe('RepositoryFormComponent', () => { component.filtered_commit_list().map(({ hash }) => hash), ).toEqual(['HEAD', 'abc123']); }); + + it('pins the newest commit when following HEAD is turned off', () => { + const component = fixture.componentInstance; + component.commit_list.set([ + { hash: 'HEAD', subject: 'Latest commit' }, + { hash: 'abc123', subject: 'Newest commit' }, + { hash: 'def456', subject: 'Older commit' }, + ]); + + component.setFollow(false); + expect(component.follow_latest()).toBe(false); + expect(component.formModel().commit_hash).toBe('abc123'); + + component.setFollow(true); + expect(component.follow_latest()).toBe(true); + expect(component.formModel().commit_hash).toBe('HEAD'); + }); + + it.each([ + { selected: '', expected: 'main' }, + { selected: 'missing', expected: 'main' }, + { selected: 'dev', expected: 'dev' }, + ])( + 'selects $expected after branches load when the branch is $selected', + async ({ selected, expected }) => { + const component = fixture.componentInstance; + component.formModel.update((model) => ({ + ...model, + branch: selected, + })); + + component.markCredentialsBlur(); + await vi.waitFor(() => { + expect(listRepositoryBranches).toHaveBeenCalledTimes(2); + expect(component.loading_branches()).toBe(false); + }); + + expect(component.formModel().branch).toBe(expected); + }, + ); }); diff --git a/src/tests/systems/system-form.component.spec.ts b/src/tests/systems/system-form.component.spec.ts new file mode 100644 index 000000000..d5eacd6c1 --- /dev/null +++ b/src/tests/systems/system-form.component.spec.ts @@ -0,0 +1,68 @@ +import { DIALOG_DATA, DialogRef } from '@angular/cdk/dialog'; +import { provideZonelessChangeDetection } from '@angular/core'; +import { TestBed } from '@angular/core/testing'; +import { PlaceSystem, PlaceZone } from '@placeos/ts-client'; +import { EMPTY } from 'rxjs'; +import { describe, expect, it, vi } from 'vitest'; +import { SystemFormComponent } from '../../app/systems/system-form.component'; + +const mocks = vi.hoisted(() => ({ + addSystem: vi.fn(), +})); +vi.mock('@placeos/ts-client', async () => ({ + ...(await vi.importActual( + '@placeos/ts-client/dist/index.es.js', + )), + ...mocks, +})); +vi.mock('@placeos/cloud-uploads', () => + vi.importActual('@placeos/cloud-uploads/dist/index.es.js'), +); +vi.mock('../../app/common/support-access', () => ({ + querySupportZones: async () => ({ data: [] }), +})); +vi.mock('../../app/common/notifications', async (importOriginal) => ({ + ...(await importOriginal()), + notifyError: vi.fn(), + notifySuccess: vi.fn(), +})); + +describe('SystemFormComponent', () => { + it('saves the selected zone as the zone list without the zone field', async () => { + mocks.addSystem.mockResolvedValue(new PlaceSystem({ id: 'sys-1' })); + TestBed.configureTestingModule({ + imports: [SystemFormComponent], + providers: [ + provideZonelessChangeDetection(), + { + provide: DialogRef, + useValue: { + close: vi.fn(), + backdropClick: EMPTY, + keydownEvents: EMPTY, + }, + }, + { + provide: DIALOG_DATA, + useValue: { item: new PlaceSystem({ zones: ['zone-1'] }) }, + }, + ], + }); + const fixture = TestBed.createComponent(SystemFormComponent); + const component = fixture.componentInstance; + await fixture.whenStable(); + + component.formModel.update((model) => ({ + ...model, + name: 'Meeting room', + zone: new PlaceZone({ id: 'zone-2' }), + })); + await fixture.whenStable(); + await component.submit(); + + expect(mocks.addSystem).toHaveBeenCalledOnce(); + const [payload] = mocks.addSystem.mock.calls[0]; + expect(payload.zones).toEqual(['zone-2']); + expect(payload).not.toHaveProperty('zone'); + }); +}); diff --git a/src/tests/systems/system-state.service.spec.ts b/src/tests/systems/system-state.service.spec.ts index f898c82a8..42c54db63 100644 --- a/src/tests/systems/system-state.service.spec.ts +++ b/src/tests/systems/system-state.service.spec.ts @@ -6,19 +6,24 @@ import { } from '@angular/core'; import { TestBed } from '@angular/core/testing'; import { NavigationEnd, Router } from '@angular/router'; -import { PlaceModule, PlaceSystem } from '@placeos/ts-client'; +import { PlaceModule, PlaceSystem, PlaceZone } from '@placeos/ts-client'; import { Subject } from 'rxjs'; import { beforeEach, describe, expect, it, vi } from 'vitest'; import { PlaceDebugService } from '../../app/common/debug.service'; import { ActiveItemService } from '../../app/common/item.service'; +import { notifyError } from '../../app/common/notifications'; +import { openConfirmModal } from '../../app/overlays/confirm-modal.component'; import { SystemStateService } from '../../app/systems/system-state.service'; const mocks = vi.hoisted(() => ({ + isSubsystemUser: vi.fn(), listMetadata: vi.fn(), listSystemTriggers: vi.fn(), listSystemZones: vi.fn(), queryModules: vi.fn(), + showZone: vi.fn(), startModule: vi.fn(), + stopSystem: vi.fn(), systemSettings: vi.fn(), })); vi.mock('@placeos/ts-client', async () => ({ @@ -34,7 +39,7 @@ vi.mock('../../app/common/debug.service', () => ({ PlaceDebugService: class {}, })); vi.mock('../../app/common/support-access', () => ({ - isSubsystemUser: () => false, + isSubsystemUser: () => mocks.isSubsystemUser(), querySupportSystems: vi.fn(), })); vi.mock('../../app/common/notifications', () => ({ @@ -65,6 +70,9 @@ describe('SystemStateService', () => { let service: SystemStateService; const stable = () => TestBed.inject(ApplicationRef).whenStable(); + // Lets a late API response finish after the app is stable + const flush = () => new Promise((resolve) => setTimeout(resolve)); + const moduleIds = () => service.modules().map(({ id }) => id); const openTab = (tab: string) => { router.url = `/systems/sys-1/${tab}`; router.events.next(new NavigationEnd(1, router.url, router.url)); @@ -74,6 +82,7 @@ describe('SystemStateService', () => { vi.resetAllMocks(); active.set(null); router = { url: '/systems/sys-1/about', events: new Subject() }; + mocks.isSubsystemUser.mockReturnValue(false); mocks.listMetadata.mockResolvedValue([]); mocks.listSystemTriggers.mockResolvedValue({ data: [], total: 3 }); mocks.listSystemZones.mockResolvedValue({ data: [] }); @@ -116,7 +125,103 @@ describe('SystemStateService', () => { await stable(); expect(mocks.queryModules).toHaveBeenCalledTimes(1); - expect(service.modules().map(({ id }) => id)).toEqual(['mod-1']); + expect(moduleIds()).toEqual(['mod-1']); + }); + + it('orders modules by the system module list', async () => { + mocks.queryModules.mockResolvedValue({ + data: ['mod-3', 'mod-1', 'mod-2'].map( + (id) => new PlaceModule({ id }), + ), + }); + openTab('modules'); + service.modules(); + active.set( + new PlaceSystem({ + id: 'sys-1', + modules: ['mod-1', 'mod-2', 'mod-3'], + }), + ); + await stable(); + + expect(moduleIds()).toEqual(['mod-1', 'mod-2', 'mod-3']); + }); + + it('ignores a module response for a system that is no longer active', async () => { + let resolve_old: (response: { data: PlaceModule[] }) => void; + mocks.queryModules + .mockReturnValueOnce( + new Promise((resolve) => (resolve_old = resolve)), + ) + .mockResolvedValueOnce({ + data: [new PlaceModule({ id: 'mod-2' })], + }); + openTab('modules'); + service.modules(); + active.set(system); + TestBed.tick(); + active.set(new PlaceSystem({ id: 'sys-2', modules: ['mod-2'] })); + await stable(); + resolve_old({ data: [new PlaceModule({ id: 'mod-1' })] }); + await flush(); + + expect(mocks.queryModules).toHaveBeenCalledTimes(2); + expect(moduleIds()).toEqual(['mod-2']); + }); + + it('keeps known connection state when the module list refreshes', async () => { + openTab('modules'); + service.modules(); + active.set(system); + await stable(); + const loaded = service.modules()[0] as PlaceModule & { + connected?: boolean; + }; + // Bindings set this, and only emit again when it changes + loaded.connected = true; + mocks.queryModules.mockResolvedValue({ + data: [new PlaceModule({ id: 'mod-1' })], + }); + + await service.toggleModulePower(loaded); + await stable(); + + expect(service.modules()[0]).not.toBe(loaded); + expect(service.modules()[0].connected).toBe(true); + }); + + it('shows the readable zones when a subsystem user cannot read one', async () => { + mocks.isSubsystemUser.mockReturnValue(true); + mocks.showZone.mockImplementation(async (id: string) => { + if (id === 'zone-2') throw new Error('Forbidden'); + return new PlaceZone({ id }); + }); + openTab('zones'); + service.zones(); + active.set( + new PlaceSystem({ + id: 'sys-1', + zones: ['zone-1', 'zone-2', 'zone-3'], + }), + ); + await stable(); + + expect(service.zones().map(({ id }) => id)).toEqual([ + 'zone-1', + 'zone-3', + ]); + expect(mocks.listSystemZones).not.toHaveBeenCalled(); + }); + + it('does not stop the system when the user cancels', async () => { + vi.mocked(openConfirmModal).mockResolvedValue({ + loading: vi.fn(), + close: vi.fn(), + }); + + await service.stopSystem(); + + expect(mocks.stopSystem).not.toHaveBeenCalled(); }); it('reloads only the module list after a module power change', async () => { @@ -136,4 +241,21 @@ describe('SystemStateService', () => { expect(mocks.systemSettings).not.toHaveBeenCalled(); expect(mocks.listMetadata).not.toHaveBeenCalled(); }); + + it('keeps the running state and module list when a power change fails', async () => { + openTab('modules'); + service.modules(); + active.set(system); + await stable(); + vi.clearAllMocks(); + mocks.startModule.mockRejectedValue('Module offline'); + const [device] = service.modules(); + + await service.toggleModulePower(device); + await stable(); + + expect(device.running).toBe(false); + expect(notifyError).toHaveBeenCalledWith('Module offline'); + expect(mocks.queryModules).not.toHaveBeenCalled(); + }); }); diff --git a/src/tests/systems/system-zones.component.spec.ts b/src/tests/systems/system-zones.component.spec.ts new file mode 100644 index 000000000..86f447c57 --- /dev/null +++ b/src/tests/systems/system-zones.component.spec.ts @@ -0,0 +1,54 @@ +import { provideZonelessChangeDetection, signal } from '@angular/core'; +import { TestBed } from '@angular/core/testing'; +import { provideRouter } from '@angular/router'; +import { PlaceSystem, PlaceZone } from '@placeos/ts-client'; +import { describe, expect, it, vi } from 'vitest'; +import { SystemStateService } from '../../app/systems/system-state.service'; +import { SystemZonesComponent } from '../../app/systems/system-zones.component'; + +vi.mock('@placeos/ts-client', () => + vi.importActual('@placeos/ts-client/dist/index.es.js'), +); +vi.mock('../../app/systems/system-state.service', () => ({ + SystemStateService: class {}, +})); +vi.mock('../../app/common/support-access', () => ({ + querySupportZones: async () => ({ data: [] }), +})); + +describe('SystemZonesComponent', () => { + it('drops unsaved zone changes when the tab shows another system', async () => { + const system = new PlaceSystem({ id: 'sys-1', zones: ['zone-1'] }); + const item = signal(system); + TestBed.configureTestingModule({ + imports: [SystemZonesComponent], + providers: [ + provideZonelessChangeDetection(), + provideRouter([]), + { + provide: SystemStateService, + useValue: { + item, + zones: signal([new PlaceZone({ id: 'zone-1' })]), + loading: signal({}), + active_item: system, + }, + }, + ], + }); + const fixture = TestBed.createComponent(SystemZonesComponent); + const component = fixture.componentInstance; + await fixture.whenStable(); + component.addPendingZone(new PlaceZone({ id: 'zone-2' })); + await component.reorder([0, 1]); + await fixture.whenStable(); + expect(component.zone_order()).toEqual(['zone-2', 'zone-1']); + + item.set(new PlaceSystem({ id: 'sys-2' })); + await fixture.whenStable(); + + expect(component.pending_zones()).toEqual([]); + expect(component.zone_order()).toEqual([]); + expect(component.has_changes()).toBe(false); + }); +}); diff --git a/src/tests/systems/systems.utilities.spec.ts b/src/tests/systems/systems.utilities.spec.ts index 0e3d3b3b2..0af24de24 100644 --- a/src/tests/systems/systems.utilities.spec.ts +++ b/src/tests/systems/systems.utilities.spec.ts @@ -1,4 +1,5 @@ -import { describe, expect, it } from 'vitest'; +import type { PlaceSystem } from '@placeos/ts-client'; +import { afterEach, describe, expect, it, vi } from 'vitest'; import { generateSystemFormModel, validateYAML, @@ -70,5 +71,39 @@ describe('systems.utilities', () => { zones: ['zone-1'], }); }); + + describe('with legacy and current snapshot URLs', () => { + const legacy_url = 'https://example.com/legacy.jpg'; + const current_url = 'https://example.com/current.jpg'; + // Local midnight at the start of the frozen day, in seconds + const midnight = new Date(2026, 0, 2).getTime() / 1000; + + afterEach(() => vi.useRealTimers()); + + it.each([ + { saved: 'never', updated_at: undefined, merged: true }, + { + saved: 'before today', + updated_at: midnight - 1, + merged: true, + }, + { saved: 'today', updated_at: midnight, merged: false }, + ])( + 'merges the legacy URL ($merged) for a system saved $saved', + ({ updated_at, merged }) => { + vi.useFakeTimers({ toFake: ['Date'] }); + vi.setSystemTime(new Date(2026, 0, 2, 12)); + const model = generateSystemFormModel({ + camera_snapshot_url: legacy_url, + camera_snapshot_urls: [current_url], + updated_at, + } as PlaceSystem); + + expect(model.camera_snapshot_urls).toEqual( + merged ? [current_url, legacy_url] : [current_url], + ); + }, + ); + }); }); }); From 6d1e94d78e894c60e9aa600932875dc53ca2f93a Mon Sep 17 00:00:00 2001 From: Alex Sorafumo Date: Fri, 13 Nov 2026 19:10:31 +1100 Subject: [PATCH 5/5] test(org): cover restricted user saves, trigger edits and bulk create failures Co-Authored-By: Claude Opus 5.5 --- .../application-form.component.spec.ts | 74 +++++++++ .../domains/domain-state.service.spec.ts | 20 ++- src/tests/groups/group-form.component.spec.ts | 86 ++++++++++ src/tests/groups/group-state.service.spec.ts | 33 ++++ .../auth-source-modal.component.spec.ts | 115 ++++++++++++++ .../bulk-item-modal.component.spec.ts | 100 ++++++++++++ .../overlays/confirm-modal.component.spec.ts | 17 -- .../duplicate-modal.component.spec.ts | 24 +++ .../triggers/trigger-state.service.spec.ts | 150 ++++++++++++++++++ src/tests/users/user-form.component.spec.ts | 82 ++++++++++ src/tests/users/users.service.spec.ts | 46 ++++++ src/tests/zones/zone-form.component.spec.ts | 22 +++ src/tests/zones/zones-state.service.spec.ts | 56 ++++++- 13 files changed, 802 insertions(+), 23 deletions(-) create mode 100644 src/tests/domains/application-form.component.spec.ts create mode 100644 src/tests/groups/group-form.component.spec.ts create mode 100644 src/tests/overlays/auth-source-modal.component.spec.ts create mode 100644 src/tests/overlays/bulk-item-modal.component.spec.ts create mode 100644 src/tests/triggers/trigger-state.service.spec.ts create mode 100644 src/tests/users/user-form.component.spec.ts create mode 100644 src/tests/users/users.service.spec.ts diff --git a/src/tests/domains/application-form.component.spec.ts b/src/tests/domains/application-form.component.spec.ts new file mode 100644 index 000000000..d7b4e6dd0 --- /dev/null +++ b/src/tests/domains/application-form.component.spec.ts @@ -0,0 +1,74 @@ +import { DIALOG_DATA, DialogRef } from '@angular/cdk/dialog'; +import { provideZonelessChangeDetection } from '@angular/core'; +import { TestBed } from '@angular/core/testing'; +import { PlaceApplication } from '@placeos/ts-client'; +import { EMPTY } from 'rxjs'; +import { describe, expect, it, vi } from 'vitest'; +import { ApplicationFormComponent } from '../../app/domains/application-form.component'; + +const mocks = vi.hoisted(() => ({ + addApplication: vi.fn(), + updateApplication: vi.fn(), +})); +vi.mock('@placeos/ts-client', async () => ({ + ...(await vi.importActual( + '@placeos/ts-client/dist/index.es.js', + )), + ...mocks, +})); +vi.mock('../../app/common/notifications', () => ({ + notifyError: vi.fn(), + notifySuccess: vi.fn(), +})); + +describe('saving applications', () => { + it('keeps the stored client ID when the redirect URL changes', async () => { + mocks.updateApplication.mockResolvedValue({}); + TestBed.configureTestingModule({ + imports: [ApplicationFormComponent], + providers: [ + provideZonelessChangeDetection(), + { + provide: DialogRef, + useValue: { + close: vi.fn(), + disableClose: false, + backdropClick: EMPTY, + keydownEvents: EMPTY, + }, + }, + { + provide: DIALOG_DATA, + useValue: { + item: new PlaceApplication({ + id: 'app-1', + name: 'Kiosk', + redirect_uri: 'https://old.example.com/callback', + uid: 'stored-uid', + }), + }, + }, + ], + }); + const fixture = TestBed.createComponent(ApplicationFormComponent); + const component = fixture.componentInstance; + await fixture.whenStable(); + component.form + .redirect_uri() + .value.set('https://new.example.com/callback'); + await fixture.whenStable(); + + await component.submit(); + + expect(mocks.updateApplication).toHaveBeenCalledExactlyOnceWith( + 'app-1', + expect.objectContaining({ + redirect_uri: 'https://new.example.com/callback', + uid: 'stored-uid', + }), + ); + expect(mocks.updateApplication.mock.calls[0][1]).not.toHaveProperty( + 'client_id', + ); + }); +}); diff --git a/src/tests/domains/domain-state.service.spec.ts b/src/tests/domains/domain-state.service.spec.ts index e58534167..9465f2bbc 100644 --- a/src/tests/domains/domain-state.service.spec.ts +++ b/src/tests/domains/domain-state.service.spec.ts @@ -6,7 +6,12 @@ import { } from '@angular/core'; import { TestBed } from '@angular/core/testing'; import { NavigationEnd, Router } from '@angular/router'; -import { PlaceDomain, PlaceUser } from '@placeos/ts-client'; +import { + PlaceDomain, + PlaceLDAPSource, + PlaceOAuthSource, + PlaceUser, +} from '@placeos/ts-client'; import { Subject } from 'rxjs'; import { beforeEach, describe, expect, it, vi } from 'vitest'; import { ActiveItemService } from '../../app/common/item.service'; @@ -132,6 +137,19 @@ describe('domain tab loading', () => { await settle(); expect(mocks.queryUsers).toHaveBeenCalledTimes(2); }); + it('keeps the other authentication sources when one source type fails', async () => { + const oauth = new PlaceOAuthSource({ id: 'oauth-1' }); + const ldap = new PlaceLDAPSource({ id: 'ldap-1' }); + mocks.querySAMLSources.mockRejectedValue(new Error('Forbidden')); + mocks.queryOAuthSources.mockResolvedValue({ data: [oauth], total: 1 }); + mocks.queryLDAPSources.mockResolvedValue({ data: [ldap], total: 1 }); + active.set(new PlaceDomain({ id: 'domain-1' })); + const url = '/domains/domain-1/authentication'; + navigation.next(new NavigationEnd(1, url, url)); + await settle(); + expect(service.auth_sources()).toEqual([oauth, ldap]); + expect(service.counts().auth_sources).toBe(2); + }); it('clears loaded tabs when selecting another domain', async () => { active.set(new PlaceDomain({ id: 'domain-1' })); navigation.next( diff --git a/src/tests/groups/group-form.component.spec.ts b/src/tests/groups/group-form.component.spec.ts new file mode 100644 index 000000000..0f4b0a0ef --- /dev/null +++ b/src/tests/groups/group-form.component.spec.ts @@ -0,0 +1,86 @@ +import { DIALOG_DATA, DialogRef } from '@angular/cdk/dialog'; +import { provideZonelessChangeDetection } from '@angular/core'; +import { TestBed } from '@angular/core/testing'; +import { PlaceGroup } from '@placeos/ts-client'; +import { EMPTY } from 'rxjs'; +import { beforeEach, describe, expect, it, vi } from 'vitest'; +import { GroupFormComponent } from '../../app/groups/group-form.component'; + +const mocks = vi.hoisted(() => ({ + authority: vi.fn(), + queryDomains: vi.fn(), + queryGroups: vi.fn(), + showGroup: vi.fn(), +})); +vi.mock('@placeos/ts-client', async () => ({ + ...(await vi.importActual( + '@placeos/ts-client/dist/index.es.js', + )), + ...mocks, +})); + +describe('group parent', () => { + async function createForm(item: PlaceGroup) { + TestBed.configureTestingModule({ + imports: [GroupFormComponent], + providers: [ + provideZonelessChangeDetection(), + { + provide: DialogRef, + useValue: { + close: vi.fn(), + disableClose: false, + backdropClick: EMPTY, + keydownEvents: EMPTY, + }, + }, + { provide: DIALOG_DATA, useValue: { item } }, + ], + }); + const fixture = TestBed.createComponent(GroupFormComponent); + await fixture.whenStable(); + return fixture.componentInstance; + } + + beforeEach(() => { + vi.resetAllMocks(); + mocks.queryDomains.mockResolvedValue({ data: [] }); + mocks.queryGroups.mockResolvedValue({ data: [] }); + }); + + it('adds each parent subsystem once and keeps the existing subsystems', async () => { + const component = await createForm( + new PlaceGroup({ subsystems: ['support', 'lighting'] }), + ); + component.setParentGroup( + new PlaceGroup({ + id: 'parent-1', + subsystems: ['signage', 'support'], + }), + ); + expect(component.formModel()).toMatchObject({ + parent_id: 'parent-1', + subsystems: ['support', 'lighting', 'signage'], + }); + }); + + it('offers only parent groups in the selected domain', async () => { + mocks.queryGroups.mockResolvedValue({ + data: [ + new PlaceGroup({ id: 'group-a', authority_id: 'domain-1' }), + new PlaceGroup({ id: 'group-b', authority_id: 'domain-2' }), + ], + }); + const component = await createForm( + new PlaceGroup({ authority_id: 'domain-1' }), + ); + const ids = async () => + (await component.query_parent_groups()('')).map(({ id }) => id); + expect(await ids()).toEqual(['group-a']); + component.formModel.update((value) => ({ + ...value, + authority_id: 'domain-2', + })); + expect(await ids()).toEqual(['group-b']); + }); +}); diff --git a/src/tests/groups/group-state.service.spec.ts b/src/tests/groups/group-state.service.spec.ts index 752584cb7..33ffa6fb2 100644 --- a/src/tests/groups/group-state.service.spec.ts +++ b/src/tests/groups/group-state.service.spec.ts @@ -169,6 +169,39 @@ describe('group membership actions', () => { ); }); + it.each([ + { + label: 'an existing member', + id: 'user-1', + authority_id: 'domain-1', + excluded: true, + }, + { + label: 'a user in another domain', + id: 'user-2', + authority_id: 'domain-2', + excluded: true, + }, + { + label: 'a new user in the group domain', + id: 'user-3', + authority_id: 'domain-1', + excluded: false, + }, + ])( + 'bulk add hides $label: $excluded', + async ({ id, authority_id, excluded }) => { + mocks.queryGroupUsers.mockResolvedValue({ data: [user], total: 1 }); + active.set(group); + await TestBed.inject(ApplicationRef).whenStable(); + expect( + service.user_members.exclude( + new PlaceUser({ id, authority_id }), + ), + ).toBe(excluded); + }, + ); + it('does not send an add request for an unsaved user', async () => { await service.user_members.add(new PlaceUser()); expect(mocks.addGroupUser).not.toHaveBeenCalled(); diff --git a/src/tests/overlays/auth-source-modal.component.spec.ts b/src/tests/overlays/auth-source-modal.component.spec.ts new file mode 100644 index 000000000..39d144a0e --- /dev/null +++ b/src/tests/overlays/auth-source-modal.component.spec.ts @@ -0,0 +1,115 @@ +import { DIALOG_DATA, DialogRef } from '@angular/cdk/dialog'; +import { provideZonelessChangeDetection } from '@angular/core'; +import { TestBed } from '@angular/core/testing'; +import { PlaceDomain } from '@placeos/ts-client'; +import { EMPTY } from 'rxjs'; +import { beforeEach, describe, expect, it, vi } from 'vitest'; +import { + AuthSourceModalComponent, + AuthSourceTypes, +} from '../../app/overlays/auth-source-modal.component'; + +const mocks = vi.hoisted(() => ({ + addOAuthSource: vi.fn(), + addSAMLSource: vi.fn(), + addLDAPSource: vi.fn(), +})); +vi.mock('@placeos/ts-client', async () => ({ + ...(await vi.importActual( + '@placeos/ts-client/dist/index.es.js', + )), + ...mocks, +})); +vi.mock('../../app/common/notifications', () => ({ + notifyError: vi.fn(), + notifySuccess: vi.fn(), +})); + +describe('saving authentication sources', () => { + let component: AuthSourceModalComponent; + + beforeEach(async () => { + vi.resetAllMocks(); + for (const add of Object.values(mocks)) add.mockResolvedValue({}); + TestBed.configureTestingModule({ + imports: [AuthSourceModalComponent], + providers: [ + provideZonelessChangeDetection(), + { + provide: DialogRef, + useValue: { + close: vi.fn(), + disableClose: false, + backdropClick: EMPTY, + keydownEvents: EMPTY, + }, + }, + { + provide: DIALOG_DATA, + useValue: { domain: new PlaceDomain({ id: 'domain-1' }) }, + }, + ], + }); + const fixture = TestBed.createComponent(AuthSourceModalComponent); + component = fixture.componentInstance; + await fixture.whenStable(); + }); + + it.each([ + { + type: 'oauth', + add: mocks.addOAuthSource, + edit: () => + component.oauthFormModel.update((value) => ({ + ...value, + name: 'Corporate sign-in', + client_id: 'client-1', + })), + saved: { name: 'Corporate sign-in', client_id: 'client-1' }, + }, + { + type: 'saml', + add: mocks.addSAMLSource, + edit: () => + component.samlFormModel.update((value) => ({ + ...value, + name: 'Corporate SAML', + issuer: 'placeos', + idp_sso_target_url: 'https://idp.example.com/sso', + assertion_consumer_service_url: + 'https://example.com/saml/callback', + })), + saved: { name: 'Corporate SAML', issuer: 'placeos' }, + }, + { + type: 'ldap', + add: mocks.addLDAPSource, + edit: () => + component.ldapFormModel.update((value) => ({ + ...value, + name: 'Directory', + host: 'ldap.example.com', + base: 'dc=example,dc=com', + })), + saved: { name: 'Directory', host: 'ldap.example.com' }, + }, + ] satisfies { + type: AuthSourceTypes; + add: (typeof mocks)[keyof typeof mocks]; + edit: () => void; + saved: Record; + }[])( + 'adds a new $type source with its edited values', + async ({ type, add, edit, saved }) => { + component.setType(type); + edit(); + await component.save(); + expect(add).toHaveBeenCalledExactlyOnceWith( + expect.objectContaining({ ...saved, authority_id: 'domain-1' }), + ); + for (const other of Object.values(mocks)) { + if (other !== add) expect(other).not.toHaveBeenCalled(); + } + }, + ); +}); diff --git a/src/tests/overlays/bulk-item-modal.component.spec.ts b/src/tests/overlays/bulk-item-modal.component.spec.ts new file mode 100644 index 000000000..8193aea77 --- /dev/null +++ b/src/tests/overlays/bulk-item-modal.component.spec.ts @@ -0,0 +1,100 @@ +import { DIALOG_DATA, DialogRef } from '@angular/cdk/dialog'; +import { provideZonelessChangeDetection } from '@angular/core'; +import { TestBed } from '@angular/core/testing'; +import { PlaceResource, PlaceUser } from '@placeos/ts-client'; +import { beforeEach, describe, expect, it, vi } from 'vitest'; +import { BulkItemModalComponent } from '../../app/overlays/bulk-item-modal/bulk-item-modal.component'; +import { StatusListComponent } from '../../app/overlays/bulk-item-modal/status-list.component'; + +vi.mock('@placeos/ts-client', () => + vi.importActual('@placeos/ts-client/dist/index.es.js'), +); +vi.mock('../../app/common/notifications', () => ({ + notifyError: vi.fn(), + notifyWarn: vi.fn(), +})); + +beforeEach(() => vi.clearAllMocks()); + +describe('bulk item review', () => { + it('keeps the review step when a user row has no domain', async () => { + const dialog = { + close: vi.fn(), + updateSize: vi.fn(), + disableClose: false, + }; + TestBed.configureTestingModule({ + imports: [BulkItemModalComponent], + providers: [ + provideZonelessChangeDetection(), + { provide: DialogRef, useValue: dialog }, + { + provide: DIALOG_DATA, + useValue: { + constr: PlaceUser, + name: 'Users', + save: vi.fn(), + }, + }, + ], + }); + const fixture = TestBed.createComponent(BulkItemModalComponent); + const component = fixture.componentInstance; + component.handleList([{ email: 'ops@example.com' }], true); + await fixture.whenStable(); + + component.showStatus(); + + expect(component.validation_errors()).toEqual([ + 'Row 1: Missing required field "authority_id"', + ]); + expect(component.flow_step()).toBe('list'); + expect(dialog.disableClose).toBe(false); + }); +}); + +describe('bulk item creation', () => { + it('finishes after a failed save and emits the saved items in list order', async () => { + const save = vi.fn(async (item: Record) => { + if (item.name === 'B') throw new Error('Name taken'); + // The first save finishes last + if (item.name === 'A') await new Promise((r) => setTimeout(r, 5)); + return { + ...item, + id: `id-${item.name}`, + } as unknown as PlaceResource; + }); + // The virtual scroll list needs ResizeObserver, which jsdom lacks + TestBed.configureTestingModule({ + imports: [StatusListComponent], + providers: [provideZonelessChangeDetection()], + }).overrideComponent(StatusListComponent, { + set: { template: '', imports: [] }, + }); + const fixture = TestBed.createComponent(StatusListComponent); + const component = fixture.componentInstance; + const done = new Promise((resolve) => + component.done.subscribe(resolve), + ); + fixture.componentRef.setInput('save', save); + fixture.componentRef.setInput('list', [ + { id: 'old-a', name: 'A' }, + { id: 'old-b', name: 'B' }, + { id: 'old-c', name: 'C' }, + ]); + + expect(await done).toEqual([ + { id: 'id-A', name: 'A' }, + { id: 'id-C', name: 'C' }, + ]); + expect(save.mock.calls.map(([item]) => item.id)).toEqual(['', '', '']); + expect(component.is_done()).toBe(true); + expect(component.completed_count()).toBe(2); + expect(component.error_count()).toBe(1); + expect(component.status().map((status) => status())).toEqual([ + 'done', + 'Error: Name taken', + 'done', + ]); + }); +}); diff --git a/src/tests/overlays/confirm-modal.component.spec.ts b/src/tests/overlays/confirm-modal.component.spec.ts index 08d79b5a8..d59ea888a 100644 --- a/src/tests/overlays/confirm-modal.component.spec.ts +++ b/src/tests/overlays/confirm-modal.component.spec.ts @@ -79,10 +79,6 @@ describe('ConfirmModalComponent', () => { it('should have empty loading signal', () => { expect(component.loading()).toBe(''); }); - - it('should have event emitter defined', () => { - expect(component.event).toBeDefined(); - }); }); describe('with provided data', () => { @@ -601,19 +597,6 @@ describe('ConfirmModalComponent', () => { }); }); - describe('loading state', () => { - it('should update loading signal', () => { - component.loading.set('Processing...'); - expect(component.loading()).toBe('Processing...'); - }); - - it('should clear loading signal', () => { - component.loading.set('Processing...'); - component.loading.set(''); - expect(component.loading()).toBe(''); - }); - }); - describe('template rendering', () => { it('should render header with title', () => { const header = fixture.nativeElement.querySelector('header'); diff --git a/src/tests/overlays/duplicate-modal.component.spec.ts b/src/tests/overlays/duplicate-modal.component.spec.ts index 7ebb4fae3..916868bf8 100644 --- a/src/tests/overlays/duplicate-modal.component.spec.ts +++ b/src/tests/overlays/duplicate-modal.component.spec.ts @@ -71,6 +71,30 @@ describe('DuplicateModalComponent', () => { ]); }); + it.each([0, 1.5, 51])('saves nothing for %s copies', async (times) => { + const save = vi.fn(); + TestBed.configureTestingModule({ + imports: [DuplicateModalComponent], + providers: [ + provideZonelessChangeDetection(), + { + provide: DIALOG_DATA, + useValue: { item: new Item({ name: 'Room' }), save }, + }, + { provide: DialogRef, useValue: { close: vi.fn() } }, + ], + }); + const component = TestBed.createComponent( + DuplicateModalComponent, + ).componentInstance; + component.times = times; + + await component.duplicate(); + + expect(save).not.toHaveBeenCalled(); + expect(component.loading()).toBe(false); + }); + it('stops saving copies once the dialog is closed', async () => { TestBed.configureTestingModule({ imports: [DuplicateModalComponent], diff --git a/src/tests/triggers/trigger-state.service.spec.ts b/src/tests/triggers/trigger-state.service.spec.ts new file mode 100644 index 000000000..526ad5995 --- /dev/null +++ b/src/tests/triggers/trigger-state.service.spec.ts @@ -0,0 +1,150 @@ +import { Dialog } from '@angular/cdk/dialog'; +import { provideZonelessChangeDetection, signal } from '@angular/core'; +import { TestBed } from '@angular/core/testing'; +import { PlaceTrigger, PlaceZone } from '@placeos/ts-client'; +import { beforeEach, describe, expect, it, vi } from 'vitest'; +import { ActiveItemService } from '../../app/common/item.service'; +import { TriggerStateService } from '../../app/triggers/trigger-state.service'; + +const mocks = vi.hoisted(() => ({ + updateTrigger: vi.fn(), + showZone: vi.fn(), + updateZone: vi.fn(), + removeSystemTrigger: vi.fn(), + confirm: vi.fn(), + replaceItem: vi.fn(), +})); +vi.mock('@placeos/ts-client', async () => ({ + ...(await vi.importActual( + '@placeos/ts-client/dist/index.es.js', + )), + updateTrigger: mocks.updateTrigger, + showZone: mocks.showZone, + updateZone: mocks.updateZone, + removeSystemTrigger: mocks.removeSystemTrigger, +})); +vi.mock('../../app/common/item.service', () => ({ + ActiveItemService: class {}, +})); +vi.mock('../../app/common/locale.service', () => ({ + i18n: (key: string) => key, +})); +vi.mock('../../app/common/notifications', () => ({ + notifyError: vi.fn(), + notifySuccess: vi.fn(), +})); +vi.mock('../../app/overlays/confirm-modal.component', () => ({ + openConfirmModal: mocks.confirm, +})); +vi.mock('../../app/ui/forms/trigger-action-modal.component', () => ({ + TriggerActionModalComponent: class {}, +})); +vi.mock('../../app/ui/forms/trigger-condition-modal.component', () => ({ + TriggerConditionModalComponent: class {}, +})); + +describe('trigger actions and instances', () => { + const trigger = new PlaceTrigger({ + id: 'template-1', + actions: { + functions: [ + { mod: 'Display_1', method: 'power_on' }, + { mod: 'Display_1', method: 'power_off' }, + { mod: 'Mixer_1', method: 'mute' }, + ], + mailers: [ + { emails: ['ops@example.com'], content: 'Alert' }, + { emails: ['facilities@example.com'], content: 'Alert' }, + ], + }, + }); + const [power_on, power_off, mute] = trigger.actions.functions; + const [ops, facilities] = trigger.actions.mailers; + const saved = new PlaceTrigger({ id: 'template-1' }); + let service: TriggerStateService; + + beforeEach(() => { + vi.resetAllMocks(); + mocks.confirm.mockResolvedValue({ + reason: 'done', + close: vi.fn(), + loading: vi.fn(), + }); + mocks.updateTrigger.mockResolvedValue(saved); + mocks.updateZone.mockResolvedValue(new PlaceZone()); + mocks.removeSystemTrigger.mockResolvedValue(undefined); + TestBed.configureTestingModule({ + providers: [ + provideZonelessChangeDetection(), + TriggerStateService, + { + provide: ActiveItemService, + useValue: { + item: signal(null), + active_item: trigger, + replaceItem: mocks.replaceItem, + }, + }, + { provide: Dialog, useValue: {} }, + ], + }); + service = TestBed.inject(TriggerStateService); + }); + + it('saves the new function order and keeps the mailers', async () => { + await service.reorderAction('function', 0, 2); + expect(mocks.updateTrigger).toHaveBeenCalledExactlyOnceWith( + 'template-1', + expect.objectContaining({ + actions: { + functions: [power_off, mute, power_on], + mailers: [ops, facilities], + }, + }), + ); + expect(mocks.replaceItem).toHaveBeenCalledExactlyOnceWith(saved); + }); + + it('removes only the selected mailer', async () => { + await service.removeAction({ ...facilities }); + expect(mocks.updateTrigger).toHaveBeenCalledExactlyOnceWith( + 'template-1', + expect.objectContaining({ + actions: { + functions: [power_on, power_off, mute], + mailers: [ops], + }, + }), + ); + expect(mocks.replaceItem).toHaveBeenCalledExactlyOnceWith(saved); + }); + + it('removes a zone instance from the zone trigger list and keeps other triggers', async () => { + mocks.showZone.mockResolvedValue( + new PlaceZone({ + id: 'zone-1', + triggers: ['other-trigger', 'template-1'], + }), + ); + await service.removeTriggerFromParent( + new PlaceTrigger({ id: 'instance-1', zone_id: 'zone-1' }), + ); + expect(mocks.updateZone).toHaveBeenCalledExactlyOnceWith( + 'zone-1', + expect.objectContaining({ triggers: ['other-trigger'] }), + ); + expect(mocks.removeSystemTrigger).not.toHaveBeenCalled(); + }); + + it('removes a system instance by its instance ID', async () => { + await service.removeTriggerFromParent( + new PlaceTrigger({ id: 'instance-1', control_system_id: 'sys-1' }), + ); + expect(mocks.removeSystemTrigger).toHaveBeenCalledExactlyOnceWith( + 'sys-1', + 'instance-1', + ); + expect(mocks.showZone).not.toHaveBeenCalled(); + expect(mocks.updateZone).not.toHaveBeenCalled(); + }); +}); diff --git a/src/tests/users/user-form.component.spec.ts b/src/tests/users/user-form.component.spec.ts new file mode 100644 index 000000000..c8aefbbd4 --- /dev/null +++ b/src/tests/users/user-form.component.spec.ts @@ -0,0 +1,82 @@ +import { DIALOG_DATA, DialogRef } from '@angular/cdk/dialog'; +import { provideZonelessChangeDetection } from '@angular/core'; +import { TestBed } from '@angular/core/testing'; +import { PlaceUser } from '@placeos/ts-client'; +import { EMPTY } from 'rxjs'; +import { describe, expect, it, vi } from 'vitest'; +import { UserFormComponent } from '../../app/users/user-form.component'; + +const mocks = vi.hoisted(() => ({ + addUser: vi.fn(), + updateUser: vi.fn(), + queryDomains: vi.fn(), + authority: vi.fn(), +})); +vi.mock('@placeos/ts-client', async () => ({ + ...(await vi.importActual( + '@placeos/ts-client/dist/index.es.js', + )), + ...mocks, +})); +vi.mock('../../app/common/support-access', async () => ({ + ...(await vi.importActual('../../app/common/support-access')), + isSubsystemUser: () => true, +})); +vi.mock('../../app/common/notifications', () => ({ + notifyError: vi.fn(), + notifySuccess: vi.fn(), +})); + +describe('saving users as a subsystem user', () => { + it('drops privileged fields and saves in the signed-in domain', async () => { + mocks.authority.mockReturnValue({ id: 'domain-1', name: 'Org' }); + mocks.updateUser.mockResolvedValue(new PlaceUser({ id: 'user-1' })); + TestBed.configureTestingModule({ + imports: [UserFormComponent], + providers: [ + provideZonelessChangeDetection(), + { + provide: DialogRef, + useValue: { + close: vi.fn(), + disableClose: false, + backdropClick: EMPTY, + keydownEvents: EMPTY, + }, + }, + { + provide: DIALOG_DATA, + useValue: { + item: new PlaceUser({ + id: 'user-1', + authority_id: 'domain-2', + first_name: 'Alex', + last_name: 'Smith', + email: 'alex@example.com', + login_name: 'alex', + sys_admin: true, + support: true, + groups: ['admins'], + }), + }, + }, + ], + }); + const fixture = TestBed.createComponent(UserFormComponent); + await fixture.whenStable(); + + await fixture.componentInstance.submit(); + + expect(mocks.updateUser).toHaveBeenCalledExactlyOnceWith( + 'user-1', + expect.objectContaining({ + authority_id: 'domain-1', + email: 'alex@example.com', + }), + ); + const saved = mocks.updateUser.mock.calls[0][1]; + for (const key of ['sys_admin', 'support', 'groups', 'login_name']) { + expect(saved).not.toHaveProperty(key); + } + }); +}); diff --git a/src/tests/users/users.service.spec.ts b/src/tests/users/users.service.spec.ts new file mode 100644 index 000000000..e1d46d5e2 --- /dev/null +++ b/src/tests/users/users.service.spec.ts @@ -0,0 +1,46 @@ +import { provideZonelessChangeDetection } from '@angular/core'; +import { TestBed } from '@angular/core/testing'; +import { NEVER } from 'rxjs'; +import { afterEach, describe, expect, it, vi } from 'vitest'; +import { SettingsService } from '../../app/common/settings.service'; +import { BackofficeUsersService } from '../../app/users/users.service'; + +const mocks = vi.hoisted(() => ({ currentUser: vi.fn() })); +vi.mock('@placeos/ts-client', async () => ({ + ...(await vi.importActual( + '@placeos/ts-client/dist/index.es.js', + )), + currentUser: mocks.currentUser, + onlineState: () => NEVER, +})); +vi.mock('../../app/common/settings.service', () => ({ + SettingsService: class {}, +})); +vi.mock('../../app/common/support-access', () => ({ + loadSupportAccess: vi.fn(), +})); + +describe('loading the signed-in user', () => { + afterEach(() => vi.useRealTimers()); + + it('stops retrying after 12 failed attempts', async () => { + vi.useFakeTimers(); + mocks.currentUser.mockRejectedValue(new Error('Offline')); + TestBed.configureTestingModule({ + providers: [ + provideZonelessChangeDetection(), + { provide: SettingsService, useValue: {} }, + ], + }); + const service = TestBed.inject(BackofficeUsersService); + + const loaded = service.load(); + await vi.runAllTimersAsync(); + await loaded; + + expect(mocks.currentUser).toHaveBeenCalledTimes(12); + expect(service.state()).toBe('error'); + await vi.advanceTimersByTimeAsync(60_000); + expect(mocks.currentUser).toHaveBeenCalledTimes(12); + }); +}); diff --git a/src/tests/zones/zone-form.component.spec.ts b/src/tests/zones/zone-form.component.spec.ts index 0c995382e..f321565d6 100644 --- a/src/tests/zones/zone-form.component.spec.ts +++ b/src/tests/zones/zone-form.component.spec.ts @@ -176,6 +176,28 @@ describe('saving zones with a stored parent', () => { ); }); + it('keeps a parent the user picks while the stored parent loads', async () => { + let resolveParent: (zone: PlaceZone) => void; + mocks.showZone.mockReturnValue( + new Promise((resolve) => (resolveParent = resolve)), + ); + const fixture = await createForm(); + fixture.componentInstance.form + .parent_zone() + .controlValue.set(new PlaceZone({ id: 'building-2' })); + await fixture.whenStable(); + resolveParent(new PlaceZone({ id: 'building-1' })); + await fixture.whenStable(); + expect(fixture.componentInstance.formModel().parent_zone?.id).toBe( + 'building-2', + ); + await fixture.componentInstance.submit(); + expect(mocks.updateZone).toHaveBeenCalledWith( + 'zone-1', + expect.objectContaining({ parent_id: 'building-2' }), + ); + }); + it('keeps the parent when the parent fails to load', async () => { mocks.showZone.mockRejectedValue(new Error('Forbidden')); const fixture = await createForm(); diff --git a/src/tests/zones/zones-state.service.spec.ts b/src/tests/zones/zones-state.service.spec.ts index 244b46fbd..7cf5355e2 100644 --- a/src/tests/zones/zones-state.service.spec.ts +++ b/src/tests/zones/zones-state.service.spec.ts @@ -1,8 +1,12 @@ import { Dialog } from '@angular/cdk/dialog'; -import { provideZonelessChangeDetection, signal } from '@angular/core'; +import { + ApplicationRef, + provideZonelessChangeDetection, + signal, +} from '@angular/core'; import { TestBed } from '@angular/core/testing'; import { NavigationEnd, Router } from '@angular/router'; -import { PlaceGroup, PlaceZone } from '@placeos/ts-client'; +import { PlaceGroup, PlaceSystem, PlaceZone } from '@placeos/ts-client'; import { of, Subject } from 'rxjs'; import { beforeEach, describe, expect, it, vi } from 'vitest'; import { ActiveItemService } from '../../app/common/item.service'; @@ -10,6 +14,11 @@ import { ZonesStateService } from '../../app/zones/zones-state.service'; const mocks = vi.hoisted(() => ({ addGroupZone: vi.fn(), + querySystems: vi.fn(), + queryZones: vi.fn(), + queryGroupZones: vi.fn(), + listZoneTriggers: vi.fn(), + listMetadata: vi.fn(), open: vi.fn(), notifyError: vi.fn(), notifySuccess: vi.fn(), @@ -19,6 +28,11 @@ vi.mock('@placeos/ts-client', async () => ({ '@placeos/ts-client/dist/index.es.js', )), addGroupZone: mocks.addGroupZone, + querySystems: mocks.querySystems, + queryZones: mocks.queryZones, + queryGroupZones: mocks.queryGroupZones, + listZoneTriggers: mocks.listZoneTriggers, + listMetadata: mocks.listMetadata, })); vi.mock('../../app/common/item.service', () => ({ ActiveItemService: class {}, @@ -35,27 +49,37 @@ vi.mock('../../app/groups/group-bulk-add-modal.component', () => ({ GroupBulkAddModalComponent: class {}, })); -describe('zone group bulk add', () => { +describe('zone tabs', () => { const zone = new PlaceZone({ id: 'zone-1' }); + const active = signal(null); + let navigation: Subject; let service: ZonesStateService; beforeEach(() => { vi.resetAllMocks(); + active.set(null); + navigation = new Subject(); + const empty = { data: [], total: 0, next: null }; mocks.addGroupZone.mockResolvedValue({}); + mocks.querySystems.mockResolvedValue(empty); + mocks.queryZones.mockResolvedValue(empty); + mocks.queryGroupZones.mockResolvedValue(empty); + mocks.listZoneTriggers.mockResolvedValue(empty); + mocks.listMetadata.mockResolvedValue([]); TestBed.configureTestingModule({ providers: [ provideZonelessChangeDetection(), ZonesStateService, { provide: ActiveItemService, - useValue: { item: signal(null), active_item: zone }, + useValue: { item: active, active_item: zone }, }, { provide: Dialog, useValue: { open: mocks.open } }, { provide: Router, useValue: { url: '/zones/zone-1/about', - events: new Subject(), + events: navigation, }, }, ], @@ -63,6 +87,28 @@ describe('zone group bulk add', () => { service = TestBed.inject(ZonesStateService); }); + it('loads every page of systems when the systems tab opens', async () => { + const systems = [ + new PlaceSystem({ id: 'sys-1' }), + new PlaceSystem({ id: 'sys-2' }), + ]; + mocks.querySystems.mockResolvedValue({ + data: [systems[0]], + total: 2, + next: async () => ({ data: [systems[1]], total: 2, next: null }), + }); + active.set(zone); + const url = '/zones/zone-1/systems'; + navigation.next(new NavigationEnd(1, url, url)); + await TestBed.inject(ApplicationRef).whenStable(); + expect(mocks.querySystems).toHaveBeenLastCalledWith({ + zone_id: 'zone-1', + limit: 500, + }); + expect(service.systems()).toEqual(systems); + expect(service.counts().systems).toBe(2); + }); + it('adds each group picked in the bulk modal', async () => { mocks.open.mockReturnValue({ closed: of({