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.

18.8 KB
Raw Blame
import { Route, Router } from '@solidjs/router';
import { cleanup, render, screen } from '@solidjs/testing-library';
import { createStore, reconcile } from 'solid-js/store';
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
import type { Alert } from '@/types/api';
import type { Resource } from '@/types/resource';
import { KubernetesPageSurface } from '../KubernetesPageSurface';

const mockUseUnifiedResources = vi.fn();
const mockPathname = vi.hoisted(() => vi.fn(() => '/'));
const mockVersionInfo = vi.hoisted(() => vi.fn());
const activeAlertsRef = vi.hoisted(() => ({ current: {} as Record<string, Alert> }));

const makeResource = (resource: Partial<Resource> & Pick<Resource, 'id' | 'type'>): Resource => ({
  name: resource.id,
  displayName: resource.id,
  platformId: 'cluster-1',
  platformType: 'kubernetes',
  sourceType: 'agent',
  sources: ['kubernetes'],
  status: 'online',
  lastSeen: 1_700_000_000_000,
  ...resource,
});

const setResources = (resources: Resource[]) => {
  mockUseUnifiedResources.mockReturnValue({
    resources: () => resources,
    loading: () => false,
    error: () => null,
    refetch: vi.fn(),
  });
};

const renderSurface = () =>
  render(() => (
    <Router>
      <Route path="/" component={KubernetesPageSurface} />
    </Router>
  ));

vi.mock('@/hooks/useUnifiedResources', () => ({
  useUnifiedResources: (...args: unknown[]) => mockUseUnifiedResources(...args),
}));

vi.mock('@/contexts/appRuntime', () => ({
  useWebSocket: () => ({ activeAlerts: activeAlertsRef.current }),
}));

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

vi.mock('@/stores/updates', () => ({
  updateStore: {
    versionInfo: mockVersionInfo,
  },
}));

vi.mock('@solidjs/router', async () => {
  const actual = await vi.importActual<typeof import('@solidjs/router')>('@solidjs/router');
  return {
    ...actual,
    useLocation: () => ({ pathname: mockPathname() }),
  };
});

vi.mock('@/features/platformPage/sharedPlatformPage', () => ({
  PLATFORM_HEALTH_FILTER_OPTIONS: [],
  PlatformErrorState: () => <div data-testid="platform-error-state" />,
  PlatformSectionTabs: (props: {
    active: string;
    tabs: Array<{ id: string; label: string; path: string }>;
  }) => (
    <div
      data-testid="platform-section-tabs"
      data-active={props.active}
      data-tabs={props.tabs.map((tab) => tab.id).join(',')}
    />
  ),
  PlatformTableEmptyState: () => <div data-testid="platform-table-empty-state" />,
  PlatformTableLoadingState: () => <div data-testid="platform-table-loading-state" />,
  PlatformTableToolbar: () => <div data-testid="platform-table-toolbar" />,
}));

vi.mock('../KubernetesAlertsTable', () => ({
  KubernetesAlertsTable: (props: { incidents: unknown[] }) => (
    <div data-testid="alerts-table" data-rows={props.incidents.length} />
  ),
}));

vi.mock('../KubernetesAutoscalingTable', () => ({
  KubernetesAutoscalingTable: (props: { resources: Resource[] }) => (
    <div data-testid="autoscaling-table" data-rows={props.resources.length} />
  ),
}));

vi.mock('../KubernetesClustersTable', () => ({
  KubernetesClustersTable: (props: { clusters: Resource[] }) => (
    <div data-testid="clusters-table" data-rows={props.clusters.length} />
  ),
}));

vi.mock('../KubernetesConfigTable', () => ({
  KubernetesConfigTable: (props: { resources: Resource[] }) => (
    <div data-testid="config-table" data-rows={props.resources.length} />
  ),
}));

vi.mock('../KubernetesControllersTable', () => ({
  KubernetesControllersTable: (props: { resources: Resource[] }) => (
    <div data-testid="controllers-table" data-rows={props.resources.length} />
  ),
}));

vi.mock('../KubernetesDeploymentsTable', () => ({
  KubernetesDeploymentsTable: (props: { resources: Resource[] }) => (
    <div data-testid="deployments-table" data-rows={props.resources.length} />
  ),
}));

