← Back to Pull requests

test(hub): Part 2 coverage for collections and common (AAP-72868) #3742

Merged
acruzgon merged 13 files (1412 lines) on Oct 12, 2026 22:09 UTC
View on GitHub
acruzgon acruzgon commented on Oct 12, 2026 16:23 UTC
Author

Summary

Adds Vitest coverage for Hub collections/ and common/ as part of AAP-72868:

  • Documentation parsers and tab content rendering

  • Collection contents and distributions pages

  • Collection hooks (sign all, delete from repository, version selector)

  • Shared API helpers (hub-api-utils, request, useGetFn) and small utilities
  • All new tests use MSW for HTTP mocking and follow existing hub test patterns.

    Type of Change

  • Bug fix

  • Enhancement

  • Tests

  • Documentation

  • Other (please specify)
  • Risk Analysis - REQUIRED

  • High — Broad platform impact

  • Medium — Scoped but cross-cutting

  • Low — Narrowly scoped
  • Dependencies

    None.

    Testing

    Ephemeral E2E Tests

    Once PR is ready and preliminary checks pass, trigger tests by posting a comment /run-playwright on this PR.

    Manual Testing

  • cd frontend/hub && npx vitest run collections common

  • cd frontend/hub && npm run tsc
  • Screenshots

    N/A (test-only change).

    Made with Cursor

    Diff: 1412 lines (+1412 / -0) across 13 files Reviewer: lgalis Review duration: 345m
    All Vouch review confidence checks passed
    Residual risk 0.09 = Change Risk (0.61) × (1 − Review Confidence (0.85)). Review depth and reviewer attention state are adequate.
    Model 1 · Change Risk (XGBoost)
    Score: 0.61 · 1412 lines diff across 13 files
    0.61
    Model 2 · Review Depth (DistilBERT)
    Depth Score: 0.80 · 5 substantive comment(s)
    0.80
    Model 3 · Review Timing & Attention
    Session adequacy: 100% · Reviewer familiarity: 50%
    85%
    Bedrock Claude 3 · Risk Narration
    (disconnected)
    Groq
    Groq Risk Narration
    AWS Bedrock is currently disconnected. Generate high-confidence PR triage narration on-demand using Groq.
    Model 1 · Change Risk Attribution
    SHAP Weights
    Diff Size diff_size
    0.400
    Real PR Conversation Timeline
    9 items
    lgalis lgalis commented on code on Oct 12, 2026 18:47 UTC
    Code Review
    frontend/hub/collections/hooks/useDeleteCollectionsFromRepository.test.tsx:1
    @@ -0,0 +1,107 @@
    +/* eslint-disable i18next/no-literal-string */
    +import { http, HttpResponse } from 'msw';
    +import { setupServer } from 'msw/node';
    +import { renderHook } from '@testing-library/react';
    +import { MemoryRouter } from 'react-router-dom';
    +import { afterAll, afterEach, beforeAll, describe, expect, it, vi } from 'vitest';
    +import { setHubApiPath } from '../../common/api/formatPath';
    +import { CollectionVersionSearch } from '../Collection';
    +import { useDeleteCollectionsFromRepository } from './useDeleteCollectionsFromRepository';
    +
    +let capturedBulkActionConfig: {
    +  actionFn?: (collection: CollectionVersionSearch) => Promise<unknown>;
    +  title?: string;
    +} = {};
    +
    +vi.mock('../../common/useHubBulkConfirmation', () => ({
    +  useHubBulkConfirmation: () => (config: typeof capturedBulkActionConfig) => {
    +    capturedBulkActionConfig = config;
    +  },
    +}));
    +
    +vi.mock('@ansible/ansible-ui-framework', async () => {
    +  const actual = await vi.importActual('@ansible/ansible-ui-framework');
    +  return {
    +    ...actual,
    +    usePageNavigate: () => vi.fn(),
    +  };
    +});
    +
    +const mockCollection: CollectionVersionSearch = {
    +  collection_version: {
    +    namespace: 'testns',
    +    name: 'testcol',
    +    version: '1.0.0',
    +    pulp_created: '2024-01-01T00:00:00Z',
    +    pulp_href: '/cv/1/',
    +    requires_ansible: '>=2.9',
    +    require_ansible: '>=2.9',
    +    description: '',
    +  },
    +  repository: {
    +    name: 'published',
    +    pulp_href: '/repositories/1/',
    +    latest_version_href: '/repositories/1/versions/1/',
    +    pulp_id: '1',
    +    pulp_last_updated: '',
    +    content_count: 0,
    +    gpgkey: '',
    +    description: '',
    +  },
    +  repository_version: '1',
    +  is_signed: false,
    +  is_deprecated: false,
    +} as CollectionVersionSearch;
    +
    +describe('useDeleteCollectionsFromRepository', () => {
    +  const taskUuid = 'aaaaaaaa-bbbb-cccc-dddd-eeeeeeeeeeee';
    +
    +  const server = setupServer(
    +    http.get('*/pulp/api/v3/repositories/ansible/ansible/', () =>
    +      HttpResponse.json({
    +        results: [
    +          {
    +            name: 'published',
    +            pulp_href: `/pulp/api/v3/repositories/ansible/ansible/${taskUuid}/`,
    +            latest_version_href: '/versions/1/',
    +          },
    +        ],
    +      })
    +    ),
    +    http.get('*/v3/plugin/ansible/search/collection-versions/', () =>
    +      HttpResponse.json({
    +        data: [mockCollection],
    +        links: { next: null },
    +      })
    +    ),
    +    http.post(`*/pulp/api/v3/repositories/ansible/ansible/${taskUuid}/modify/`, () =>
    +      HttpResponse.json({ task: `/pulp/api/v3/tasks/${taskUuid}/` })
    +    ),
    +    http.get(`*/pulp/api/v3/tasks/${taskUuid}/`, () => HttpResponse.json({ state: 'completed' }))
    +  );
    +
    +  beforeAll(() => {
    +    setHubApiPath('/api/galaxy');
    +    server.listen({ onUnhandledRequest: 'warn' });
    +  });
    +  afterEach(() => {
    +    server.resetHandlers();
    +    capturedBulkActionConfig = {};
    +  });
    +  afterAll(() => server.close());
    +
    +  it('configures bulk delete action for collections in repository', async () => {
    +    const wrapper = ({ children }: { children: React.ReactNode }) => (
    +      <MemoryRouter>{children}</MemoryRouter>
    +    );
    +
    +    const { result } = renderHook(() => useDeleteCollectionsFromRepository(), { wrapper });
    +
    +    result.current([mockCollection]);
    +
    +    expect(capturedBulkActionConfig.title).toContain('delete');
    +    expect(capturedBulkActionConfig.actionFn).toBeDefined();
    +
    +    await capturedBulkActionConfig.actionFn?.(mockCollection);

    MSW is wired for repository lookup, collection-versions search, modify, and task polling, but the test only checks that title contains "delete" and that actionFn resolves.

    Please assert the delete path more directly—e.g. POST …/modify/ body (remove_content_units, base_version), that expected endpoints were called, and/or task completion—so a no-op actionFn cannot pass.

    lgalis lgalis commented on code on Oct 12, 2026 18:47 UTC
    Code Review
    frontend/hub/collections/hooks/useDeleteCollectionsFromRepository.test.tsx:1
    @@ -0,0 +1,107 @@
    +/* eslint-disable i18next/no-literal-string */
    +import { http, HttpResponse } from 'msw';
    +import { setupServer } from 'msw/node';
    +import { renderHook } from '@testing-library/react';
    +import { MemoryRouter } from 'react-router-dom';
    +import { afterAll, afterEach, beforeAll, describe, expect, it, vi } from 'vitest';
    +import { setHubApiPath } from '../../common/api/formatPath';
    +import { CollectionVersionSearch } from '../Collection';
    +import { useDeleteCollectionsFromRepository } from './useDeleteCollectionsFromRepository';
    +
    +let capturedBulkActionConfig: {
    +  actionFn?: (collection: CollectionVersionSearch) => Promise<unknown>;
    +  title?: string;
    +} = {};
    +
    +vi.mock('../../common/useHubBulkConfirmation', () => ({
    +  useHubBulkConfirmation: () => (config: typeof capturedBulkActionConfig) => {
    +    capturedBulkActionConfig = config;
    +  },
    +}));
    +
    +vi.mock('@ansible/ansible-ui-framework', async () => {
    +  const actual = await vi.importActual('@ansible/ansible-ui-framework');
    +  return {
    +    ...actual,
    +    usePageNavigate: () => vi.fn(),
    +  };
    +});
    +
    +const mockCollection: CollectionVersionSearch = {
    +  collection_version: {
    +    namespace: 'testns',
    +    name: 'testcol',
    +    version: '1.0.0',
    +    pulp_created: '2024-01-01T00:00:00Z',
    +    pulp_href: '/cv/1/',
    +    requires_ansible: '>=2.9',
    +    require_ansible: '>=2.9',
    +    description: '',
    +  },
    +  repository: {
    +    name: 'published',
    +    pulp_href: '/repositories/1/',
    +    latest_version_href: '/repositories/1/versions/1/',
    +    pulp_id: '1',
    +    pulp_last_updated: '',
    +    content_count: 0,
    +    gpgkey: '',
    +    description: '',
    +  },
    +  repository_version: '1',
    +  is_signed: false,
    +  is_deprecated: false,
    +} as CollectionVersionSearch;
    +
    +describe('useDeleteCollectionsFromRepository', () => {
    +  const taskUuid = 'aaaaaaaa-bbbb-cccc-dddd-eeeeeeeeeeee';
    +
    +  const server = setupServer(
    +    http.get('*/pulp/api/v3/repositories/ansible/ansible/', () =>
    +      HttpResponse.json({
    +        results: [
    +          {
    +            name: 'published',
    +            pulp_href: `/pulp/api/v3/repositories/ansible/ansible/${taskUuid}/`,
    +            latest_version_href: '/versions/1/',
    +          },
    +        ],
    +      })
    +    ),
    +    http.get('*/v3/plugin/ansible/search/collection-versions/', () =>
    +      HttpResponse.json({
    +        data: [mockCollection],
    +        links: { next: null },
    +      })
    +    ),
    +    http.post(`*/pulp/api/v3/repositories/ansible/ansible/${taskUuid}/modify/`, () =>
    +      HttpResponse.json({ task: `/pulp/api/v3/tasks/${taskUuid}/` })
    +    ),
    +    http.get(`*/pulp/api/v3/tasks/${taskUuid}/`, () => HttpResponse.json({ state: 'completed' }))
    +  );
    +
    +  beforeAll(() => {
    +    setHubApiPath('/api/galaxy');
    +    server.listen({ onUnhandledRequest: 'warn' });

    Most new Hub tests in this PR use onUnhandledRequest: 'error'. This file uses 'warn', so a missing or mistyped handler may not fail CI.

    Recommend 'error' here once handlers cover every request deleteCollectionFromRepository issues.

    lgalis lgalis commented on code on Oct 12, 2026 18:47 UTC
    Code Review
    frontend/hub/collections/hooks/useCollectionVersionSelector.test.tsx:1
    @@ -0,0 +1,33 @@
    +import { renderHook } from '@testing-library/react';
    +import { describe, expect, it, vi } from 'vitest';
    +import {
    +  useCollectionVersionColumns,
    +  useCollectionVersionFilters,
    +  useSelectCollectionVersionMulti,
    +  useSelectCollectionVersionSingle,
    +} from './useCollectionVersionSelector';
    +
    +vi.mock('../../common/ToolbarAsyncSelectFilterBuilder', () => ({

    Mocking ToolbarAsyncSelectFilterBuilder means these tests only smoke-check that hooks return objects/column headers—not version picker behavior or API wiring.

    Acceptable for coverage epic part 2, but consider a follow-up with MSW (or less mocking) if we want regression signal comparable to CollectionContents / useSignAllCollections.

    lgalis lgalis commented on code on Oct 12, 2026 18:47 UTC
    Code Review
    frontend/hub/common/api/hub-api-utils.test.tsx:1
    @@ -0,0 +1,225 @@
    +/* eslint-disable i18next/no-literal-string */
    +import { http, HttpResponse } from 'msw';
    +import { setupServer } from 'msw/node';
    +import { renderHook, waitFor } from '@testing-library/react';
    +import { afterAll, afterEach, beforeAll, describe, expect, it, vi } from 'vitest';
    +import { setHubApiPath } from './formatPath';
    +import {
    +  appendTrailingSlash,
    +  collectionKeyFn,
    +  getRepositoryBasePath,
    +  getRepoURL,
    +  hubAPIDelete,
    +  hubAPIPatch,
    +  hubAPIPost,
    +  hubAPIPut,
    +  parsePulpIDFromURL,
    +  parseTaskResponse,
    +  pulpHrefKeyFn,
    +  pulpIdKeyFn,
    +  serverlessURL,
    +  useRepositoryBasePath,
    +  waitForTask,
    +} from './hub-api-utils';
    +
    +const pulpUuid = 'aaaaaaaa-bbbb-cccc-dddd-eeeeeeeeeeee';
    +
    +const server = setupServer();
    +
    +beforeAll(() => {
    +  setHubApiPath('/api/galaxy');
    +  server.listen({ onUnhandledRequest: 'error' });
    +});
    +afterEach(() => server.resetHandlers());
    +afterAll(() => server.close());
    +
    +describe('hub-api-utils', () => {
    +  describe('utility helpers', () => {
    +    it('parsePulpIDFromURL extracts UUID segments', () => {
    +      expect(parsePulpIDFromURL(`/pulp/api/v3/tasks/${pulpUuid}/`)).toBe(pulpUuid);
    +      expect(parsePulpIDFromURL(null)).toBeNull();
    +    });
    +
    +    it('serverlessURL strips host from absolute pulp links', () => {
    +      expect(serverlessURL('/api/foo')).toBe('/api/foo');
    +      expect(serverlessURL('http://localhost:5001/api/foo?x=1#hash')).toBe('/api/foo?x=1#hash');
    +      expect(serverlessURL()).toBeUndefined();
    +    });
    +
    +    it('key functions and appendTrailingSlash', () => {
    +      expect(pulpIdKeyFn({ pulp_id: '1' })).toBe('1');
    +      expect(pulpHrefKeyFn({ pulp_href: '/href/' })).toBe('/href/');
    +      expect(
    +        collectionKeyFn({
    +          collection_version: { pulp_href: '/cv/', version: '1.0.0' },
    +          repository: { name: 'published' },
    +        })
    +      ).toBe('/cv/_published_1.0.0');
    +      expect(appendTrailingSlash('/api')).toBe('/api/');
    +      expect(appendTrailingSlash('/api/')).toBe('/api/');
    +    });
    +
    +    it('getRepoURL handles published and custom base paths', () => {
    +      vi.stubEnv('HUB_API_PREFIX', '/api/galaxy/pulp/api/v3');
    +      const origin = window.location.origin;
    +      expect(getRepoURL('published')).toBe(`${origin}/api/galaxy/pulp/api/v3/`);
    +      expect(getRepoURL('community', true)).toBe(
    +        `${origin}/api/galaxy/pulp/api/v3/content/community/`
    +      );
    +      vi.unstubAllEnvs();
    +    });
    +  });
    +
    +  describe('getRepositoryBasePath', () => {
    +    it('returns matching distribution base path when repository matches', async () => {
    +      server.use(
    +        http.get('*/pulp/api/v3/distributions/ansible/ansible/', ({ request }) => {
    +          const url = new URL(request.url);
    +          if (url.searchParams.get('name') === 'repo-a') {
    +            return HttpResponse.json({
    +              results: [{ base_path: 'repo-a', repository: '/repositories/1/' }],
    +            });
    +          }
    +          return HttpResponse.json({ results: [] });
    +        })
    +      );
    +
    +      const basePath = await getRepositoryBasePath(
    +        'repo-a',
    +        '/repositories/1/',
    +        ((key: string) => key) as Parameters<typeof getRepositoryBasePath>[2]
    +      );
    +      expect(basePath).toBe('repo-a');
    +    });
    +
    +    it('loads repository by name when pulp_href is empty', async () => {
    +      server.use(
    +        http.get('*/pulp/api/v3/repositories/ansible/ansible/', () =>
    +          HttpResponse.json({
    +            results: [{ name: 'repo-c', pulp_href: '/repositories/3/' }],
    +          })
    +        ),
    +        http.get('*/pulp/api/v3/distributions/ansible/ansible/', ({ request }) => {
    +          const url = new URL(request.url);
    +          if (url.searchParams.get('name') === 'repo-c') {
    +            return HttpResponse.json({
    +              results: [{ base_path: 'from-name', repository: '/repositories/3/' }],
    +            });
    +          }
    +          return HttpResponse.json({ results: [] });
    +        })
    +      );
    +
    +      const basePath = await getRepositoryBasePath(
    +        'repo-c',
    +        '',
    +        ((key: string) => key) as Parameters<typeof getRepositoryBasePath>[2]
    +      );
    +      expect(basePath).toBe('from-name');
    +    });
    +  });
    +
    +  describe('useRepositoryBasePath', () => {
    +    it('exposes base path from getRepositoryBasePath', async () => {
    +      server.use(
    +        http.get('*/pulp/api/v3/distributions/ansible/ansible/', () =>
    +          HttpResponse.json({
    +            results: [{ base_path: 'hook-path', repository: '/repositories/9/' }],
    +          })
    +        )
    +      );
    +
    +      const { result } = renderHook(() => useRepositoryBasePath('hook-repo', '/repositories/9/'));
    +
    +      await waitFor(() => {
    +        expect(result.current.loading).toBe(false);
    +      });
    +      expect(result.current.basePath).toBe('hook-path');
    +    });
    +  });
    +
    +  describe('waitForTask and parseTaskResponse', () => {
    +    it('waits until task completes successfully', async () => {
    +      let polls = 0;
    +      server.use(
    +        http.get(`*/pulp/api/v3/tasks/${pulpUuid}/`, () => {
    +          polls++;
    +          if (polls < 2) {
    +            return HttpResponse.json({ state: 'running' });
    +          }
    +          return HttpResponse.json({ state: 'completed' });
    +        })
    +      );
    +
    +      const result = await waitForTask(pulpUuid, undefined, 10, 1, 5);

    waitForTask(..., 10, 1, 5) polls every 1 ms. Hub CI is green, but this can flake on slower runners.

    Consider fake timers or a slightly larger interval if we see intermittent failures.

    lgalis lgalis commented on Oct 12, 2026 18:49 UTC
    Reviewer

    Strong MSW coverage overall (request, hub-api-utils, collection pages, sign-all modal). Four inline suggestions: tighten delete-hook assertions, use onUnhandledRequest: 'error' for that test, richer version-selector tests later, and slightly less aggressive waitForTask polling in tests.

    redhat-chai-bot redhat-chai-bot commented on Oct 12, 2026 21:48 UTC
    Reviewer

    Reviewed the current revision. The earlier review feedback is addressed or acknowledged, and all required checks are green. I found no additional actionable issues.

    ---
    AI-generated. Review for accuracy.

    lgalis lgalis approved these changes on Oct 12, 2026 21:59 UTC
    Approved Reviewer

    LGTM

    Reviewers
    Assignees
    acruzgon acruzgon
    Labels
    risk: low confidence: 85.3% reviewed
    Vouch Risk Breakdown
    AI-powered review risk analysis
    Change Risk
    Change Risk · Model 1 (XGBoost)
    Predicted defect probability (0.00–1.00) based on diff churn, modified sensitive files, and author risk history.
    Score: 60.6% (MEDIUM) · Higher = larger blast radius
    60.6%
    Review Confidence
    Review Confidence · Models 2 & 3
    Scrutiny score (0.00–1.00) combining DistilBERT semantic review depth with reviewer familiarity and session dwell time.
    Score: 85.3% · Lower = rushed or shallow review
    85.3%
    Residual Risk
    Residual Risk · Core Equation
    Residual = Change × (1 − Confidence)
    Unmitigated risk surviving review. ≥ 0.65 triggers an automated re-queue to protect production.
    Score: 8.9% · Safe to merge
    8.9%