ci: expand shared package validation and test coverage
- Add lint, formatting, vet, and publish workflow checks - Run Go database tests with PostgreSQL and add Java tests - Make consumer sync opt-in; update docs and Go dependency
This commit is contained in:
1 parent
937f51b4fb
commit
0ff94f9b10
107 files changed
+10124
-410
No files matched your search
@@ -0,0 +1,166 @@
|
||||
import { cleanup, fireEvent, render, screen, waitFor } from '@testing-library/svelte';
|
||||
import { afterEach, describe, expect, it, vi } from 'vitest';
|
||||
import AuthPage from '../src/lib/components/AuthPage.svelte';
|
||||
|
||||
afterEach(cleanup);
|
||||
|
||||
const input = (name: string): HTMLInputElement => {
|
||||
const element = document.querySelector<HTMLInputElement>(`input[name="${name}"]`);
|
||||
if (!element) throw new Error(`no input named ${name}`);
|
||||
return element;
|
||||
};
|
||||
|
||||
async function fill(name: string, value: string): Promise<void> {
|
||||
await fireEvent.input(input(name), { target: { value } });
|
||||
}
|
||||
|
||||
async function submit(): Promise<void> {
|
||||
const form = document.querySelector('form');
|
||||
if (!form) throw new Error('no form');
|
||||
await fireEvent.submit(form);
|
||||
}
|
||||
|
||||
describe('AuthPage login', () => {
|
||||
it('shows the login form and passes the trimmed credentials to onLogin', async () => {
|
||||
const onLogin = vi.fn().mockResolvedValue(undefined);
|
||||
render(AuthPage, { props: { brand: 'Demo', onLogin } });
|
||||
expect(screen.getByRole('heading', { name: 'Welcome back' })).toBeTruthy();
|
||||
expect(document.querySelector('input[name="confirmPassword"]')).toBeNull();
|
||||
|
||||
await fill('identifier', 'alice@example.com');
|
||||
await fill('password', 'correct horse');
|
||||
await submit();
|
||||
await waitFor(() => expect(onLogin).toHaveBeenCalledTimes(1));
|
||||
expect(onLogin).toHaveBeenCalledWith({
|
||||
identifier: 'alice@example.com',
|
||||
password: 'correct horse',
|
||||
totpToken: '',
|
||||
});
|
||||
});
|
||||
|
||||
it('shows the error from a failed login and lets the user retry', async () => {
|
||||
const onLogin = vi
|
||||
.fn()
|
||||
.mockRejectedValueOnce(new Error('Invalid username or password.'))
|
||||
.mockResolvedValue(undefined);
|
||||
render(AuthPage, { props: { onLogin } });
|
||||
await fill('identifier', 'alice');
|
||||
await fill('password', 'wrong password');
|
||||
await submit();
|
||||
await waitFor(() => expect(screen.getByText('Invalid username or password.')).toBeTruthy());
|
||||
await submit();
|
||||
await waitFor(() => expect(onLogin).toHaveBeenCalledTimes(2));
|
||||
await waitFor(() => expect(screen.queryByText('Invalid username or password.')).toBeNull());
|
||||
});
|
||||
|
||||
it('asks for the authenticator code after a two-factor challenge and sends it on the next try', async () => {
|
||||
const onLogin = vi
|
||||
.fn()
|
||||
.mockRejectedValueOnce(new Error('Two-factor authentication code required.'))
|
||||
.mockResolvedValue(undefined);
|
||||
render(AuthPage, { props: { onLogin } });
|
||||
await fill('identifier', 'alice');
|
||||
await fill('password', 'correct horse');
|
||||
expect(document.querySelector('input[name="totpToken"]')).toBeNull();
|
||||
await submit();
|
||||
await waitFor(() => expect(input('totpToken')).toBeTruthy());
|
||||
expect(screen.getByText('Enter the six-digit authenticator code to continue.')).toBeTruthy();
|
||||
|
||||
await submit(); // an empty code is not sent
|
||||
expect(onLogin).toHaveBeenCalledTimes(1);
|
||||
|
||||
await fill('totpToken', ' 123456 ');
|
||||
await submit();
|
||||
await waitFor(() => expect(onLogin).toHaveBeenCalledTimes(2));
|
||||
expect(onLogin).toHaveBeenLastCalledWith({ identifier: 'alice', password: 'correct horse', totpToken: '123456' });
|
||||
});
|
||||
|
||||
it('does not offer the authenticator field when showTotp is off', async () => {
|
||||
const onLogin = vi.fn().mockRejectedValue(new Error('Two-factor authentication code required.'));
|
||||
render(AuthPage, { props: { onLogin, showTotp: false } });
|
||||
await fill('identifier', 'alice');
|
||||
await submit();
|
||||
await waitFor(() => expect(screen.getByText('Two-factor authentication code required.')).toBeTruthy());
|
||||
expect(document.querySelector('input[name="totpToken"]')).toBeNull();
|
||||
});
|
||||
|
||||
it('reports a missing login handler instead of failing silently', async () => {
|
||||
render(AuthPage);
|
||||
await submit();
|
||||
await waitFor(() => expect(screen.getByText('The application has not configured its login handler.')).toBeTruthy());
|
||||
});
|
||||
|
||||
it('shows only the loading heading while loading', () => {
|
||||
render(AuthPage, { props: { loading: true } });
|
||||
expect(screen.getByRole('heading', { name: 'Loading...' })).toBeTruthy();
|
||||
expect(document.querySelector('form')).toBeNull();
|
||||
});
|
||||
|
||||
it('falls back to the login view when the status check failed, whatever setupRequired says', () => {
|
||||
render(AuthPage, { props: { setupRequired: true, error: 'Could not reach the server.' } });
|
||||
expect(screen.getByRole('heading', { name: 'Welcome back' })).toBeTruthy();
|
||||
expect(screen.getByText('Could not reach the server.')).toBeTruthy();
|
||||
});
|
||||
});
|
||||
|
||||
describe('AuthPage setup', () => {
|
||||
it('refuses mismatched passwords without calling onSetup', async () => {
|
||||
const onSetup = vi.fn();
|
||||
render(AuthPage, { props: { setupRequired: true, onSetup } });
|
||||
expect(screen.getByRole('heading', { name: 'Create your account' })).toBeTruthy();
|
||||
await fill('username', 'root');
|
||||
await fill('email', 'root@example.com');
|
||||
await fill('password', 'password one');
|
||||
await fill('confirmPassword', 'password two');
|
||||
await submit();
|
||||
await waitFor(() => expect(screen.getByText('Passwords do not match.')).toBeTruthy());
|
||||
expect(onSetup).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it('passes the new account to onSetup when the passwords match', async () => {
|
||||
const onSetup = vi.fn().mockResolvedValue(undefined);
|
||||
render(AuthPage, { props: { setupRequired: true, onSetup } });
|
||||
await fill('username', 'root');
|
||||
await fill('email', 'root@example.com');
|
||||
await fill('password', 'password one');
|
||||
await fill('confirmPassword', 'password one');
|
||||
await submit();
|
||||
await waitFor(() =>
|
||||
expect(onSetup).toHaveBeenCalledWith({ username: 'root', email: 'root@example.com', password: 'password one' }),
|
||||
);
|
||||
});
|
||||
});
|
||||
|
||||
describe('AuthPage account reset', () => {
|
||||
it('offers the reset link only when both handlers are given', () => {
|
||||
render(AuthPage, { props: { onRequestReset: vi.fn() } });
|
||||
expect(screen.queryByText('Reset admin account')).toBeNull();
|
||||
cleanup();
|
||||
render(AuthPage, { props: { onRequestReset: vi.fn(), onConfirmReset: vi.fn() } });
|
||||
expect(screen.getByText('Reset admin account')).toBeTruthy();
|
||||
});
|
||||
|
||||
it('requests a code, then confirms the trimmed code the user types', async () => {
|
||||
const onRequestReset = vi.fn().mockResolvedValue(undefined);
|
||||
const onConfirmReset = vi.fn().mockResolvedValue(undefined);
|
||||
render(AuthPage, { props: { onRequestReset, onConfirmReset } });
|
||||
await fireEvent.click(screen.getByText('Reset admin account'));
|
||||
await waitFor(() => expect(onRequestReset).toHaveBeenCalledTimes(1));
|
||||
expect(screen.getByText('A reset code has been printed to the server console.')).toBeTruthy();
|
||||
|
||||
await fireEvent.click(screen.getByText('Confirm reset'));
|
||||
await waitFor(() => expect(screen.getByText('Enter the code printed in the server console.')).toBeTruthy());
|
||||
expect(onConfirmReset).not.toHaveBeenCalled();
|
||||
|
||||
await fireEvent.input(screen.getByLabelText('Reset code'), { target: { value: ' ABCD1234 ' } });
|
||||
await fireEvent.click(screen.getByText('Confirm reset'));
|
||||
await waitFor(() => expect(onConfirmReset).toHaveBeenCalledWith('ABCD1234'));
|
||||
});
|
||||
|
||||
it('shows the error when the reset request fails', async () => {
|
||||
const onRequestReset = vi.fn().mockRejectedValue(new Error('AuthGuard is not reachable.'));
|
||||
render(AuthPage, { props: { onRequestReset, onConfirmReset: vi.fn() } });
|
||||
await fireEvent.click(screen.getByText('Reset admin account'));
|
||||
await waitFor(() => expect(screen.getByText('AuthGuard is not reachable.')).toBeTruthy());
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,38 @@
|
||||
import { cleanup, fireEvent, render, screen, waitFor } from '@testing-library/svelte';
|
||||
import { afterEach, describe, expect, it, vi } from 'vitest';
|
||||
import NotificationStack from '../src/lib/components/NotificationStack.svelte';
|
||||
import { notifications, notify } from '../src/lib/notifications.svelte';
|
||||
|
||||
// The icon library compiles over a thousand components on import; the icons are not under test.
|
||||
vi.mock('@lucide/svelte', () => {
|
||||
const Icon = (): void => {};
|
||||
return { CircleAlert: Icon, CircleCheck: Icon, Info: Icon, OctagonAlert: Icon, X: Icon };
|
||||
});
|
||||
|
||||
afterEach(() => {
|
||||
cleanup();
|
||||
for (const entry of [...notifications.entries]) notifications.dismiss(entry.id);
|
||||
});
|
||||
|
||||
describe('NotificationStack', () => {
|
||||
it('renders each notification with its variant and message', async () => {
|
||||
render(NotificationStack);
|
||||
notify.success('Saved', 0);
|
||||
notify.error('Failed', 0);
|
||||
await waitFor(() => expect(screen.getByText('Saved')).toBeTruthy());
|
||||
expect(screen.getByText('Failed')).toBeTruthy();
|
||||
const variants = [...document.querySelectorAll('.sc-notification')].map((node) =>
|
||||
node.getAttribute('data-variant'),
|
||||
);
|
||||
expect(variants).toEqual(['success', 'error']);
|
||||
expect(screen.getByRole('status').getAttribute('aria-live')).toBe('polite');
|
||||
});
|
||||
|
||||
it('dismisses a notification from its close button', async () => {
|
||||
render(NotificationStack);
|
||||
notify.info('Dismiss me', 0);
|
||||
await waitFor(() => expect(screen.getByText('Dismiss me')).toBeTruthy());
|
||||
await fireEvent.click(screen.getByLabelText('Dismiss notification'));
|
||||
expect(notifications.entries).toHaveLength(0);
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,59 @@
|
||||
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
|
||||
import { notifications, notify } from '../src/lib/notifications.svelte';
|
||||
|
||||
function clear(): void {
|
||||
for (const entry of [...notifications.entries]) notifications.dismiss(entry.id);
|
||||
}
|
||||
|
||||
describe('notification store', () => {
|
||||
beforeEach(() => {
|
||||
vi.useFakeTimers();
|
||||
clear();
|
||||
});
|
||||
|
||||
afterEach(() => {
|
||||
clear();
|
||||
vi.useRealTimers();
|
||||
});
|
||||
|
||||
it('adds an entry per variant with increasing ids', () => {
|
||||
const ids = [notify.success('saved'), notify.error('failed'), notify.warning('careful'), notify.info('fyi')];
|
||||
expect(new Set(ids).size).toBe(4);
|
||||
expect([...ids].sort((a, b) => a - b)).toEqual(ids);
|
||||
expect(notifications.entries.map((entry) => [entry.variant, entry.message])).toEqual([
|
||||
['success', 'saved'],
|
||||
['error', 'failed'],
|
||||
['warning', 'careful'],
|
||||
['info', 'fyi'],
|
||||
]);
|
||||
});
|
||||
|
||||
it('removes an entry once its duration has passed, and only that entry', () => {
|
||||
notify.info('short', 1000);
|
||||
notify.info('long', 5000);
|
||||
vi.advanceTimersByTime(999);
|
||||
expect(notifications.entries).toHaveLength(2);
|
||||
vi.advanceTimersByTime(1);
|
||||
expect(notifications.entries.map((entry) => entry.message)).toEqual(['long']);
|
||||
vi.advanceTimersByTime(4000);
|
||||
expect(notifications.entries).toHaveLength(0);
|
||||
});
|
||||
|
||||
it('uses a five second default and keeps an entry with duration 0 until it is dismissed', () => {
|
||||
const timed = notify.success('default duration');
|
||||
const sticky = notify.error('sticky', 0);
|
||||
expect(notifications.entries.find((entry) => entry.id === timed)?.duration).toBe(5000);
|
||||
vi.advanceTimersByTime(60_000);
|
||||
expect(notifications.entries.map((entry) => entry.id)).toEqual([sticky]);
|
||||
notify.dismiss(sticky);
|
||||
expect(notifications.entries).toHaveLength(0);
|
||||
});
|
||||
|
||||
it('dismissing early cancels the timer, and dismissing an unknown id is harmless', () => {
|
||||
const id = notify.info('dismissed early', 1000);
|
||||
notifications.dismiss(id);
|
||||
expect(vi.getTimerCount()).toBe(0);
|
||||
expect(() => notifications.dismiss(9999)).not.toThrow();
|
||||
expect(notifications.entries).toHaveLength(0);
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,117 @@
|
||||
import { afterEach, beforeEach, describe, expect, it } from 'vitest';
|
||||
import {
|
||||
PRIMARY_COLOR_PALETTE,
|
||||
applyPrimaryColor,
|
||||
initPrimaryColor,
|
||||
primaryColorByName,
|
||||
setPrimaryColor,
|
||||
setPrimaryColorUser,
|
||||
storedPrimaryColor,
|
||||
} from '../src/lib/primary-color.svelte';
|
||||
|
||||
const styleText = (): string => document.getElementById('sc-primary-color')?.textContent ?? '';
|
||||
|
||||
function reset(): void {
|
||||
document.getElementById('sc-primary-color')?.remove();
|
||||
document.documentElement.removeAttribute('data-primary-color-user');
|
||||
localStorage.clear();
|
||||
}
|
||||
|
||||
describe('primary color palette', () => {
|
||||
it('has unique names and valid colors', () => {
|
||||
const names = PRIMARY_COLOR_PALETTE.map((color) => color.name);
|
||||
expect(new Set(names).size).toBe(names.length);
|
||||
for (const color of PRIMARY_COLOR_PALETTE) {
|
||||
for (const value of [color.dark, color.light, color.darkFg]) {
|
||||
expect(value, `${color.name} ${value}`).toMatch(/^#[0-9a-f]{6}$/);
|
||||
}
|
||||
}
|
||||
});
|
||||
|
||||
it('finds a color by name and nothing for an unknown name', () => {
|
||||
expect(primaryColorByName('Vermilion')?.light).toBe('#db3e24');
|
||||
expect(primaryColorByName('Not a color')).toBeUndefined();
|
||||
});
|
||||
});
|
||||
|
||||
describe('primary color', () => {
|
||||
beforeEach(reset);
|
||||
afterEach(reset);
|
||||
|
||||
it('writes the light and dark declarations into one stylesheet, and replaces them on a change', () => {
|
||||
applyPrimaryColor('app', 'Vermilion');
|
||||
const css = styleText();
|
||||
expect(css).toContain('--color-primary: #db3e24 !important;');
|
||||
expect(css).toContain("[data-theme='dark']");
|
||||
expect(css).toContain('--color-primary: #f59080 !important;');
|
||||
expect(css).toContain('--sc-primary-fg: #ffffff !important;');
|
||||
expect(css).toContain('--sc-primary-fg: #2b110d !important;');
|
||||
expect(css).toMatch(/--sc-primary-hover: #[0-9a-f]{6} !important;/);
|
||||
|
||||
applyPrimaryColor('app', 'Cyan');
|
||||
expect(document.querySelectorAll('#sc-primary-color')).toHaveLength(1);
|
||||
expect(styleText()).toContain('#249edb');
|
||||
expect(styleText()).not.toContain('#db3e24');
|
||||
});
|
||||
|
||||
it('makes the hover lighter on dark and darker on light', () => {
|
||||
applyPrimaryColor('app', 'Clover');
|
||||
const [light, dark] = styleText().split("[data-theme='dark']");
|
||||
const hover = (css: string): number => {
|
||||
const hex = /--sc-primary-hover: #([0-9a-f]{6})/.exec(css)?.[1] ?? '';
|
||||
return [0, 2, 4].reduce((sum, start) => sum + parseInt(hex.slice(start, start + 2), 16), 0);
|
||||
};
|
||||
const base = (hexValue: string): number =>
|
||||
[1, 3, 5].reduce((sum, start) => sum + parseInt(hexValue.slice(start, start + 2), 16), 0);
|
||||
expect(hover(light)).toBeLessThan(base('#16a34a'));
|
||||
expect(hover(dark)).toBeGreaterThan(base('#22c55e'));
|
||||
});
|
||||
|
||||
it('removes the stylesheet for an unknown or empty color', () => {
|
||||
applyPrimaryColor('app', 'Vermilion');
|
||||
applyPrimaryColor('app', 'Not a color');
|
||||
expect(document.getElementById('sc-primary-color')).toBeNull();
|
||||
applyPrimaryColor('app', '');
|
||||
expect(document.getElementById('sc-primary-color')).toBeNull();
|
||||
});
|
||||
|
||||
it('stores the choice per project and user, and clears it', () => {
|
||||
setPrimaryColorUser('Alice');
|
||||
setPrimaryColor('My App', 'Violet');
|
||||
expect(localStorage.getItem('primary-color:my%20app:alice')).toBe('Violet');
|
||||
expect(storedPrimaryColor('my app')).toBe('Violet');
|
||||
expect(styleText()).toContain('#6d24db');
|
||||
|
||||
setPrimaryColorUser('bob');
|
||||
expect(storedPrimaryColor('my app')).toBe('');
|
||||
setPrimaryColorUser('alice');
|
||||
expect(storedPrimaryColor('my app')).toBe('Violet');
|
||||
|
||||
setPrimaryColor('my app', '');
|
||||
expect(storedPrimaryColor('my app')).toBe('');
|
||||
expect(localStorage.getItem('primary-color:my%20app:alice')).toBeNull();
|
||||
expect(document.getElementById('sc-primary-color')).toBeNull();
|
||||
});
|
||||
|
||||
it('ignores a stored name that is not in the palette', () => {
|
||||
localStorage.setItem('primary-color:app:anonymous', 'Chartreuse-ish');
|
||||
expect(storedPrimaryColor('app')).toBe('');
|
||||
});
|
||||
|
||||
it('applies the stored color on init and re-applies it when the user changes', () => {
|
||||
localStorage.setItem('primary-color:shop:carol', 'Rose');
|
||||
initPrimaryColor('shop', 'Carol');
|
||||
expect(styleText()).toContain('#db2474');
|
||||
|
||||
localStorage.setItem('primary-color:shop:dave', 'Lime');
|
||||
setPrimaryColorUser('dave');
|
||||
expect(styleText()).toContain('#72b814');
|
||||
setPrimaryColorUser('someone-without-a-choice');
|
||||
expect(document.getElementById('sc-primary-color')).toBeNull();
|
||||
});
|
||||
|
||||
it('treats a blank user as anonymous', () => {
|
||||
setPrimaryColor('app', 'Gold');
|
||||
expect(localStorage.getItem('primary-color:app:anonymous')).toBe('Gold');
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,19 @@
|
||||
// jsdom has no Web Animations API, which Svelte's transitions call. This stand-in finishes at once,
|
||||
// so an element that leaves with a transition is removed straight away.
|
||||
if (typeof Element.prototype.animate !== 'function') {
|
||||
Element.prototype.animate = function animate(): Animation {
|
||||
const animation = {
|
||||
currentTime: 0,
|
||||
onfinish: null as (() => void) | null,
|
||||
cancel() {},
|
||||
finish() {
|
||||
animation.onfinish?.();
|
||||
},
|
||||
pause() {},
|
||||
play() {},
|
||||
finished: Promise.resolve(),
|
||||
};
|
||||
queueMicrotask(() => animation.onfinish?.());
|
||||
return animation as unknown as Animation;
|
||||
};
|
||||
}
|
||||
Reference in new issue
Block a user