vi.mock('../KubernetesEventsTable', () => ({
  KubernetesEventsTable: (props: { resources: Resource[] }) => (
    <div data-testid="events-table" data-rows={props.resources.length} />
  ),
}));

vi.mock('../KubernetesNetworkingTable', () => ({
  KubernetesNetworkingTable: (props: { resources: Resource[] }) => (
    <div data-testid="networking-table" data-rows={props.resources.length} />
  ),
}));

vi.mock('../KubernetesNodesTable', () => ({
  KubernetesNodesTable: (props: {
    resources: Resource[];
    title?: string;
    sortStorageKey?: string;
  }) => (
    <div
      data-testid="nodes-table"
      data-rows={props.resources.length}
      data-ids={props.resources.map((resource) => resource.id).join(',')}
      data-title={props.title}
      data-sort-key={props.sortStorageKey}
    />
  ),
}));

vi.mock('../KubernetesPodsTable', () => ({
  KubernetesPodsTable: (props: { resources: Resource[] }) => (
    <div data-testid="pods-table" data-rows={props.resources.length} />
  ),
}));

vi.mock('../KubernetesPolicyTable', () => ({
  KubernetesPolicyTable: (props: { resources: Resource[] }) => (
    <div data-testid="policy-table" data-rows={props.resources.length} />
  ),
}));

vi.mock('../KubernetesServicesTable', () => ({
  KubernetesServicesTable: (props: { resources: Resource[] }) => (
    <div data-testid="services-table" data-rows={props.resources.length} />
  ),
}));

vi.mock('../KubernetesStorageTable', () => ({
  KubernetesStorageTable: (props: { resources: Resource[] }) => (
    <div data-testid="storage-table" data-rows={props.resources.length} />
  ),
}));

const [activeAlerts, setActiveAlerts] = createStore<Record<string, Alert>>({});
activeAlertsRef.current = activeAlerts;

