Add tests for the calendar integrations

This commit is contained in:
raucao committed 2026-10-27 18:20:15 +04:00
1 parent ba66a9c78f
commit e68d5cf23c
6 files changed
+814 -1

No files matched your search

@@ -0,0 +1,164 @@
import { module, test } from 'qunit';
import { setupRenderingTest } from 'dashtab/tests/helpers';
import { render, fillIn, click, triggerEvent } from '@ember/test-helpers';
import CalendarCaldavForm from 'dashtab/components/settings/integrations/calendar-caldav-form';
function registerServices(owner, overrides = {}) {
const calendar = overrides.calendar ?? {
fetchCalendars: async () => [],
configureCaldav: async () => {},
};
const sockethub = overrides.sockethub ?? {
url: 'https://sh.example.org',
setUrl: async () => {},
};
owner.register('service:calendar', calendar, { instantiate: false });
owner.register('service:sockethub', sockethub, { instantiate: false });
}
module(
'Integration | Component | settings/integrations/calendar-caldav-form',
function (hooks) {
setupRenderingTest(hooks);
test('walks through server, account and calendar selection', async function (assert) {
const fetched = [];
const configured = [];
let closed = false;
registerServices(this.owner, {
calendar: {
fetchCalendars: async (config) => {
fetched.push(config);
return [
{ id: 'c1', name: 'Work', components: ['event'] },
{ id: 'c2', name: 'Tasks', components: ['task'] },
];
},
configureCaldav: async (config, key) =>
configured.push({ config, key }),
},
});
const closeDialog = () => {
closed = true;
};
await render(
<template><CalendarCaldavForm @close={{closeDialog}} /></template>
);
assert.dom().containsText('Add CalDAV Calendar');
assert.dom('#caldav-server-url').hasValue('https://sh.example.org');
await triggerEvent('form', 'submit');
assert.dom('#caldav-url').exists();
await fillIn('#caldav-url', 'cal.example/dav/');
await fillIn('#caldav-username', 'alice');
await fillIn('#caldav-password', 'secret');
await triggerEvent('form', 'submit');
assert.strictEqual(fetched.length, 1);
assert.strictEqual(fetched[0].url, 'https://cal.example/dav/');
assert.dom('#caldav-calendar-0').exists();
// A tasks-only calendar is not offered.
assert.dom('#caldav-calendar-1').doesNotExist();
await click('#caldav-calendar-0');
await triggerEvent('form', 'submit');
assert.strictEqual(configured.length, 1);
assert.deepEqual(configured[0].config.selectedCalendarIds, ['c1']);
assert.strictEqual(configured[0].config.calendars.length, 2);
assert.strictEqual(configured[0].key, undefined);
assert.true(closed);
});
test('validates the CalDAV URL', async function (assert) {
const fetched = [];
registerServices(this.owner, {
calendar: {
fetchCalendars: async (...args) => fetched.push(args),
configureCaldav: async () => {},
},
});
const noop = () => {};
await render(<template><CalendarCaldavForm @close={{noop}} /></template>);
await triggerEvent('form', 'submit');
await fillIn('#caldav-username', 'alice');
await fillIn('#caldav-password', 'secret');
await triggerEvent('form', 'submit');
assert.dom().containsText('Please enter a valid CalDAV URL');
assert.strictEqual(fetched.length, 0);
});
test('requires at least one calendar', async function (assert) {
const configured = [];
registerServices(this.owner, {
calendar: {
fetchCalendars: async () => [
{ id: 'c1', name: 'Work', components: ['event'] },
],
configureCaldav: async (...args) => configured.push(args),
},
});
const noop = () => {};
await render(<template><CalendarCaldavForm @close={{noop}} /></template>);
await triggerEvent('form', 'submit');
await fillIn('#caldav-url', 'https://cal.example/dav/');
await fillIn('#caldav-username', 'alice');
await fillIn('#caldav-password', 'secret');
await triggerEvent('form', 'submit');
await triggerEvent('form', 'submit');
assert.dom().containsText('Select at least one calendar');
assert.strictEqual(configured.length, 0);
});
test('edit opens on the selection step with the stored calendars', async function (assert) {
const fetched = [];
registerServices(this.owner, {
calendar: {
fetchCalendars: async (config) => {
fetched.push(config);
return [{ id: 'c1', name: 'Work', components: ['event'] }];
},
configureCaldav: async () => {},
},
});
this.props = {
mode: 'edit',
integration: {
id: 'calendar-caldav-cal.example.com-alice',
url: 'https://cal.example/dav/',
username: 'alice',
password: 'secret',
calendars: [{ id: 'c1', name: 'Work', components: ['event'] }],
selectedCalendarIds: ['c1'],
},
};
const noop = () => {};
await render(
<template>
<CalendarCaldavForm @props={{this.props}} @close={{noop}} />
</template>
);
assert.dom().containsText('Edit CalDAV Calendar');
assert.dom('#caldav-calendar-0').isChecked();
assert.strictEqual(fetched.length, 1);
assert.strictEqual(fetched[0].password, 'secret');
});
}
);
@@ -0,0 +1,108 @@
import { module, test } from 'qunit';
import { setupRenderingTest } from 'dashtab/tests/helpers';
import { render, fillIn, triggerEvent } from '@ember/test-helpers';
import CalendarIcsForm from 'dashtab/components/settings/integrations/calendar-ics-form';
function registerServices(owner, overrides = {}) {
const calendar = overrides.calendar ?? {
verifyFeed: async () => ({ name: 'Calendar' }),
configureIcs: async () => {},
};
const sockethub = overrides.sockethub ?? {
url: 'https://sh.example.org',
setUrl: async () => {},
};
owner.register('service:calendar', calendar, { instantiate: false });
owner.register('service:sockethub', sockethub, { instantiate: false });
}
module(
'Integration | Component | settings/integrations/calendar-ics-form',
function (hooks) {
setupRenderingTest(hooks);
test('walks through server and feed, then saves', async function (assert) {
const verified = [];
const configured = [];
let closed = false;
registerServices(this.owner, {
calendar: {
verifyFeed: async (url) => {
verified.push(url);
return { name: 'Holidays' };
},
configureIcs: async (config, key) => configured.push({ config, key }),
},
});
const closeDialog = () => {
closed = true;
};
await render(
<template><CalendarIcsForm @close={{closeDialog}} /></template>
);
assert.dom().containsText('Add ICS / WebCal Calendar');
assert.dom('#ics-server-url').hasValue('https://sh.example.org');
await triggerEvent('form', 'submit');
assert.dom('#ics-feed-url').exists();
await fillIn('#ics-feed-url', 'https://example.org/h.ics');
await triggerEvent('form', 'submit');
assert.deepEqual(verified, ['https://example.org/h.ics']);
assert.strictEqual(configured.length, 1);
assert.strictEqual(configured[0].config.name, 'Holidays');
assert.strictEqual(configured[0].config.url, 'https://example.org/h.ics');
assert.true(closed);
});
test('validates the feed link', async function (assert) {
const verified = [];
registerServices(this.owner, {
calendar: {
verifyFeed: async (...args) => verified.push(args),
configureIcs: async () => {},
},
});
const noop = () => {};
await render(<template><CalendarIcsForm @close={{noop}} /></template>);
await triggerEvent('form', 'submit');
await fillIn('#ics-feed-url', 'not a link');
await triggerEvent('form', 'submit');
assert.dom().containsText('Please enter a valid .ics or webcal:// link');
assert.strictEqual(verified.length, 0);
});
test('edit opens on the feed step prefilled', async function (assert) {
registerServices(this.owner);
this.props = {
mode: 'edit',
integration: {
id: 'calendar-ics-example.org',
url: 'https://example.org/h.ics',
label: 'Holidays',
},
};
const noop = () => {};
await render(
<template>
<CalendarIcsForm @props={{this.props}} @close={{noop}} />
</template>
);
assert.dom().containsText('Edit ICS / WebCal Calendar');
assert.dom('#ics-feed-url').hasValue('https://example.org/h.ics');
});
}
);
+151
View File
@@ -0,0 +1,151 @@
import { module, test } from 'qunit';
import {
classifyCalendarError,
fetchWindow,
groupEvents,
normalizeEvent,
parseEventDate,
} from 'dashtab/config/calendar';
module('Unit | Config | calendar', function () {
test('fetchWindow spans from now to local midnight plus the fetch days', function (assert) {
const now = new Date(2026, 9, 27, 15, 30);
const { startTime, endTime } = fetchWindow(now);
assert.strictEqual(startTime, now.toISOString());
const end = new Date(endTime);
assert.strictEqual(end.getFullYear(), 2026);
assert.strictEqual(end.getMonth(), 10);
assert.strictEqual(end.getDate(), 3);
assert.strictEqual(end.getHours(), 0);
});
test('parseEventDate reads date-only values as local dates', function (assert) {
const date = parseEventDate('2026-08-03', true);
assert.strictEqual(date.getFullYear(), 2026);
assert.strictEqual(date.getMonth(), 7);
assert.strictEqual(date.getDate(), 3);
assert.strictEqual(date.getHours(), 0);
assert.strictEqual(parseEventDate(null), null);
});
test('parseEventDate reads timed values as instants', function (assert) {
const value = '2026-08-03T13:00:00Z';
assert.strictEqual(
parseEventDate(value).getTime(),
new Date(value).getTime()
);
});
test('normalizeEvent keeps events and drops tasks, recurrences and untimed items', function (assert) {
assert.strictEqual(
normalizeEvent({ type: 'task', name: 'x', startTime: '2026-08-03' }),
null
);
assert.strictEqual(
normalizeEvent({
type: 'event',
name: 'x',
startTime: '2026-08-03',
recurrence: { frequency: 'weekly' },
}),
null
);
assert.strictEqual(normalizeEvent({ type: 'event', name: 'x' }), null);
assert.deepEqual(
normalizeEvent({
type: 'event',
id: 'e1',
name: 'Standup',
startTime: '2026-08-03T09:00:00Z',
endTime: '2026-08-03T09:15:00Z',
location: 'Room 1',
}),
{
id: 'e1',
name: 'Standup',
startTime: '2026-08-03T09:00:00Z',
endTime: '2026-08-03T09:15:00Z',
allDay: false,
location: 'Room 1',
}
);
});
test('groupEvents splits today from the next days that have events', function (assert) {
const now = new Date(2026, 9, 27, 15, 0);
const events = [
{
id: 'past',
startTime: '2026-10-27T10:00:00',
endTime: '2026-10-27T11:00:00',
},
{
id: 'today',
startTime: '2026-10-27T16:00:00',
endTime: '2026-10-27T17:00:00',
},
{ id: 'day1', startTime: '2026-10-28T09:00:00' },
{ id: 'day2', startTime: '2026-10-29T09:00:00' },
{ id: 'day3', startTime: '2026-10-30T09:00:00' },
];
const grouped = groupEvents(events, now, 2);
assert.deepEqual(
grouped.today.map((event) => event.id),
['today']
);
assert.deepEqual(
grouped.days.map((day) => day.key),
['2026-10-28', '2026-10-29']
);
assert.deepEqual(
grouped.days.map((day) => day.events.map((event) => event.id)),
[['day1'], ['day2']]
);
});
test('groupEvents shows all-day events as today', function (assert) {
const now = new Date(2026, 9, 27, 15, 0);
const grouped = groupEvents(
[{ id: 'holiday', startTime: '2026-10-27', allDay: true }],
now,
2
);
assert.deepEqual(
grouped.today.map((event) => event.id),
['holiday']
);
});
test('classifyCalendarError maps platform and connection failures', function (assert) {
assert.strictEqual(
classifyCalendarError({ name: 'SockethubConnectionError' }),
'Unable to reach the Sockethub server'
);
assert.strictEqual(
classifyCalendarError({
name: 'SockethubPlatformError',
message: 'caldav:authentication-failed',
}),
'Invalid username or password'
);
assert.strictEqual(
classifyCalendarError({
name: 'SockethubPlatformError',
message: 'caldav:feed-failed',
}),
'Unable to read that calendar link'
);
assert.strictEqual(
classifyCalendarError(new Error('boom')),
'Unable to load calendar events'
);
});
});
@@ -0,0 +1,58 @@
import { module, test } from 'qunit';
import { setupTest } from 'dashtab/tests/helpers';
function entry(key, type, instanceKey, events = []) {
return {
key,
source: { type, instanceKey, calendarId: key, name: key },
fetchedAt: 1,
events,
};
}
module('Unit | Service | calendar-cache', function (hooks) {
setupTest(hooks);
hooks.beforeEach(async function () {
const cache = this.owner.lookup('service:calendar-cache');
await cache.ready;
await cache.clear();
});
test('it exists', function (assert) {
assert.ok(this.owner.lookup('service:calendar-cache'));
});
test('put stores an entry and exposes it by key and source', async function (assert) {
const cache = this.owner.lookup('service:calendar-cache');
const record = entry('calendar-ics:a', 'calendar-ics', 'a', [{ id: 'e1' }]);
await cache.put(record);
assert.deepEqual(cache.get(record.key), record);
assert.strictEqual(cache.all().length, 1);
assert.strictEqual(cache.forSource('calendar-ics', 'a').length, 1);
assert.strictEqual(cache.forSource('calendar-caldav', 'a').length, 0);
});
test('removeSource removes only the matching source', async function (assert) {
const cache = this.owner.lookup('service:calendar-cache');
await cache.put(entry('calendar-ics:a', 'calendar-ics', 'a'));
await cache.put(entry('calendar-ics:b', 'calendar-ics', 'b'));
await cache.removeSource('calendar-ics', 'a');
assert.strictEqual(cache.get('calendar-ics:a'), null);
assert.ok(cache.get('calendar-ics:b'));
});
test('load restores persisted entries', async function (assert) {
const cache = this.owner.lookup('service:calendar-cache');
await cache.put(entry('calendar-ics:a', 'calendar-ics', 'a'));
await cache.load();
assert.ok(cache.get('calendar-ics:a'));
});
});
+269
View File
@@ -0,0 +1,269 @@
import { module, test } from 'qunit';
import { setupTest } from 'dashtab/tests/helpers';
import { caldavInstanceKey } from 'dashtab/config/caldav';
import { icsInstanceKey } from 'dashtab/config/ics';
class FakeSockethub {
constructor(overrides = {}) {
this.connected = false;
this.consumer = null;
this.calls = [];
this.releases = 0;
this.handler = overrides.handler ?? (() => ({ items: [] }));
}
async acquire(id) {
this.consumer = id;
this.connected = true;
}
release() {
this.connected = false;
this.releases += 1;
}
contextFor(platform) {
return ['ctx', platform];
}
async sendCredentials(message) {
this.calls.push({ event: 'credentials', message });
}
async send(message) {
this.calls.push({ event: 'message', message });
return this.handler(message);
}
}
const CALENDAR = {
id: 'c1',
type: 'calendar',
name: 'Work',
components: ['event'],
};
const EVENT = {
id: 'e1',
type: 'event',
name: 'Standup',
startTime: '2026-08-03T09:00:00Z',
};
module('Unit | Service | calendar', function (hooks) {
setupTest(hooks);
async function setup(context, overrides = {}) {
const storage = context.owner.lookup('service:storage');
await storage.clear('integrations');
const cache = context.owner.lookup('service:calendar-cache');
await cache.ready;
await cache.clear();
const sockethub = new FakeSockethub(overrides);
context.owner.register('service:sockethub', sockethub, {
instantiate: false,
});
const service = context.owner.lookup('service:calendar');
await service.ready;
// Ignore the release from the initial (empty) load so tests measure only
// the calls they make.
sockethub.releases = 0;
return { service, sockethub, cache, storage };
}
test('it exists', function (assert) {
assert.ok(this.owner.lookup('service:calendar'));
});
test('stays disabled and unconnected without sources', async function (assert) {
const { service, sockethub } = await setup(this);
assert.false(service.enabled);
assert.strictEqual(sockethub.consumer, null);
assert.strictEqual(service.intervalId, null);
});
test('fetchCalendars sends credentials and a fetch, then releases', async function (assert) {
const { service, sockethub } = await setup(this, {
handler: () => ({ items: [CALENDAR, { type: 'event' }] }),
});
const calendars = await service.fetchCalendars({
url: 'https://cal.example/dav/',
username: 'alice',
password: 'secret',
});
assert.deepEqual(calendars, [
{ id: 'c1', name: 'Work', components: ['event'] },
]);
assert.deepEqual(
sockethub.calls.map((call) => call.event),
['credentials', 'message']
);
assert.strictEqual(sockethub.calls[1].message.type, 'fetch');
assert.false(sockethub.connected);
assert.strictEqual(sockethub.releases, 1);
});
test('verifyFeed sends a read and returns the feed name', async function (assert) {
const { service, sockethub } = await setup(this, {
handler: () => ({ summary: 'Holidays', items: [EVENT] }),
});
const result = await service.verifyFeed('https://example.org/h.ics');
assert.strictEqual(result.name, 'Holidays');
assert.strictEqual(sockethub.calls[0].message.type, 'read');
assert.strictEqual(sockethub.calls[0].message.target.type, 'feed');
assert.false(sockethub.connected);
});
test('configureCaldav persists, connects and caches queried events', async function (assert) {
const { service, sockethub, cache, storage } = await setup(this, {
handler: (message) =>
message.type === 'query' ? { items: [EVENT] } : { items: [] },
});
await service.configureCaldav({
url: 'https://cal.example/dav/',
username: 'alice',
password: 'secret',
calendars: [CALENDAR],
selectedCalendarIds: ['c1'],
});
await service.refreshAll();
const key = caldavInstanceKey('https://cal.example/dav/', 'alice');
const record = await storage.get('integrations', key);
assert.strictEqual(record.type, 'calendar-caldav');
assert.strictEqual(record.status, 'active');
assert.true(service.enabled);
assert.strictEqual(sockethub.consumer, 'calendar');
assert.ok(service.intervalId);
const cached = cache.get(`calendar-caldav:${key}:c1`);
assert.strictEqual(cached.source.name, 'Work');
assert.strictEqual(cached.events.length, 1);
assert.strictEqual(cached.events[0].id, 'e1');
service.stopPolling();
});
test('configureIcs reads the feed and caches its events', async function (assert) {
const { service, cache } = await setup(this, {
handler: () => ({ summary: 'Holidays', items: [EVENT] }),
});
await service.configureIcs({
url: 'https://example.org/h.ics',
name: 'Holidays',
});
await service.refreshAll();
const key = icsInstanceKey('https://example.org/h.ics');
const cached = cache.get(`calendar-ics:${key}:https://example.org/h.ics`);
assert.strictEqual(cached.source.name, 'Holidays');
assert.strictEqual(cached.events.length, 1);
service.stopPolling();
});
test('remove deletes the record and cache, then disconnects', async function (assert) {
const { service, sockethub, cache, storage } = await setup(this, {
handler: (message) =>
message.type === 'query' ? { items: [EVENT] } : { items: [] },
});
await service.configureCaldav({
url: 'https://cal.example/dav/',
username: 'alice',
password: 'secret',
calendars: [CALENDAR],
selectedCalendarIds: ['c1'],
});
const key = caldavInstanceKey('https://cal.example/dav/', 'alice');
await service.remove({ id: key, type: 'calendar-caldav' });
assert.strictEqual(await storage.get('integrations', key), null);
assert.strictEqual(cache.forSource('calendar-caldav', key).length, 0);
assert.false(service.enabled);
assert.false(sockethub.connected);
assert.strictEqual(service.intervalId, null);
});
test('refresh failures surface a classified error', async function (assert) {
const { service } = await setup(this, {
handler: () => {
throw Object.assign(new Error('caldav:connection-failed'), {
name: 'SockethubPlatformError',
});
},
});
await service.configureCaldav({
url: 'https://cal.example/dav/',
username: 'alice',
password: 'secret',
calendars: [CALENDAR],
selectedCalendarIds: ['c1'],
});
await service.refreshAll();
assert.strictEqual(service.error, 'Unable to reach the calendar server');
service.stopPolling();
});
test('events groups cached events from enabled sources', async function (assert) {
const { service, cache } = await setup(this);
const now = new Date();
const today = `${now.getFullYear()}-${now.getMonth() + 1}-${now.getDate()}`;
const tomorrow = new Date(now.getTime() + 24 * 60 * 60 * 1000);
service.instances = [{ id: 'x', type: 'calendar-ics' }];
await cache.put({
key: 'calendar-ics:x:feed',
source: {
type: 'calendar-ics',
instanceKey: 'x',
calendarId: 'feed',
name: 'Feed',
},
fetchedAt: Date.now(),
events: [
{
id: 'today',
name: 'Today',
startTime: today,
allDay: true,
},
{
id: 'future',
name: 'Future',
startTime: tomorrow.toISOString(),
allDay: false,
},
],
});
const grouped = service.events;
assert.deepEqual(
grouped.today.map((event) => event.id),
['today']
);
assert.strictEqual(grouped.days.length, 1);
assert.strictEqual(grouped.days[0].events[0].id, 'future');
});
});
+64 -1
View File
@@ -36,19 +36,34 @@ class FakeBitcoinService {
}
}
class FakeCalendarService {
instancesByType = { 'calendar-caldav': [], 'calendar-ics': [] };
removed = [];
instancesFor(type) {
return this.instancesByType[type] ?? [];
}
async remove(instance) {
this.removed.push(instance.id);
}
}
function register(owner, overrides = {}) {
const sites = overrides.sites ?? new FakeSitesService();
const notifications =
overrides.notifications ?? new FakeNotificationsService();
const bitcoin = overrides.bitcoin ?? new FakeBitcoinService();
const calendar = overrides.calendar ?? new FakeCalendarService();
owner.register('service:sites', sites, { instantiate: false });
owner.register('service:notifications', notifications, {
instantiate: false,
});
owner.register('service:bitcoin', bitcoin, { instantiate: false });
owner.register('service:calendar', calendar, { instantiate: false });
return { sites, notifications, bitcoin };
return { sites, notifications, bitcoin, calendar };
}
module('Unit | Service | integrations', function (hooks) {
@@ -348,4 +363,52 @@ module('Unit | Service | integrations', function (hooks) {
assert.strictEqual(row.label, 'Home');
assert.strictEqual(row.byline, 'ha.example.com:8123');
});
test('calendar adapters expose instances and remove', async function (assert) {
const calendar = new FakeCalendarService();
calendar.instancesByType['calendar-caldav'] = [
{
id: 'calendar-caldav-cal.example.com-alice',
type: 'calendar-caldav',
label: 'cal.example.com',
url: 'https://cal.example.com/dav/',
username: 'alice',
password: 'secret',
calendars: [{ id: 'c1', name: 'Work', components: ['event'] }],
selectedCalendarIds: ['c1'],
},
];
calendar.instancesByType['calendar-ics'] = [
{
id: 'calendar-ics-example.org',
type: 'calendar-ics',
label: 'Holidays',
url: 'https://example.org/h.ics',
},
];
const { calendar: registered } = register(this.owner, { calendar });
const service = this.owner.lookup('service:integrations');
const caldav = service.all.find((entry) => entry.id === 'calendar-caldav');
const ics = service.all.find((entry) => entry.id === 'calendar-ics');
assert.true(caldav.supportsMultiple);
assert.true(caldav.hasSettings);
assert.strictEqual(caldav.instances.length, 1);
assert.strictEqual(caldav.instances[0].username, 'alice');
assert.deepEqual(caldav.instances[0].selectedCalendarIds, ['c1']);
assert.true(ics.supportsMultiple);
assert.strictEqual(ics.instances.length, 1);
assert.strictEqual(ics.instances[0].label, 'Holidays');
await service.remove({
type: 'calendar-caldav',
id: 'calendar-caldav-cal.example.com-alice',
});
assert.deepEqual(registered.removed, [
'calendar-caldav-cal.example.com-alice',
]);
});
});