Skip to content

tests: Add API tests for sorting by various categories on the Search page#918

Open
matejnesuta wants to merge 3 commits intoguacsec:mainfrom
matejnesuta:api-sorting
Open

tests: Add API tests for sorting by various categories on the Search page#918
matejnesuta wants to merge 3 commits intoguacsec:mainfrom
matejnesuta:api-sorting

Conversation

@matejnesuta
Copy link
Contributor

@matejnesuta matejnesuta commented Feb 5, 2026

Adding this, as it is a more convenient and less flaky approach of testing the sorting than directly in the UI.

Summary by Sourcery

Add API-level tests to verify sorting behavior for PURLs, vulnerabilities, and SBOMs across multiple sortable fields.

Tests:

  • Add PURL sorting tests covering name, namespace, and version in both ascending and descending orders.
  • Add vulnerability sorting tests validating ID, CVSS score, and published date ordering for ascending and descending sort directions.
  • Add SBOM sorting tests that assert correct name and published-date ordering for ascending and descending sorts.

@sourcery-ai
Copy link
Contributor

sourcery-ai bot commented Feb 5, 2026

Reviewer's Guide

Adds API-level end-to-end tests to validate sorting behavior for PURLs, vulnerabilities, and SBOMs across multiple sort keys and directions, preferring API checks over UI-based sorting tests for stability.

File-Level Changes

Change Details Files
Add API tests to validate PURL sorting across name, namespace, and version in both ascending and descending order.
  • Introduce a new Playwright test.describe block for PURL sorting validation using the /api/v2/purl endpoint.
  • Add tests that assert successful responses and non-empty results when sorting by name, namespace, and version in ascending order.
  • Add descending sort tests that compare first items between asc/desc or explicitly parse PURL components to ensure the ordering meaningfully differs.
e2e/tests/api/features/purl.ts
Add API tests to validate vulnerability sorting across ID, CVSS score, and published date, including basic order verification for numeric and date fields.
  • Introduce a new Playwright test.describe block for vulnerability sorting validation using the /api/v2/vulnerability endpoint.
  • Add tests that verify the API accepts sort options for id and base_score and returns non-empty results for both ascending and descending directions.
  • Implement assertions that CVSS average_score and published date fields are actually ordered correctly (ascending/descending) while handling null values safely.
e2e/tests/api/features/vulnerability.ts
Add API tests to validate SBOM sorting by name and published date with strict order checks.
  • Add tests that call /api/v2/sbom with sort parameters for name and published, verifying 200 responses and non-zero totals.
  • Implement locale-insensitive string sorting checks for SBOM names in both ascending and descending order by comparing to a locally sorted copy.
  • Implement date-based ascending and descending checks for SBOM published timestamps using Date comparisons.
e2e/tests/api/features/sboms.ts

Tips and commands

Interacting with Sourcery

  • Trigger a new review: Comment @sourcery-ai review on the pull request.
  • Continue discussions: Reply directly to Sourcery's review comments.
  • Generate a GitHub issue from a review comment: Ask Sourcery to create an
    issue from a review comment by replying to it. You can also reply to a
    review comment with @sourcery-ai issue to create an issue from it.
  • Generate a pull request title: Write @sourcery-ai anywhere in the pull
    request title to generate a title at any time. You can also comment
    @sourcery-ai title on the pull request to (re-)generate the title at any time.
  • Generate a pull request summary: Write @sourcery-ai summary anywhere in
    the pull request body to generate a PR summary at any time exactly where you
    want it. You can also comment @sourcery-ai summary on the pull request to
    (re-)generate the summary at any time.
  • Generate reviewer's guide: Comment @sourcery-ai guide on the pull
    request to (re-)generate the reviewer's guide at any time.
  • Resolve all Sourcery comments: Comment @sourcery-ai resolve on the
    pull request to resolve all Sourcery comments. Useful if you've already
    addressed all the comments and don't want to see them anymore.
  • Dismiss all Sourcery reviews: Comment @sourcery-ai dismiss on the pull
    request to dismiss all existing Sourcery reviews. Especially useful if you
    want to start fresh with a new review - don't forget to comment
    @sourcery-ai review to trigger a new review!

Customizing Your Experience

Access your dashboard to:

  • Enable or disable review features such as the Sourcery-generated pull request
    summary, the reviewer's guide, and others.
  • Change the review language.
  • Add, remove or edit custom review instructions.
  • Adjust other review settings.

Getting Help

Copy link
Contributor

@sourcery-ai sourcery-ai bot left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Hey - I've found 4 issues, and left some high level feedback:

  • The ascending/descending tests for PURLs, vulnerabilities, and SBOMs repeat a lot of boilerplate (request params, status checks, sort comparison loops); consider extracting shared helpers (e.g., fetchSorted, expectSortedAscending/Descending) to make the tests shorter and easier to maintain.
  • In the vulnerability CVSS score tests you sort by base_score but assert against average_score; if both exist in the API this mismatch could make the tests misleading, so it would be clearer to validate the same field that is used in the sort parameter.
  • The SBOM published-date sort tests assume item.published is always non-null, unlike the vulnerability date tests which explicitly filter out nulls; aligning the SBOM tests to handle potential null published dates would reduce flakiness if such data exists.
Prompt for AI Agents
Please address the comments from this code review:

## Overall Comments
- The ascending/descending tests for PURLs, vulnerabilities, and SBOMs repeat a lot of boilerplate (request params, status checks, sort comparison loops); consider extracting shared helpers (e.g., `fetchSorted`, `expectSortedAscending/Descending`) to make the tests shorter and easier to maintain.
- In the vulnerability CVSS score tests you sort by `base_score` but assert against `average_score`; if both exist in the API this mismatch could make the tests misleading, so it would be clearer to validate the same field that is used in the `sort` parameter.
- The SBOM published-date sort tests assume `item.published` is always non-null, unlike the vulnerability date tests which explicitly filter out nulls; aligning the SBOM tests to handle potential null published dates would reduce flakiness if such data exists.

