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.

9.8 KB
Raw Blame
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
import { cleanup, render } from '@solidjs/testing-library';

import type { ThresholdsTableProps } from '@/features/alerts/thresholds/types';
import { useThresholdsTableState } from '../useThresholdsTableState';

let mockPathname = '/alerts/thresholds/systems';
let mockHash = '';
let mockSearch = '';
const setCollapsedSpy = vi.fn();
const navigateSpy = vi.fn();

vi.mock('@solidjs/router', () => ({
  useLocation: () => ({ pathname: mockPathname, hash: mockHash, search: mockSearch }),
  useNavigate: () => navigateSpy,
}));

vi.mock('@/stores/alertsActivation', () => ({
  useAlertsActivation: () => ({ detectionEnabled: () => true }),
}));

vi.mock('@/components/Alerts/Thresholds/hooks/useCollapsedSections', () => ({
  useCollapsedSections: () => ({
    collapseAll: vi.fn(),
    expandAll: vi.fn(),
    isCollapsed: () => false,
    setCollapsed: setCollapsedSpy,
    toggleSection: vi.fn(),
  }),
}));

vi.mock('../useThresholdsData', () => ({
  useThresholdsData: () => ({
    agentDisksGroupedByAgent: () => ({}),
    agentGroupHeaderMeta: () => ({}),
    agentDisksWithOverrides: () => [],
    agentsWithOverrides: () => [],
    dockerContainersFlat: () => [],
    dockerContainersGroupedByHost: () => ({}),
    dockerHostGroupMeta: () => ({}),
    dockerHostsWithOverrides: () => [],
    guestsFlat: () => [],
    guestsGroupedByNode: () => ({}),
    guestDisksGroupedByGuest: () => ({
      flatcar: [
        {
          id: 'cluster-a:node-1:100-disk-boot-dev-vda1',
          name: '/boot',
          type: 'guestDisk',
          hasOverride: true,
        },
      ],
    }),
    guestDisksWithOverrides: () => [
      {
        id: 'cluster-a:node-1:100-disk-boot-dev-vda1',
        name: '/boot',
        type: 'guestDisk',
        hasOverride: true,
      },
    ],
    guestGroupHeaderMeta: () => ({}),
    nodesWithOverrides: () => [],
    pbsServersWithOverrides: () => [],
    pmgGlobalDefaults: () => ({}),
    pmgServersWithOverrides: () => [],
    storageGroupedByNode: () => ({}),
    storageWithOverrides: () => [],
    totalDockerContainers: () => 0,
  }),
}));

vi.mock('../useThresholdsRecoveryDefaultsState', () => ({
  useThresholdsRecoveryDefaultsState: () => ({
    backupDefaultsRecord: () => ({}),
    backupFactoryConfig: () => ({ enabled: false }),
    backupFactoryDefaultsRecord: () => ({}),
    backupOverridesCount: () => 0,
    sanitizeBackupConfig: <T,>(value: T) => value,
    sanitizeSnapshotConfig: <T,>(value: T) => value,
    snapshotDefaultsRecord: () => ({}),
    snapshotFactoryConfig: () => ({ enabled: false }),
    snapshotFactoryDefaultsRecord: () => ({}),
    snapshotOverridesCount: () => 0,
  }),
}));

