Skip to content

armgit / Pulse

Public Imported from GitHub
0

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.

6.9 KB
Raw Blame
import { describe, expect, it, vi } from 'vitest';
import { fireEvent, render, screen, waitFor } from '@solidjs/testing-library';

import type { ResourceCapability } from '@/types/resource';

const apiClientMock = vi.hoisted(() => ({
  apiFetchJSON: vi.fn(),
}));

vi.mock('@/utils/apiClient', async (importOriginal) => {
  const actual = await importOriginal<typeof import('@/utils/apiClient')>();
  return {
    ...actual,
    apiFetchJSON: apiClientMock.apiFetchJSON,
  };
});

import { ResourceOperatorStateSection } from '@/components/Infrastructure/ResourceOperatorStateSection';

// Regression for issue #1621: rows saved with only "intentionally offline"
// left the auto_remediation_policy_json column NULL, and the pre-fix read
// path skipped normalization for NULL columns, so the wire carried
// "capabilityNames": null. The section's dirty-state memo spread that value
// during render, throwing "null is not iterable" straight into the route
// error boundary. These tests feed the section the real pre-fix wire
// payload through the canonical API client to pin the null tolerance.
const OPERATOR_STATE_WITH_NULL_CAPABILITIES = JSON.parse(
  `{
    "canonicalId": "docker:host-1/ct-nginx",
    "intentionallyOffline": true,
    "neverAutoRemediate": false,
    "autoRemediationPolicy": {"enabled": false, "capabilityNames": null},
    "setAt": "2026-07-20T10:00:00Z",
    "setBy": "admin"
  }`,
) as unknown;

const RESTART_CAPABILITY: ResourceCapability[] = [
  {
    name: 'restart',
    type: 'docker',
    description: 'Restart the container',
    autoAuthorization: 'low_risk',
  },
];

describe('ResourceOperatorStateSection render with capabilityNames: null', () => {
  it('renders the persisted record without crashing and reports a clean (not dirty) state', async () => {
    apiClientMock.apiFetchJSON.mockResolvedValue(OPERATOR_STATE_WITH_NULL_CAPABILITIES);

    render(() => (
      <ResourceOperatorStateSection
        resourceId="docker:host-1/ct-nginx"
        capabilities={RESTART_CAPABILITY}
      />
    ));

    // The section itself must be up (pre-fix, the throw escaped render
    // and nothing below the header survived).
    expect(screen.getByText('Operator overrides')).toBeTruthy();
    expect(screen.getByText('Monitoring')).toBeTruthy();
    expect(screen.getByText('Never auto-remediate')).toBeTruthy();

    // "Clear all overrides" only renders for persisted() && !isDirty() —
    // reaching it proves the dirty-state memo evaluated the null
    // capabilityNames without throwing and treated it as [].
    await waitFor(() => {
      expect(screen.getByText('Clear all overrides')).toBeTruthy();
    });
    expect(screen.getByText(/Set by admin/)).toBeTruthy();
    expect(screen.queryByText('Save overrides')).toBeNull();
  });

  it('hydrates a null capability allowlist as an empty selection in the automatic-actions block', async () => {
    apiClientMock.apiFetchJSON.mockResolvedValue(OPERATOR_STATE_WITH_NULL_CAPABILITIES);

    render(() => (
      <ResourceOperatorStateSection
        resourceId="docker:host-1/ct-nginx-2"
        capabilities={RESTART_CAPABILITY}
      />
    ));

    await waitFor(() => {
      expect(screen.getByText('Clear all overrides')).toBeTruthy();
    });

    // The automatic-actions block renders (the resource has an eligible
    // capability) with its toggle off and no phantom selection derived
    // from the null allowlist.
    expect(screen.getByLabelText('Automatic actions')).toBeTruthy();
    expect(screen.queryByText('Allowed actions')).toBeNull();
  });
});

describe('maintenance schedule timestamps', () => {
  it.each(['active', 'scheduled'] as const)(
    'shows absolute future times for a %s window',
    async (kind) => {
      const start = new Date(Date.now() + (kind === 'active' ? -60_000 : 3_600_000)).toISOString();
      const end = new Date(Date.now() + 7_200_000).toISOString();
      apiClientMock.apiFetchJSON.mockResolvedValue({
        canonicalId: `maintenance-${kind}`,
        maintenanceStartAt: start,
        maintenanceEndAt: end,
      });
      render(() => <ResourceOperatorStateSection resourceId={`maintenance-${kind}`} />);
      const badge = await screen.findByText(
        kind === 'active' ? 'Maintenance window active.' : 'Maintenance window scheduled.',
      );
      expect(badge.parentElement).toHaveTextContent(new Date(end).toLocaleString());
      if (kind === 'scheduled')
        expect(badge.parentElement).toHaveTextContent(new Date(start).toLocaleString());
      expect(badge.parentElement).not.toHaveTextContent('just now');
      expect(badge.parentElement).toHaveTextContent(/attention.*paused/i);
    },
  );
});

describe('operator override validation', () => {
  it('keeps Save window disabled until a one-time window ends after it starts', async () => {
    apiClientMock.apiFetchJSON.mockResolvedValue({ canonicalId: 'schedule-validation' });
    render(() => <ResourceOperatorStateSection resourceId="schedule-validation" />);

    fireEvent.click(await screen.findByRole('button', { name: 'Schedule window' }));
    const saveWindow = screen.getByRole('button', { name: 'Save window' });
    const start = screen.getByLabelText('Start') as HTMLInputElement;
    const end = screen.getByLabelText('End') as HTMLInputElement;
    expect(saveWindow).toBeEnabled();

    fireEvent.input(end, { target: { value: '2000-01-01T00:00' } });
    expect(screen.getByText('End must be after start.')).toBeInTheDocument();
    expect(saveWindow).toBeDisabled();

    const hoursBetween = () =>
      (new Date(end.value).getTime() - new Date(start.value).getTime()) / 3_600_000;
    fireEvent.click(screen.getByRole('button', { name: '4h' }));
    expect(screen.queryByText('End must be after start.')).not.toBeInTheDocument();
    expect(saveWindow).toBeEnabled();
    expect(hoursBetween()).toBe(4);

    fireEvent.click(screen.getByRole('button', { name: '1h' }));
    expect(hoursBetween()).toBe(1);
    // Daylight saving can make a calendar day 23 or 25 hours.
    fireEvent.click(screen.getByRole('button', { name: '24h' }));
    expect(hoursBetween()).toBeGreaterThanOrEqual(23);
    expect(hoursBetween()).toBeLessThanOrEqual(25);
  });

  it('keeps Save overrides disabled while automatic actions are limited to no action', async () => {
    apiClientMock.apiFetchJSON.mockResolvedValue({ canonicalId: 'auto-validation' });
    render(() => (
      <ResourceOperatorStateSection
        resourceId="auto-validation"
        capabilities={RESTART_CAPABILITY}
      />
    ));

    fireEvent.click(
      await screen.findByRole('button', { name: 'Limit automatic actions for this resource' }),
    );
    expect(screen.getByText('Select at least one eligible capability.')).toBeInTheDocument();
    const save = screen.getByRole('button', { name: 'Save overrides' });
    expect(save).toBeDisabled();

    fireEvent.click(screen.getByRole('checkbox', { name: /^Restart/ }));
    expect(screen.queryByText('Select at least one eligible capability.')).not.toBeInTheDocument();
    expect(save).toBeEnabled();
  });
});