describe('KubernetesPageSurface contract', () => {
  beforeEach(() => {
    mockPathname.mockReturnValue('/');
    mockVersionInfo.mockReturnValue(null);
  });

  afterEach(() => {
    cleanup();
    setActiveAlerts(reconcile({}));
    vi.clearAllMocks();
  });

  it('leads the overview with health signals and not-ready nodes before inventory', () => {
    setResources([
      makeResource({ id: 'cluster-1', type: 'k8s-cluster' }),
      makeResource({
        id: 'node-down',
        type: 'k8s-node',
        kubernetes: { ready: false } as Resource['kubernetes'],
      }),
      makeResource({
        id: 'node-ok',
        type: 'k8s-node',
        kubernetes: { ready: true } as Resource['kubernetes'],
      }),
      makeResource({
        id: 'pod-1',
        type: 'pod',
        incidents: [{ code: 'pod_crashloop', severity: 'warning', summary: 'CrashLoopBackOff' }],
      }),
    ]);

    renderSurface();

    const signals = screen.getByTestId('alerts-table');
    const attention = screen.getByTestId('nodes-table');
    const clusters = screen.getByTestId('clusters-table');
    expect(attention).toHaveAttribute('data-title', 'Nodes needing attention');
    expect(attention).toHaveAttribute('data-rows', '1');
    // Its own persisted sort, so sorting the Nodes tab cannot reorder this list.
    expect(attention).toHaveAttribute('data-sort-key', 'kubernetesNodesNeedingAttention');
    expect(
      signals.compareDocumentPosition(attention) & Node.DOCUMENT_POSITION_FOLLOWING,
    ).toBeTruthy();
    expect(
      attention.compareDocumentPosition(clusters) & Node.DOCUMENT_POSITION_FOLLOWING,
    ).toBeTruthy();
  });

  it('names a Ready node with an open alert among the nodes needing attention', () => {
    setResources([
      makeResource({ id: 'cluster-1', type: 'k8s-cluster' }),
      makeResource({
        id: 'node-memory',
        type: 'agent',
        sources: ['agent', 'kubernetes'],
        agent: { agentId: 'host-k8s-02' },
        kubernetes: { ready: true } as Resource['kubernetes'],
      } as Partial<Resource> & Pick<Resource, 'id' | 'type'>),
      makeResource({
        id: 'node-ok',
        type: 'k8s-node',
        kubernetes: { ready: true } as Resource['kubernetes'],
      }),
    ]);
    renderSurface();
    // Every node is Ready, so nothing needs attention until an alert opens.
    expect(screen.queryByTestId('nodes-table')).toBeNull();

    // The node's agent raises it: keyed on the agent, labelled with the hostname.
    setActiveAlerts({
      memory: {
        id: 'memory',
        type: 'memory',
        level: 'critical',
        resourceId: 'agent:host-k8s-02',
        resourceName: 'Prod Euw1 K8s 02',
        node: 'prod-euw1-k8s-02',
        instance: '',
        message: 'Agent memory at 100.0%',
        value: 100,
        threshold: 90,
        startTime: '2026-10-06T10:00:00Z',
        acknowledged: false,
      },
    });

    const attention = screen.getByTestId('nodes-table');
    expect(attention).toHaveAttribute('data-title', 'Nodes needing attention');
    expect(attention).toHaveAttribute('data-ids', 'node-memory');

    // Acknowledged: someone owns it, and the row is no longer tinted either.
    setActiveAlerts('memory', 'acknowledged', true);
    expect(screen.queryByTestId('nodes-table')).toBeNull();
    setActiveAlerts('memory', 'acknowledged', false);
    expect(screen.getByTestId('nodes-table')).toHaveAttribute('data-ids', 'node-memory');
    // Resolved: the alert leaves the store and the node leaves the list.
    setActiveAlerts(reconcile({}));
    expect(screen.queryByTestId('nodes-table')).toBeNull();
  });

  it('shows no attention table when every node is Ready', () => {
    setResources([
      makeResource({ id: 'cluster-1', type: 'k8s-cluster' }),
      makeResource({
        id: 'node-ok',
        type: 'k8s-node',
        kubernetes: { ready: true } as Resource['kubernetes'],
      }),
    ]);

    renderSurface();

    expect(screen.queryByTestId('nodes-table')).toBeNull();
    expect(screen.queryByTestId('alerts-table')).toBeNull();
  });

  it('declares inventory-backed workflow tabs while querying API-native Kubernetes resources', () => {
    setResources([
      makeResource({ id: 'cluster-1', type: 'k8s-cluster' }),
      makeResource({ id: 'pod-1', type: 'pod' }),
      makeResource({ id: 'deployment-1', type: 'k8s-deployment' }),
      makeResource({ id: 'statefulset-1', type: 'k8s-statefulset' }),
    ]);

    renderSurface();

    expect(mockUseUnifiedResources).toHaveBeenCalledWith(
      expect.objectContaining({
        query: expect.stringContaining('pod'),
      }),
    );
    expect(mockUseUnifiedResources).toHaveBeenCalledWith(
      expect.objectContaining({
        query: expect.stringContaining('k8s-deployment'),
      }),
    );
    expect(mockUseUnifiedResources).toHaveBeenCalledWith(
      expect.objectContaining({
        query: expect.stringContaining('k8s-replicaset'),
      }),
    );
    expect(mockUseUnifiedResources).toHaveBeenCalledWith(
      expect.objectContaining({
        query: expect.stringContaining('k8s-statefulset'),
      }),
    );
    expect(mockUseUnifiedResources).toHaveBeenCalledWith(
      expect.objectContaining({
        query: expect.stringContaining('&source=kubernetes'),
      }),
    );
    expect(screen.getByTestId('platform-section-tabs')).toHaveAttribute(
      'data-tabs',
      'overview,workloads',
    );
    expect(screen.getByTestId('platform-section-tabs')).toHaveAttribute('data-active', 'overview');
    expect(screen.getByTestId('clusters-table')).toHaveAttribute('data-rows', '1');
    expect(screen.getByTestId('pods-table')).toHaveAttribute('data-rows', '1');
    expect(screen.getByTestId('deployments-table')).toHaveAttribute('data-rows', '1');
    expect(screen.getByTestId('controllers-table')).toHaveAttribute('data-rows', '1');
  });

  it('falls back to Overview when a requested Kubernetes workflow has no inventory', () => {
    mockPathname.mockReturnValue('/kubernetes/services');
    setResources([makeResource({ id: 'cluster-1', type: 'k8s-cluster' })]);

    renderSurface();

    expect(screen.getByTestId('platform-section-tabs')).toHaveAttribute('data-tabs', 'overview');
    expect(screen.getByTestId('platform-section-tabs')).toHaveAttribute('data-active', 'overview');
    expect(screen.getByTestId('clusters-table')).toHaveAttribute('data-rows', '1');
    expect(screen.queryByTestId('services-table')).toBeNull();
  });

  it('hydrates only the active Kubernetes workflow resource family', () => {
    mockPathname.mockReturnValue('/kubernetes/events');
    setResources([
      makeResource({ id: 'cluster-1', type: 'k8s-cluster' }),
      makeResource({ id: 'event-1', type: 'k8s-event' }),
    ]);

    renderSurface();

    const activeCall = mockUseUnifiedResources.mock.calls.find(([options]) =>
      (options as { enabled: () => boolean }).enabled(),
    );
    expect(activeCall?.[0]).toEqual(
      expect.objectContaining({
        cacheKey: 'kubernetes-events',
        query: 'type=agent,k8s-cluster,k8s-event&source=kubernetes',
      }),
    );
  });

  it('surfaces stale agent-backed Kubernetes nodes', () => {
    mockVersionInfo.mockReturnValue({
      version: 'v6.0.0-rc.6',
      agentUpdateTargetVersion: 'v6.0.0-rc.6',
    });
    setResources([
      makeResource({
        id: 'agent:k8s-node-1',
        name: 'k8s-node-1',
        type: 'agent',
        sources: ['agent', 'kubernetes'],
        agent: { agentId: 'agent-k8s-node-1', agentVersion: 'v5.1.34' },
      }),
    ]);

    renderSurface();

    const notice = screen.getByTestId('platform-outdated-agent-notice');
    expect(notice).toHaveTextContent('k8s-node-1 runs an older Pulse agent (v5.1.34), so');
    expect(notice).toHaveTextContent('Kubernetes nodes, workloads, services, storage');
    expect(screen.getByRole('link', { name: 'Open agent upgrade commands' })).toHaveAttribute(
      'href',
      '/settings/infrastructure/agent-doctor?agents=agent%3Aagent-k8s-node-1',
    );
  });

  it('surfaces stale cluster-backed Kubernetes node rows without agent metadata', () => {
    mockVersionInfo.mockReturnValue({
      version: 'v6.0.0-rc.6',
      agentUpdateTargetVersion: 'v6.0.0-rc.6',
    });
    setResources([
      makeResource({
        id: 'cluster-1',
        name: 'prod-cluster',
        type: 'k8s-cluster',
        kubernetes: {
          agentId: 'agent-k8s-cluster',
          agentVersion: 'v5.1.34',
          clusterId: 'cluster-1',
          clusterName: 'prod-cluster',
        },
      }),
      makeResource({
        id: 'k8s-node:worker-1',
        name: 'worker-1',
        type: 'k8s-node',
        agent: undefined,
        kubernetes: {
          agentId: 'agent-k8s-cluster',
          agentVersion: 'v5.1.34',
          clusterId: 'cluster-1',
          clusterName: 'prod-cluster',
          nodeName: 'worker-1',
        },
      }),
    ]);

    renderSurface();

    const notice = screen.getByTestId('platform-outdated-agent-notice');
    expect(notice).toHaveTextContent('worker-1 runs an older Pulse agent (v5.1.34), so');
    expect(notice).toHaveTextContent('for this node');
    expect(notice).toHaveTextContent('Kubernetes nodes, workloads, services, storage');
    expect(screen.getByRole('link', { name: 'Open agent upgrade commands' })).toHaveAttribute(
      'href',
      '/settings/infrastructure/agent-doctor?agents=agent%3Aagent-k8s-cluster',
    );
  });

  it('groups workload API tables under the Workloads tab', () => {
    mockPathname.mockReturnValue('/kubernetes/workloads');
    setResources([
      makeResource({ id: 'checkout-api', type: 'pod' }),
      makeResource({ id: 'checkout-deployment', type: 'k8s-deployment' }),
      makeResource({ id: 'checkout-replicaset', type: 'k8s-replicaset' }),
      makeResource({ id: 'checkout-stateful', type: 'k8s-statefulset' }),
      makeResource({ id: 'checkout-hpa', type: 'k8s-horizontal-pod-autoscaler' }),
    ]);

    renderSurface();

    expect(screen.getByTestId('platform-section-tabs')).toHaveAttribute('data-active', 'workloads');
    expect(screen.getByTestId('pods-table')).toHaveAttribute('data-rows', '1');
    expect(screen.getByTestId('deployments-table')).toHaveAttribute('data-rows', '1');
    expect(screen.getByTestId('controllers-table')).toHaveAttribute('data-rows', '2');
    expect(screen.getByTestId('autoscaling-table')).toHaveAttribute('data-rows', '1');
  });

  it('routes ReplicaSets to the rendered workload controllers table', () => {
    mockPathname.mockReturnValue('/kubernetes/workloads');
    setResources([makeResource({ id: 'checkout-replicaset', type: 'k8s-replicaset' })]);

    renderSurface();

    expect(screen.getByTestId('controllers-table')).toHaveAttribute('data-rows', '1');
    expect(screen.queryByTestId('pods-table')).toBeNull();
    expect(screen.queryByTestId('deployments-table')).toBeNull();
  });

  it('groups Services, ingress, and endpoints under the Services tab without duplicating services in networking', () => {
    mockPathname.mockReturnValue('/kubernetes/services');
    setResources([
      makeResource({ id: 'checkout-service', type: 'k8s-service' }),
      makeResource({ id: 'checkout-ingress', type: 'k8s-ingress' }),
      makeResource({ id: 'checkout-endpoints', type: 'k8s-endpoint-slice' }),
    ]);

    renderSurface();

    expect(screen.getByTestId('platform-section-tabs')).toHaveAttribute('data-active', 'services');
    expect(screen.getByTestId('services-table')).toHaveAttribute('data-rows', '1');
    expect(screen.getByTestId('networking-table')).toHaveAttribute('data-rows', '2');
  });

  it('groups config and policy API tables under the Configuration tab', () => {
    mockPathname.mockReturnValue('/kubernetes/configuration');
    setResources([
      makeResource({ id: 'checkout-config', type: 'k8s-configmap' }),
      makeResource({ id: 'checkout-policy', type: 'k8s-network-policy' }),
    ]);

    renderSurface();

    expect(screen.getByTestId('platform-section-tabs')).toHaveAttribute(
      'data-active',
      'configuration',
    );
    expect(screen.getByTestId('config-table')).toHaveAttribute('data-rows', '1');
    expect(screen.getByTestId('policy-table')).toHaveAttribute('data-rows', '1');
  });

  it.each([
    ['/kubernetes/nodes', 'k8s-node', 'nodes', 'nodes-table'],
    ['/kubernetes/pods', 'pod', 'workloads', 'pods-table'],
    ['/kubernetes/deployments', 'k8s-deployment', 'workloads', 'deployments-table'],
    ['/kubernetes/controllers', 'k8s-statefulset', 'workloads', 'controllers-table'],
    ['/kubernetes/autoscaling', 'k8s-horizontal-pod-autoscaler', 'workloads', 'autoscaling-table'],
    ['/kubernetes/services', 'k8s-service', 'services', 'services-table'],
    ['/kubernetes/networking', 'k8s-ingress', 'services', 'networking-table'],
    ['/kubernetes/storage', 'k8s-storage-class', 'storage', 'storage-table'],
    ['/kubernetes/config', 'k8s-configmap', 'configuration', 'config-table'],
    ['/kubernetes/policy', 'k8s-network-policy', 'configuration', 'policy-table'],
    ['/kubernetes/events', 'k8s-event', 'events', 'events-table'],
  ] as const)(
    'maps %s to the %s workflow and renders its API-native table',
    (path, type, expectedActive, testId) => {
      mockPathname.mockReturnValue(path);
      setResources([makeResource({ id: `${type}-1`, type })]);

      renderSurface();

      expect(screen.getByTestId('platform-section-tabs')).toHaveAttribute(
        'data-active',
        expectedActive,
      );
      expect(screen.getByTestId(testId)).toHaveAttribute('data-rows', '1');
    },
  );
});