const buildProps = (): ThresholdsTableProps =>
  ({
    agentDefaults: {},
    agents: [],
    allGuests: () => [],
    allResources: [],
    backupDefaults: () => ({ criticalDays: 7, enabled: false, warningDays: 3 }),
    containerRuntimes: [],
    disableAllAgents: () => false,
    disableAllAgentsOffline: () => false,
    disableAllDockerContainers: () => false,
    disableAllDockerHosts: () => false,
    disableAllDockerHostsOffline: () => false,
    disableAllDockerServices: () => false,
    disableAllGuests: () => false,
    disableAllNodes: () => false,
    disableAllPBS: () => false,
    disableAllPMG: () => false,
    disableAllPMGOffline: () => false,
    disableAllStorage: () => false,
    dockerDefaults: {
      cpu: 80,
      disk: 90,
      memory: 85,
      memoryCriticalPct: 95,
      memoryWarnPct: 80,
      restartCount: 3,
      restartWindow: 10,
      serviceCriticalGapPercent: 15,
      serviceWarnGapPercent: 5,
    },
    dockerDisableConnectivity: () => false,
    dockerHosts: [],
    dockerIgnoredPrefixes: () => [],
    dockerPoweredOffSeverity: () => 'warning',
    factoryAgentDefaults: {},
    factoryDockerDefaults: {},
    factoryGuestDefaults: {},
    factoryNodeDefaults: {},
    factoryPBSDefaults: {},
    factoryStorageDefault: 85,
    guestDefaults: {},
    guestDisableConnectivity: () => false,
    guestPoweredOffSeverity: () => 'warning',
    guestTagBlacklist: () => [],
    guestTagWhitelist: () => [],
    ignoredGuestPrefixes: () => [],
    metricTimeThresholds: () => ({}),
    nodeDefaults: {},
    nodes: [],
    overrides: () => [],
    pmgInstances: [],
    pmgThresholds: () => ({}) as any,
    pbsDefaults: {},
    pbsInstances: [],
    rawOverridesConfig: () => ({}),
    setAgentDefaults: vi.fn(),
    setDisableAllAgents: vi.fn(),
    setDisableAllAgentsOffline: vi.fn(),
    setDisableAllDockerContainers: vi.fn(),
    setDisableAllDockerHosts: vi.fn(),
    setDisableAllDockerHostsOffline: vi.fn(),
    setDisableAllDockerServices: vi.fn(),
    setDisableAllGuests: vi.fn(),
    setDisableAllNodes: vi.fn(),
    setDisableAllPBS: vi.fn(),
    setDisableAllPMG: vi.fn(),
    setDisableAllPMGOffline: vi.fn(),
    setDisableAllStorage: vi.fn(),
    setDockerDefaults: vi.fn(),
    setDockerDisableConnectivity: vi.fn(),
    setDockerIgnoredPrefixes: vi.fn(),
    setDockerPoweredOffSeverity: vi.fn(),
    setGuestDefaults: vi.fn(),
    setGuestDisableConnectivity: vi.fn(),
    setGuestPoweredOffSeverity: vi.fn(),
    setGuestTagBlacklist: vi.fn(),
    setGuestTagWhitelist: vi.fn(),
    setHasUnsavedChanges: vi.fn(),
    setIgnoredGuestPrefixes: vi.fn(),
    setMetricTimeThresholds: vi.fn(),
    setNodeDefaults: vi.fn(),
    setOverrides: vi.fn(),
    setPMGThresholds: vi.fn(),
    setRawOverridesConfig: vi.fn(),
    setSnapshotDefaults: vi.fn(),
    setStorageDefault: vi.fn(),
    snapshotDefaults: () => ({
      criticalDays: 7,
      criticalSizeGiB: 16,
      enabled: false,
      warningDays: 3,
      warningSizeGiB: 8,
    }),
    storage: [],
    storageDefault: () => 85,
    timeThresholds: () => ({ agent: 0, guest: 0, node: 0, pbs: 0, storage: 0 }),
  }) as unknown as ThresholdsTableProps;

beforeEach(() => {
  mockPathname = '/alerts/thresholds/systems';
  mockHash = '';
  mockSearch = '';
  setCollapsedSpy.mockReset();
  navigateSpy.mockReset();
  localStorage.clear();
});

afterEach(() => {
  cleanup();
});

