Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
31 changes: 31 additions & 0 deletions src/tests/admin/admin-data.service.spec.ts
Original file line number Diff line number Diff line change
@@ -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<ReturnType<typeof queryDomains>>;
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<DomainPage>((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);
});
});
61 changes: 61 additions & 0 deletions src/tests/admin/api-key-modal.component.spec.ts
Original file line number Diff line number Diff line change
@@ -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');
});
});
55 changes: 55 additions & 0 deletions src/tests/admin/cluster-task-list.component.spec.ts
Original file line number Diff line number Diff line change
@@ -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<ReturnType<typeof queryClusters>>);

await component.loadCluster('cluster-1');

expect(component.cluster()).toBeNull();
expect(component.process_list()).toEqual([]);
expect(queryProcesses).not.toHaveBeenCalled();
});
});
95 changes: 94 additions & 1 deletion src/tests/admin/database-details.component.spec.ts
Original file line number Diff line number Diff line change
@@ -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,
Expand All @@ -18,6 +26,10 @@ vi.mock('@placeos/ts-client', () => ({
sourceResync: vi.fn(),
sourceResyncStatus: vi.fn(),
}));
vi.mock('../../app/common/general', async (importOriginal) => ({
...(await importOriginal<object>()),
downloadFile: vi.fn(),
}));
vi.mock('../../app/common/notifications', () => ({
notifyError: vi.fn(),
notifySuccess: vi.fn(),
Expand Down Expand Up @@ -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<string, PlaceZone[]> = {
'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<typeof queryZones>,
);
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',
]);
});
});
42 changes: 42 additions & 0 deletions src/tests/admin/edge.component.spec.ts
Original file line number Diff line number Diff line change
@@ -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);
});
});
Loading
Loading