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.

20.0 KB
Raw Blame
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
import { cleanup, fireEvent, render, screen, waitFor } from '@solidjs/testing-library';
import { createSignal } from 'solid-js';
import type { Resource } from '@/types/resource';
import { ResourcePicker, type SelectedResource } from '../ResourcePicker';

let mockResources: Resource[] = [];
let mockLoading = false;
let mockError: unknown;
const [resourceVersion, setResourceVersion] = createSignal(0);
const updateResourceRead = () => setResourceVersion((version) => version + 1);
const refetchMock = vi.fn<() => Promise<Resource[]>>();
const showWarningMock = vi.fn();

vi.mock('@/hooks/useResources', () => ({
  useResources: () => ({
    resources: () => {
      resourceVersion();
      return mockResources;
    },
    loading: () => {
      resourceVersion();
      return mockLoading;
    },
    error: () => {
      resourceVersion();
      return mockError;
    },
    refetch: () => refetchMock(),
  }),
}));

vi.mock('@/utils/toast', () => ({
  showWarning: (...args: unknown[]) => showWarningMock(...args),
}));

const makeResource = (overrides: Partial<Resource> = {}): Resource => ({
  id: 'vm-1',
  type: 'vm',
  name: 'Alpha VM',
  displayName: 'Alpha VM',
  platformId: 'pve-1',
  platformType: 'proxmox-pve',
  sourceType: 'api',
  status: 'running',
  lastSeen: Date.now(),
  tags: [],
  ...overrides,
});

const createSelectedResources = (count: number): SelectedResource[] =>
  Array.from({ length: count }, (_, index) => ({
    id: `preselected-${index}`,
    type: 'vm',
    name: `Preselected ${index}`,
  }));

const renderPicker = (initialSelection: SelectedResource[] = []) => {
  return renderPickerWithOptions(initialSelection, {});
};

const renderPickerWithOptions = (
  initialSelection: SelectedResource[] = [],
  options: { maxSelection?: number | null; resourceTypes?: Resource['type'][] } = {},
) => {
  const onSelectionChange = vi.fn();
  render(() => {
    const [selected, setSelected] = createSignal<SelectedResource[]>(initialSelection);
    const handleSelectionChange = (items: SelectedResource[]) => {
      setSelected(items);
      onSelectionChange(items);
    };
    return (
      <ResourcePicker
        maxSelection={options.maxSelection}
        resourceTypes={options.resourceTypes}
        selected={selected}
        onSelectionChange={handleSelectionChange}
      />
    );
  });
  return { onSelectionChange };
};

beforeEach(() => {
  showWarningMock.mockReset();
  mockResources = [];
  mockLoading = false;
  mockError = undefined;
  refetchMock.mockReset();
});

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

describe('ResourcePicker', () => {
  it('reports a denied inventory as unavailable, not an empty estate or provider error', () => {
    mockError = new Error('403: private endpoint https://internal.invalid/token');
    const { onSelectionChange } = renderPicker(createSelectedResources(1));

    expect(screen.getByRole('alert')).toHaveTextContent('Resources could not be loaded.');
    expect(screen.getByRole('alert')).toHaveTextContent('Existing selections are unchanged.');
    expect(screen.queryByText('No resources available')).not.toBeInTheDocument();
    expect(screen.queryByText(/private endpoint/)).not.toBeInTheDocument();
    expect(screen.getByRole('button', { name: /Select all visible/ })).toBeDisabled();
    expect(screen.getByText('1 selected')).toBeInTheDocument();
    expect(onSelectionChange).not.toHaveBeenCalled();
    expect(refetchMock).not.toHaveBeenCalled();
  });

  it('withdraws retained rows after failure without clearing a saved report scope', async () => {
    mockResources = [makeResource()];
    const { onSelectionChange } = renderPicker(createSelectedResources(1));
    const oldRow = screen.getByRole('button', { name: /Alpha VM/ });

    mockError = new Error('Unavailable');
    updateResourceRead();

    expect(screen.queryByRole('button', { name: /Alpha VM/ })).not.toBeInTheDocument();
    expect(screen.getByRole('alert')).toBeInTheDocument();
    await fireEvent.click(oldRow);
    await fireEvent.click(screen.getByRole('button', { name: /Select all visible/ }));
    expect(onSelectionChange).not.toHaveBeenCalled();
    expect(screen.getByText('Preselected 0')).toBeInTheDocument();
    expect(screen.getByText('1 selected')).toBeInTheDocument();
  });

  it('keeps retained rows unselectable while a canonical read is pending', async () => {
    mockResources = [makeResource()];
    mockLoading = true;
    const { onSelectionChange } = renderPicker();

    expect(screen.getByRole('status')).toHaveTextContent('Loading resources…');
    expect(screen.queryByText('Alpha VM')).not.toBeInTheDocument();
    expect(screen.queryByText('No resources available')).not.toBeInTheDocument();
    await fireEvent.click(screen.getByRole('button', { name: /Select all visible/ }));
    expect(onSelectionChange).not.toHaveBeenCalled();
  });

  it('admits only recovered rows after one explicit, non-duplicating retry', async () => {
    mockResources = [makeResource()];
    mockError = new Error('Unavailable');
    let finishRead!: () => void;
    refetchMock.mockImplementation(async () => {
      await new Promise<void>((resolve) => (finishRead = resolve));
      mockResources = [
        makeResource({ id: 'vm-new', name: 'Recovered VM', displayName: 'Recovered VM' }),
      ];
      mockError = undefined;
      updateResourceRead();
      return mockResources;
    });
    const { onSelectionChange } = renderPicker(createSelectedResources(1));

    const retry = screen.getByRole('button', { name: 'Retry loading resources' });
    await fireEvent.click(retry);
    await fireEvent.click(retry);
    expect(refetchMock).toHaveBeenCalledTimes(1);
    expect(screen.getByRole('button', { name: 'Retrying resources…' })).toBeDisabled();
    expect(screen.getByRole('alert')).toBeInTheDocument();
    expect(screen.queryByText('No resources available')).not.toBeInTheDocument();
    expect(onSelectionChange).not.toHaveBeenCalled();

    finishRead();
    const row = await screen.findByRole('button', { name: /Recovered VM/ });
    expect(screen.queryByRole('alert')).not.toBeInTheDocument();
    expect(screen.queryByText('Alpha VM')).not.toBeInTheDocument();
    expect(screen.getByText('1 selected')).toBeInTheDocument();
    expect(onSelectionChange).not.toHaveBeenCalled();
    await fireEvent.click(row);
    expect(onSelectionChange).toHaveBeenLastCalledWith([
      ...createSelectedResources(1),
      { id: 'vm-new', type: 'vm', name: 'Recovered VM' },
    ]);
  });

  it('keeps an unsuccessful retry recoverable and preserves the caller selection', async () => {
    mockError = new Error('Unavailable');
    refetchMock.mockRejectedValue(new Error('Still unavailable'));
    const { onSelectionChange } = renderPicker(createSelectedResources(1));

    await fireEvent.click(screen.getByRole('button', { name: 'Retry loading resources' }));
    await waitFor(() =>
      expect(screen.getByRole('button', { name: 'Retry loading resources' })).toBeEnabled(),
    );
    expect(screen.getByRole('alert')).toBeInTheDocument();
    expect(screen.queryByText('No resources available')).not.toBeInTheDocument();
    expect(screen.getByText('1 selected')).toBeInTheDocument();
    expect(refetchMock).toHaveBeenCalledTimes(1);
    expect(onSelectionChange).not.toHaveBeenCalled();
  });

  it('reserves the empty-estate message for an accepted empty read', () => {
    renderPicker();
    expect(screen.getByText('No resources available')).toBeInTheDocument();
    expect(screen.queryByRole('alert')).not.toBeInTheDocument();
    expect(screen.getByRole('button', { name: /Select all visible/ })).toBeDisabled();
  });

  it('selects a whole client estate beyond the performance cap while excluding other resource types', async () => {
    mockResources = [
      ...Array.from({ length: 61 }, (_, index) =>
        makeResource({ id: `vm-${index}`, name: `VM ${index}`, displayName: `VM ${index}` }),
      ),
      makeResource({ id: 'host', type: 'agent', name: 'Host', displayName: 'Host' }),
    ];
    const { onSelectionChange } = renderPickerWithOptions([], {
      maxSelection: null,
      resourceTypes: ['vm'],
    });
    await fireEvent.click(screen.getByRole('button', { name: /select all/i }));
    expect(onSelectionChange).toHaveBeenLastCalledWith(
      expect.arrayContaining([expect.objectContaining({ id: 'vm-60' })]),
    );
    expect(onSelectionChange.mock.lastCall?.[0]).toHaveLength(61);
    expect(
      onSelectionChange.mock.lastCall?.[0].some(
        (resource: SelectedResource) => resource.type === 'agent',
      ),
    ).toBe(false);
    expect(showWarningMock).not.toHaveBeenCalled();
  });

  it('mounts a bounded window of a large resource inventory', () => {
    mockResources = Array.from({ length: 61 }, (_, index) =>
      makeResource({ id: `vm-${index}`, name: `VM ${index}`, displayName: `VM ${index}` }),
    );
    const { container } = render(() => (
      <ResourcePicker maxSelection={null} selected={() => []} onSelectionChange={vi.fn()} />
    ));

    const rows = screen.getAllByText(/^VM \d+$/);
    expect(rows.length).toBeGreaterThan(0);
    expect(rows.length).toBeLessThan(61);
    expect(container.querySelectorAll('[data-platform-window-spacer]')).toHaveLength(2);
  });

  it('keeps the initial hydration state distinct from a genuinely empty estate', () => {
    mockLoading = true;

    renderPicker();

    expect(screen.getByRole('status')).toHaveTextContent('Loading resources…');
    expect(screen.queryByText('No resources available')).not.toBeInTheDocument();
  });

  it('renders reportable resources from useResources()', async () => {
    mockResources = [
      makeResource({
        id: 'node-1',
        type: 'agent',
        name: 'Node One',
        displayName: 'Node One',
        status: 'online',
      }),
      makeResource({ id: 'vm-1', type: 'vm', name: 'Alpha VM', displayName: 'Alpha VM' }),
      makeResource({
        id: 'truenas-1',
        type: 'agent',
        name: 'TrueNAS',
        displayName: 'TrueNAS',
        platformType: 'truenas',
      }),
    ];

    renderPicker();

    expect(await screen.findByText('Node One')).toBeInTheDocument();
    expect(screen.getByText('Alpha VM')).toBeInTheDocument();
    expect(screen.getByText('TrueNAS')).toBeInTheDocument();
  });

  it('renders policy-redacted resources with their raw display name (operator-local picker does not redact)', async () => {
    // The Reporting Panel picker is the operator selecting their own resources.
    // Per docs/PRIVACY.md, redaction is a transmission-boundary policy and must
    // not be applied to local /settings UI; the operator needs the raw name to
    // recognize the resource.
    mockResources = [
      makeResource({
        id: 'vm-2',
        type: 'vm',
        name: 'secret-vm-2',
        displayName: 'secret-vm-2',
        policy: {
          sensitivity: 'restricted',
          routing: { scope: 'local-only', redact: ['hostname'] },
        },
        aiSafeSummary: 'Production VM',
        status: 'running',
      }),
    ];

    renderPicker();

    expect(await screen.findByText('secret-vm-2')).toBeInTheDocument();
    expect(screen.queryByText('Production VM')).not.toBeInTheDocument();
  });

  it('applies type filter buttons', async () => {
    mockResources = [
      makeResource({
        id: 'node-1',
        type: 'agent',
        name: 'Node One',
        displayName: 'Node One',
        status: 'online',
      }),
      makeResource({ id: 'vm-1', type: 'vm', name: 'Workload VM', displayName: 'Workload VM' }),
      makeResource({
        id: 'storage-1',
        type: 'storage',
        name: 'Storage Main',
        displayName: 'Storage Main',
        status: 'online',
      }),
      makeResource({
        id: 'pbs-1',
        type: 'pbs',
        name: 'Backup Server',
        displayName: 'Backup Server',
        status: 'online',
      }),
    ];

    renderPicker();

    fireEvent.click(screen.getByRole('button', { name: 'Infrastructure' }));
    expect(await screen.findByText('Node One')).toBeInTheDocument();
    expect(screen.queryByText('Workload VM')).not.toBeInTheDocument();

    fireEvent.click(screen.getByRole('button', { name: 'Workloads' }));
    expect(await screen.findByText('Workload VM')).toBeInTheDocument();
    expect(screen.queryByText('Storage Main')).not.toBeInTheDocument();

    fireEvent.click(screen.getByRole('button', { name: 'Storage' }));
    expect(await screen.findByText('Storage Main')).toBeInTheDocument();
    expect(screen.queryByText('Backup Server')).not.toBeInTheDocument();

    fireEvent.click(screen.getByRole('button', { name: 'Recovery' }));
    expect(await screen.findByText('Backup Server')).toBeInTheDocument();
    expect(screen.queryByText('Workload VM')).not.toBeInTheDocument();

    fireEvent.click(screen.getByRole('button', { name: 'All' }));
    expect(await screen.findByText('Node One')).toBeInTheDocument();
    expect(screen.getByText('Workload VM')).toBeInTheDocument();
  });

  it('filters resources by search on display name and ID', async () => {
    mockResources = [
      makeResource({
        id: 'vm-prod-101',
        type: 'vm',
        name: 'Production VM',
        displayName: 'Production VM',
      }),
      makeResource({
        id: 'host-dev-55',
        type: 'agent',
        name: 'Edge Host',
        displayName: 'Edge Host',
        status: 'online',
      }),
    ];

    renderPicker();

    const searchInput = screen.getByPlaceholderText('Search by name or ID...');

    fireEvent.input(searchInput, { target: { value: 'production' } });
    expect(await screen.findByText('Production VM')).toBeInTheDocument();
    expect(screen.queryByText('Edge Host')).not.toBeInTheDocument();

    fireEvent.input(searchInput, { target: { value: 'host-dev' } });
    expect(await screen.findByText('Edge Host')).toBeInTheDocument();
    expect(screen.queryByText('Production VM')).not.toBeInTheDocument();
  });

  it('filters resources by tag through the shared search field', async () => {
    mockResources = [
      makeResource({
        id: 'vm-prod-101',
        type: 'vm',
        name: 'Production VM',
        displayName: 'Production VM',
        tags: ['critical', 'finance'],
      }),
      makeResource({
        id: 'host-dev-55',
        type: 'agent',
        name: 'Edge Host',
        displayName: 'Edge Host',
        status: 'online',
        tags: ['lab'],
      }),
    ];

    renderPicker();

    const tagInput = screen.getByPlaceholderText('Filter by tag...');
    fireEvent.input(tagInput, { target: { value: 'finance' } });

    expect(await screen.findByText('Production VM')).toBeInTheDocument();
    expect(screen.queryByText('Edge Host')).not.toBeInTheDocument();
    expect(screen.getByRole('button', { name: 'Clear search' })).toBeInTheDocument();
  });

  it('toggles individual selection on and off', async () => {
    mockResources = [
      makeResource({ id: 'vm-1', type: 'vm', name: 'Alpha VM', displayName: 'Alpha VM' }),
    ];

    const { onSelectionChange } = renderPicker();

    const resourceButton = (await screen.findByText('Alpha VM')).closest('button');
    expect(resourceButton).toBeTruthy();

    fireEvent.click(resourceButton!);
    await waitFor(() => {
      expect(screen.getByText('1 selected')).toBeInTheDocument();
    });
    expect(onSelectionChange).toHaveBeenCalledWith([{ id: 'vm-1', type: 'vm', name: 'Alpha VM' }]);

    fireEvent.click(resourceButton!);
    await waitFor(() => {
      expect(screen.getByText('0 selected')).toBeInTheDocument();
    });
  });

  it('keeps docker host selections on canonical docker-host report type', async () => {
    mockResources = [
      makeResource({
        id: 'docker-host-1',
        type: 'docker-host',
        name: 'Docker Agent 1',
        displayName: 'Docker Agent 1',
      }),
    ];

    const { onSelectionChange } = renderPicker();

    const resourceButton = (await screen.findByText('Docker Agent 1')).closest('button');
    expect(resourceButton).toBeTruthy();
    fireEvent.click(resourceButton!);

    expect(onSelectionChange).toHaveBeenCalledWith([
      { id: 'docker-host-1', type: 'docker-host', name: 'Docker Agent 1' },
    ]);
  });

  it('keeps docker container selections on canonical app-container report type', async () => {
    mockResources = [
      makeResource({
        id: 'docker-container-1',
        type: 'app-container',
        name: 'web',
        displayName: 'web',
      }),
    ];

    const { onSelectionChange } = renderPicker();

    const resourceButton = (await screen.findByText('web')).closest('button');
    expect(resourceButton).toBeTruthy();
    fireEvent.click(resourceButton!);

    expect(onSelectionChange).toHaveBeenCalledWith([
      { id: 'docker-container-1', type: 'app-container', name: 'web' },
    ]);
  });

  it('keeps kubernetes cluster selections on canonical k8s-cluster type', async () => {
    mockResources = [
      makeResource({
        id: 'k8s-cluster:edge',
        type: 'k8s-cluster',
        name: 'edge-cluster',
        displayName: 'edge-cluster',
      }),
    ];

    const { onSelectionChange } = renderPicker();

    const resourceButton = (await screen.findByText('edge-cluster')).closest('button');
    expect(resourceButton).toBeTruthy();
    fireEvent.click(resourceButton!);

    expect(onSelectionChange).toHaveBeenCalledWith([
      { id: 'k8s-cluster:edge', type: 'k8s-cluster', name: 'edge-cluster' },
    ]);
  });

  it('keeps pod selections on canonical pod type', async () => {
    mockResources = [
      makeResource({
        id: 'k8s:edge:pod:api-7f9d',
        type: 'pod',
        name: 'api-7f9d',
        displayName: 'api-7f9d',
      }),
    ];

    const { onSelectionChange } = renderPicker();

    const resourceButton = (await screen.findByText('api-7f9d')).closest('button');
    expect(resourceButton).toBeTruthy();
    fireEvent.click(resourceButton!);

    expect(onSelectionChange).toHaveBeenCalledWith([
      { id: 'k8s:edge:pod:api-7f9d', type: 'pod', name: 'api-7f9d' },
    ]);
  });

  it('enforces the max selection limit when toggling', async () => {
    mockResources = [
      makeResource({ id: 'vm-new', type: 'vm', name: 'Overflow VM', displayName: 'Overflow VM' }),
    ];

    const { onSelectionChange } = renderPicker(createSelectedResources(50));

    const resourceButton = (await screen.findByText('Overflow VM')).closest('button');
    expect(resourceButton).toBeTruthy();
    fireEvent.click(resourceButton!);

    expect(showWarningMock).toHaveBeenCalledWith('Maximum 50 resources can be selected');
    expect(screen.getByText('50 selected')).toBeInTheDocument();
    expect(onSelectionChange).not.toHaveBeenCalled();
  });

  it('obeys a caller-provided max selection limit', async () => {
    mockResources = [
      makeResource({ id: 'vm-new', type: 'vm', name: 'Overflow VM', displayName: 'Overflow VM' }),
    ];

    const { onSelectionChange } = renderPickerWithOptions(createSelectedResources(2), {
      maxSelection: 2,
    });

    const resourceButton = (await screen.findByText('Overflow VM')).closest('button');
    expect(resourceButton).toBeTruthy();
    fireEvent.click(resourceButton!);

    expect(showWarningMock).toHaveBeenCalledWith('Maximum 2 resources can be selected');
    expect(screen.getByText('2 selected')).toBeInTheDocument();
    expect(onSelectionChange).not.toHaveBeenCalled();
  });

  it('supports select-all-visible and clear-all', async () => {
    mockResources = [
      makeResource({
        id: 'node-1',
        type: 'agent',
        name: 'Node One',
        displayName: 'Node One',
        status: 'online',
      }),
      makeResource({ id: 'vm-1', type: 'vm', name: 'Alpha VM', displayName: 'Alpha VM' }),
      makeResource({
        id: 'storage-1',
        type: 'storage',
        name: 'Storage Main',
        displayName: 'Storage Main',
        status: 'online',
      }),
    ];

    renderPicker();

    fireEvent.click(screen.getByRole('button', { name: /Select all visible \(3\)/i }));
    await waitFor(() => {
      expect(screen.getByText('3 selected')).toBeInTheDocument();
    });

    fireEvent.click(screen.getByRole('button', { name: 'Clear all' }));
    await waitFor(() => {
      expect(screen.getByText('0 selected')).toBeInTheDocument();
    });
  });
});