describe('useThresholdsTableState', () => {
  it('owns thresholds route state, help-banner persistence, and tab navigation', () => {
    let captured: ReturnType<typeof useThresholdsTableState> | undefined;

    const Harness = () => {
      captured = useThresholdsTableState(buildProps());
      return null;
    };

    render(() => <Harness />);

    expect(captured).toBeDefined();
    expect(captured!.activeTab()).toBe('systems');
    expect(captured!.hasDockerSpecificControls()).toBe(false);
    expect(captured!.guestDisksWithOverrides()).toHaveLength(1);
    expect(captured!.guestDisksGroupedByGuest().flatcar?.[0]?.name).toBe('/boot');

    captured!.dismissHelpBanner();
    expect(captured!.helpBannerDismissed()).toBe(true);
    expect(localStorage.getItem('pulse-thresholds-help-dismissed')).toBe('true');

    captured!.handleTabClick('docker');
    expect(navigateSpy).toHaveBeenCalledWith('/alerts/thresholds/docker');

    captured!.handleTabClick('vmware');
    expect(navigateSpy).toHaveBeenCalledWith('/alerts/thresholds/vmware');
  });

  it('includes guest filesystems in the Proxmox threshold summary', () => {
    mockPathname = '/alerts/thresholds/proxmox';
    let captured: ReturnType<typeof useThresholdsTableState> | undefined;

    const Harness = () => {
      captured = useThresholdsTableState(buildProps());
      return null;
    };

    render(() => <Harness />);

    expect(captured!.summaryItems()).toContainEqual(
      expect.objectContaining({
        key: 'guestDisks',
        overrides: 1,
        tab: 'proxmox',
        total: 1,
      }),
    );
  });
  // The backup shield's dialog links here, so a user can change when a backup
  // counts as old (#2858): the Recovery section opens and scrolls into view.
  it('opens and scrolls to the Recovery section from a #backups link', () => {
    mockPathname = '/alerts/thresholds/proxmox';
    mockHash = '#backups';
    let captured: ReturnType<typeof useThresholdsTableState> | undefined;

    const Harness = () => {
      captured = useThresholdsTableState(buildProps());
      return null;
    };

    render(() => <Harness />);
    expect(setCollapsedSpy).toHaveBeenCalledWith('backups', false);

    const section = { scrollIntoView: vi.fn() } as unknown as HTMLDivElement;
    captured!.registerSection('backups')(section);
    expect(section.scrollIntoView).toHaveBeenCalledWith({ block: 'start' });
  });
  // Patrol links a bare alert's decision here to change when that resource's
  // alert fires, so the search must arrive from the link and survive tabs.
  it('keeps the resource search in the route across edits, tabs and redirects', () => {
    mockPathname = '/alerts/thresholds/proxmox';
    mockSearch = '?q=nginx';
    mockHash = '#backups';
    let captured: ReturnType<typeof useThresholdsTableState> | undefined;
    const Harness = () => {
      captured = useThresholdsTableState(buildProps());
      return null;
    };
    render(() => <Harness />);

    expect(captured!.searchTerm()).toBe('nginx');

    captured!.setSearchTerm('web');
    expect(navigateSpy).toHaveBeenLastCalledWith('/alerts/thresholds/proxmox?q=web#backups', {
      replace: true,
    });
    captured!.setSearchTerm('');
    expect(navigateSpy).toHaveBeenLastCalledWith('/alerts/thresholds/proxmox#backups', {
      replace: true,
    });

    captured!.handleTabClick('docker');
    expect(navigateSpy).toHaveBeenLastCalledWith('/alerts/thresholds/docker?q=nginx');
  });

  it('keeps the search when a legacy thresholds address redirects', () => {
    mockPathname = '/alerts/thresholds/containers';
    mockSearch = '?q=nginx';
    const Harness = () => {
      useThresholdsTableState(buildProps());
      return null;
    };
    render(() => <Harness />);

    expect(navigateSpy).toHaveBeenCalledWith('/alerts/thresholds/docker?q=nginx', {
      replace: true,
    });
  });
});