import { render, screen, act, waitFor } from '@testing-library/react'; import '@testing-library/jest-dom'; import { saveAs } from 'file-saver'; import { useIsOnFeatureFlag } from '~/feature-flags/hooks'; import { KUBEARCHIVE_TAIL_LINES } from '~/kubearchive/const'; import { ResourceSource } from '~/types/k8s'; import { commonFetchText } from '../../../../../k8s'; import { getK8sResourceURL, getWebsocketSubProtocolAndPathPrefix, } from '../../../../../k8s/k8s-utils'; import { TaskRunKind } from '../../../../../types'; import { ContainerStatus, PodKind, ContainerSpec } from '../../../types'; import { containerToLogSourceStatus, isContainerStepCompleted } from '../../utils'; import Logs from '../Logs'; const mockLogViewer = jest.fn(); const getLastSectionsData = (): string => { const lastCall = mockLogViewer.mock.calls[mockLogViewer.mock.calls.length - 1][0]; return (lastCall.normalizedSections || []) .map((s: { lines: string[] }) => s.lines.join('\n')) .join('\n'); }; const getLastOnDownloadFullLogs = (): ((sectionIndex: number) => Promise) | undefined => { const lastCall = mockLogViewer.mock.calls[mockLogViewer.mock.calls.length - 1][0]; return lastCall.onDownloadFullLogs; }; const getLastAllowExpandAllSections = (): boolean | undefined => { const lastCall = mockLogViewer.mock.calls[mockLogViewer.mock.calls.length - 1][0]; return lastCall.allowExpandAllSections; }; jest.mock('file-saver', () => ({ saveAs: jest.fn(), })); jest.mock('../LogViewer', () => { return function MockLogViewer(props: { normalizedSections: Array<{ containerName: string; lines: string[]; isCompleted?: boolean; isTailed?: boolean; }>; allowAutoScroll: boolean; isLoading?: boolean; onScroll?: () => void; onDownloadFullLogs?: (sectionIndex: number) => Promise; allowExpandAllSections?: boolean; }) { mockLogViewer(props); return
; }; }); // Mock external dependencies jest.mock('../../../../../k8s', () => ({ commonFetchText: jest.fn(), })); jest.mock('../../../../../k8s/k8s-utils', () => ({ getK8sResourceURL: jest.fn(), getWebsocketSubProtocolAndPathPrefix: jest.fn(), })); const mockWebSocketInstance = { onMessage: jest.fn().mockReturnThis(), onError: jest.fn().mockReturnThis(), destroy: jest.fn(), }; jest.mock('../../../../../k8s/web-socket/WebSocketFactory', () => ({ WebSocketFactory: jest.fn().mockImplementation(() => mockWebSocketInstance), })); jest.mock('~/feature-flags/hooks', () => ({ useIsOnFeatureFlag: jest.fn(), })); jest.mock('~/shared/providers/Namespace'); jest.mock('../../utils', () => ({ containerToLogSourceStatus: jest.fn(), isContainerStepCompleted: jest.fn(), LOG_SOURCE_TERMINATED: 'terminated', LOG_SOURCE_RUNNING: 'running', LOG_SOURCE_WAITING: 'waiting', })); jest.mock('react-i18next', () => ({ useTranslation: () => ({ t: (key: string) => key, }), })); // Mock Base64 decoding (append newline so LineBuffer.append flushes the line from the tail) jest.mock('js-base64', () => ({ Base64: { decode: jest.fn((str: string) => `decoded-${str}\n`), }, })); describe('Logs', () => { const mockResource: PodKind = { apiVersion: 'v1', kind: 'Pod', metadata: { name: 'test-pod', namespace: 'test-namespace', }, spec: { containers: [], }, status: { phase: 'Running', containerStatuses: [], }, }; const mockContainers: ContainerSpec[] = [{ name: 'container1' }, { name: 'container2' }]; const mockTaskRun: TaskRunKind = { apiVersion: 'tekton.dev/v1beta1', kind: 'TaskRun', metadata: { name: 'test-taskrun', uid: 'test-uid', }, spec: { taskRef: { name: 'test-task', }, }, status: { podName: 'test-pod', }, }; const defaultProps = { resource: mockResource, containers: mockContainers, allowAutoScroll: false, taskRun: mockTaskRun, isLoading: false, source: ResourceSource.Cluster, }; beforeEach(() => { jest.clearAllMocks(); (useIsOnFeatureFlag as jest.Mock).mockReturnValue(false); (getK8sResourceURL as jest.Mock).mockReturnValue('http://test-url'); (getWebsocketSubProtocolAndPathPrefix as jest.Mock).mockReturnValue({}); (containerToLogSourceStatus as jest.Mock).mockReturnValue('running'); (isContainerStepCompleted as jest.Mock).mockImplementation( (container?: ContainerStatus) => containerToLogSourceStatus(container) === 'terminated', ); }); describe('rendering', () => { it('should render logs container', () => { render(); expect(screen.getByTestId('mock-log-viewer')).toBeInTheDocument(); }); it('should render LogViewer with correct props', () => { render(); expect(mockLogViewer).toHaveBeenCalledWith( expect.objectContaining({ normalizedSections: expect.any(Array), allowAutoScroll: true, onScroll: undefined, }), ); }); it('should pass onScroll prop to LogViewer', () => { const mockOnScroll = jest.fn(); render(); expect(mockLogViewer).toHaveBeenCalledWith( expect.objectContaining({ onScroll: mockOnScroll, }), ); }); }); describe('error handling', () => { it('should not show error message initially', () => { render(); expect(screen.queryByTestId('error-message')).not.toBeInTheDocument(); }); describe('empty containers', () => { it('should handle empty containers array', () => { render(); expect(screen.getByTestId('mock-log-viewer')).toBeInTheDocument(); expect(mockLogViewer).toHaveBeenCalledWith( expect.objectContaining({ normalizedSections: [], }), ); }); }); }); describe('sections prop', () => { it('should pass sections with correct container names and pre-split lines', async () => { const terminatedContainer1: ContainerStatus = { name: 'container1', state: { terminated: { exitCode: 0 } }, ready: false, restartCount: 0, image: 'test-image', imageID: 'test-image-id', }; const terminatedContainer2: ContainerStatus = { name: 'container2', state: { terminated: { exitCode: 0 } }, ready: false, restartCount: 0, image: 'test-image', imageID: 'test-image-id', }; const resourceWithStatus: PodKind = { ...mockResource, status: { phase: 'Succeeded', containerStatuses: [terminatedContainer1, terminatedContainer2], }, }; (containerToLogSourceStatus as jest.Mock).mockReturnValue('terminated'); (commonFetchText as jest.Mock) .mockResolvedValueOnce('log line 1\nlog line 2\n') .mockResolvedValueOnce('log line 3\nlog line 4\n'); render( , ); await waitFor(() => { expect(mockLogViewer).toHaveBeenLastCalledWith( expect.objectContaining({ normalizedSections: expect.arrayContaining([ expect.objectContaining({ containerName: 'CONTAINER1', lines: ['log line 1', 'log line 2'], isCompleted: true, }), expect.objectContaining({ containerName: 'CONTAINER2', lines: ['log line 3', 'log line 4'], isCompleted: true, }), ]), }), ); }); }); it('should preserve container ordering from containers prop', async () => { const terminatedContainer1: ContainerStatus = { name: 'container1', state: { terminated: { exitCode: 0 } }, ready: false, restartCount: 0, image: 'test-image', imageID: 'test-image-id', }; const terminatedContainer2: ContainerStatus = { name: 'container2', state: { terminated: { exitCode: 0 } }, ready: false, restartCount: 0, image: 'test-image', imageID: 'test-image-id', }; const resourceWithStatus: PodKind = { ...mockResource, status: { phase: 'Succeeded', containerStatuses: [terminatedContainer1, terminatedContainer2], }, }; (containerToLogSourceStatus as jest.Mock).mockReturnValue('terminated'); (commonFetchText as jest.Mock) .mockResolvedValueOnce('first\n') .mockResolvedValueOnce('second\n'); render( , ); await waitFor(() => { const lastCall = mockLogViewer.mock.calls[mockLogViewer.mock.calls.length - 1][0]; expect(lastCall.normalizedSections[0].containerName).toBe('CONTAINER2'); expect(lastCall.normalizedSections[1].containerName).toBe('CONTAINER1'); }); }); it('should include containers with empty fetched logs so folding can evaluate them', async () => { const terminatedContainer1: ContainerStatus = { name: 'container1', state: { terminated: { exitCode: 0 } }, ready: false, restartCount: 0, image: 'test-image', imageID: 'test-image-id', }; const terminatedContainer2: ContainerStatus = { name: 'container2', state: { terminated: { exitCode: 0 } }, ready: false, restartCount: 0, image: 'test-image', imageID: 'test-image-id', }; const resourceWithStatus: PodKind = { ...mockResource, status: { phase: 'Succeeded', containerStatuses: [terminatedContainer1, terminatedContainer2], }, }; (containerToLogSourceStatus as jest.Mock).mockReturnValue('terminated'); (commonFetchText as jest.Mock).mockResolvedValueOnce('has logs\n').mockResolvedValueOnce(''); // container2 returns empty string (no logs) render( , ); await waitFor(() => { // Both containers appear in sections; container2 has an empty buffer const lastCall = mockLogViewer.mock.calls[mockLogViewer.mock.calls.length - 1][0]; expect(lastCall.normalizedSections).toHaveLength(2); expect(lastCall.normalizedSections[0].containerName).toBe('CONTAINER1'); expect(lastCall.normalizedSections[0].lines).toEqual(['has logs']); expect(lastCall.normalizedSections[1].containerName).toBe('CONTAINER2'); expect(lastCall.normalizedSections[1].lines).toEqual([]); }); await act(async () => { await Promise.resolve(); }); const lastCall = mockLogViewer.mock.calls[mockLogViewer.mock.calls.length - 1][0]; expect(lastCall.normalizedSections).toHaveLength(2); expect(lastCall.normalizedSections[0]).toEqual( expect.objectContaining({ containerName: 'CONTAINER1', lines: ['has logs'], isCompleted: true, hasTerminatedWithError: false, }), ); expect(lastCall.normalizedSections[1]).toEqual( expect.objectContaining({ containerName: 'CONTAINER2', lines: [], isCompleted: true, hasTerminatedWithError: false, }), ); }); it('should mark sections with hasTerminatedWithError as true when a container exits with a non-zero code', async () => { const failedContainer: ContainerStatus = { name: 'container1', state: { terminated: { exitCode: 1 } }, ready: false, restartCount: 0, image: 'test-image', imageID: 'test-image-id', }; const resourceWithStatus: PodKind = { ...mockResource, status: { phase: 'Failed', containerStatuses: [failedContainer], }, }; (containerToLogSourceStatus as jest.Mock).mockReturnValue('terminated'); (commonFetchText as jest.Mock).mockResolvedValueOnce('failed step logs\n'); render( , ); await waitFor(() => { const lastCall = mockLogViewer.mock.calls[mockLogViewer.mock.calls.length - 1][0]; expect(lastCall.normalizedSections[0]).toEqual( expect.objectContaining({ containerName: 'CONTAINER1', isCompleted: true, hasTerminatedWithError: true, }), ); }); }); it('should mark a section with hasTerminatedWithError as true when log fetching fails', async () => { const terminatedContainer: ContainerStatus = { name: 'container1', state: { terminated: { exitCode: 0 } }, ready: false, restartCount: 0, image: 'test-image', imageID: 'test-image-id', }; const resourceWithStatus: PodKind = { ...mockResource, status: { phase: 'Failed', containerStatuses: [terminatedContainer], }, }; (containerToLogSourceStatus as jest.Mock).mockReturnValue('terminated'); (commonFetchText as jest.Mock).mockRejectedValue(new Error('Network error')); render( , ); await waitFor(() => { const lastCall = mockLogViewer.mock.calls[mockLogViewer.mock.calls.length - 1][0]; expect(lastCall.normalizedSections[0].hasTerminatedWithError).toBe(true); }); }); it('should not mark sections with hasTerminatedWithError for running containers', async () => { const runningContainer: ContainerStatus = { name: 'container1', state: { running: { startedAt: new Date().toISOString() } }, ready: true, restartCount: 0, image: 'test-image', imageID: 'test-image-id', }; const resourceWithStatus: PodKind = { ...mockResource, status: { phase: 'Running', containerStatuses: [runningContainer], }, }; (containerToLogSourceStatus as jest.Mock).mockReturnValue('running'); render( , ); // Simulate websocket message so a section appears in the viewer const messageHandler = mockWebSocketInstance.onMessage.mock.calls[0][0]; act(() => { messageHandler('aGVsbG8gd29ybGQ='); }); await waitFor(() => { const lastCall = mockLogViewer.mock.calls[mockLogViewer.mock.calls.length - 1][0]; expect(lastCall.normalizedSections[0]).toEqual( expect.objectContaining({ containerName: 'CONTAINER1', isCompleted: false, hasTerminatedWithError: false, }), ); }); }); it('should pass empty sections when no containers have logs', () => { render(); expect(mockLogViewer).toHaveBeenCalledWith( expect.objectContaining({ normalizedSections: [], }), ); }); }); describe('container log fetching', () => { it('should use HTTP request for terminated containers', () => { const terminatedContainer: ContainerStatus = { name: 'container1', state: { terminated: { exitCode: 0 } }, ready: false, restartCount: 0, image: 'test-image', imageID: 'test-image-id', }; const resourceWithStatus: PodKind = { ...mockResource, status: { phase: 'Succeeded', containerStatuses: [terminatedContainer], }, }; (containerToLogSourceStatus as jest.Mock).mockReturnValue('terminated'); (commonFetchText as jest.Mock).mockResolvedValue('terminated container logs'); render( , ); expect(commonFetchText as jest.Mock).toHaveBeenCalledWith( 'http://test-url', expect.objectContaining({ signal: expect.any(AbortSignal), }), ); expect(getK8sResourceURL as jest.Mock).toHaveBeenCalledWith( expect.objectContaining({ kind: 'Pod' }), undefined, expect.objectContaining({ ns: 'test-namespace', name: 'test-pod', path: 'log', queryParams: { container: 'container1', follow: 'false', // terminated containers don't follow }, }), ); }); it('should use kubearchive prefix for terminated containers from archive source', () => { const terminatedContainer: ContainerStatus = { name: 'container1', state: { terminated: { exitCode: 0 } }, ready: false, restartCount: 0, image: 'test-image', imageID: 'test-image-id', }; const resourceWithStatus: PodKind = { ...mockResource, status: { phase: 'Succeeded', containerStatuses: [terminatedContainer], }, }; (containerToLogSourceStatus as jest.Mock).mockReturnValue('terminated'); (useIsOnFeatureFlag as jest.Mock).mockReturnValue(true); // kubearchive enabled (commonFetchText as jest.Mock).mockResolvedValue('kubearchive logs'); render( , ); expect(commonFetchText as jest.Mock).toHaveBeenCalledWith( 'http://test-url', expect.objectContaining({ signal: expect.any(AbortSignal), pathPrefix: 'plugins/kubearchive', }), ); }); it('should handle fetch errors for terminated containers', async () => { const terminatedContainer: ContainerStatus = { name: 'container1', state: { terminated: { exitCode: 1 } }, ready: false, restartCount: 0, image: 'test-image', imageID: 'test-image-id', }; const resourceWithStatus: PodKind = { ...mockResource, status: { phase: 'Failed', containerStatuses: [terminatedContainer], }, }; (containerToLogSourceStatus as jest.Mock).mockReturnValue('terminated'); (commonFetchText as jest.Mock).mockRejectedValue(new Error('Network error')); render( , ); expect(commonFetchText as jest.Mock).toHaveBeenCalled(); // Should show error message in LogViewer await waitFor(() => { expect(getLastSectionsData()).toContain('LOG FETCH ERROR'); }); }); it('should display formatted error message for 404 errors from archive source', async () => { const terminatedContainer: ContainerStatus = { name: 'container1', state: { terminated: { exitCode: 0 } }, ready: false, restartCount: 0, image: 'test-image', imageID: 'test-image-id', }; const resourceWithStatus: PodKind = { ...mockResource, status: { phase: 'Succeeded', containerStatuses: [terminatedContainer], }, }; (containerToLogSourceStatus as jest.Mock).mockReturnValue('terminated'); const error404 = Object.assign(new Error('Not Found'), { code: 404 }); (commonFetchText as jest.Mock).mockRejectedValue(error404); render( , ); expect(commonFetchText as jest.Mock).toHaveBeenCalled(); // Archive 404s with a message should display it with ANSI-styled LOG FETCH ERROR await waitFor(() => { const sectionsData = getLastSectionsData(); expect(sectionsData).toContain('LOG FETCH ERROR'); expect(sectionsData).toContain('Not Found'); }); }); it('should display empty content for archive 404 when err.message is empty', async () => { const terminatedContainer: ContainerStatus = { name: 'container1', state: { terminated: { exitCode: 0 } }, ready: false, restartCount: 0, image: 'test-image', imageID: 'test-image-id', }; const resourceWithStatus: PodKind = { ...mockResource, status: { phase: 'Succeeded', containerStatuses: [terminatedContainer], }, }; (containerToLogSourceStatus as jest.Mock).mockReturnValue('terminated'); const error404 = Object.assign(new Error(''), { code: 404 }); (commonFetchText as jest.Mock).mockRejectedValue(error404); render( , ); expect(commonFetchText as jest.Mock).toHaveBeenCalled(); // Archive 404s with empty message should show empty content await waitFor(() => { const sectionsData = getLastSectionsData(); expect(sectionsData).not.toContain('LOG FETCH ERROR'); expect(sectionsData).not.toContain('Not Found'); }); }); it('should display error message for 404 errors from cluster source', async () => { const terminatedContainer: ContainerStatus = { name: 'container1', state: { terminated: { exitCode: 0 } }, ready: false, restartCount: 0, image: 'test-image', imageID: 'test-image-id', }; const resourceWithStatus: PodKind = { ...mockResource, status: { phase: 'Succeeded', containerStatuses: [terminatedContainer], }, }; (containerToLogSourceStatus as jest.Mock).mockReturnValue('terminated'); const error404 = Object.assign( new Error('container step-build is waiting to start: ImagePullBackOff'), { code: 404 }, ); (commonFetchText as jest.Mock).mockRejectedValue(error404); render( , ); expect(commonFetchText as jest.Mock).toHaveBeenCalled(); // Cluster-sourced 404s carry meaningful messages that should be shown await waitFor(() => { const sectionsData = getLastSectionsData(); expect(sectionsData).toContain('LOG FETCH ERROR'); expect(sectionsData).toContain( 'container step-build is waiting to start: ImagePullBackOff', ); }); }); it('should use websocket for running containers', async () => { const runningContainer: ContainerStatus = { name: 'container1', state: { running: { startedAt: new Date().toISOString() } }, ready: true, restartCount: 0, image: 'test-image', imageID: 'test-image-id', }; const resourceWithStatus: PodKind = { ...mockResource, status: { phase: 'Running', containerStatuses: [runningContainer], }, }; (containerToLogSourceStatus as jest.Mock).mockReturnValue('running'); (getWebsocketSubProtocolAndPathPrefix as jest.Mock).mockReturnValue({ subprotocol: 'v4.channel.k8s.io', }); render( , ); await waitFor(() => { expect(getWebsocketSubProtocolAndPathPrefix as jest.Mock).toHaveBeenCalledWith( 'http://test-url', ); }); expect(getK8sResourceURL as jest.Mock).toHaveBeenCalledWith( expect.objectContaining({ kind: 'Pod' }), undefined, expect.objectContaining({ ns: 'test-namespace', name: 'test-pod', path: 'log', queryParams: { container: 'container1', follow: 'true', // running containers follow logs }, }), ); }); it('should handle websocket messages and decode base64 logs', async () => { const runningContainer: ContainerStatus = { name: 'container1', state: { running: { startedAt: new Date().toISOString() } }, ready: true, restartCount: 0, image: 'test-image', imageID: 'test-image-id', }; const resourceWithStatus: PodKind = { ...mockResource, status: { phase: 'Running', containerStatuses: [runningContainer], }, }; (containerToLogSourceStatus as jest.Mock).mockReturnValue('running'); render( , ); // Simulate websocket message const messageHandler = mockWebSocketInstance.onMessage.mock.calls[0][0]; act(() => { messageHandler('aGVsbG8gd29ybGQ='); // base64 encoded message }); await waitFor(() => { expect(getLastSectionsData()).toContain('decoded-aGVsbG8gd29ybGQ='); }); }); }); it('should handle waiting containers', () => { const waitingContainer: ContainerStatus = { name: 'container1', state: { waiting: { reason: 'PodInitializing' } }, ready: false, restartCount: 0, image: 'test-image', imageID: 'test-image-id', }; const resourceWithStatus: PodKind = { ...mockResource, status: { phase: 'Pending', containerStatuses: [waitingContainer], }, }; (containerToLogSourceStatus as jest.Mock).mockReturnValue('waiting'); render( , ); // Should use websocket for waiting containers (follow=true) expect(getK8sResourceURL as jest.Mock).toHaveBeenCalledWith( expect.objectContaining({ kind: 'Pod' }), undefined, expect.objectContaining({ queryParams: expect.objectContaining({ follow: 'true', }), }), ); }); it('should not use kubearchive prefix when feature flag is disabled', () => { const terminatedContainer: ContainerStatus = { name: 'container1', state: { terminated: { exitCode: 0 } }, ready: false, restartCount: 0, image: 'test-image', imageID: 'test-image-id', }; const resourceWithStatus: PodKind = { ...mockResource, status: { phase: 'Succeeded', containerStatuses: [terminatedContainer], }, }; (containerToLogSourceStatus as jest.Mock).mockReturnValue('terminated'); (useIsOnFeatureFlag as jest.Mock).mockReturnValue(false); // kubearchive disabled (commonFetchText as jest.Mock).mockResolvedValue('cluster logs'); render( , ); expect(commonFetchText as jest.Mock).toHaveBeenCalledWith( 'http://test-url', expect.objectContaining({ signal: expect.any(AbortSignal), // Should not have pathPrefix when kubearchive is disabled }), ); // Verify pathPrefix is not included const fetchCall = (commonFetchText as jest.Mock).mock.calls[0][1]; expect(fetchCall).not.toHaveProperty('pathPrefix'); }); it('should use kubearchive prefix when feature flag is enabled and source is Archive', () => { const terminatedContainer: ContainerStatus = { name: 'container1', state: { terminated: { exitCode: 0 } }, ready: false, restartCount: 0, image: 'test-image', imageID: 'test-image-id', }; const resourceWithStatus: PodKind = { ...mockResource, status: { phase: 'Succeeded', containerStatuses: [terminatedContainer], }, }; (containerToLogSourceStatus as jest.Mock).mockReturnValue('terminated'); (useIsOnFeatureFlag as jest.Mock).mockReturnValue(true); // kubearchive enabled (commonFetchText as jest.Mock).mockResolvedValue('kubearchive logs'); render( , ); expect(commonFetchText as jest.Mock).toHaveBeenCalledWith( 'http://test-url', expect.objectContaining({ signal: expect.any(AbortSignal), pathPrefix: 'plugins/kubearchive', }), ); }); it('should not use kubearchive prefix for cluster source even when flag is enabled', () => { const terminatedContainer: ContainerStatus = { name: 'container1', state: { terminated: { exitCode: 0 } }, ready: false, restartCount: 0, image: 'test-image', imageID: 'test-image-id', }; const resourceWithStatus: PodKind = { ...mockResource, status: { phase: 'Succeeded', containerStatuses: [terminatedContainer], }, }; (containerToLogSourceStatus as jest.Mock).mockReturnValue('terminated'); (useIsOnFeatureFlag as jest.Mock).mockReturnValue(true); // kubearchive enabled (commonFetchText as jest.Mock).mockResolvedValue('cluster logs'); render( , ); expect(commonFetchText as jest.Mock).toHaveBeenCalledWith( 'http://test-url', expect.objectContaining({ signal: expect.any(AbortSignal), }), ); // Verify pathPrefix is not included for cluster source const fetchCall = (commonFetchText as jest.Mock).mock.calls[0][1]; expect(fetchCall).not.toHaveProperty('pathPrefix'); }); it('should disable auto scroll when all containers are terminated', () => { const terminatedContainer1: ContainerStatus = { name: 'container1', state: { terminated: { exitCode: 0 } }, ready: false, restartCount: 0, image: 'test-image', imageID: 'test-image-id', }; const terminatedContainer2: ContainerStatus = { name: 'container2', state: { terminated: { exitCode: 0 } }, ready: false, restartCount: 0, image: 'test-image', imageID: 'test-image-id', }; const resourceWithStatus: PodKind = { ...mockResource, status: { phase: 'Succeeded', containerStatuses: [terminatedContainer1, terminatedContainer2], }, }; (containerToLogSourceStatus as jest.Mock).mockReturnValue('terminated'); render( , ); expect(mockLogViewer).toHaveBeenCalledWith( expect.objectContaining({ allowAutoScroll: false, // Should be false when all containers terminated }), ); }); it('should enable auto scroll when some containers are still running', () => { const terminatedContainer: ContainerStatus = { name: 'container1', state: { terminated: { exitCode: 0 } }, ready: false, restartCount: 0, image: 'test-image', imageID: 'test-image-id', }; const runningContainer: ContainerStatus = { name: 'container2', state: { running: { startedAt: new Date().toISOString() } }, ready: true, restartCount: 0, image: 'test-image', imageID: 'test-image-id', }; const resourceWithStatus: PodKind = { ...mockResource, status: { phase: 'Running', containerStatuses: [terminatedContainer, runningContainer], }, }; (containerToLogSourceStatus as jest.Mock) .mockReturnValueOnce('terminated') .mockReturnValue('running'); render( , ); expect(mockLogViewer).toHaveBeenCalledWith( expect.objectContaining({ allowAutoScroll: true, // Should be true when some containers still running }), ); }); it('should return false for allLogsTerminated when containers array is empty', () => { render(); expect(mockLogViewer).toHaveBeenCalledWith( expect.objectContaining({ allowAutoScroll: true, // Should be true when no containers (empty array) }), ); }); describe('loading indicator while fetching logs', () => { it('should show loading while terminated container logs are being fetched', async () => { let resolveFetch: ((value: string) => void) | undefined; const fetchPromise = new Promise((resolve) => { resolveFetch = resolve; }); (commonFetchText as jest.Mock).mockReturnValue(fetchPromise); (containerToLogSourceStatus as jest.Mock).mockReturnValue('terminated'); const terminatedContainer: ContainerStatus = { name: 'container1', state: { terminated: { exitCode: 0 } }, ready: false, restartCount: 0, image: 'test-image', imageID: 'test-image-id', }; const resourceWithStatus: PodKind = { ...mockResource, status: { phase: 'Succeeded', containerStatuses: [terminatedContainer], }, }; render( , ); expect(mockLogViewer).toHaveBeenCalledWith( expect.objectContaining({ isLoading: true, }), ); await act(async () => { resolveFetch?.('some log output'); await fetchPromise; }); await waitFor(() => { expect(mockLogViewer).toHaveBeenLastCalledWith( expect.objectContaining({ isLoading: false, }), ); }); }); it('should not show loading when there are no containers to fetch', () => { render(); expect(mockLogViewer).toHaveBeenCalledWith( expect.objectContaining({ isLoading: false, normalizedSections: [], }), ); }); }); it('should handle containers that are not yet started', () => { const resourceWithNoContainerStatuses: PodKind = { ...mockResource, status: { phase: 'Pending', containerStatuses: [], // No container statuses yet }, }; // When no container status is found, containerToLogSourceStatus should handle undefined (containerToLogSourceStatus as jest.Mock).mockReturnValue('waiting'); render( , ); // Should still try to create websocket connection for waiting containers expect(getK8sResourceURL as jest.Mock).toHaveBeenCalledWith( expect.objectContaining({ kind: 'Pod' }), undefined, expect.objectContaining({ queryParams: expect.objectContaining({ follow: 'true', }), }), ); }); describe('tailed container detection', () => { it('should mark container as tailed when log lines reach KUBEARCHIVE_TAIL_LINES', async () => { const terminatedContainer: ContainerStatus = { name: 'container1', state: { terminated: { exitCode: 0 } }, ready: false, restartCount: 0, image: 'test-image', imageID: 'test-image-id', }; const resourceWithStatus: PodKind = { ...mockResource, status: { phase: 'Succeeded', containerStatuses: [terminatedContainer], }, }; // Generate log text with KUBEARCHIVE_TAIL_LINES lines const lines = Array.from({ length: KUBEARCHIVE_TAIL_LINES }, (_, i) => `line ${i}`).join( '\n', ); (containerToLogSourceStatus as jest.Mock).mockReturnValue('terminated'); (useIsOnFeatureFlag as jest.Mock).mockReturnValue(true); (commonFetchText as jest.Mock).mockResolvedValue(`${lines}\n`); render( , ); await waitFor(() => { const lastCall = mockLogViewer.mock.calls[mockLogViewer.mock.calls.length - 1][0]; expect(lastCall.normalizedSections[0].isTailed).toBe(true); }); }); it('should not mark container as tailed when log lines are below KUBEARCHIVE_TAIL_LINES', async () => { const terminatedContainer: ContainerStatus = { name: 'container1', state: { terminated: { exitCode: 0 } }, ready: false, restartCount: 0, image: 'test-image', imageID: 'test-image-id', }; const resourceWithStatus: PodKind = { ...mockResource, status: { phase: 'Succeeded', containerStatuses: [terminatedContainer], }, }; (containerToLogSourceStatus as jest.Mock).mockReturnValue('terminated'); (useIsOnFeatureFlag as jest.Mock).mockReturnValue(true); (commonFetchText as jest.Mock).mockResolvedValue('short log\n'); render( , ); await waitFor(() => { const lastCall = mockLogViewer.mock.calls[mockLogViewer.mock.calls.length - 1][0]; expect(lastCall.normalizedSections[0].isTailed).toBe(false); }); }); it('should not mark container as tailed for cluster source', async () => { const terminatedContainer: ContainerStatus = { name: 'container1', state: { terminated: { exitCode: 0 } }, ready: false, restartCount: 0, image: 'test-image', imageID: 'test-image-id', }; const resourceWithStatus: PodKind = { ...mockResource, status: { phase: 'Succeeded', containerStatuses: [terminatedContainer], }, }; const lines = Array.from({ length: KUBEARCHIVE_TAIL_LINES }, (_, i) => `line ${i}`).join( '\n', ); (containerToLogSourceStatus as jest.Mock).mockReturnValue('terminated'); (useIsOnFeatureFlag as jest.Mock).mockReturnValue(true); (commonFetchText as jest.Mock).mockResolvedValue(`${lines}\n`); render( , ); await waitFor(() => { const lastCall = mockLogViewer.mock.calls[mockLogViewer.mock.calls.length - 1][0]; expect(lastCall.normalizedSections[0].isTailed).toBe(false); }); }); }); describe('kubearchive tailLines query param', () => { it('should include tailLines query param for archive source', () => { const terminatedContainer: ContainerStatus = { name: 'container1', state: { terminated: { exitCode: 0 } }, ready: false, restartCount: 0, image: 'test-image', imageID: 'test-image-id', }; const resourceWithStatus: PodKind = { ...mockResource, status: { phase: 'Succeeded', containerStatuses: [terminatedContainer], }, }; (containerToLogSourceStatus as jest.Mock).mockReturnValue('terminated'); (useIsOnFeatureFlag as jest.Mock).mockReturnValue(true); (commonFetchText as jest.Mock).mockResolvedValue('logs'); render( , ); expect(getK8sResourceURL as jest.Mock).toHaveBeenCalledWith( expect.objectContaining({ kind: 'Pod' }), undefined, expect.objectContaining({ queryParams: expect.objectContaining({ tailLines: String(KUBEARCHIVE_TAIL_LINES), }), }), ); }); it('should not include tailLines query param for cluster source', () => { const terminatedContainer: ContainerStatus = { name: 'container1', state: { terminated: { exitCode: 0 } }, ready: false, restartCount: 0, image: 'test-image', imageID: 'test-image-id', }; const resourceWithStatus: PodKind = { ...mockResource, status: { phase: 'Succeeded', containerStatuses: [terminatedContainer], }, }; (containerToLogSourceStatus as jest.Mock).mockReturnValue('terminated'); (useIsOnFeatureFlag as jest.Mock).mockReturnValue(false); (commonFetchText as jest.Mock).mockResolvedValue('logs'); render( , ); expect(getK8sResourceURL as jest.Mock).toHaveBeenCalledWith( expect.objectContaining({ kind: 'Pod' }), undefined, expect.objectContaining({ queryParams: expect.not.objectContaining({ tailLines: expect.anything(), }), }), ); }); }); describe('handleDownloadFullLogs', () => { it('should pass onDownloadFullLogs when source is archive', async () => { const terminatedContainer: ContainerStatus = { name: 'container1', state: { terminated: { exitCode: 0 } }, ready: false, restartCount: 0, image: 'test-image', imageID: 'test-image-id', }; const resourceWithStatus: PodKind = { ...mockResource, status: { phase: 'Succeeded', containerStatuses: [terminatedContainer], }, }; (containerToLogSourceStatus as jest.Mock).mockReturnValue('terminated'); (useIsOnFeatureFlag as jest.Mock).mockReturnValue(true); (commonFetchText as jest.Mock).mockResolvedValue('log data\n'); render( , ); await waitFor(() => { const onDownloadFullLogs = getLastOnDownloadFullLogs(); expect(onDownloadFullLogs).toBeDefined(); }); }); it('should not pass onDownloadFullLogs when source is cluster', () => { (containerToLogSourceStatus as jest.Mock).mockReturnValue('terminated'); (useIsOnFeatureFlag as jest.Mock).mockReturnValue(false); render( , ); const onDownloadFullLogs = getLastOnDownloadFullLogs(); expect(onDownloadFullLogs).toBeUndefined(); }); it('should fetch full logs and save file when onDownloadFullLogs is called', async () => { const terminatedContainer: ContainerStatus = { name: 'container1', state: { terminated: { exitCode: 0 } }, ready: false, restartCount: 0, image: 'test-image', imageID: 'test-image-id', }; const resourceWithStatus: PodKind = { ...mockResource, status: { phase: 'Succeeded', containerStatuses: [terminatedContainer], }, }; (containerToLogSourceStatus as jest.Mock).mockReturnValue('terminated'); (useIsOnFeatureFlag as jest.Mock).mockReturnValue(true); const tailedLog = `${Array.from({ length: KUBEARCHIVE_TAIL_LINES }, (_, i) => `line ${i}`).join('\n')}\n`; (commonFetchText as jest.Mock).mockResolvedValue(tailedLog); render( , ); await waitFor(() => { const lastCall = mockLogViewer.mock.calls[mockLogViewer.mock.calls.length - 1][0]; expect(lastCall.normalizedSections).toHaveLength(1); expect(lastCall.onDownloadFullLogs).toBeDefined(); }); (commonFetchText as jest.Mock).mockResolvedValue('full log content for download'); const onDownloadFullLogs = getLastOnDownloadFullLogs(); await act(async () => { await onDownloadFullLogs?.(0); }); expect(commonFetchText as jest.Mock).toHaveBeenCalledWith( 'http://test-url', expect.objectContaining({ pathPrefix: 'plugins/kubearchive', }), ); expect(saveAs).toHaveBeenCalledWith(expect.any(Blob), 'container1.log'); }); it('should not save file when section index is invalid', async () => { const terminatedContainer: ContainerStatus = { name: 'container1', state: { terminated: { exitCode: 0 } }, ready: false, restartCount: 0, image: 'test-image', imageID: 'test-image-id', }; const resourceWithStatus: PodKind = { ...mockResource, status: { phase: 'Succeeded', containerStatuses: [terminatedContainer], }, }; (containerToLogSourceStatus as jest.Mock).mockReturnValue('terminated'); (useIsOnFeatureFlag as jest.Mock).mockReturnValue(true); (commonFetchText as jest.Mock).mockResolvedValue('log data\n'); render( , ); await waitFor(() => { const onDownloadFullLogs = getLastOnDownloadFullLogs(); expect(onDownloadFullLogs).toBeDefined(); }); (commonFetchText as jest.Mock).mockClear(); (saveAs as jest.Mock).mockClear(); const onDownloadFullLogs = getLastOnDownloadFullLogs(); await act(async () => { await onDownloadFullLogs?.(999); // invalid index }); // Should not have fetched anything for an invalid section index expect(commonFetchText).not.toHaveBeenCalled(); expect(saveAs).not.toHaveBeenCalled(); }); }); describe('allowExpandAllSections', () => { it('should pass allowExpandAllSections=false for cluster source', () => { render(); expect(mockLogViewer).toHaveBeenCalledWith( expect.objectContaining({ allowExpandAllSections: false }), ); expect(getLastAllowExpandAllSections()).toBe(false); }); it('should pass allowExpandAllSections=true for archive source when kubearchive is enabled', () => { (useIsOnFeatureFlag as jest.Mock).mockReturnValue(true); render(); expect(mockLogViewer).toHaveBeenCalledWith( expect.objectContaining({ allowExpandAllSections: true }), ); expect(getLastAllowExpandAllSections()).toBe(true); }); it('should pass allowExpandAllSections=false for archive source when kubearchive is disabled', () => { (useIsOnFeatureFlag as jest.Mock).mockReturnValue(false); render(); expect(mockLogViewer).toHaveBeenCalledWith( expect.objectContaining({ allowExpandAllSections: false }), ); expect(getLastAllowExpandAllSections()).toBe(false); }); }); describe('rAF cleanup', () => { it('should cancel pending animation frame on unmount', () => { const cancelAnimationFrameSpy = jest.spyOn(window, 'cancelAnimationFrame'); const runningContainer: ContainerStatus = { name: 'container1', state: { running: { startedAt: new Date().toISOString() } }, ready: true, restartCount: 0, image: 'test-image', imageID: 'test-image-id', }; const resourceWithStatus: PodKind = { ...mockResource, status: { phase: 'Running', containerStatuses: [runningContainer], }, }; (containerToLogSourceStatus as jest.Mock).mockReturnValue('running'); const { unmount } = render( , ); // Simulate a websocket message to trigger rAF scheduling const messageHandler = mockWebSocketInstance.onMessage.mock.calls[0][0]; act(() => { messageHandler('dGVzdA=='); }); unmount(); // cancelAnimationFrame should have been called during cleanup expect(cancelAnimationFrameSpy).toHaveBeenCalled(); cancelAnimationFrameSpy.mockRestore(); }); }); });