## Individual Comments

### Comment 1
<location> `e2e/tests/api/features/purl.ts:41-50` </location>
<code_context>
 });
+
+test.describe("PURL sorting validation", () => {
+  test("Sort PURLs by name ascending", async ({ axios }) => {
+    const response = await axios.get("/api/v2/purl", {
+      params: {
+        offset: 0,
+        limit: 100,
+        sort: "name:asc",
+      },
+    });
+
+    expect(response.status).toBe(200);
+    expect(response.data.total).toBeGreaterThan(0);
+    expect(response.data.items.length).toBeGreaterThan(0);
+
+    // Verify the sort parameter is accepted and returns data
+    // Note: We don't validate exact sort order because database collation
+    // may differ from JavaScript's string comparison
+  });
</code_context>

<issue_to_address>
**suggestion (testing):** The ascending name sort test only checks that data is returned, not that the sort actually works.

This only asserts that `sort=name:asc` returns data, so it won’t catch regressions where the sort parameter is ignored. You can still check ordering by asserting that the extracted `name` values are monotonic, or by comparing them to a locally sorted copy using the same comparison logic as the backend. Without that, the test provides little validation of sorting behavior.
</issue_to_address>

### Comment 2
<location> `e2e/tests/api/features/purl.ts:59-68` </location>
<code_context>
+  test("Sort PURLs by name descending", async ({ axios }) => {
</code_context>

<issue_to_address>
**suggestion (testing):** Comparing only the first item between asc/desc is a fragile way to validate sorting.

`expect(descFirst).not.toEqual(ascFirst);` can still pass even if sorting is wrong (e.g., many items share the same name or the backend only partially sorts). Instead, extract all names, build full asc/desc arrays, and assert that one is the reverse of the other (or at least that both sequences are monotonic in opposite directions) to more reliably verify the sort behavior.
</issue_to_address>

### Comment 3
<location> `e2e/tests/api/features/purl.ts:140-143` </location>
<code_context>
+      return match ? match[1] : null;
+    };
+
+    const descFirst = getNamespace(response.data.items[0].purl);
+    const ascFirst = getNamespace(ascResponse.data.items[0].purl);
+
+    if (descFirst && ascFirst) {
+      // First item should be different between asc and desc
+      expect(descFirst).not.toEqual(ascFirst);
</code_context>

<issue_to_address>
**issue (testing):** The namespace descending test silently passes when all namespaces are null or unparsable.

Since the assertion is guarded by `if (descFirst && ascFirst)`, the test becomes a no-op (but still passes) when either extracted namespace is falsy. If all items can have null/empty namespaces, the sort behavior isn’t actually tested. You could either filter to items with non-null namespaces and assert on those, or first assert that at least one non-null namespace exists before comparing asc/desc results.
</issue_to_address>

### Comment 4
<location> `e2e/tests/api/features/vulnerability.ts:25-34` </location>
<code_context>
 });
+
+test.describe("Vulnerability sorting validation", () => {
+  test("Sort vulnerabilities by ID ascending", async ({ axios }) => {
+    const response = await axios.get("/api/v2/vulnerability", {
+      params: {
+        offset: 0,
+        limit: 100,
+        sort: "id:asc",
+      },
+    });
+
+    expect(response.status).toBe(200);
+    expect(response.data.total).toBeGreaterThan(0);
+    expect(response.data.items.length).toBeGreaterThan(0);
+
+    // Verify the sort parameter is accepted and returns data
+    // Note: We don't validate exact sort order because database collation
+    // may differ from JavaScript's string comparison
+  });
</code_context>

<issue_to_address>
**suggestion (testing):** ID ascending vulnerability test doesn’t assert any ordering, so it won’t catch sorting regressions.

Right now this only checks that the endpoint returns data; it would still pass if `sort=id:asc` were ignored. Please also assert on the ordering by extracting the identifier/canonical ID field and verifying the list is non‑decreasing, or matches a locally sorted copy, so the test actually detects sorting regressions.
</issue_to_address>

Sourcery is free for open source - if you like our reviews please consider sharing them ✨
Help me be more useful! Please click 👍 or 👎 on each comment and I'll use the feedback to improve your reviews.

@codecov
Copy link

codecov bot commented Feb 5, 2026

Codecov Report

✅ All modified and coverable lines are covered by tests.
✅ Project coverage is 64.91%. Comparing base (93fc4ab) to head (7a8f58b).

Additional details and impacted files
@@            Coverage Diff             @@
##             main     #918      +/-   ##
==========================================
+ Coverage   64.11%   64.91%   +0.80%     
==========================================
  Files         195      195              
  Lines        3338     3338              
  Branches      751      751              
==========================================
+ Hits         2140     2167      +27     
+ Misses        908      876      -32     
- Partials      290      295       +5     

☔ View full report in Codecov by Sentry.
📢 Have feedback on the report? Share it here.

🚀 New features to boost your workflow:
  • ❄️ Test Analytics: Detect flaky tests, report on failures, and find test suite problems.
  • 📦 JS Bundle Analysis: Save yourself from yourself by tracking and limiting bundle sizes in JS merges.

@matejnesuta matejnesuta changed the title test: Add API tests for sorting by various categories on the Search page tests: Add API tests for sorting by various categories on the Search page Feb 16, 2026
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

Projects

Status: No status

Development

Successfully merging this pull request may close these issues.

1 participant