tests: Add API tests for sorting by various categories on the Search page#918
tests: Add API tests for sorting by various categories on the Search page#918vobratil merged 5 commits intoguacsec:mainfrom
Conversation
Reviewer's GuideAdds 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
Tips and commandsInteracting with Sourcery
Customizing Your ExperienceAccess your dashboard to:
Getting Help
|
There was a problem hiding this comment.
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_scorebut assert againstaverage_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 thesortparameter. - The SBOM published-date sort tests assume
item.publishedis 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>Help me be more useful! Please click 👍 or 👎 on each comment and I'll use the feedback to improve your reviews.
Codecov Report✅ All modified and coverable lines are covered by tests. Additional details and impacted files@@ Coverage Diff @@
## main #918 +/- ##
==========================================
+ Coverage 66.50% 67.21% +0.70%
==========================================
Files 218 218
Lines 3828 3828
Branches 873 873
==========================================
+ Hits 2546 2573 +27
+ Misses 948 916 -32
- Partials 334 339 +5 ☔ View full report in Codecov by Sentry. 🚀 New features to boost your workflow:
|
vobratil
left a comment
There was a problem hiding this comment.
I would say that this PR looks pretty good, no major changes needed. The only thing I would like to ask for is moving the helpers file, so that we keep at least some order in the repo. And then there are my questions about why we are okay with the basic sort in some places and actually do a proper validation elsewhere.
| // Handle null values | ||
| if (a === null && b === null) return 0; | ||
|
|
||
| if (order === "ascending") { |
There was a problem hiding this comment.
Just a small nitpick, but for better readability, I would make this an if else block or specifically state the order for both options.
| /** | ||
| * Helper to validate that numeric scores in an array are sorted in the specified order | ||
| */ | ||
| export function validateNumericSorting( |
There was a problem hiding this comment.
Again, just a nitpick, but this method and validateDateSorting could probably share a big part of the body, since the only difference seems to be in the sorted data type.
| ) { | ||
| const [ascResponse, descResponse] = await Promise.all([ | ||
| axios.get(endpoint, { | ||
| params: { offset: 0, limit: 100, sort: `${sortField}:asc` }, |
There was a problem hiding this comment.
Oh, this is neat, I should start writing my requests like this.
| validateSortDirectionDiffers, | ||
| } from "../helpers/sorting-helpers"; | ||
|
|
||
| test.describe("Advisory sorting validation", () => { |
There was a problem hiding this comment.
Once again, I know that this is not really important to your PR, but we should probably agree on how to name the tests, so that the test results are a little easier to read. It's already getting messy and we haven't even reached 100 tests.
e2e/tests/api/features/advisory.ts
Outdated
|
|
||
| test.describe("Advisory sorting validation", () => { | ||
| test("Sort advisories by ID ascending", async ({ axios }) => { | ||
| await testBasicSort(axios, "/api/v2/advisory", "id", "asc"); |
There was a problem hiding this comment.
So why are we not running actual sorting checks here and in purl.ts, like we do in sboms.ts and vulnerability.ts?
There was a problem hiding this comment.
Yeah, that was a mistake. I fixed it.
vobratil
left a comment
There was a problem hiding this comment.
@matejnesuta Alright, thank you for the changes! I think that it's good to go, now.
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: