Real-time monitoring dashboard for Proxmox VE, PBS, Docker, Kubernetes, TrueNAS and vSphere. Self-hosted, with alerts for failed backups, full disks, unhealthy containers and offline nodes.
Go aialertsdashboarddockerdocker-monitoringgohomelabinfrastructure-monitoringkubernetesmonitoringmspproxmoxproxmox-backup-serverproxmox-mail-gatewayproxmox-veself-hostedtruenastypescriptvspherewebhooks
test(frontend): branch coverage for 5 pure modules (GLM wave 0712 batch 3b)
rcourtman243f10f3c066
diff --git a/frontend-modern/src/components/AI/__tests__/aiChatUtils.branchcov0712.test.ts b/frontend-modern/src/components/AI/__tests__/aiChatUtils.branchcov0712.test.tsnew file mode 100644index 0000000000..56787dd8d7--- /dev/null+++ b/frontend-modern/src/components/AI/__tests__/aiChatUtils.branchcov0712.test.ts@@ -0,0 +1,150 @@+import { describe, expect, it } from 'vitest';++import * as utils from '@/components/AI/aiChatUtils';++// Branch-coverage companion to aiChatUtils.test.ts. Both target functions+// (coerceMarkdownInput, configureDOMPurify) are module-private, so every+// branch below is driven through the public renderMarkdown entry point and+// asserted against concrete rendered output. renderMarkdown's signature is+// (content: unknown), so non-string inputs type-check without casts; a branch+// is pinned by showing renderMarkdown(<branch input>) equals renderMarkdown of+// the exact string that branch must coerce to.++// ---------------------------------------------------------------------------+// coerceMarkdownInput — every arm of its input-type ladder.+// ---------------------------------------------------------------------------++describe('coerceMarkdownInput branch coverage', () => {+ it('returns a string input unchanged (string branch -> rendered as markdown)', () => {+ // A real markdown string reaches marked.parse directly: the heading is+ // rendered, proving the value was NOT routed through String()/JSON first.+ const out = utils.renderMarkdown('# Heading One');+ expect(out).toContain('<h1');+ expect(out).toContain('Heading One');+ });++ it('extracts record.text from an object (object.text branch)', () => {+ const out = utils.renderMarkdown({ text: 'alpha' });+ expect(out).toEqual(utils.renderMarkdown('alpha'));+ // Discriminator: the JSON.stringify arm would have emitted the literal+ // {"text":"alpha"} payload instead.+ expect(out).not.toContain('"text"');+ });++ it('extracts record.content when record.text is absent (object.content branch)', () => {+ const out = utils.renderMarkdown({ content: 'beta' });+ expect(out).toEqual(utils.renderMarkdown('beta'));+ expect(out).not.toContain('"content"');+ });++ it('prefers record.text over record.content (precedence between the two arms)', () => {+ const out = utils.renderMarkdown({ text: 'from-text', content: 'from-content' });+ expect(out).toEqual(utils.renderMarkdown('from-text'));+ expect(out).not.toContain('from-content');+ });++ it('JSON.stringifies an object with neither text nor content (JSON branch)', () => {+ const out = utils.renderMarkdown({ foo: 'bar', n: 42 });+ expect(out).toEqual(utils.renderMarkdown('{"foo":"bar","n":42}'));+ expect(out).toContain('"foo":"bar"');+ expect(out).toContain('"n":42');+ });++ it('falls back to String() when JSON.stringify throws on a circular object (catch branch)', () => {+ const circular: Record<string, unknown> = {};+ circular.self = circular; // JSON.stringify throws -> catch -> String(content)+ const out = utils.renderMarkdown(circular);+ expect(out).toEqual(utils.renderMarkdown('[object Object]'));+ expect(out).toContain('[object Object]');+ });++ it('coerces null to empty string (null arm of the final ternary)', () => {+ expect(utils.renderMarkdown(null)).toBe('');+ });++ it('coerces undefined to empty string (undefined arm of the final ternary)', () => {+ expect(utils.renderMarkdown(undefined)).toBe('');+ });++ it('coerces a number primitive via String() (non-null primitive arm)', () => {+ expect(utils.renderMarkdown(42)).toEqual(utils.renderMarkdown('42'));+ expect(utils.renderMarkdown(42)).toContain('42');+ });++ it('coerces a falsy number (0) via String(), not the null branch', () => {+ // 0 is falsy so `content && typeof === 'object'` short-circuits, but+ // 0 != null, so it must still reach String(0) === '0' rather than ''.+ expect(utils.renderMarkdown(0)).toEqual(utils.renderMarkdown('0'));+ expect(utils.renderMarkdown(0)).toContain('0');+ });++ it('coerces a boolean primitive via String() (true and false)', () => {+ expect(utils.renderMarkdown(true)).toEqual(utils.renderMarkdown('true'));+ expect(utils.renderMarkdown(false)).toEqual(utils.renderMarkdown('false'));+ // false is falsy but not null -> must NOT collapse to ''.+ expect(utils.renderMarkdown(false)).not.toBe('');+ });+});++// ---------------------------------------------------------------------------+// configureDOMPurify — the idempotency guard and both sanitize hooks, driven+// through renderMarkdown. vitest isolates modules per file, so the first+// renderMarkdown call in this file runs the configure body; later calls take+// the early-return.+// ---------------------------------------------------------------------------++describe('configureDOMPurify branch coverage', () => {+ it('configures hooks exactly once and keeps them active on later calls (early-return guard)', () => {+ const md = '[link](https://example.com)';+ const first = utils.renderMarkdown(md);+ const second = utils.renderMarkdown(md);+ const third = utils.renderMarkdown(md);+ // Identical output every call: the `if (domPurifyConfigured) return`+ // guard short-circuits calls 2 and 3, yet the afterSanitizeAttributes+ // hook registered on call 1 still fires.+ expect(second).toEqual(first);+ expect(third).toEqual(first);+ expect(first).toContain('href="https://example.com"');+ expect(first).toContain('target="_blank"');+ expect(first).toContain('rel="noopener noreferrer"');+ });++ it('does not add target/rel to non-anchor elements (afterSanitizeAttributes non-A arm)', () => {+ // <div> hits the `element.tagName !== 'A'` early return inside the hook.+ const out = utils.renderMarkdown('<div>box</div>');+ expect(out).toContain('<div>box</div>');+ expect(out).not.toContain('target=');+ expect(out).not.toContain('rel=');+ });++ it('keeps a valid language-x class on <code> (uponSanitizeAttribute code+class+regex-true arm)', () => {+ const out = utils.renderMarkdown(['```ts', 'const x = 1;', '```'].join('\n'));+ expect(out).toContain('<code');+ expect(out).toContain('language-ts');+ });++ it('drops an invalid class on <code> (uponSanitizeAttribute code+class+regex-false arm)', () => {+ // 'highlight' fails ^language-[a-z0-9+#_-]{1,30}$ -> forceKeepAttr stays+ // unset -> DOMPurify strips 'class' (not in ALLOWED_ATTR).+ const out = utils.renderMarkdown('<code class="highlight">x</code>');+ expect(out).toContain('<code>x</code>');+ expect(out).not.toContain('class=');+ expect(out).not.toContain('highlight');+ });++ it('drops a language-x class on a non-code element (uponSanitizeAttribute non-CODE arm)', () => {+ const out = utils.renderMarkdown('<div class="language-bash">z</div>');+ expect(out).toContain('>z<');+ expect(out).not.toContain('class=');+ expect(out).not.toContain('language-bash');+ });++ it('ignores non-class attributes on <code> while still validating class (attrName !== class arm)', () => {+ // The hook processes 'id' (attrName !== 'class' -> early return; the attr+ // is then stripped by DOMPurify) and 'class' (validated + kept).+ const out = utils.renderMarkdown('<code id="ignored" class="language-js">y</code>');+ expect(out).toContain('language-js');+ expect(out).not.toContain('id=');+ expect(out).not.toContain('ignored');+ });+});diff --git a/frontend-modern/src/components/Infrastructure/__tests__/resourceDetailDrawerMetricsHistoryModel.branchcov0712.test.ts b/frontend-modern/src/components/Infrastructure/__tests__/resourceDetailDrawerMetricsHistoryModel.branchcov0712.test.tsnew file mode 100644index 0000000000..d60d0d56e9--- /dev/null+++ b/frontend-modern/src/components/Infrastructure/__tests__/resourceDetailDrawerMetricsHistoryModel.branchcov0712.test.ts@@ -0,0 +1,224 @@+import { describe, expect, it } from 'vitest';++import {+ getResourceMetricsHistoryFallbackMetrics,+ getResourceMetricsHistoryTarget,+} from '@/components/Infrastructure/resourceDetailDrawerMetricsHistoryModel';+import type {+ MetricsHistoryTargetResourceType,+ Resource,+} from '@/types/resource';++// Minimal valid Resource fixture; mirrors the baseResource() convention used by+// sibling branchcov tests in this directory.+const baseResource = (overrides: Partial<Resource>): Resource => ({+ id: 'agent-1',+ type: 'agent',+ name: 'host-1',+ displayName: 'Host 1',+ platformId: 'host-1',+ platformType: 'agent',+ sourceType: 'hybrid',+ status: 'online',+ lastSeen: 1_700_000_000_000,+ ...overrides,+});++describe('getResourceMetricsHistoryTarget branch coverage', () => {+ it('returns the metricsTarget pair when both resourceType and resourceId resolve', () => {+ // TRUE arm of `if (metricsType && metricsId)`.+ const resource = baseResource({+ metricsTarget: { resourceType: 'pod', resourceId: 'pod-7' },+ });+ expect(getResourceMetricsHistoryTarget(resource)).toStrictEqual({+ resourceType: 'pod',+ resourceId: 'pod-7',+ });+ });++ it('trims whitespace around metricsTarget fields before returning them', () => {+ // Drives asTrimmedString's "non-empty after trim -> return trimmed" arm for+ // both fields, then the TRUE arm of the `metricsType && metricsId` guard.+ const resource = baseResource({+ metricsTarget: {+ resourceType: ' vm ' as MetricsHistoryTargetResourceType,+ resourceId: ' vm-9 ',+ },+ });+ expect(getResourceMetricsHistoryTarget(resource)).toStrictEqual({+ resourceType: 'vm',+ resourceId: 'vm-9',+ });+ });++ it('falls through the metricsTarget branch when resourceId is empty/whitespace', () => {+ // asTrimmedString(' ') -> undefined, so metricsId is falsy ->+ // FALSE arm of `metricsType && metricsId`. Non-agent type then hits the+ // final `return null`.+ const resource = baseResource({+ type: 'vm',+ metricsTarget: { resourceType: 'vm', resourceId: ' ' },+ });+ expect(getResourceMetricsHistoryTarget(resource)).toBeNull();+ });++ it('falls through the metricsTarget branch when resourceType is empty string', () => {+ // metricsType falsy -> FALSE arm of the guard even though resourceId is set.+ const resource = baseResource({+ type: 'pod',+ metricsTarget: {+ resourceType: '' as MetricsHistoryTargetResourceType,+ resourceId: 'pod-1',+ },+ });+ expect(getResourceMetricsHistoryTarget(resource)).toBeNull();+ });++ it('treats a non-string metricsTarget.resourceType as undefined', () => {+ // typeof !== 'string' -> asTrimmedString returns undefined -> guard FALSE.+ // The cast is required because resourceType is typed as a string union.+ const resource = baseResource({+ type: 'pod',+ metricsTarget: {+ resourceType: 42 as unknown as MetricsHistoryTargetResourceType,+ resourceId: 'pod-1',+ },+ });+ expect(getResourceMetricsHistoryTarget(resource)).toBeNull();+ });++ it('synthesizes an agent target from resource.id when metricsTarget is absent', () => {+ // TRUE arm of `resource.type === 'agent'` AND TRUE arm of the+ // `resourceId ? {...} : null` ternary.+ const resource = baseResource({ type: 'agent', id: 'host-42' });+ expect(getResourceMetricsHistoryTarget(resource)).toStrictEqual({+ resourceType: 'agent',+ resourceId: 'host-42',+ });+ });++ it('returns null for an agent whose id trims to empty', () => {+ // TRUE arm of `resource.type === 'agent'` but asTrimmedString(' ') is+ // undefined -> FALSE arm of the ternary.+ const resource = baseResource({ type: 'agent', id: ' ' });+ expect(getResourceMetricsHistoryTarget(resource)).toBeNull();+ });++ it('returns null for a non-agent resource with no metricsTarget', () => {+ // FALSE arm of `resource.type === 'agent'` -> final `return null`.+ const resource = baseResource({ type: 'vm' });+ expect(getResourceMetricsHistoryTarget(resource)).toBeNull();+ });+});++describe('getResourceMetricsHistoryFallbackMetrics branch coverage', () => {+ it('returns every metric as a finite number when the resource is fully populated', () => {+ // All finiteMetric calls take the "finite number -> return value" arm;+ // memory/disk ternaries take the TRUE arm and getMemoryPercent/getDiskPercent+ // take their `(used/total)*100` arms.+ const resource = baseResource({+ cpu: { current: 12.5 },+ memory: { current: 0, total: 100, used: 30 },+ disk: { current: 0, total: 200, used: 80 },+ network: { rxBytes: 1000, txBytes: 2000 },+ diskIO: { readRate: 3000, writeRate: 4000 },+ });+ expect(getResourceMetricsHistoryFallbackMetrics(resource)).toStrictEqual({+ cpu: 12.5,+ memory: 30, // (30 / 100) * 100+ disk: 40, // (80 / 200) * 100+ netin: 1000,+ netout: 2000,+ diskread: 3000,+ diskwrite: 4000,+ });+ });++ it('returns undefined for every field when no metric objects are present', () => {+ // Every optional chain short-circuits to undefined; memory/disk ternaries+ // take the FALSE arm because `resource.memory`/`resource.disk` are falsy.+ const resource = baseResource({});+ expect(getResourceMetricsHistoryFallbackMetrics(resource)).toStrictEqual({+ cpu: undefined,+ memory: undefined,+ disk: undefined,+ netin: undefined,+ netout: undefined,+ diskread: undefined,+ diskwrite: undefined,+ });+ });++ it('uses memory.current when total/used are absent', () => {+ // getMemoryPercent: `memory.total && memory.used` is falsy -> returns current.+ const resource = baseResource({ memory: { current: 45.5 } });+ expect(getResourceMetricsHistoryFallbackMetrics(resource).memory).toBe(45.5);+ });++ it('uses disk.current when total/used are absent', () => {+ // getDiskPercent: `disk.total && disk.used` is falsy -> returns current.+ const resource = baseResource({ disk: { current: 67 } });+ expect(getResourceMetricsHistoryFallbackMetrics(resource).disk).toBe(67);+ });++ it('coerces a NaN memory.current to undefined via finiteMetric', () => {+ // getMemoryPercent returns NaN; finiteMetric: typeof === 'number' but+ // Number.isFinite is FALSE -> undefined.+ const resource = baseResource({ memory: { current: Number.NaN } });+ expect(getResourceMetricsHistoryFallbackMetrics(resource).memory).toBeUndefined();+ });++ it('coerces a NaN disk.current to undefined via finiteMetric', () => {+ const resource = baseResource({ disk: { current: Number.NaN } });+ expect(getResourceMetricsHistoryFallbackMetrics(resource).disk).toBeUndefined();+ });++ it('coerces an Infinity cpu.current to undefined via finiteMetric', () => {+ const resource = baseResource({+ cpu: { current: Number.POSITIVE_INFINITY },+ });+ expect(getResourceMetricsHistoryFallbackMetrics(resource).cpu).toBeUndefined();+ });++ it('coerces a NaN cpu.current to undefined via finiteMetric', () => {+ const resource = baseResource({ cpu: { current: Number.NaN } });+ expect(getResourceMetricsHistoryFallbackMetrics(resource).cpu).toBeUndefined();+ });++ it('coerces a non-number cpu.current (malformed payload) to undefined', () => {+ // finiteMetric: `typeof value === 'number'` is FALSE -> undefined.+ // Cast required because ResourceMetric.current is typed as number.+ const resource = baseResource({+ cpu: { current: 'busy' as unknown as number },+ });+ expect(getResourceMetricsHistoryFallbackMetrics(resource).cpu).toBeUndefined();+ });++ it('coerces non-finite network and diskIO rates to undefined', () => {+ const resource = baseResource({+ network: { rxBytes: Number.NaN, txBytes: Number.NEGATIVE_INFINITY },+ diskIO: {+ readRate: Number.POSITIVE_INFINITY,+ writeRate: Number.NaN,+ },+ });+ expect(getResourceMetricsHistoryFallbackMetrics(resource)).toStrictEqual({+ cpu: undefined,+ memory: undefined,+ disk: undefined,+ netin: undefined,+ netout: undefined,+ diskread: undefined,+ diskwrite: undefined,+ });+ });++ it('emits the memory ternary FALSE arm as undefined when memory is explicitly absent but disk is present', () => {+ // Mixes a present disk (TRUE arm) with an absent memory (FALSE arm) to prove+ // the two ternaries are evaluated independently.+ const resource = baseResource({ disk: { current: 18 } });+ const result = getResourceMetricsHistoryFallbackMetrics(resource);+ expect(result.memory).toBeUndefined();+ expect(result.disk).toBe(18);+ });+});diff --git a/frontend-modern/src/components/Settings/__tests__/nodeModalModel.branchcov0712.test.ts b/frontend-modern/src/components/Settings/__tests__/nodeModalModel.branchcov0712.test.tsnew file mode 100644index 0000000000..b31cd0444a--- /dev/null+++ b/frontend-modern/src/components/Settings/__tests__/nodeModalModel.branchcov0712.test.ts@@ -0,0 +1,166 @@+import { describe, expect, it } from 'vitest';+import type { ClusterEndpoint } from '@/types/nodes';+import {+ buildClusterEndpointOverridesPayload,+ deriveNameFromHost,+} from '../nodeModalModel';++// Same fixture builder shape as the sibling nodeModalModel.test.ts suite so the+// private comparison/trim branches under test are driven through the single+// exported `buildClusterEndpointOverridesPayload` orchestrator.+const endpoint = (nodeName: string, ipOverride?: string): ClusterEndpoint => ({+ nodeId: `node/${nodeName}`,+ nodeName,+ host: `https://${nodeName}.local:8006`,+ ip: '10.0.0.1',+ ipOverride,+ online: true,+ lastSeen: '',+});++// ---- deriveNameFromHost -----------------------------------------------------+//+// Branches exercised below (in order of the function body):+// * `host.trim()` then `if (!value) return ''` — empty + whitespace-only+// inputs, plus the leading/trailing-trim path.+// * ternary `value.includes('://') ? new URL(value) : new URL('https://' + v)`+// — both the scheme-present (`https://...`, `file://...`) and scheme-absent+// (`pve1.local`, `[::1]:8006`) arms.+// * `url.hostname || value` — the truthy-hostname arm (normal hosts) AND the+// falsy-hostname defensive fallback (a valid URL whose hostname is empty,+// e.g. `file://`), which keeps the raw input.+// * `catch` arm — inputs that fail WHATWG URL parsing (spaces in the host)+// hit `value.replace(/^https?:\/\//, '')`.+// * post-URL `.replace(/\/.*$/, '')` — strips a trailing path that survived+// into the catch branch.+// * post-URL `.replace(/^\[(.*)\]$/, '$1')` — unwraps the IPv6 brackets that+// `URL.hostname` emits for an IPv6 literal.+// * post-URL `.replace(/\s+/g, '-')` — collapses internal whitespace that+// survived into the catch branch.++describe('deriveNameFromHost', () => {+ it('returns the empty string for an empty host (early return before URL parsing)', () => {+ expect(deriveNameFromHost('')).toBe('');+ });++ it('returns the empty string for a whitespace-only host (trim() -> empty -> early return)', () => {+ expect(deriveNameFromHost(' ')).toBe('');+ });++ it('trims surrounding whitespace before parsing (host with no scheme, success arm)', () => {+ expect(deriveNameFromHost(' pve1.local ')).toBe('pve1.local');+ });++ it('parses a bare hostname via the no-scheme arm (new URL(`https://${value}`))', () => {+ expect(deriveNameFromHost('pve1.local')).toBe('pve1.local');+ });++ it('uses the scheme-present arm and drops port + path from url.hostname', () => {+ // `value.includes('://')` is true, so `new URL(value)` runs directly and+ // url.hostname is the truthy 'example.com'; the trailing /\/.*$/ and IPv6+ // regexes are no-ops on a plain hostname.+ expect(deriveNameFromHost('https://example.com:8006/path?q=1')).toBe('example.com');+ });++ it('unwraps IPv6 brackets emitted by URL.hostname for an IPv6 literal', () => {+ // No scheme -> `new URL('https://[::1]:8006')`; URL.hostname returns+ // '[::1]' (bracketed), which the `/^\[(.*)\]$/` regex reduces to '::1'.+ expect(deriveNameFromHost('[::1]:8006')).toBe('::1');+ });++ it('keeps the raw input when url.hostname is empty (falsy-hostname `|| value` fallback)', () => {+ // `file:///etc/hosts` parses (so no catch) but URL.hostname is '' for the+ // file scheme; the `|| value` fallback keeps 'file:///etc/hosts', then+ // /\/.*$/ strips from the first slash, leaving 'file:'.+ expect(deriveNameFromHost('file:///etc/hosts')).toBe('file:');+ });++ it('falls into the catch arm and collapses internal whitespace', () => {+ // 'foo bar' (no scheme) -> `new URL('https://foo bar')` throws; the catch+ // leaves 'foo bar' (no leading scheme to strip), and /\s+/g -> 'foo-bar'.+ expect(deriveNameFromHost('foo bar')).toBe('foo-bar');+ });++ it('strips a leading http(s):// scheme inside the catch arm', () => {+ // Scheme present -> `new URL('http://bad url')` throws; the catch regex+ // removes 'http://', leaving 'bad url', then whitespace collapse.+ expect(deriveNameFromHost('http://bad url')).toBe('bad-url');+ });++ it('strips a trailing path that survived into the catch arm', () => {+ // 'foo bar/baz' -> `new URL('https://foo bar/baz')` throws (space in+ // host); the catch keeps 'foo bar/baz', /\/.*$/ drops '/baz', then+ // whitespace collapse -> 'foo-bar' (not 'foo-bar/baz').+ expect(deriveNameFromHost('foo bar/baz')).toBe('foo-bar');+ });+});++// ---- buildClusterEndpointOverridesPayload ----------------------------------+//+// The sibling suite already covers the core happy/undefined paths; these tests+// target the comparison/trim nuances and the defensive `?? ''` fallback inside+// the `.map` that the happy-path inputs never reach:+// * `(overrides[name] ?? '').trim()` — the OUTPUT trim of a non-empty form+// value (siblings only asserted an untrimmed value or a whitespace-only+// no-op).+// * multi-member inclusion with an unchanged member in the middle (order+// preservation + selective filtering).+// * `value.trim() !== (endpoint.ipOverride ?? '')` where trim changes the+// form value but it still equals the saved override -> treated as unchanged.+// * the map's unreachable-in-practice `(overrides[name] ?? '')` defensive+// fallback, driven via a Proxy that returns undefined on the second read.++describe('buildClusterEndpointOverridesPayload', () => {+ it('trims a non-empty form value when emitting the override', () => {+ const payload = buildClusterEndpointOverridesPayload([endpoint('pve1')], {+ pve1: ' 10.0.0.11 ',+ });+ expect(payload).toStrictEqual([{ nodeName: 'pve1', ipOverride: '10.0.0.11' }]);+ });++ it('includes multiple changed members in order and skips an unchanged middle member', () => {+ const endpoints = [+ endpoint('pve1'), // no saved override -> '' !== '10.0.0.11' -> changed+ endpoint('pve2', '10.0.0.2'), // '10.0.0.2' === '10.0.0.2' -> unchanged (skipped)+ endpoint('pve3', '10.0.0.3'), // '10.0.0.33' !== '10.0.0.3' -> changed+ ];+ const payload = buildClusterEndpointOverridesPayload(endpoints, {+ pve1: '10.0.0.11',+ pve2: '10.0.0.2',+ pve3: '10.0.0.33',+ });+ expect(payload).toStrictEqual([+ { nodeName: 'pve1', ipOverride: '10.0.0.11' },+ { nodeName: 'pve3', ipOverride: '10.0.0.33' },+ ]);+ });++ it('treats a whitespace-padded form value as unchanged when it trims to the saved override', () => {+ // value.trim() ('10.0.0.5') === (endpoint.ipOverride ?? '') ('10.0.0.5'),+ // so the member is filtered out and the result collapses to undefined.+ const payload = buildClusterEndpointOverridesPayload([endpoint('pve1', '10.0.0.5')], {+ pve1: ' 10.0.0.5 ',+ });+ expect(payload).toBeUndefined();+ });++ it('hits the map defensive `(overrides[name] ?? "")` fallback via a second-read Proxy', () => {+ // The filter reads overrides.pve1 once (returns the defined value so the+ // member survives), then the map reads it again — the Proxy returns+ // undefined on that second access, forcing `(undefined ?? '').trim()` => ''.+ const target: Record<string, string> = { pve1: '10.0.0.11' };+ let accesses = 0;+ const flaky = new Proxy(target, {+ get(t, prop) {+ if (prop === 'pve1') {+ accesses += 1;+ return accesses === 2 ? undefined : t.pve1;+ }+ return Reflect.get(t, prop);+ },+ });+ const payload = buildClusterEndpointOverridesPayload([endpoint('pve1')], flaky);+ expect(payload).toStrictEqual([{ nodeName: 'pve1', ipOverride: '' }]);+ expect(accesses).toBe(2);+ });+});diff --git a/frontend-modern/src/components/Storage/__tests__/storageSummaryGroups.branchcov0712.test.ts b/frontend-modern/src/components/Storage/__tests__/storageSummaryGroups.branchcov0712.test.tsnew file mode 100644index 0000000000..7a99b9651b--- /dev/null+++ b/frontend-modern/src/components/Storage/__tests__/storageSummaryGroups.branchcov0712.test.ts@@ -0,0 +1,222 @@+import { describe, expect, it } from 'vitest';+import type { NormalizedHealth, StorageRecord } from '@/features/storageBackups/models';+import type {+ StorageGroupedRecords,+ StorageGroupKey,+} from '@/components/Storage/useStorageModel';+import {+ buildStorageSummaryGroupId,+ buildStorageSummaryGroupScope,+} from '@/components/Storage/storageSummaryGroups';++const emptyByHealth = (): Record<NormalizedHealth, number> => ({+ healthy: 0,+ warning: 0,+ critical: 0,+ offline: 0,+ unknown: 0,+});++const makeRecord = (overrides: Partial<StorageRecord> = {}): StorageRecord => ({+ id: 'storage-1',+ name: 'pool-1',+ category: 'pool',+ health: 'healthy',+ location: { label: 'pve1', scope: 'node' },+ capacity: { totalBytes: 100, usedBytes: 40, freeBytes: 60, usagePercent: 40 },+ capabilities: [],+ source: {+ platform: 'truenas',+ family: 'generic',+ origin: 'resource',+ adapterId: 'adapter-1',+ },+ observedAt: 0,+ ...overrides,+});++const makeGroup = (overrides: Partial<StorageGroupedRecords> = {}): StorageGroupedRecords => ({+ key: 'pve1',+ items: [],+ stats: {+ totalBytes: 0,+ usedBytes: 0,+ usagePercent: 0,+ byHealth: emptyByHealth(),+ },+ ...overrides,+});++describe('buildStorageSummaryGroupId (branch coverage)', () => {+ it('returns null when groupBy is "none" (first guard true arm)', () => {+ // `if (groupBy === 'none')` -> true: short-circuits before touching groupKey.+ expect(buildStorageSummaryGroupId('none', 'pve1')).toBeNull();+ // Even a would-be-valid key is irrelevant once groupBy is 'none'.+ expect(buildStorageSummaryGroupId('none', 'anything')).toBeNull();+ });++ it('returns null when groupBy is not "none" but groupKey trims to empty', () => {+ // First guard false arm + second guard (`!normalizedGroupKey`) true arm.+ // `normalizeStorageSummaryGroupKey` is `value.trim()`; each of these trims to ''.+ expect(buildStorageSummaryGroupId('node', '')).toBeNull();+ expect(buildStorageSummaryGroupId('type', ' ')).toBeNull();+ expect(buildStorageSummaryGroupId('status', '\t\n')).toBeNull();+ });++ it.each<[StorageGroupKey, string]>([+ ['node', 'pve1'],+ ['type', 'zfs'],+ ['status', 'healthy'],+ ])('composes the id as storage:%s:<trimmed key> for groupBy %s (happy path)', (groupBy, key) => {+ // Both guards false -> final return statement.+ expect(buildStorageSummaryGroupId(groupBy, key)).toBe(`storage:${groupBy}:${key}`);+ });++ it('uses the trimmed groupKey in the composed id, not the raw whitespace-padded input', () => {+ // Confirms normalizeStorageSummaryGroupKey (trim) is applied before interpolation.+ expect(buildStorageSummaryGroupId('node', ' pve1 ')).toBe('storage:node:pve1');+ expect(buildStorageSummaryGroupId('type', '\tZFS\n')).toBe('storage:type:ZFS');+ });+});++describe('buildStorageSummaryGroupScope (branch coverage)', () => {+ it('returns null when the resolved id is null because groupBy is "none"', () => {+ // `if (!id)` true arm, reached via buildStorageSummaryGroupId -> 'none' guard.+ const group = makeGroup({ items: [makeRecord()] });+ expect(buildStorageSummaryGroupScope(group, 'none')).toBeNull();+ });++ it('returns null when the resolved id is null because group.key trims to empty', () => {+ // `if (!id)` true arm, reached via the empty-normalized-key guard inside buildStorageSummaryGroupId.+ const group = makeGroup({ key: ' ', items: [makeRecord()] });+ expect(buildStorageSummaryGroupScope(group, 'node')).toBeNull();+ });++ it('returns null when the group has no items (seriesIds.length === 0)', () => {+ // `if (seriesIds.length === 0)` true arm: items.map -> [] -> Set -> [] -> length 0.+ const group = makeGroup({ items: [] });+ expect(buildStorageSummaryGroupScope(group, 'node')).toBeNull();+ });++ it('returns null when every item resolves to an empty/falsy metric resource id', () => {+ // `if (seriesIds.length === 0)` true arm, but items is non-empty: each record's+ // resolveStorageRecordMetricResourceId falls through metricsTarget/refs to id,+ // and `.filter(Boolean)` strips the empty strings.+ const blankRecord = makeRecord({ id: '' });+ const group = makeGroup({ items: [blankRecord, makeRecord({ id: ' ' })] });+ expect(buildStorageSummaryGroupScope(group, 'node')).toBeNull();+ });++ it('builds a scope using the record id fallback when items have no metricsTarget/refs', () => {+ // Happy path: resolveStorageRecordMetricResourceId's third operand (record.id).+ const group = makeGroup({+ key: 'pve1',+ items: [makeRecord({ id: 'storage-1' }), makeRecord({ id: 'storage-2' })],+ });+ expect(buildStorageSummaryGroupScope(group, 'node')).toStrictEqual({+ id: 'storage:node:pve1',+ label: 'pve1 (2 storage items)',+ seriesIds: ['storage-1', 'storage-2'],+ });+ });++ it('prefers metricsTarget.resourceId over refs.resourceId and record.id in the emitted seriesIds', () => {+ // resolveStorageRecordMetricResourceId's first operand wins: metricsTarget.resourceId.+ const group = makeGroup({+ key: 'node-a',+ items: [+ makeRecord({+ id: 'storage-1',+ metricsTarget: { resourceType: 'pool', resourceId: 'series-via-metrics' },+ refs: { resourceId: 'series-via-refs' },+ }),+ ],+ });+ expect(buildStorageSummaryGroupScope(group, 'node')).toStrictEqual({+ id: 'storage:node:node-a',+ label: 'node-a (1 storage item)',+ seriesIds: ['series-via-metrics'],+ });+ });++ it('falls back to refs.resourceId when metricsTarget.resourceId is absent/blank', () => {+ // resolveStorageRecordMetricResourceId's second operand: refs.resourceId.+ const group = makeGroup({+ key: 'node-b',+ items: [+ makeRecord({+ id: 'storage-1',+ metricsTarget: { resourceType: 'pool', resourceId: ' ' },+ refs: { resourceId: 'series-via-refs' },+ }),+ ],+ });+ expect(buildStorageSummaryGroupScope(group, 'type')).toStrictEqual({+ id: 'storage:type:node-b',+ label: 'node-b (1 storage item)',+ seriesIds: ['series-via-refs'],+ });+ });++ it('deduplicates seriesIds that collapse to the same resource id (new Set de-dup arm)', () => {+ // `new Set(...)` collapses duplicates while preserving first-seen order.+ const group = makeGroup({+ key: 'pve1',+ items: [+ makeRecord({ id: 'r1', metricsTarget: { resourceType: 'pool', resourceId: 'series-a' } }),+ makeRecord({ id: 'r2', refs: { resourceId: 'series-a' } }),+ makeRecord({ id: 'r3', metricsTarget: { resourceType: 'pool', resourceId: 'series-b' } }),+ ],+ });+ expect(buildStorageSummaryGroupScope(group, 'status')!.seriesIds).toStrictEqual([+ 'series-a',+ 'series-b',+ ]);+ });++ it('drops blank resolved ids while keeping non-blank ones (filter(Boolean) arm)', () => {+ // A single group with a mix: one record resolves to '' (metricsTarget, refs AND id all+ // blank/whitespace so every operand of resolveStorageRecordMetricResourceId is falsy),+ // another resolves to 'series-a'. filter(Boolean) must drop only the blank one.+ const group = makeGroup({+ key: 'pve1',+ items: [+ makeRecord({+ id: ' ',+ metricsTarget: { resourceType: 'pool', resourceId: ' ' },+ refs: { resourceId: ' ' },+ }),+ makeRecord({ id: 'real', metricsTarget: { resourceType: 'pool', resourceId: 'series-a' } }),+ ],+ });+ expect(buildStorageSummaryGroupScope(group, 'node')!.seriesIds).toStrictEqual(['series-a']);+ });++ it('uses the plural count label when the group has more than one item', () => {+ // getStorageGroupPoolCountLabel: count === 1 ? 'storage item' : 'storage items'.+ const group = makeGroup({+ key: 'pve1',+ items: [+ makeRecord({ id: 'a', metricsTarget: { resourceType: 'pool', resourceId: 's1' } }),+ makeRecord({ id: 'b', metricsTarget: { resourceType: 'pool', resourceId: 's2' } }),+ makeRecord({ id: 'c', metricsTarget: { resourceType: 'pool', resourceId: 's3' } }),+ ],+ });+ expect(buildStorageSummaryGroupScope(group, 'node')!.label).toBe('pve1 (3 storage items)');+ });++ it('propagates a whitespace-padded group key untrimmed into the label but trimmed into the id', () => {+ // Documents current behaviour: the scope `id` is built from the *trimmed* key+ // (via buildStorageSummaryGroupId), but the label is built from+ // buildStorageGroupRowPresentation, which reads `group.key` verbatim.+ const group = makeGroup({+ key: ' pve1 ',+ items: [makeRecord({ id: 'storage-1' })],+ });+ expect(buildStorageSummaryGroupScope(group, 'node')).toStrictEqual({+ id: 'storage:node:pve1',+ label: ' pve1 (1 storage item)',+ seriesIds: ['storage-1'],+ });+ });+});diff --git a/frontend-modern/src/components/shared/__tests__/pulseDataGridModel.branchcov0712.test.ts b/frontend-modern/src/components/shared/__tests__/pulseDataGridModel.branchcov0712.test.tsnew file mode 100644index 0000000000..e37f614872--- /dev/null+++ b/frontend-modern/src/components/shared/__tests__/pulseDataGridModel.branchcov0712.test.ts@@ -0,0 +1,150 @@+import { describe, expect, it } from 'vitest';+import {+ getPulseDataGridAlignClass,+ getPulseDataGridWidthAttr,+} from '@/components/shared/pulseDataGridModel';++// Branch-coverage tests for the two still-uncovered model helpers in+// pulseDataGridModel.ts. Each `it` targets a specific branch (switch arm,+// regex arm, optional-chain arm, falsy guard) and asserts the concrete string+// or undefined return value — never truthiness alone.++describe('pulseDataGridModel.branchcov2', () => {+ describe('getPulseDataGridAlignClass', () => {+ it.each([+ { align: 'center', expected: 'text-center justify-center' },+ { align: 'right', expected: 'text-right justify-end' },+ { align: 'left', expected: 'text-left justify-start' },+ ] as const)(+ 'returns the dedicated class tuple for the $align switch arm',+ ({ align, expected }) => {+ // Drives each named case label. 'left' falls through into the default+ // body but still lands on its own case label first.+ expect(getPulseDataGridAlignClass(align)).toBe(expected);+ },+ );++ it('falls through to the default arm when called with no argument (align === undefined)', () => {+ // The optional parameter is undefined -> no case matches -> default body.+ expect(getPulseDataGridAlignClass()).toBe('text-left justify-start');+ });++ it('hits the default arm when align is explicitly undefined', () => {+ // Same default arm via an explicit undefined argument.+ expect(getPulseDataGridAlignClass(undefined)).toBe('text-left justify-start');+ });++ it('hits the default arm for a malformed align value cast through unknown', () => {+ // Defensive branch: a runtime-only value outside the union still reaches+ // the default arm and must yield the left-aligned class tuple.+ type AlignArg = Parameters<typeof getPulseDataGridAlignClass>[0];+ const bogus = 'justify' as unknown as AlignArg;+ expect(getPulseDataGridAlignClass(bogus)).toBe('text-left justify-start');+ });+ });++ describe('getPulseDataGridWidthAttr', () => {+ describe('optional chain (width?.trim()) and falsy guard (!trimmed)', () => {+ it('returns undefined when width is undefined (?. short-circuit)', () => {+ // width?.trim() -> undefined; !trimmed truthy -> early return undefined.+ expect(getPulseDataGridWidthAttr(undefined)).toBeUndefined();+ });++ it('returns undefined when width is null cast to string (?. short-circuit on null)', () => {+ // null is nullish, so the ?. optional chain short-circuits to undefined+ // exactly like the undefined case.+ const nullable = null as unknown as string;+ expect(getPulseDataGridWidthAttr(nullable)).toBeUndefined();+ });++ it('returns undefined for an empty string (trim yields "" -> !trimmed truthy)', () => {+ // .trim() is actually invoked; result is "" which is falsy -> early return.+ expect(getPulseDataGridWidthAttr('')).toBeUndefined();+ });++ it('returns undefined for a whitespace-only string (trim yields "" -> !trimmed truthy)', () => {+ // Proves trim() runs before the guard: " " is truthy pre-trim but+ // collapses to "" and is rejected.+ expect(getPulseDataGridWidthAttr(' ')).toBeUndefined();+ });+ });++ describe('px branch (/^\\d+(\\.\\d+)?px$/)', () => {+ it('strips the trailing "px" for an integer pixel value', () => {+ // First regex matches -> returns trimmed.slice(0, -2) == "100".+ expect(getPulseDataGridWidthAttr('100px')).toBe('100');+ });++ it('strips the trailing "px" for a decimal pixel value (\\d+\\.\\d+ optional group)', () => {+ // Exercises the (\\.\\d+)? optional group inside the px regex.+ expect(getPulseDataGridWidthAttr('10.5px')).toBe('10.5');+ });++ it('returns "0" for "0px" (zero is not collapsed by the guard)', () => {+ // "0px" is truthy so the guard is skipped; the px arm returns "0".+ expect(getPulseDataGridWidthAttr('0px')).toBe('0');+ });++ it('trims surrounding whitespace before applying the px regex', () => {+ // width?.trim() -> "100px" -> px arm -> "100". Confirms trim precedes+ // regex evaluation.+ expect(getPulseDataGridWidthAttr(' 100px ')).toBe('100');+ });+ });++ describe('percent branch (/^\\d+(\\.\\d+)?%$)', () => {+ it('returns the trimmed percent string verbatim for an integer percent', () => {+ // Left operand of the || matches -> returns trimmed unmodified.+ expect(getPulseDataGridWidthAttr('50%')).toBe('50%');+ });++ it('returns the trimmed percent string verbatim for a decimal percent (optional group)', () => {+ // Exercises the (\\.\\d+)? optional group inside the % regex.+ expect(getPulseDataGridWidthAttr('10.5%')).toBe('10.5%');+ });++ it('returns "0%" for "0%" (zero percent passes through)', () => {+ expect(getPulseDataGridWidthAttr('0%')).toBe('0%');+ });+ });++ describe('bare-number branch (/^\\d+(\\.\\d+)?$)', () => {+ it('returns the trimmed bare integer verbatim', () => {+ // % operand of the || fails, bare-number operand matches -> returns+ // trimmed unmodified.+ expect(getPulseDataGridWidthAttr('100')).toBe('100');+ });++ it('returns the trimmed bare decimal verbatim (optional group)', () => {+ // Exercises the (\\.\\d+)? optional group inside the bare-number regex.+ expect(getPulseDataGridWidthAttr('10.5')).toBe('10.5');+ });++ it('returns "0" for bare "0" (zero passes through, not collapsed)', () => {+ expect(getPulseDataGridWidthAttr('0')).toBe('0');+ });+ });++ describe('final fallback return undefined (no regex arm matches)', () => {+ it('returns undefined for a CSS keyword like "auto"', () => {+ // All three regexes fail -> final return undefined.+ expect(getPulseDataGridWidthAttr('auto')).toBeUndefined();+ });++ it('returns undefined for a non-px unit like "10em"', () => {+ // "10em" looks numeric but the unit is not px/% -> no match.+ expect(getPulseDataGridWidthAttr('10em')).toBeUndefined();+ });++ it('returns undefined for a near-miss px value "100p" (missing x)', () => {+ // Boundary: only the "px" suffix is rejected, proving the regex is not+ // a loose "ends with p" check.+ expect(getPulseDataGridWidthAttr('100p')).toBeUndefined();+ });++ it('returns undefined for a value with internal letters "5rem"', () => {+ expect(getPulseDataGridWidthAttr('5rem')).toBeUndefined();+ });+ });+ });+});