diff --git a/README.md b/README.md index ab45aef0..7dd84412 100644 --- a/README.md +++ b/README.md @@ -21,7 +21,7 @@ It is designed for teams that want more than "a newer tag exists". The app keeps - **Observed Images**: repositories and tags discovered from Docker Hub account data - **Runtime Containers**: live workload inventory with update and vulnerability state - **Docker Instances**: configured engines plus usage history -- **Shared Base Images**: base-image reuse across observed images +- **Base Images**: base-image reuse across observed images - **Scan History**: recent background activity and outcomes ## Runtime requirements diff --git a/docs/areas/README.md b/docs/areas/README.md index 01ebc486..3238624e 100644 --- a/docs/areas/README.md +++ b/docs/areas/README.md @@ -41,6 +41,6 @@ operator or another component can rely on — formats, limits, error behavior, g | [Scan engine](scan-engine.md) | Background jobs and their intervals, dynamic own-image interval, overlap rules, scan runs, crash recovery, retention and cleanup, single-instance assumption | What a scan evaluates (the feature areas) | | [Web UI](web-ui.md) | Pages and routes, what each page shows and triggers, dashboard refresh, error and not-found pages, theme | How the shown values are computed (the feature areas) | | [Detail pages](detail-pages.md) | Layout and contents of the detail pages: header, details column, panels in order, resource history charts | Routes, actions table, shared display and errors (Web UI); how values are computed (the feature areas) | -| [List pages](list-pages.md) | Layout and contents of the list pages, so far Vulnerabilities: header, severity overview, filters, table, expanded rows, pager | Routes, actions table, shared display and errors (Web UI); how values are computed (the feature areas) | +| [List pages](list-pages.md) | Layout and contents of the list pages (My Images, Observed Images, Base Images, Docker Instances, Scan History, Vulnerabilities): headers, panels, columns, shared vulnerability cell, form, meter, cards | Routes, actions table, shared display and errors (Web UI); how values are computed (the feature areas) | | [Telemetry](telemetry.md) | Logs, traces and metrics, OTLP export, activity and instrument names, inventory gauges, what never reaches telemetry | Deployment of the observability stack (`INSTALL.md`) | diff --git a/docs/areas/list-pages.md b/docs/areas/list-pages.md index 7ba0b89b..bf35c14c 100644 --- a/docs/areas/list-pages.md +++ b/docs/areas/list-pages.md @@ -2,12 +2,100 @@ ## Scope -The layout and contents of the list pages, so far the Vulnerabilities page: its header, the severity overview, the -filters, the table, the expanded rows and the pager. Users rely on it to see how the active advisories are spread -over the severities and to find the ones that matter. +The layout and contents of the list pages My Images, Observed Images, Base Images, Docker Instances, Scan History and +Vulnerabilities: header, panels, columns and cell variants, the registration form, the memory meter, the single-instance +panel, the shared vulnerability cell and the cards below 960 px. Runtime Containers uses the shared cell too. Users +rely on them to see what is running, what was scanned and what needs attention. ## Behavior +### All list pages + +- Each page shows the page header with its title and one sentence, without an eyebrow, then one panel per list with + its title and a muted meta text on the right, and no description line. The table fills its panel to the edges. + Column heads are sentence case. Names that lead to a detail page are semibold links. +- Every scan status is a dot with its status text in the shared tone (`Succeeded` green, `Partial` orange, `Failed` + red, `Running` blue); any other status, such as `NotScanned`, is neutral. Every other state is a chip. +- While a page loads, its panel shows the table skeleton with the panel title. A list without items shows its empty-state + text in a panel, with no meta text and no table. A failed first load shows the alert of + [Web UI](web-ui.md#limits-and-errors) in place of the skeleton. +- A count in a meta text is singular for one (`1 image`, `1 container`). + +### My Images + +- Header `My Images`: `Own images discovered from the configured Docker Hub account; running ones come first.`. The panel + title is the configured Docker Hub user name, trimmed, or `Images from Docker account` without one, also on the + skeleton. The meta reads `{n} images · {r} running`, where `r` counts the images with at least one running container. +- Columns: *Name* (link to the image, the description muted below it when there is one), *Image* (the reference), *Latest + scan* (indicator, the scan message muted below it when there is one), *Running* (`{n} containers`, `1 container`, or + muted `Not running`), *Base runtime* (the alert summary in semibold high-severity text, or muted `No runtime + warning`) and *Vulnerabilities* ([shared cell](#vulnerability-cell)). + +### Observed Images + +- Header `Observed Images`: `Manually tracked images. Register a registry reference to scan it right away.`. +- The panel `Register image` shows a label above each of the fields `Name`, `Image reference` (placeholder + `registry/repository:tag`) and `Description` (with a muted `(optional)`), and the primary button `Register and scan` + in one row from 960 px, in the proportions 1 : 2 : 2 : auto. Each label is tied to its input. The button is offset by + the label height, so a validation message under a field lengthens only that field. Below 960 px the fields stack, + below 600 px the button takes the full width. The formats hint stands muted below the row. Validation, the busy + button, the error alert with its `Open own image` link and the move to the new image's page are described in + [Web UI](web-ui.md#actions). +- The panel `Manual images` has the meta `{n} images`. Its columns are *Name*, *Image* and *Latest scan* as on My + Images, *Updates* (the number of active update findings in medium weight, or `—`), *Base runtime* (the hint summary + muted, or `—`) and *Vulnerabilities* (shared cell). An empty list or a failed load shows its text or alert inside + this panel, and the form stays usable. + +### Base Images + +- Header `Base Images`: `Base images shared by two or more enabled images or containers, with the images built on + them, the containers that run them and their vulnerability status.`; the browser tab reads `Base Images`. The panel + `Base image overview` has the meta `{n} base images`. +- Columns: *Base image* (semibold), *Parent images* (one plain reference per line, no links, or muted `No parent image + recorded`), *Runtime containers* (one link per line to the container's page with the instance name muted beside it, + or muted `No linked container`), *Observed images* (the count) and *Vulnerabilities*: the chips of the shared cell, + below them the muted line `{count} active · {source}` and the assessment message when there is one. This cell has no + rescan button and no per-severity counts. + +### Docker Instances + +- Header `Docker Instances`: `Configured Docker endpoints with their connection, latest runtime scan and current + resource usage.`. The panel `Configured instances` has the meta `{n} instances · {c} containers`, `c` being the sum of + the instances' container counts. +- Columns: *Name* (link), *Endpoint* (masked as in [Web UI](web-ui.md), 13 px monospace, breaks anywhere), *Connection*, + *Latest scan* (indicator, the completion time in UTC muted below it; none for an instance never scanned), *CPU*, + *Memory*, *Network* (one line) and *Containers*. +- *Memory* shows the value, and below it a meter 6 px high and at most 140 px wide announced as `{p} percent of host + memory`, only when the usage and a host memory total above 0 are known. `p` is the share rounded to a whole percent, + half away from zero; above 100 the bar is full and `p` stays real. Without a total the cell shows the bytes alone, and + `n/a` without usage. +- With exactly one instance whose detail has loaded, a panel above the table has the instance name as title and its + endpoint as meta, and shows the cells `CPU`, `Memory` and `Network` with their current value and history chart; the + table then hides those three columns. Without stored history the cells show no chart and the text `No resource + history is currently stored for this Docker instance.` stands below them. + +### Scan History + +- Header `Scan History`: `Image, runtime container and vulnerability scan runs with trigger, target and outcome.`. The + panel `Latest 20 runs` has as meta the counts above 0 of the listed runs in the order succeeded, running, pending, + partial, failed, joined by ` · ` (`17 succeeded · 1 running · 1 partial · 1 failed`); runs with another status are not + counted. +- Columns: *Type*, *Status* (indicator), *Trigger* (muted), *Target*, *Started* (muted, tabular figures) and *Error*: + the stored message, red for a `Failed` run and muted otherwise. +- While vulnerability scanning is enabled the header holds the primary button `Refresh vulnerabilities` (`Refreshing + vulnerabilities...` while busy), with `Next scheduled vulnerability refresh: {value}` in 13 px muted text to its left + when scanning is scheduled. A failed refresh shows an error alert between header and panel. + +### Vulnerability cell + +- One component serves Runtime Containers, My Images and Observed Images. With active findings it shows a chip of the + highest active severity, beside it a chip of the status when that is not `Findings detected`, and below the line + `{count} active · {n} critical, …` in the order critical, high, medium, low, unknown (`Unknown` is in the low tone). + Without active findings only the status chip shows, in the tone of its status. +- Then follow `Checked {UTC time}` or `Never scanned`, the rescan error when there is one, and the chip `Base images + affected` with its summary when base images have active findings. The rescan icon button stands on the right. +- The stored assessment message is not shown in this cell; the detail pages show it. + ### Vulnerabilities page header and panel - The page header shows the title `Vulnerabilities` and the description `Active advisories across all images, with the @@ -50,9 +138,14 @@ over the severities and to find the ones that matter. ### Layout -- Below 960 px each row is a card that keeps its expand button, and the filter field and the severity select each - take the full width of the panel header. Long values, such as a package name or an image reference, wrap - inside the card instead of widening it. From 960 px the field is 260 px and the select 150 px wide. +- Below 960 px each row of every list is a card with a label before each value; multi-line cells (name, scan, base + runtime, vulnerabilities, parent images, containers, memory) stack their lines, and the rescan control of the + vulnerability cell takes the full width of its card. On Vulnerabilities the card keeps its expand button, and the + filter field and the severity select each take the full width of the panel header. From 960 px the tables of My + Images, Observed Images, Base Images, Docker Instances and Scan History are fixed-layout and never wider than their + panel, with the columns in fixed shares; on Vulnerabilities the field is 260 px and the select 150 px wide. +- Long values, such as a package name, an image reference with a digest, a stored error or an endpoint, break anywhere + and wrap inside their cell or card instead of widening the page. ## Limits and errors @@ -61,6 +154,8 @@ over the severities and to find the ones that matter. ## Related decisions +- [`decisions/0082-the-runtime-container-list-names-the-highest-active-severity-and-keeps-a-failed-checks-status-beside-it.md`](../decisions/0082-the-runtime-container-list-names-the-highest-active-severity-and-keeps-a-failed-checks-status-beside-it.md) + — the shared cell names the highest active severity and keeps a failed check's status beside it. - [`decisions/0084-the-vulnerabilities-page-pages-its-advisories-itself-and-draws-its-own-pager.md`](../decisions/0084-the-vulnerabilities-page-pages-its-advisories-itself-and-draws-its-own-pager.md) — the page keeps the page index and size and draws its own pager. @@ -68,4 +163,4 @@ over the severities and to find the ones that matter. - Routes, the actions table, shared display and error behavior in [Web UI](web-ui.md). - How severities, CVSS scores and fix status are computed in [Vulnerabilities](vulnerabilities.md). -- The detail pages in [Detail pages](detail-pages.md); the other list pages join this area when they are converted. \ No newline at end of file +- The detail pages in [Detail pages](detail-pages.md). \ No newline at end of file diff --git a/docs/areas/web-ui.md b/docs/areas/web-ui.md index d7da12d0..7621044a 100644 --- a/docs/areas/web-ui.md +++ b/docs/areas/web-ui.md @@ -27,8 +27,8 @@ to read the state the other areas compute and to start manual scans; it computes `DockerUpdateGuard:DockerHub:UserName` and `DockerUpdateGuard:DockerHub:Pat` are set; *Base Images* only when at least one shared base image exists. Both conditions are evaluated once per page load. The pages stay reachable by their routes either way. When the check for shared base images fails, *Base Images* is hidden. -- When the first load of the Dashboard, My Images, Observed Images, Runtime Containers, Docker Instances, Shared Base - Images, Vulnerabilities or Scan History page fails, the page shows an error alert in place of its loading skeleton +- When the first load of the Dashboard, My Images, Observed Images, Runtime Containers, Docker Instances, Base Images, + Vulnerabilities or Scan History page fails, the page shows an error alert in place of its loading skeleton (on Observed Images inside the *Manual images* section, the registration form stays usable) until a later load succeeds. A page whose load needs two answers (Docker Instances, Scan History) shows no part of its data when either fails. A reload that fails after a successful load keeps what is shown. @@ -37,8 +37,7 @@ to read the state the other areas compute and to start manual scans; it computes - Timestamps are shown in UTC as `yyyy-MM-dd HH:mm UTC`, the same for every browser and independent of the time zone and culture of the server process. The resource chart labels are UTC too: the first and the last label read `MM-dd HH:mm UTC`, the visible labels between them `HH:mm`. -- The scan status chips of the scan history, observed image, My Images and image detail - pages share one color mapping: `Succeeded` green, `Partial` and `Pending` orange, `Failed` red, `Running` blue; any +- The scan status chips of the image detail pages share one color mapping: `Succeeded` green, `Partial` and `Pending` orange, `Failed` red, `Running` blue; any other value, such as `NotSet` or `NotScanned`, stays neutral. The chip text is the status name. - While a page loads its data it shows placeholder skeletons; a list without data shows an explanatory empty state. A detail page (Docker instance, own image, observed image, runtime container) whose record does not exist shows a @@ -62,7 +61,7 @@ to read the state the other areas compute and to start manual scans; it computes - The status of a vulnerability assessment, `Findings detected`, takes the tone of its highest severity with at least one finding (critical, high, medium or low); without a counted known severity it is low. Any other status ignores the severities, so `Failed` stays red. A severity chip uses the tone of its own severity; an unknown one is low. -- The runtime container list shows the highest active severity as chip (`Unknown` in the low tone), beside it the status chip for a status other than `Findings detected`, and the count line `{count} active · {n} critical, …` in the order critical, high, medium, low, unknown. +- The vulnerability cell of the runtime container, My Images and Observed Images lists is described in [List pages](list-pages.md#vulnerability-cell). - The severity bar shows the active findings as segments in the order critical, high, medium, low, each as wide as its count and at least 4 px; findings of an unknown severity count as low. A legend lists the counts and the bar is announced as `Severity distribution: ...`. Without findings nothing is shown. @@ -76,17 +75,17 @@ to read the state the other areas compute and to start manual scans; it computes | Route | Page | Shows | | --- | --- | --- | | `/` | Dashboard | What needs attention: a headline sentence with the counts, the containers with an available update, the advisories of running containers, the own images with a base runtime warning, the last 10 scans and a strip of inventory counts; a configuration hint for vulnerability scanning (see [Dashboard](#dashboard)) | -| `/my-images` | My Images | Images discovered from the configured Docker Hub account, with latest scan status and message, number of running containers, derived-runtime hint and vulnerability status | +| `/my-images` | My Images | [List pages](list-pages.md#my-images) | | `/my-images/{id}` | My Image details | One observed image: reference, latest scan, derived-runtime hint, running containers, base image chain, update findings with tag candidates, and — when there are any — vulnerability findings and its 20 most recent scan runs | -| `/observed-images` | Observed Images | The registration form and the manually registered images with latest scan, active update findings, derived-runtime hint and vulnerability status | +| `/observed-images` | Observed Images | [List pages](list-pages.md#observed-images) | | `/observed-images/{id}` | Observed Image detail | One observed image: reference, latest scan, whether it is an own or a manual image, derived-runtime hint, running containers (own images only), base image chain, vulnerability findings and update findings with tag candidates; no scan history | | `/runtime-containers` | Runtime Containers | A panel `Container inventory` with the meta text `{n} containers on {m} Docker instances`; seven columns: container (name, tag with the version an alias resolves to, link to the own image), instance, CPU, memory and network usage with a trend of up to the 12 latest samples, update state with the available version, and vulnerabilities (chip, count line, last check, rescan, base image warning); [0082](../decisions/0082-the-runtime-container-list-names-the-highest-active-severity-and-keeps-a-failed-checks-status-beside-it.md) | | `/runtime-containers/{instanceId}/{containerId}` | Runtime Container detail | One container, laid out as [Detail pages](detail-pages.md) describes; with Portainer enabled for its Docker instance, a *Container actions* panel with the 20 most recent action runs of the container | -| `/docker-instances` | Docker Instances | Configured Docker instances with endpoint, connection kind, latest runtime scan status and time, current resource usage and number of containers; with exactly one instance its current usage and usage history are shown on this page directly | +| `/docker-instances` | Docker Instances | [List pages](list-pages.md#docker-instances) | | `/docker-instances/{id}` | Docker Instance detail | The containers currently observed on one instance with linked own image and resource usage | -| `/base-images` | Shared Base Images | Base images used by two or more enabled images or containers, with the images built on them, the containers and number of enabled observed images that use them, and their vulnerability status | +| `/base-images` | Base Images | [List pages](list-pages.md#base-images) | | `/vulnerabilities` | Vulnerabilities | Active advisories across all images, one row per advisory, with severity and CVSS score, affected packages, fixed versions, number of affected images and running containers; a row expands to the affected images; a severity bar of all advisories ([List pages](list-pages.md)) | -| `/scan-history` | Scan History | The 20 most recent scan runs (observed image scans, runtime container scans and vulnerability refreshes, [Scan runs](scan-engine.md#scan-runs)) with type, status, trigger, target, start time and error message | +| `/scan-history` | Scan History | [List pages](list-pages.md#scan-history) | | `/error` | Error | "Unexpected error" — the request could not be completed | | `/not-found` | Not found | "Page not found" with a link back to the dashboard | @@ -296,7 +295,7 @@ never their values. | Observed Images | `Loading the observed images failed` | `LoadObservedImages` | | Runtime Containers | `Loading the containers failed` | `LoadRuntimeContainers` | | Docker Instances | `Loading the Docker instances failed` | `LoadDockerInstances` | - | Shared Base Images | `Loading the shared base images failed` | `LoadSharedBaseImages` | + | Base Images | `Loading the shared base images failed` | `LoadSharedBaseImages` | | Vulnerabilities | `Loading the vulnerabilities failed` | `LoadVulnerabilities` | | Scan History | `Loading the scan history failed` | `LoadScanHistory` | @@ -339,8 +338,6 @@ never their values. map to tones in one mapping, beside the chip colors of unconverted pages. - [0080](../decisions/0080-the-dashboard-counts-the-containers-advisories-and-own-images-it-lists.md) — The dashboard counts the containers, advisories and own images it lists. -- [0082](../decisions/0082-the-runtime-container-list-names-the-highest-active-severity-and-keeps-a-failed-checks-status-beside-it.md) — The - runtime container list names the highest active severity and keeps a failed check's status beside it. - [0083](../decisions/0083-resource-histories-are-drawn-as-svg-sparklines-from-one-shared-path-builder.md) — Resource histories share one path builder. diff --git a/docs/decisions/0082-the-runtime-container-list-names-the-highest-active-severity-and-keeps-a-failed-checks-status-beside-it.md b/docs/decisions/0082-the-runtime-container-list-names-the-highest-active-severity-and-keeps-a-failed-checks-status-beside-it.md index 72153dc7..57c7683b 100644 --- a/docs/decisions/0082-the-runtime-container-list-names-the-highest-active-severity-and-keeps-a-failed-checks-status-beside-it.md +++ b/docs/decisions/0082-the-runtime-container-list-names-the-highest-active-severity-and-keeps-a-failed-checks-status-beside-it.md @@ -1,9 +1,9 @@ -# 0082: The runtime container list names the highest active severity and keeps a failed check's status beside it +# 0082: The list pages name the highest active severity and keep a failed check's status beside it - **Status:** Accepted -- **Date:** 2026-11-30 -- **Area:** Web UI -- **Source:** Issue #455 +- **Date:** 2026-12-01 +- **Area:** List pages +- **Source:** Issue #455, Issue #458 - **Supersedes:** — ## Context @@ -15,24 +15,31 @@ assessment status and its active findings. A failed or unavailable check leaves while the status turns `Failed` or `Unavailable`. Until now the count line showed the stored assessment message, which after such a check is the failure message, so the failure was visible. A severity chip alone would hide it. +Issue #458 makes the #455 cell a shared component for My Images, Observed Images and Runtime Containers, but words its +count line `{count} active · {message}`; on Base Images it asks for one chip, the highest severity or the status. Both +image lists showed the compact severity chips and the message line until then. + ## Options considered 1. **Severity chip, and the status chip beside it whenever the status is not `Findings detected` (chosen)** — the failed check stays visible in the row as a red `Failed` chip; such rows show two chips. 2. **Severity chip only** — the mockup's look in every row, but after a failed check the row looks as if the findings - were current, and nothing says the check failed. + were current, and nothing says the check failed. On Base Images, as #458 words it, the same defect. 3. **Status chip only, in the tone of the highest severity** — one chip per row, but `Findings detected` says less than the severity the issue asks for, and a failed check would still lose its severity. 4. **Keep the assessment message as the count line** — shows the failure text, but the line no longer carries the - severities the removed chips showed. + severities the removed chips showed. In #458 this is the issue's wording of the shared cell; it would change the + Runtime Containers list that #455 just settled and drop the breakdown from all three lists. ## Decision -With active findings the Vulnerabilities cell of the runtime container list shows the highest active severity as its -chip and the severity counts as its count line; a status other than `Findings detected` is shown as a second chip -beside it. The texts, tones and order are stated in [Web UI](../areas/web-ui.md). +With active findings the Vulnerabilities cell of the runtime container, My Images and Observed Images lists — one +shared component — shows the highest active severity as its chip and the severity counts as its count line; a status +other than `Findings detected` is shown as a second chip beside it. The Base Images list shows the same chips with its +own `{count} active · {source}` line. The texts and order are stated in [List pages](../areas/list-pages.md), the tones in [Web UI](../areas/web-ui.md). ## Consequences -The stored assessment message no longer appears on the list; the detail page still shows it. The pages converted later -in #450 (My Images, Observed Images) can take the same cell; whether they do is decided in their issues. +The stored assessment message no longer appears on the runtime container, My Images and Observed Images lists; their +detail pages still show it. The Base Images list keeps the message but loses the per-severity counts of its compact +chips. One rule (status beside the severity) decides the chips of all four lists, so it changes in one place. \ No newline at end of file diff --git a/docs/decisions/README.md b/docs/decisions/README.md index af1b2319..aaa466c0 100644 --- a/docs/decisions/README.md +++ b/docs/decisions/README.md @@ -147,7 +147,7 @@ once in the [area document](../areas/README.md) of the record's area, and the re | [0079](0079-statuses-map-to-tones-in-one-mapping-beside-the-chip-colors-of-unconverted-pages.md) | Statuses map to tones in one mapping, beside the chip colors of unconverted pages | Accepted | 2026-11-28 | | [0080](0080-the-dashboard-counts-the-containers-advisories-and-own-images-it-lists.md) | The dashboard counts the containers, advisories and own images it lists | Accepted | 2026-11-29 | | [0081](0081-the-navigation-row-shows-from-1360-px-and-a-drawer-below.md) | The navigation row shows from 1360 px, and a drawer below | Accepted | 2026-11-29 | -| [0082](0082-the-runtime-container-list-names-the-highest-active-severity-and-keeps-a-failed-checks-status-beside-it.md) | The runtime container list names the highest active severity and keeps a failed check's status beside it | Accepted | 2026-11-30 | +| [0082](0082-the-runtime-container-list-names-the-highest-active-severity-and-keeps-a-failed-checks-status-beside-it.md) | The list pages name the highest active severity and keep a failed check's status beside it | Accepted | 2026-12-01 | | [0083](0083-resource-histories-are-drawn-as-svg-sparklines-from-one-shared-path-builder.md) | Resource histories are drawn as SVG sparklines from one shared path builder | Accepted | 2026-11-30 | | [0084](0084-the-vulnerabilities-page-pages-its-advisories-itself-and-draws-its-own-pager.md) | The Vulnerabilities page pages its advisories itself and draws its own pager | Accepted | 2026-12-01 | diff --git a/src/DockerUpdateGuard/Components/Common/VulnerabilityListCell.razor b/src/DockerUpdateGuard/Components/Common/VulnerabilityListCell.razor new file mode 100644 index 00000000..f37f12cc --- /dev/null +++ b/src/DockerUpdateGuard/Components/Common/VulnerabilityListCell.razor @@ -0,0 +1,21 @@ +@{ + var summary = SeveritySummary ?? new VulnerabilitySeveritySummaryViewData(); +} + + + + + + @if (summary.TotalCount > 0) + { + @VulnerabilityCellFormatter.FormatActiveFindings(summary) + } + + + @if (ActiveBaseImageFindingCount > 0) + { + + @BaseImageSummary + } + + \ No newline at end of file diff --git a/src/DockerUpdateGuard/Components/Common/VulnerabilityListCell.razor.cs b/src/DockerUpdateGuard/Components/Common/VulnerabilityListCell.razor.cs new file mode 100644 index 00000000..dc0e961c --- /dev/null +++ b/src/DockerUpdateGuard/Components/Common/VulnerabilityListCell.razor.cs @@ -0,0 +1,57 @@ +using DockerUpdateGuard.UI; + +using Microsoft.AspNetCore.Components; + +namespace DockerUpdateGuard.Components.Common; + +/// +/// Vulnerability cell of the list tables: severity chips, status chip, count line, rescan control and base image note +/// +public partial class VulnerabilityListCell +{ + #region Properties + + /// + /// Image version to rescan + /// + [Parameter] + public Guid ImageVersionId { get; set; } + + /// + /// Vulnerability status of the image version + /// + [Parameter] + public string? Status { get; set; } + + /// + /// Active finding counts per severity + /// + [Parameter] + public VulnerabilitySeveritySummaryViewData? SeveritySummary { get; set; } + + /// + /// Timestamp of the last vulnerability scan of the image version + /// + [Parameter] + public DateTimeOffset? CheckedAtUtc { get; set; } + + /// + /// Number of active findings inherited from base images + /// + [Parameter] + public int ActiveBaseImageFindingCount { get; set; } + + /// + /// Summary text of the base image findings + /// + [Parameter] + public string? BaseImageSummary { get; set; } + + /// + /// Raised after a manual rescan completed + /// + [Parameter] + public EventCallback OnRescanned { get; set; } + + #endregion // Properties +} \ No newline at end of file diff --git a/src/DockerUpdateGuard/Components/Common/VulnerabilityStatusChips.razor b/src/DockerUpdateGuard/Components/Common/VulnerabilityStatusChips.razor new file mode 100644 index 00000000..e0944eb7 --- /dev/null +++ b/src/DockerUpdateGuard/Components/Common/VulnerabilityStatusChips.razor @@ -0,0 +1,15 @@ +@{ + var summary = SeveritySummary ?? new VulnerabilitySeveritySummaryViewData(); +} +@if (summary.TotalCount > 0) +{ + + @if (VulnerabilityCellFormatter.IsStatusShownBesideSeverity(summary, Status)) + { + + } +} +else +{ + +} \ No newline at end of file diff --git a/src/DockerUpdateGuard/Components/Common/VulnerabilityStatusChips.razor.cs b/src/DockerUpdateGuard/Components/Common/VulnerabilityStatusChips.razor.cs new file mode 100644 index 00000000..9343e6ec --- /dev/null +++ b/src/DockerUpdateGuard/Components/Common/VulnerabilityStatusChips.razor.cs @@ -0,0 +1,27 @@ +using DockerUpdateGuard.UI; + +using Microsoft.AspNetCore.Components; + +namespace DockerUpdateGuard.Components.Common; + +/// +/// Severity chips of a vulnerability summary with the status chip beside them where the status adds information +/// +public partial class VulnerabilityStatusChips +{ + #region Properties + + /// + /// Vulnerability status of the image version + /// + [Parameter] + public string? Status { get; set; } + + /// + /// Active finding counts per severity + /// + [Parameter] + public VulnerabilitySeveritySummaryViewData? SeveritySummary { get; set; } + + #endregion // Properties +} \ No newline at end of file diff --git a/src/DockerUpdateGuard/Components/Pages/DockerInstances.razor b/src/DockerUpdateGuard/Components/Pages/DockerInstances.razor index 1765a760..ef7b9397 100644 --- a/src/DockerUpdateGuard/Components/Pages/DockerInstances.razor +++ b/src/DockerUpdateGuard/Components/Pages/DockerInstances.razor @@ -3,13 +3,8 @@ Docker Instances - + @if (_instances is null) { @@ -32,126 +27,79 @@ { @if (_singleInstanceDetail is not null) { - -
- @_singleInstanceDetail.Name - @_singleInstanceDetail.EndpointUri + +
+
+ CPU + @FormatCpu(_singleInstanceDetail.CurrentResourceUsage) + +
+
+ Memory + @FormatMemory(_singleInstanceDetail.CurrentResourceUsage) + +
+
+ Network + @FormatNetwork(_singleInstanceDetail.CurrentResourceUsage) + +
- - - - CPU - @FormatCpu(_singleInstanceDetail.CurrentResourceUsage) - - - - - Memory - @FormatMemory(_singleInstanceDetail.CurrentResourceUsage) - - - - - Network - @FormatNetwork(_singleInstanceDetail.CurrentResourceUsage) - - - - - - -
- Usage history - Recent aggregated samples across the containers currently running on this Docker instance, with host memory total from Docker engine info. -
@if (_singleInstanceDetail.ResourceUsageHistory.Count == 0) { No resource history is currently stored for this Docker instance. } - else - { - - - - CPU history -
- -
-
-
- - - Memory history -
- -
-
-
- - - Network history -
- -
-
-
-
- } -
+
} - -
- Configured instances - Registered endpoints with connection details, runtime coverage, and recent container RAM usage relative to host memory. -
- + + - Name - Endpoint - Connection + Name + Endpoint + Connection + Latest scan @if (_singleInstanceDetail is null) { - CPU - Memory - Network + CPU + Memory + Network } - Containers + Containers - + @context.Name - @context.LatestScanStatus · @TimestampFormatter.FormatOptional(context.LatestScanCompletedAtUtc) - @context.EndpointUri - @context.ConnectionKind + @context.EndpointUri + @context.ConnectionKind + + + @if (context.LatestScanCompletedAtUtc.HasValue) + { + @TimestampFormatter.FormatOptional(context.LatestScanCompletedAtUtc) + } + @if (_singleInstanceDetail is null) { - @FormatCpu(context.CurrentResourceUsage) - @FormatMemory(context.CurrentResourceUsage) - @FormatNetwork(context.CurrentResourceUsage) + @FormatCpu(context.CurrentResourceUsage) + + @FormatMemory(context.CurrentResourceUsage) + @if (GetMemoryPercent(context.CurrentResourceUsage) is { } memoryPercent) + { + + } + + @FormatNetwork(context.CurrentResourceUsage) } - @context.RuntimeContainerCount + @context.RuntimeContainerCount -
+ } - + \ No newline at end of file diff --git a/src/DockerUpdateGuard/Components/Pages/DockerInstances.razor.cs b/src/DockerUpdateGuard/Components/Pages/DockerInstances.razor.cs index 05e15771..c6cf2078 100644 --- a/src/DockerUpdateGuard/Components/Pages/DockerInstances.razor.cs +++ b/src/DockerUpdateGuard/Components/Pages/DockerInstances.razor.cs @@ -103,10 +103,31 @@ private static string FormatNetwork(ResourceUsagePointViewData? usage) : $"{ResourceUsageFormatter.FormatBytesPerSecond(usage.NetworkRxBytesPerSecond)} ↓ / {ResourceUsageFormatter.FormatBytesPerSecond(usage.NetworkTxBytesPerSecond)} ↑"; } + /// + /// Calculate the memory usage as a percentage of the host memory total + /// + /// Usage data + /// Rounded percentage, or null without usage or host memory total + private static int? GetMemoryPercent(ResourceUsagePointViewData? usage) + { + return usage is null ? null : ResourceUsageFormatter.GetMemoryPercent(usage.MemoryUsageBytes, usage.MemoryLimitBytes); + } + #endregion // Static methods #region Methods + /// + /// Resolve the CSS classes of the instance table + /// + /// CSS classes + private string GetTableClass() + { + return _singleInstanceDetail is null + ? "section-table dug-list-table docker-instances-table" + : "section-table dug-list-table docker-instances-table docker-instances-table--single"; + } + /// /// Load the Docker-instance list and, for a single configured instance, its detail /// diff --git a/src/DockerUpdateGuard/Components/Pages/MyImages.razor b/src/DockerUpdateGuard/Components/Pages/MyImages.razor index c69bf2e2..d1fa47ea 100644 --- a/src/DockerUpdateGuard/Components/Pages/MyImages.razor +++ b/src/DockerUpdateGuard/Components/Pages/MyImages.razor @@ -3,13 +3,8 @@ My Images - + @if (_images is null) { @@ -19,7 +14,7 @@ } else { - + } } else if (_images.Count == 0) @@ -30,62 +25,63 @@ } else { - -
- @GetSectionTitle(_dockerHubUserName) - Automatically discovered images from the configured Docker account, prioritized when they are currently running. -
- - + + - Name - Image - Latest Scan - Running - Base runtime - Vulnerabilities + Name + Image + Latest scan + Running + Base runtime + Vulnerabilities - + @context.Name - @context.Description - - - @ImageReferenceFormatter.GetReference(context.ImageReference) + @if (string.IsNullOrWhiteSpace(context.Description) == false) + { + @context.Description + } - - @context.LatestScanStatus - @context.LatestScanMessage + @ImageReferenceFormatter.GetReference(context.ImageReference) + + + @if (string.IsNullOrWhiteSpace(context.LatestScanMessage) == false) + { + @context.LatestScanMessage + } - - - @(context.LinkedRuntimeContainerCount > 0 ? $"{context.LinkedRuntimeContainerCount} containers" : "Not running") - + + @if (context.LinkedRuntimeContainerCount > 0) + { + @DashboardTextFormatter.FormatCount(context.LinkedRuntimeContainerCount, "container", "containers") + } + else + { + Not running + } - + @if (string.IsNullOrWhiteSpace(context.BaseRuntimeAlertSummary)) { No runtime warning } else { - Runtime warning - @context.BaseRuntimeAlertSummary + @context.BaseRuntimeAlertSummary } - - @context.VulnerabilityStatus - - @($"{context.ActiveVulnerabilityFindingCount} active · {context.VulnerabilityMessage}") - @if (context.ActiveBaseImageVulnerabilityFindingCount > 0) - { - Base images affected - @context.BaseImageVulnerabilitySummary - } - + + -
+ } -
+ \ No newline at end of file diff --git a/src/DockerUpdateGuard/Components/Pages/MyImages.razor.cs b/src/DockerUpdateGuard/Components/Pages/MyImages.razor.cs index 1ed51e2b..00d36622 100644 --- a/src/DockerUpdateGuard/Components/Pages/MyImages.razor.cs +++ b/src/DockerUpdateGuard/Components/Pages/MyImages.razor.cs @@ -4,8 +4,6 @@ using Microsoft.AspNetCore.Components; using Microsoft.Extensions.Options; -using MudBlazor; - namespace DockerUpdateGuard.Components.Pages; /// @@ -94,23 +92,7 @@ internal static string GetSectionTitle(string? userName) return "Images from Docker account"; } - return $"Images from Docker account ({userName})"; - } - - /// - /// Resolve the chip color for a vulnerability assessment status - /// - /// Vulnerability assessment status - /// Severity summary of the active findings - /// Chip color - private static Color GetVulnerabilityStatusColor(string? status, VulnerabilitySeveritySummaryViewData? severitySummary) - { - if (string.IsNullOrWhiteSpace(status)) - { - return Color.Default; - } - - return VulnerabilityDisplayFormatter.GetStatusColor(status, severitySummary); + return userName.Trim(); } #endregion // Static methods diff --git a/src/DockerUpdateGuard/Components/Pages/ObservedImages.razor b/src/DockerUpdateGuard/Components/Pages/ObservedImages.razor index 75050b89..2eab0cce 100644 --- a/src/DockerUpdateGuard/Components/Pages/ObservedImages.razor +++ b/src/DockerUpdateGuard/Components/Pages/ObservedImages.razor @@ -3,19 +3,10 @@ Observed Images - - - -
- Register image -
+ + @if (string.IsNullOrWhiteSpace(_errorMessage) == false) { @@ -30,120 +21,123 @@ - - +
+
+ - - + InputId="register-image-name" + Variant="Variant.Outlined" + Margin="Margin.Dense" /> +
+
+ - - + InputId="register-image-reference" + Placeholder="registry/repository:tag" + Variant="Variant.Outlined" + Margin="Margin.Dense" /> +
+
+ - - - - Register and scan - - - - - Formats: image:tag · repo/image:tag · registry.com/image:tag · image:tag@sha256:… — digest is optional, registry defaults to docker.io - - - + InputId="register-image-description" + Variant="Variant.Outlined" + Margin="Margin.Dense" /> +
+ + Register and scan + +
+

+ Formats: image:tag · repo/image:tag · registry.com/image:tag · image:tag@sha256:… — digest is optional, registry defaults to docker.io +

-
- - -
- Manual images - Images that were manually registered by the operator. -
+ - @if (_images is null) + @if (_images is null) + { + @if (_loadErrorMessage is not null) { - @if (_loadErrorMessage is not null) - { + @_loadErrorMessage - } - else - { - - } + } - else if (_images.Count == 0) + else { + + } + } + else if (_images.Count == 0) + { + No manual observed images are registered yet. - } - else - { - + + } + else + { + + - Name - Image - Latest Scan - Updates - Base runtime - Vulnerabilities + Name + Image + Latest scan + Updates + Base runtime + Vulnerabilities - + @context.Name - @context.Description - - - @ImageReferenceFormatter.GetReference(context.ImageReference) + @if (string.IsNullOrWhiteSpace(context.Description) == false) + { + @context.Description + } - - @context.LatestScanStatus - @context.LatestScanMessage + @ImageReferenceFormatter.GetReference(context.ImageReference) + + + @if (string.IsNullOrWhiteSpace(context.LatestScanMessage) == false) + { + @context.LatestScanMessage + } - @context.ActiveUpdateFindingCount - - @if (string.IsNullOrWhiteSpace(context.BaseRuntimeAlertSummary)) + + @if (context.ActiveUpdateFindingCount > 0) { - No runtime hint + @context.ActiveUpdateFindingCount } else { - Runtime hint - @context.BaseRuntimeAlertSummary + — } - - @context.VulnerabilityStatus - - @($"{context.ActiveVulnerabilityFindingCount} active · {context.VulnerabilityMessage}") - @if (context.ActiveBaseImageVulnerabilityFindingCount > 0) - { - Base images affected - @context.BaseImageVulnerabilitySummary - } - + + @(string.IsNullOrWhiteSpace(context.BaseRuntimeAlertSummary) ? "—" : context.BaseRuntimeAlertSummary) + + + - } -
-
+ + } + \ No newline at end of file diff --git a/src/DockerUpdateGuard/Components/Pages/ObservedImages.razor.cs b/src/DockerUpdateGuard/Components/Pages/ObservedImages.razor.cs index 373c80e6..d6613a44 100644 --- a/src/DockerUpdateGuard/Components/Pages/ObservedImages.razor.cs +++ b/src/DockerUpdateGuard/Components/Pages/ObservedImages.razor.cs @@ -7,8 +7,6 @@ using Microsoft.AspNetCore.Components; -using MudBlazor; - namespace DockerUpdateGuard.Components.Pages; /// @@ -110,26 +108,6 @@ public sealed partial class ObservedImages : IDisposable #endregion // Properties - #region Static methods - - /// - /// Resolve the chip color for a vulnerability assessment status - /// - /// Vulnerability assessment status - /// Severity summary of the active findings - /// Chip color - private static Color GetVulnerabilityStatusColor(string? status, VulnerabilitySeveritySummaryViewData? severitySummary) - { - if (string.IsNullOrWhiteSpace(status)) - { - return Color.Default; - } - - return VulnerabilityDisplayFormatter.GetStatusColor(status, severitySummary); - } - - #endregion // Static methods - #region Methods /// diff --git a/src/DockerUpdateGuard/Components/Pages/RuntimeContainers.razor b/src/DockerUpdateGuard/Components/Pages/RuntimeContainers.razor index 53bac526..9630b025 100644 --- a/src/DockerUpdateGuard/Components/Pages/RuntimeContainers.razor +++ b/src/DockerUpdateGuard/Components/Pages/RuntimeContainers.razor @@ -120,35 +120,13 @@ } - - - - @if (context.VulnerabilitySeveritySummary.TotalCount > 0) - { - - @if (RuntimeContainerListFormatter.IsStatusShownBesideSeverity(context)) - { - - } - } - else - { - - } - - @if (context.VulnerabilitySeveritySummary.TotalCount > 0) - { - @RuntimeContainerListFormatter.FormatActiveFindings(context.VulnerabilitySeveritySummary) - } - - - @if (context.ActiveBaseImageVulnerabilityFindingCount > 0) - { - - @context.BaseImageVulnerabilitySummary - } - - + diff --git a/src/DockerUpdateGuard/Components/Pages/ScanHistory.razor b/src/DockerUpdateGuard/Components/Pages/ScanHistory.razor index 3124f4df..791276e5 100644 --- a/src/DockerUpdateGuard/Components/Pages/ScanHistory.razor +++ b/src/DockerUpdateGuard/Components/Pages/ScanHistory.razor @@ -3,39 +3,37 @@ Scan History - + } + + @if (string.IsNullOrWhiteSpace(_errorMessage) == false) { @@ -50,7 +48,7 @@ } else { - + } } else if (_scans.Count == 0) @@ -61,31 +59,32 @@ } else { - -
- Recent and historical scans - Review trigger source, target, and outcome of the latest 20 runs. -
- + + - Type - Status - Trigger - Target - Started - Error + Type + Status + Trigger + Target + Started + Error - @context.Type - - @context.Status + @context.Type + + + + @context.TriggerSource + @context.SubjectName + @TimestampFormatter.Format(context.StartedAtUtc) + + @if (string.IsNullOrWhiteSpace(context.ErrorMessage) == false) + { + @context.ErrorMessage + } - @context.TriggerSource - @context.SubjectName - @TimestampFormatter.Format(context.StartedAtUtc) - @context.ErrorMessage -
+ } -
+ \ No newline at end of file diff --git a/src/DockerUpdateGuard/Components/Pages/ScanHistory.razor.cs b/src/DockerUpdateGuard/Components/Pages/ScanHistory.razor.cs index b39502af..8fea8797 100644 --- a/src/DockerUpdateGuard/Components/Pages/ScanHistory.razor.cs +++ b/src/DockerUpdateGuard/Components/Pages/ScanHistory.razor.cs @@ -109,6 +109,18 @@ public sealed partial class ScanHistory : IDisposable #region Static methods + /// + /// Resolve the CSS classes of the error text of a run + /// + /// Run status + /// CSS classes + private static string GetErrorClass(string status) + { + return string.Equals(status, "Failed", StringComparison.Ordinal) + ? "scan-history-table__error--failed" + : "table-secondary"; + } + /// /// Format the estimated next scheduled vulnerability refresh /// diff --git a/src/DockerUpdateGuard/Components/Pages/SharedBaseImages.razor b/src/DockerUpdateGuard/Components/Pages/SharedBaseImages.razor index 7ff31deb..22405c3b 100644 --- a/src/DockerUpdateGuard/Components/Pages/SharedBaseImages.razor +++ b/src/DockerUpdateGuard/Components/Pages/SharedBaseImages.razor @@ -1,15 +1,10 @@ @page "/base-images" -Shared Base Images +Base Images - + @if (_items is null) { @@ -30,56 +25,55 @@ } else { - -
- Base image overview - Track shared base images, the images built on them, their running containers, and their vulnerability status. -
- + + - Base Image - Parent Images - Runtime Containers - Observed Images - Vulnerabilities + Base image + Parent images + Runtime containers + Observed images + Vulnerabilities - @ImageReferenceFormatter.GetReference(context.ImageReference) - + @ImageReferenceFormatter.GetReference(context.ImageReference) + @if (context.ParentImageReferences.Count == 0) { No parent image recorded } else { - +
@foreach (var parentImageReference in context.ParentImageReferences) { @ImageReferenceFormatter.GetReference(parentImageReference) } - +
}
- + @if (context.RuntimeContainers.Count == 0) { No linked container } else { - +
@foreach (var runtimeContainer in context.RuntimeContainers) { - @runtimeContainer.ContainerName - @runtimeContainer.DockerInstanceName +
+ @runtimeContainer.ContainerName + @runtimeContainer.DockerInstanceName +
} - +
}
- @context.ObservedImageCount - - @context.VulnerabilityAssessment.Status - + @context.ObservedImageCount + + + + @($"{context.VulnerabilityAssessment.ActiveFindingCount} active · {context.VulnerabilityAssessment.Source}") @if (string.IsNullOrWhiteSpace(context.VulnerabilityAssessment.Message) == false) { @@ -88,6 +82,6 @@
-
+ } -
+ \ No newline at end of file diff --git a/src/DockerUpdateGuard/Components/Pages/SharedBaseImages.razor.cs b/src/DockerUpdateGuard/Components/Pages/SharedBaseImages.razor.cs index 511fe9bf..cff23d62 100644 --- a/src/DockerUpdateGuard/Components/Pages/SharedBaseImages.razor.cs +++ b/src/DockerUpdateGuard/Components/Pages/SharedBaseImages.razor.cs @@ -2,8 +2,6 @@ using Microsoft.AspNetCore.Components; -using MudBlazor; - namespace DockerUpdateGuard.Components.Pages; /// @@ -61,26 +59,6 @@ public sealed partial class SharedBaseImages : IDisposable #endregion // Properties - #region Static methods - - /// - /// Resolve the chip color for a vulnerability assessment status - /// - /// Vulnerability assessment status - /// Severity summary of the active findings - /// Chip color - private static Color GetVulnerabilityStatusColor(string? status, VulnerabilitySeveritySummaryViewData? severitySummary) - { - if (string.IsNullOrWhiteSpace(status)) - { - return Color.Default; - } - - return VulnerabilityDisplayFormatter.GetStatusColor(status, severitySummary); - } - - #endregion // Static methods - #region Methods /// diff --git a/src/DockerUpdateGuard/UI/ListPageMetaFormatter.cs b/src/DockerUpdateGuard/UI/ListPageMetaFormatter.cs new file mode 100644 index 00000000..4ea1d57f --- /dev/null +++ b/src/DockerUpdateGuard/UI/ListPageMetaFormatter.cs @@ -0,0 +1,45 @@ +namespace DockerUpdateGuard.UI; + +/// +/// Composes the meta texts of the list page panels +/// +internal static class ListPageMetaFormatter +{ + #region Methods + + /// + /// Formats the meta text of the My Images panel + /// + /// Listed images + /// Meta text + public static string FormatMyImagesMeta(IReadOnlyList images) + { + var running = images.Count(image => image.LinkedRuntimeContainerCount > 0); + + return $"{DashboardTextFormatter.FormatCount(images.Count, "image", "images")} · {running} running"; + } + + /// + /// Formats the meta text of the Docker Instances panel + /// + /// Listed Docker instances + /// Meta text + public static string FormatDockerInstancesMeta(IReadOnlyList instances) + { + var containers = instances.Sum(instance => instance.RuntimeContainerCount); + + return $"{DashboardTextFormatter.FormatCount(instances.Count, "instance", "instances")} · {DashboardTextFormatter.FormatCount(containers, "container", "containers")}"; + } + + /// + /// Formats the meta text of the Scan History panel + /// + /// Listed scans + /// Meta text + public static string FormatScanHistoryMeta(IReadOnlyList scans) + { + return string.Join(" · ", DashboardScanStripFormatter.GetStatusCounts(scans).Select(DashboardScanStripFormatter.FormatCountText)); + } + + #endregion // Methods +} \ No newline at end of file diff --git a/src/DockerUpdateGuard/UI/ResourceUsageChartBuilder.cs b/src/DockerUpdateGuard/UI/ResourceUsageChartBuilder.cs deleted file mode 100644 index 882e07e1..00000000 --- a/src/DockerUpdateGuard/UI/ResourceUsageChartBuilder.cs +++ /dev/null @@ -1,147 +0,0 @@ -using MudBlazor; - -namespace DockerUpdateGuard.UI; - -/// -/// Builds chart data from resource usage history -/// -internal static class ResourceUsageChartBuilder -{ - #region Methods - - /// - /// Build chart labels from the resource history - /// - /// Resource history - /// Chart labels - internal static string[] GetChartLabels(IReadOnlyList history) - { - return GetChartLabels(history, 8); - } - - /// - /// Build chart labels from the resource history with a maximum number of visible labels - /// - /// Resource history - /// Maximum number of visible labels - /// Chart labels - internal static string[] GetChartLabels(IReadOnlyList history, int maxVisibleLabels) - { - var chronologicalHistory = GetChronologicalHistory(history); - - if (chronologicalHistory.Count == 0) - { - return []; - } - - var effectiveMaxVisibleLabels = Math.Max(2, maxVisibleLabels); - var visibleLabelStep = chronologicalHistory.Count <= effectiveMaxVisibleLabels - ? 1 - : (int)Math.Ceiling((chronologicalHistory.Count - 1d) / (effectiveMaxVisibleLabels - 1d)); - - return [ - .. chronologicalHistory.Select((point, index) => - { - if (index != 0 - && index != chronologicalHistory.Count - 1 - && index % visibleLabelStep != 0) - { - return string.Empty; - } - - return TimestampFormatter.FormatChartLabel(point.RecordedAtUtc, index == 0 || index == chronologicalHistory.Count - 1); - }) - ]; - } - - /// - /// Build a CPU chart series - /// - /// Resource history - /// Chart series - internal static List> GetCpuSeries(IReadOnlyList history) - { - return [ - new ChartSeries - { - Name = "CPU", - Data = GetChronologicalHistory(history).Select(point => (double)point.CpuPercent) - .ToArray(), - }, - ]; - } - - /// - /// Build a memory chart series - /// - /// Resource history - /// Chart series - internal static List> GetMemorySeries(IReadOnlyList history) - { - return [ - new ChartSeries - { - Name = "Memory (MiB)", - Data = GetChronologicalHistory(history).Select(point => ConvertBytesToMebibytes(point.MemoryUsageBytes)) - .ToArray(), - }, - ]; - } - - /// - /// Build network chart series - /// - /// Resource history - /// Chart series - internal static List> GetNetworkSeries(IReadOnlyList history) - { - var chronologicalHistory = GetChronologicalHistory(history); - - return [ - new ChartSeries - { - Name = "Receive (KB/s)", - Data = chronologicalHistory.Select(point => ConvertBytesPerSecondToKilobytes(point.NetworkRxBytesPerSecond)) - .ToArray(), - }, - new ChartSeries - { - Name = "Transmit (KB/s)", - Data = chronologicalHistory.Select(point => ConvertBytesPerSecondToKilobytes(point.NetworkTxBytesPerSecond)) - .ToArray(), - }, - ]; - } - - /// - /// Order the resource history from oldest to newest - /// - /// Resource history - /// Chronological history - private static List GetChronologicalHistory(IReadOnlyList history) - { - return [.. history.OrderBy(point => point.RecordedAtUtc)]; - } - - /// - /// Convert a byte count to mebibytes - /// - /// Byte count - /// Mebibytes - private static double ConvertBytesToMebibytes(long bytes) - { - return bytes / 1024d / 1024d; - } - - /// - /// Convert bytes per second to kilobytes per second - /// - /// Bytes per second - /// Kilobytes per second - private static double ConvertBytesPerSecondToKilobytes(decimal value) - { - return (double)value / 1024d; - } - - #endregion // Methods -} \ No newline at end of file diff --git a/src/DockerUpdateGuard/UI/ResourceUsageFormatter.cs b/src/DockerUpdateGuard/UI/ResourceUsageFormatter.cs index 8da1b6df..dcd3c5ca 100644 --- a/src/DockerUpdateGuard/UI/ResourceUsageFormatter.cs +++ b/src/DockerUpdateGuard/UI/ResourceUsageFormatter.cs @@ -30,6 +30,22 @@ public static string FormatMemory(long usageBytes, long limitBytes) : FormatBytes(usageBytes); } + /// + /// Calculates the memory usage as a percentage of the limit + /// + /// Usage bytes + /// Limit bytes + /// Rounded percentage, or null without a limit + public static int? GetMemoryPercent(long usageBytes, long limitBytes) + { + if (limitBytes <= 0) + { + return null; + } + + return (int)Math.Round((decimal)usageBytes / limitBytes * 100, MidpointRounding.AwayFromZero); + } + /// /// Format a byte-rate value /// diff --git a/src/DockerUpdateGuard/UI/RuntimeContainerListFormatter.cs b/src/DockerUpdateGuard/UI/RuntimeContainerListFormatter.cs index 4515572b..ac25c010 100644 --- a/src/DockerUpdateGuard/UI/RuntimeContainerListFormatter.cs +++ b/src/DockerUpdateGuard/UI/RuntimeContainerListFormatter.cs @@ -21,57 +21,5 @@ public static string FormatInventoryMeta(IReadOnlyList - /// Formats the count line of the active findings - /// - /// Active finding counts per severity - /// Count line - public static string FormatActiveFindings(VulnerabilitySeveritySummaryViewData summary) - { - if (summary.TotalCount == 0) - { - return string.Empty; - } - - var counts = new List(); - - AddCount(counts, summary.CriticalCount, "critical"); - AddCount(counts, summary.HighCount, "high"); - AddCount(counts, summary.MediumCount, "medium"); - AddCount(counts, summary.LowCount, "low"); - AddCount(counts, summary.OtherCount, "unknown"); - - return $"{summary.TotalCount} active · {string.Join(", ", counts)}"; - } - - /// - /// Determines whether the vulnerability status is shown as a chip beside the severity chip - /// - /// Listed runtime container - /// true when the status chip is shown - public static bool IsStatusShownBesideSeverity(RuntimeContainerListItemData container) - { - return container.VulnerabilitySeveritySummary.TotalCount > 0 - && string.Equals(container.VulnerabilityStatus, "Findings detected", StringComparison.OrdinalIgnoreCase) == false; - } - #endregion // Methods - - #region Helper methods - - /// - /// Adds a count text when the count is above zero - /// - /// Count texts - /// Count - /// Severity label - private static void AddCount(List counts, int count, string label) - { - if (count > 0) - { - counts.Add($"{count} {label}"); - } - } - - #endregion // Helper methods } \ No newline at end of file diff --git a/src/DockerUpdateGuard/UI/VulnerabilityCellFormatter.cs b/src/DockerUpdateGuard/UI/VulnerabilityCellFormatter.cs new file mode 100644 index 00000000..9e5717cf --- /dev/null +++ b/src/DockerUpdateGuard/UI/VulnerabilityCellFormatter.cs @@ -0,0 +1,64 @@ +namespace DockerUpdateGuard.UI; + +/// +/// Composes the texts and display decisions of the shared vulnerability list cell +/// +internal static class VulnerabilityCellFormatter +{ + #region Methods + + /// + /// Formats the count line of the active findings + /// + /// Active finding counts per severity + /// Count line + public static string FormatActiveFindings(VulnerabilitySeveritySummaryViewData summary) + { + if (summary.TotalCount == 0) + { + return string.Empty; + } + + var counts = new List(); + + AddCount(counts, summary.CriticalCount, "critical"); + AddCount(counts, summary.HighCount, "high"); + AddCount(counts, summary.MediumCount, "medium"); + AddCount(counts, summary.LowCount, "low"); + AddCount(counts, summary.OtherCount, "unknown"); + + return $"{summary.TotalCount} active · {string.Join(", ", counts)}"; + } + + /// + /// Determines whether the vulnerability status is shown as a chip beside the severity chip + /// + /// Active finding counts per severity + /// Vulnerability status + /// true when the status chip is shown + public static bool IsStatusShownBesideSeverity(VulnerabilitySeveritySummaryViewData summary, string? status) + { + return summary.TotalCount > 0 + && string.Equals(status, "Findings detected", StringComparison.OrdinalIgnoreCase) == false; + } + + #endregion // Methods + + #region Helper methods + + /// + /// Adds a count text when the count is above zero + /// + /// Count texts + /// Count + /// Severity label + private static void AddCount(List counts, int count, string label) + { + if (count > 0) + { + counts.Add($"{count} {label}"); + } + } + + #endregion // Helper methods +} \ No newline at end of file diff --git a/src/DockerUpdateGuard/wwwroot/app.css b/src/DockerUpdateGuard/wwwroot/app.css index 0f7dd796..fe051e59 100644 --- a/src/DockerUpdateGuard/wwwroot/app.css +++ b/src/DockerUpdateGuard/wwwroot/app.css @@ -522,26 +522,6 @@ a { margin-top: 0.1rem; } -.dug-chart { - position: relative; - min-height: 200px; - height: 280px; - overflow: hidden; -} - -.dug-chart .mud-chart { - width: 100%; - height: 100%; - min-width: 0; - min-height: 0; -} - -.dug-chart .mud-chart svg { - flex: 1 1 auto; - width: 100%; - min-height: 0; -} - .empty-state-panel { padding: 1.75rem; } @@ -1126,6 +1106,23 @@ a { border: 1px solid var(--dug-border); } +.dug-list-table .mud-table-cell { + min-width: 0; +} + +.dug-list-table .dug-list-table__stacked { + min-width: 0; + white-space: normal; + overflow-wrap: anywhere; +} + +@media (min-width: 960px) { + .dug-list-table .mud-table-root { + table-layout: fixed; + width: 100%; + } +} + .runtime-containers-table .runtime-containers-table__container, .runtime-containers-table .runtime-containers-table__update, .runtime-containers-table .runtime-containers-table__vulnerabilities { @@ -1150,13 +1147,13 @@ a { font-variant-numeric: tabular-nums; } -.runtime-containers-table .runtime-containers-table__chips { +.dug-vulnerability-cell__chips { display: inline-flex; flex-wrap: wrap; gap: 0.35rem; } -.runtime-containers-table .runtime-containers-table__findings { +.dug-vulnerability-cell__findings { color: var(--dug-text); font-size: 13px; } @@ -1541,12 +1538,27 @@ a { width: 100%; } - .runtime-containers-table .runtime-containers-table__sparkline { - max-width: 100%; + .dug-list-table .mud-table-body .mud-table-cell { + min-width: 0; + overflow-wrap: anywhere; + } + + .dug-list-table .mud-table-body .mud-table-cell::before { + flex-shrink: 0; + } + + .dug-list-table .dug-list-table__stacked { + flex-direction: column; + align-items: flex-start; + gap: 0.35rem; } - .dug-chart { - height: 240px; + .dug-list-table .dug-list-table__stacked .vulnerability-rescan-control { + width: 100%; + } + + .runtime-containers-table .runtime-containers-table__sparkline { + max-width: 100%; } } @@ -1566,14 +1578,6 @@ a { .hero-panel { padding: 1.2rem; } - - .dug-chart { - height: 200px; - } - - .dug-form-submit { - width: 100%; - } } @media (max-width: 399.98px) { @@ -1818,4 +1822,293 @@ a { transition-duration: 0.01ms !important; animation-duration: 0.01ms !important; } -} \ No newline at end of file +} + +.my-images-table .my-images-table__image { + min-width: 0; + white-space: normal; + overflow-wrap: anywhere; +} + +.observed-images-table .observed-images-table__image { + min-width: 0; + white-space: normal; + overflow-wrap: anywhere; +} + +.base-images-table .base-images-table__base-image { + min-width: 0; + white-space: normal; + overflow-wrap: anywhere; +} + +.docker-instances-table .docker-instances-table__endpoint { + min-width: 0; + white-space: normal; + overflow-wrap: anywhere; + font-family: ui-monospace, SFMono-Regular, Menlo, Consolas, monospace; + font-size: 13px; +} + +.scan-history-table .scan-history-table__error { + min-width: 0; + white-space: normal; + overflow-wrap: anywhere; +} + +.my-images-table .my-images-table__warning { + color: var(--dug-chip-high-fg); + font-weight: 600; +} + +.observed-images-table .observed-images-table__update-count { + font-weight: 500; +} + +.base-images-table .base-images-table__reference { + font-weight: 600; +} + +.base-images-table .base-images-table__lines { + display: flex; + flex-direction: column; + gap: 0.25rem; + min-width: 0; + overflow-wrap: anywhere; +} + +.docker-instances-table .docker-instances-table__network { + white-space: nowrap; +} + +.scan-history-table .scan-history-table__started { + font-variant-numeric: tabular-nums; +} + +.scan-history-table .scan-history-table__error--failed { + color: var(--dug-danger); +} + +.scan-history-actions { + display: flex; + flex-wrap: wrap; + align-items: center; + justify-content: flex-end; + gap: 0.75rem; +} + +.scan-history-actions .table-secondary { + font-size: 13px; +} + +.dug-meter { + width: 100%; + max-width: 140px; + height: 6px; + margin-top: 0.35rem; + overflow: hidden; + background: var(--dug-border-inner); + border-radius: 3px; +} + +.dug-meter__fill { + height: 100%; + background: var(--dug-chart-memory); + border-radius: 3px; +} + +.register-image-form { + display: grid; + grid-template-columns: 1fr; + gap: 0.75rem 1rem; + align-items: start; +} + +.register-image-form__field { + min-width: 0; +} + +.register-image-form__label { + display: block; + margin-bottom: 6px; + font-size: 13px; + font-weight: 500; + line-height: 18px; +} + +.register-image-form__hint { + margin: 0.75rem 0 0; + font-size: 13px; +} + +@media (min-width: 960px) { + .register-image-form { + display: grid; + grid-template-columns: 1fr 2fr 2fr auto; + align-items: start; + } + + .register-image-form .register-image-form__submit { + margin-top: 24px; + } + + .my-images-table .my-images-table__name { + width: 17%; + } + + .my-images-table .my-images-table__image { + width: 22%; + } + + .my-images-table .my-images-table__scan { + width: 14%; + } + + .my-images-table .my-images-table__running { + width: 9%; + } + + .my-images-table .my-images-table__runtime { + width: 14%; + } + + .my-images-table .my-images-table__vulnerabilities { + width: 24%; + } + + .observed-images-table .observed-images-table__name { + width: 17%; + } + + .observed-images-table .observed-images-table__image { + width: 22%; + } + + .observed-images-table .observed-images-table__scan { + width: 14%; + } + + .observed-images-table .observed-images-table__updates { + width: 8%; + } + + .observed-images-table .observed-images-table__runtime { + width: 15%; + } + + .observed-images-table .observed-images-table__vulnerabilities { + width: 24%; + } + + .base-images-table .base-images-table__base-image { + width: 22%; + } + + .base-images-table .base-images-table__parents { + width: 24%; + } + + .base-images-table .base-images-table__containers { + width: 22%; + } + + .base-images-table .base-images-table__observed { + width: 8%; + } + + .base-images-table .base-images-table__vulnerabilities { + width: 24%; + } + + .docker-instances-table .docker-instances-table__name { + width: 10%; + } + + .docker-instances-table .docker-instances-table__endpoint { + width: 17%; + } + + .docker-instances-table .docker-instances-table__connection { + width: 8%; + } + + .docker-instances-table .docker-instances-table__scan { + width: 12%; + } + + .docker-instances-table .docker-instances-table__cpu { + width: 7%; + } + + .docker-instances-table .docker-instances-table__memory { + width: 15%; + } + + .docker-instances-table .docker-instances-table__network { + width: 23%; + } + + .docker-instances-table .docker-instances-table__containers { + width: 8%; + } + + .docker-instances-table--single .docker-instances-table__name { + width: 18%; + } + + .docker-instances-table--single .docker-instances-table__endpoint { + width: 30%; + } + + .docker-instances-table--single .docker-instances-table__connection { + width: 14%; + } + + .docker-instances-table--single .docker-instances-table__scan { + width: 22%; + } + + .docker-instances-table--single .docker-instances-table__containers { + width: 16%; + } + + .scan-history-table .scan-history-table__type { + width: 12%; + } + + .scan-history-table .scan-history-table__status { + width: 12%; + } + + .scan-history-table .scan-history-table__trigger { + width: 11%; + } + + .scan-history-table .scan-history-table__target { + width: 20%; + } + + .scan-history-table .scan-history-table__started { + width: 17%; + } + + .scan-history-table .scan-history-table__error { + width: 28%; + } +} + +@media (max-width: 959.98px) { + .register-image-form { + grid-template-columns: 1fr; + } + + .register-image-form .register-image-form__submit { + margin-top: 0; + } +} + +@media (max-width: 599.98px) { + .register-image-form .register-image-form__submit { + width: 100%; + } +} diff --git a/src/Tests/DockerUpdateGuard.Tests/AppStylesheetListPagesTests.cs b/src/Tests/DockerUpdateGuard.Tests/AppStylesheetListPagesTests.cs new file mode 100644 index 00000000..aa8bcad5 --- /dev/null +++ b/src/Tests/DockerUpdateGuard.Tests/AppStylesheetListPagesTests.cs @@ -0,0 +1,290 @@ +using System.Text.RegularExpressions; + +using DockerUpdateGuard.Tests.Helper; + +namespace DockerUpdateGuard.Tests; + +/// +/// Tests for the rules of wwwroot/app.css that style the list pages My Images, Observed Images, Base Images, Docker Instances and Scan History +/// +[TestClass] +public partial class AppStylesheetListPagesTests +{ + #region Constants + + /// + /// Shipped stylesheet below the host project directory + /// + private const string StylesheetPath = "wwwroot/app.css"; + + /// + /// Start of the media context of the table layout, which begins at 960 px + /// + private const string TableContextStart = "@media (min-width: 960"; + + /// + /// Media context of the card layout of table rows + /// + private const string CardContext = "@media (max-width: 959.98px)"; + + /// + /// Media context below 600 px + /// + private const string PhoneContext = "@media (max-width: 599.98px)"; + + /// + /// Selector of the registration form row + /// + private const string RegisterForm = ".register-image-form"; + + /// + /// Selector of the submit button of the registration form + /// + private const string RegisterSubmit = ".register-image-form__submit"; + + /// + /// Time limit of the column pattern in milliseconds + /// + private const int RegexTimeoutMilliseconds = 5000; + + #endregion // Constants + + #region Fields + + /// + /// Column templates that stack the fields in one column + /// + private static readonly string[] _stackedColumns = ["1fr", "minmax(0, 1fr)"]; + + #endregion // Fields + + #region Static methods + + /// + /// Match the value of a percentage width + /// + /// Regular expression + [GeneratedRegex(@"^(\d+(\.\d+)?)%$", RegexOptions.None, RegexTimeoutMilliseconds)] + private static partial Regex CreatePercentPattern(); + + #endregion // Static methods + + #region Methods + + /// + /// Verify the registration form is one grid row from 960 px, with the widths of the issue, and the button lines up with the inputs + /// + [TestMethod] + [TestCategory("AC6")] + public void AppStylesheetListPagesRegisterFormIsOneRowFrom960Px() + { + var row = GetDeclarations(rule => IsTableOrTopLevel(rule.Context) && rule.Entry.EndsWith(RegisterForm, StringComparison.Ordinal)); + var submit = GetDeclarations(rule => IsTableOrTopLevel(rule.Context) && rule.Entry.EndsWith(RegisterSubmit, StringComparison.Ordinal)); + var offset = submit.GetValueOrDefault("margin-top") ?? submit.GetValueOrDefault("padding-top") ?? "0"; + + Assert.AreEqual("grid", row.GetValueOrDefault("display"), "The form row must be a grid"); + Assert.AreEqual("1fr 2fr 2fr auto", row.GetValueOrDefault("grid-template-columns"), "The row must give the fields their proportions and the button its own width"); + Assert.AreEqual("start", row.GetValueOrDefault("align-items"), "The fields must start at the top so a validation message lengthens only its own cell, not the button's position"); + Assert.IsTrue(offset.Length > 0 && char.IsDigit(offset[0]) && offset.StartsWith('0') == false, $"The button must be offset from the top by the label height to line up with the inputs, but its offset is '{offset}'"); + } + + /// + /// Verify the fields stack in one column below 960 px + /// + [TestMethod] + [TestCategory("AC6")] + public void AppStylesheetListPagesRegisterFormStacksBelow960Px() + { + var row = GetDeclarations(rule => rule.Context == CardContext && rule.Entry.EndsWith(RegisterForm, StringComparison.Ordinal)); + var submit = GetDeclarations(rule => rule.Context == CardContext && rule.Entry.EndsWith(RegisterSubmit, StringComparison.Ordinal)); + + Assert.Contains(row.GetValueOrDefault("grid-template-columns") ?? string.Empty, _stackedColumns, "The fields must stack in one column below 960 px"); + Assert.IsTrue(submit.GetValueOrDefault("margin-top") is null or "0", "Stacked, the button must need no label offset"); + } + + /// + /// Verify the button takes the full width below 600 px + /// + [TestMethod] + [TestCategory("AC6")] + public void AppStylesheetListPagesRegisterButtonIsFullWidthBelow600Px() + { + var submit = GetDeclarations(rule => rule.Context == PhoneContext && rule.Entry.EndsWith(RegisterSubmit, StringComparison.Ordinal)); + + Assert.AreEqual("100%", submit.GetValueOrDefault("width"), "The button must take the full width below 600 px"); + } + + /// + /// Verify the memory meter is a 6 px high bar of at most 140 px that takes its colors from tokens + /// + [TestMethod] + [TestCategory("AC7")] + public void AppStylesheetListPagesMemoryMeterUsesTokensAndSize() + { + var track = GetDeclarations(rule => rule.Context.Length == 0 && rule.Entry.EndsWith(".dug-meter", StringComparison.Ordinal)); + var fill = GetDeclarations(rule => rule.Context.Length == 0 && rule.Entry.EndsWith(".dug-meter__fill", StringComparison.Ordinal)); + + Assert.AreEqual("6px", track.GetValueOrDefault("height"), "The meter must be 6 px high"); + Assert.AreEqual("140px", track.GetValueOrDefault("max-width"), "The meter must be at most 140 px wide"); + Assert.AreEqual("var(--dug-border-inner)", track.GetValueOrDefault("background"), "The track must use the inner border token"); + Assert.AreEqual("var(--dug-chart-memory)", fill.GetValueOrDefault("background"), "The fill must use the memory chart token"); + } + + /// + /// Verify the endpoint is shown in a 13 px monospace font + /// + [TestMethod] + [TestCategory("AC2")] + public void AppStylesheetListPagesEndpointIsMonospaceSmall() + { + var endpoint = GetDeclarations(rule => rule.Context.Length == 0 && rule.Entry.EndsWith("docker-instances-table__endpoint", StringComparison.Ordinal)); + + Assert.Contains("monospace", endpoint.GetValueOrDefault("font-family") ?? string.Empty, "The endpoint must use a monospace font"); + Assert.AreEqual("13px", endpoint.GetValueOrDefault("font-size"), "The endpoint must be 13 px"); + } + + /// + /// Verify the error text of a failed run takes the danger token + /// + [TestMethod] + [TestCategory("AC9")] + public void AppStylesheetListPagesFailedErrorUsesDangerToken() + { + var failed = GetDeclarations(rule => rule.Context.Length == 0 && rule.Entry.EndsWith("scan-history-table__error--failed", StringComparison.Ordinal)); + + Assert.AreEqual("var(--dug-danger)", failed.GetValueOrDefault("color"), "The error of a failed run must use the danger token"); + } + + /// + /// Verify long values of the cells that hold them wrap in the table and in the card, instead of widening the page + /// + /// Class of the page's table + /// Column class suffix of the cell with the long value + [TestMethod] + [TestCategory("AC10")] + [DataRow("my-images-table", "image")] + [DataRow("observed-images-table", "image")] + [DataRow("base-images-table", "base-image")] + [DataRow("docker-instances-table", "endpoint")] + [DataRow("scan-history-table", "error")] + public void AppStylesheetListPagesCardCellsWrapLongValues(string tableClass, string column) + { + var cell = GetDeclarations(rule => IsTableOrTopLevel(rule.Context) && rule.Entry.EndsWith($"{tableClass}__{column}", StringComparison.Ordinal)); + var card = GetDeclarations(rule => rule.Context == CardContext && rule.Entry.EndsWith(".dug-list-table .mud-table-body .mud-table-cell", StringComparison.Ordinal)); + var label = GetDeclarations(rule => rule.Context == CardContext && rule.Entry.EndsWith(".dug-list-table .mud-table-body .mud-table-cell::before", StringComparison.Ordinal)); + + Assert.AreEqual("anywhere", cell.GetValueOrDefault("overflow-wrap"), $"The {column} cell of the table must break long values anywhere from 960 px"); + Assert.AreEqual("0", card.GetValueOrDefault("min-width"), "A card cell must be allowed to shrink below its content"); + Assert.AreEqual("anywhere", card.GetValueOrDefault("overflow-wrap"), "A card cell must break long values anywhere"); + Assert.AreEqual("0", label.GetValueOrDefault("flex-shrink"), "The label of a card cell must keep its width"); + } + + /// + /// Verify the tables are laid out fixed inside their panel from 960 px, and the column widths of each page add up to at most the full width + /// + /// Class of the page's table + /// Number of columns that have a width + /// Whether the widths are those of the single-instance modifier + [TestMethod] + [TestCategory("AC10")] + [DataRow("my-images-table", 6, false)] + [DataRow("observed-images-table", 6, false)] + [DataRow("base-images-table", 5, false)] + [DataRow("docker-instances-table", 8, false)] + [DataRow("docker-instances-table", 5, true)] + [DataRow("scan-history-table", 6, false)] + public void AppStylesheetListPagesTablesStayInsidePanelFrom960Px(string tableClass, int columnCount, bool isSingle) + { + var layout = GetDeclarations(rule => IsTableContext(rule.Context) && rule.Entry.EndsWith(".dug-list-table .mud-table-root", StringComparison.Ordinal)); + var columnPattern = new Regex($@"{Regex.Escape(tableClass)}__([a-z0-9-]+)", RegexOptions.None, TimeSpan.FromMilliseconds(RegexTimeoutMilliseconds)); + var widths = new Dictionary(); + + foreach (var rule in GetEntries().Where(rule => IsTableContext(rule.Context) && rule.Entry.Contains("--single", StringComparison.Ordinal) == isSingle)) + { + var match = columnPattern.Match(rule.Entry); + var width = StylesheetReader.GetDeclarationList(rule.Body).FirstOrDefault(declaration => declaration.Name == "width").Value; + var percent = CreatePercentPattern().Match(width ?? string.Empty); + + if (match.Success && percent.Success) + { + widths[match.Groups[1].Value] = double.Parse(percent.Groups[1].Value, System.Globalization.CultureInfo.InvariantCulture); + } + } + + Assert.AreEqual("fixed", layout.GetValueOrDefault("table-layout"), "From 960 px the table layout must be fixed"); + Assert.AreEqual("100%", layout.GetValueOrDefault("width"), "From 960 px the table must not be wider than its panel"); + Assert.HasCount(columnCount, widths, $"Every column of {tableClass} must have a percentage width from 960 px"); + Assert.IsLessThanOrEqualTo(100.01, widths.Values.Sum(), "The column widths must not add up to more than the panel"); + } + + /// + /// Verify the card cells that hold several lines stack them left aligned, and the rescan control takes the full width of the card + /// + [TestMethod] + [TestCategory("AC10")] + public void AppStylesheetListPagesStackedCellsStackLinesAndRescanIsFullWidth() + { + var stacked = GetDeclarations(rule => rule.Context == CardContext && rule.Entry.EndsWith(".dug-list-table .dug-list-table__stacked", StringComparison.Ordinal)); + var rescan = GetDeclarations(rule => rule.Context == CardContext && rule.Entry.EndsWith(".dug-list-table .dug-list-table__stacked .vulnerability-rescan-control", StringComparison.Ordinal)); + + Assert.AreEqual("column", stacked.GetValueOrDefault("flex-direction"), "A stacked cell must stack its lines in the card"); + Assert.AreEqual("flex-start", stacked.GetValueOrDefault("align-items"), "A stacked cell must align its lines to the left"); + Assert.IsTrue(stacked.ContainsKey("gap"), "A stacked cell must space its lines"); + Assert.AreEqual("100%", rescan.GetValueOrDefault("width"), "The rescan control must take the full width of the card"); + } + + #endregion // Methods + + #region Helper methods + + /// + /// Determine whether a media context is the table layout from 960 px + /// + /// Media context, empty at the top level + /// true for the table layout context + private static bool IsTableContext(string context) + { + return context.StartsWith(TableContextStart, StringComparison.Ordinal); + } + + /// + /// Determine whether a media context is the top level or the table layout from 960 px + /// + /// Media context, empty at the top level + /// true for the top level or the table layout context + private static bool IsTableOrTopLevel(string context) + { + return context.Length == 0 || IsTableContext(context); + } + + /// + /// Merge the declarations of the rules matching the predicate + /// + /// Rule predicate + /// Property name to value, later rules winning + private static Dictionary GetDeclarations(Func<(string Entry, string Body, string Context), bool> match) + { + var merged = new Dictionary(); + + foreach (var rule in GetEntries().Where(match)) + { + foreach (var (name, value) in StylesheetReader.GetDeclarationList(rule.Body)) + { + merged[name] = value; + } + } + + return merged; + } + + /// + /// Read every selector of every rule of the stylesheet, in every media context + /// + /// Selector, rule body and media context + private static List<(string Entry, string Body, string Context)> GetEntries() + { + return [.. StylesheetReader.GetRules(StylesheetReader.ReadHostFile(StylesheetPath)).SelectMany(rule => StylesheetReader.SplitTopLevel(rule.Selector, ',').Select(entry => (entry, rule.Body, rule.Context)))]; + } + + #endregion // Helper methods +} \ No newline at end of file diff --git a/src/Tests/DockerUpdateGuard.Tests/DockerInstancesRenderTests.cs b/src/Tests/DockerUpdateGuard.Tests/DockerInstancesRenderTests.cs index 5852feeb..dd97a131 100644 --- a/src/Tests/DockerUpdateGuard.Tests/DockerInstancesRenderTests.cs +++ b/src/Tests/DockerUpdateGuard.Tests/DockerInstancesRenderTests.cs @@ -19,88 +19,319 @@ namespace DockerUpdateGuard.Tests; [TestClass] public class DockerInstancesRenderTests { + #region Constants + + /// + /// Class of the page's table + /// + private const string TableClass = "docker-instances-table"; + + #endregion // Constants + + #region Fields + + /// + /// Column heads of several instances in order + /// + private static readonly string[] _columnHeads = ["Name", "Endpoint", "Connection", "Latest scan", "CPU", "Memory", "Network", "Containers"]; + + /// + /// Column heads of a single instance in order + /// + private static readonly string[] _singleColumnHeads = ["Name", "Endpoint", "Connection", "Latest scan", "Containers"]; + + /// + /// Labels of the usage cells in order + /// + private static readonly string[] _usageLabels = ["CPU", "Memory", "Network"]; + + #endregion // Fields + #region Methods /// - /// Verify the single-instance history charts render inside the responsive chart wrapper + /// Verify the page shows one header without eyebrow and one panel with the instance and container counts as meta /// /// Task [TestMethod] - public async Task DockerInstancesSingleInstanceWithHistoryRendersResponsiveCharts() + [TestCategory("AC1")] + public async Task DockerInstancesRenderShowsHeaderWithoutEyebrowAndPanelMeta() { - var testContext = BlazorTestContextFactory.Create(); + var testContext = CreateContext([CreateInstance("one", 3), CreateInstance("two", 2)]); await using (testContext) { - var viewService = Substitute.For(); - var instanceId = Guid.NewGuid(); + var page = testContext.Render(); - viewService.GetDockerInstancesAsync(Arg.Any()) - .Returns(Task.FromResult>([ - new DockerInstanceListItemData - { - Id = instanceId, - Name = "local", - EndpointUri = "unix:///var/run/docker.sock", - }, - ])); + ListPageAssert.AssertHeader(page, "Docker Instances", "Configured Docker endpoints with their connection, latest runtime scan and current resource usage."); + ListPageAssert.AssertPanel(page, "Configured instances", "2 instances · 5 containers"); + Assert.HasCount(1, page.FindAll("section.dug-panel"), "Two instances must show only the list panel"); + } + } - viewService.GetDockerInstanceDetailAsync(instanceId, Arg.Any()) - .Returns(Task.FromResult(new DockerInstanceDetailViewData - { - Id = instanceId, - Name = "local", - EndpointUri = "unix:///var/run/docker.sock", - CurrentResourceUsage = CreateUsagePoint(), - ResourceUsageHistory = [CreateUsagePoint(), CreateUsagePoint()], - })); + /// + /// Verify the table of several instances has the eight column heads in order + /// + /// Task + [TestMethod] + [TestCategory("AC2")] + public async Task DockerInstancesRenderShowsColumnHeadsInOrder() + { + var testContext = CreateContext([CreateInstance("one", 1), CreateInstance("two", 1)]); - testContext.Services.AddSingleton(viewService); + await using (testContext) + { + var page = testContext.Render(); - var component = testContext.Render(); + Assert.AreSequenceEqual(_columnHeads, ListPageAssert.GetHeads(page), "The heads must be the eight columns in order"); + } + } - Assert.Contains("dug-chart", component.Markup, "The usage-history charts must render inside the responsive chart wrapper"); + /// + /// Verify an empty list shows the empty state in a panel of its own, without table and meta + /// + /// Task + [TestMethod] + [TestCategory("AC1")] + public async Task DockerInstancesRenderEmptyListShowsEmptyStateWithoutTable() + { + var testContext = CreateContext([]); + + await using (testContext) + { + var page = testContext.Render(); + + Assert.AreEqual("No docker instances are configured.", page.Find(".empty-state-panel").TextContent.Trim(), "The empty state must show today's text"); + Assert.IsEmpty(page.FindAll("table"), "The table must not be shown for an empty list"); + Assert.IsEmpty(page.FindAll(".dug-panel__meta"), "The meta text must not be shown for an empty list"); } } /// - /// Verify the instance list shows the latest scan completion in UTC and nothing for an instance never scanned + /// Verify the latest scan column shows the status as an indicator in its tone /// + /// Scan status + /// Expected tone CSS name /// Task [TestMethod] [TestCategory("AC3")] + [DataRow("Succeeded", "success")] + [DataRow("Partial", "warning")] + [DataRow("NotScanned", "neutral")] + public async Task DockerInstancesRenderLatestScanShowsIndicatorInTone(string status, string tone) + { + var instance = CreateInstance("one", 1); + + instance.LatestScanStatus = status; + + var testContext = CreateContext([instance, CreateInstance("two", 1)]); + + await using (testContext) + { + var page = testContext.Render(); + + ListPageAssert.AssertIndicator(ListPageAssert.FindCell(page, 0, "Latest scan"), status, tone); + } + } + + /// + /// Verify the latest scan column shows the completion in UTC below the indicator and no time line for an instance never scanned + /// + /// Task + [TestMethod] + [TestCategory("AC7")] public async Task DockerInstancesWithAndWithoutScanCompletionRendersUtcOrEmptyAsync() { - var testContext = BlazorTestContextFactory.Create(); + var scanned = CreateInstance("scanned", 1); + var fresh = CreateInstance("fresh", 1); + + scanned.LatestScanStatus = "Succeeded"; + scanned.LatestScanCompletedAtUtc = new DateTimeOffset(2026, 11, 23, 23, 27, 0, TimeSpan.FromHours(2)); + fresh.LatestScanStatus = "NotScanned"; + + var testContext = CreateContext([scanned, fresh]); await using (testContext) { - var viewService = Substitute.For(); + var page = testContext.Render(); + var scannedCell = ListPageAssert.FindCell(page, 0, "Latest scan"); + var freshCell = ListPageAssert.FindCell(page, 1, "Latest scan"); - viewService.GetDockerInstancesAsync(Arg.Any()) - .Returns(Task.FromResult>([ - new DockerInstanceListItemData - { - Id = Guid.NewGuid(), - Name = "scanned", - LatestScanStatus = "Succeeded", - LatestScanCompletedAtUtc = new DateTimeOffset(2026, 11, 23, 23, 27, 0, TimeSpan.FromHours(2)), - }, - new DockerInstanceListItemData - { - Id = Guid.NewGuid(), - Name = "fresh", - LatestScanStatus = "NotScanned", - }, - ])); + Assert.AreEqual("2026-11-23 21:27 UTC", scannedCell.QuerySelector("span.table-secondary")?.TextContent.Trim(), "A completed scan must be shown in UTC with the zone suffix below the indicator"); + Assert.IsEmpty(freshCell.QuerySelectorAll("span.table-secondary"), "An instance without a completed scan must show no time line"); + Assert.IsEmpty(page.FindAll("td[data-label='Name'] span.table-secondary"), "The Name column must no longer carry the scan status"); + } + } - testContext.Services.AddSingleton(viewService); + /// + /// Verify the memory meter stands below the value only when the host memory total is known, and the value stays as today without it + /// + /// Task + [TestMethod] + [TestCategory("AC7")] + public async Task DockerInstancesRenderMemoryMeterOnlyWithHostTotal() + { + var known = CreateInstance("known", 1); + var noLimit = CreateInstance("no-limit", 1); + var noUsage = CreateInstance("no-usage", 1); + var over = CreateInstance("over", 1); + + known.CurrentResourceUsage = CreateUsagePoint(250, 1000); + noLimit.CurrentResourceUsage = CreateUsagePoint(250, 0); + noUsage.CurrentResourceUsage = null; + over.CurrentResourceUsage = CreateUsagePoint(2000, 1000); + + var testContext = CreateContext([known, noLimit, noUsage, over]); + + await using (testContext) + { + var page = testContext.Render(); + var knownMeter = ListPageAssert.FindCell(page, 0, "Memory").QuerySelector(".dug-meter"); + var overMeter = ListPageAssert.FindCell(page, 3, "Memory").QuerySelector(".dug-meter"); + + Assert.IsNotNull(knownMeter, "A known host total must show the meter"); + Assert.AreEqual("img", knownMeter.GetAttribute("role"), "The meter must be an image for assistive technology"); + Assert.AreEqual("25 percent of host memory", knownMeter.GetAttribute("aria-label"), "The meter must announce the share"); + Assert.Contains("width: 25%", knownMeter.QuerySelector(".dug-meter__fill")?.GetAttribute("style") ?? string.Empty, "The fill must be as wide as the share"); + Assert.Contains(ResourceUsageFormatter.FormatMemory(250, 1000), ListPageAssert.FindCell(page, 0, "Memory").TextContent, "The value must stay as today"); + Assert.IsEmpty(ListPageAssert.FindCell(page, 1, "Memory").QuerySelectorAll(".dug-meter"), "A host total of 0 must show no meter"); + Assert.Contains(ResourceUsageFormatter.FormatMemory(250, 0), ListPageAssert.FindCell(page, 1, "Memory").TextContent, "Without a host total the cell must show the bytes alone"); + Assert.IsEmpty(ListPageAssert.FindCell(page, 2, "Memory").QuerySelectorAll(".dug-meter"), "A missing usage must show no meter"); + Assert.Contains("n/a", ListPageAssert.FindCell(page, 2, "Memory").TextContent, "A missing usage must show n/a"); + Assert.IsNotNull(overMeter, "A usage above the total must still show the meter"); + Assert.AreEqual("200 percent of host memory", overMeter.GetAttribute("aria-label"), "The meter must read the real percentage above 100"); + Assert.Contains("width: 100%", overMeter.QuerySelector(".dug-meter__fill")?.GetAttribute("style") ?? string.Empty, "The fill must stop at the full width"); + } + } + + /// + /// Verify the meter announces the share rounded to a whole percent, half away from zero + /// + /// Memory usage bytes + /// Expected aria label + /// Task + [TestMethod] + [TestCategory("AC7")] + [DataRow(614L, "61 percent of host memory")] + [DataRow(615L, "62 percent of host memory")] + [DataRow(0L, "0 percent of host memory")] + public async Task DockerInstancesRenderMemoryMeterAnnouncesShare(long usageBytes, string expectedLabel) + { + var instance = CreateInstance("one", 1); + + instance.CurrentResourceUsage = CreateUsagePoint(usageBytes, 1000); + + var testContext = CreateContext([instance, CreateInstance("two", 1)]); + + await using (testContext) + { + var page = testContext.Render(); + + Assert.AreEqual(expectedLabel, ListPageAssert.FindCell(page, 0, "Memory").QuerySelector(".dug-meter")?.GetAttribute("aria-label"), "The meter must announce the rounded share"); + } + } + + /// + /// Verify the single-instance panel shows the three usage cells with their history charts in place of cards and chart section + /// + /// Task + [TestMethod] + [TestCategory("AC8")] + public async Task DockerInstancesSingleInstanceWithHistoryRendersResponsiveCharts() + { + var testContext = CreateSingleInstanceContext([CreateUsagePoint(256, 1024), CreateUsagePoint(300, 1024)]); + + await using (testContext) + { + var page = testContext.Render(); + var cells = page.FindAll(".dug-usage__cell"); + + ListPageAssert.AssertPanel(page, "local", "unix:///var/run/docker.sock"); + Assert.AreSequenceEqual(_usageLabels, cells.Select(cell => cell.QuerySelector(".dug-usage__label")?.TextContent.Trim()).ToList(), "The panel must show the CPU, Memory and Network cells"); + Assert.HasCount(3, page.FindAll(".dug-history-chart"), "Every usage cell must draw its history chart"); + Assert.DoesNotContain("dug-chart\"", page.Markup, "The old chart wrapper must be gone"); + Assert.IsEmpty(page.FindAll(".summary-card"), "The summary cards must be gone"); + Assert.IsEmpty(page.FindAll(".mud-chart"), "The large MudBlazor charts must be gone"); + Assert.DoesNotContain("Usage history", page.Markup, "The Usage history section must be gone"); + Assert.DoesNotContain("No resource history", page.Markup, "With history there must be no empty-history text"); + } + } - var component = testContext.Render(); - var secondaries = component.FindAll("span.table-secondary").Select(element => element.TextContent.Trim()).ToList(); + /// + /// Verify without stored history the usage cells show their current values without a chart and the empty-history text stands below + /// + /// Task + [TestMethod] + [TestCategory("AC8")] + public async Task DockerInstancesRenderSingleInstanceWithoutHistoryShowsEmptyHistoryText() + { + var testContext = CreateSingleInstanceContext([]); - Assert.Contains("Succeeded · 2026-11-23 21:27 UTC", secondaries, "A completed scan must be shown in UTC with the zone suffix"); - Assert.Contains("NotScanned ·", secondaries, "An instance without a completed scan must show no timestamp"); + await using (testContext) + { + var page = testContext.Render(); + + Assert.HasCount(3, page.FindAll(".dug-usage__cell"), "The three usage cells must stay"); + Assert.AreEqual(ResourceUsageFormatter.FormatCpuPercent(12.5m), page.Find(".dug-usage__cell .dug-usage__value").TextContent.Trim(), "The cells must show their current values"); + Assert.IsEmpty(page.FindAll(".dug-history-chart"), "Without history no chart must be drawn"); + Assert.Contains("No resource history is currently stored for this Docker instance.", page.Find(".dug-panel__body .empty-state-panel").TextContent, "The empty-history text must stand below the cells"); + } + } + + /// + /// Verify with exactly one loaded instance the table hides the usage columns and keeps the latest scan + /// + /// Task + [TestMethod] + [TestCategory("AC8")] + public async Task DockerInstancesRenderSingleInstanceHidesUsageColumns() + { + var testContext = CreateSingleInstanceContext([CreateUsagePoint(256, 1024)]); + + await using (testContext) + { + var page = testContext.Render(); + + Assert.AreSequenceEqual(_singleColumnHeads, ListPageAssert.GetHeads(page), "The table must keep five columns, with the latest scan"); + Assert.IsNotEmpty(page.FindAll(".docker-instances-table--single"), "The table must carry the single-instance modifier for its column widths"); + } + } + + /// + /// Verify one instance without a loaded detail keeps the usage columns and shows no usage panel + /// + /// Task + [TestMethod] + [TestCategory("AC8")] + public async Task DockerInstancesRenderSingleInstanceWithoutDetailKeepsUsageColumns() + { + var testContext = CreateContext([CreateInstance("local", 1)]); + + await using (testContext) + { + var page = testContext.Render(); + + Assert.AreSequenceEqual(_columnHeads, ListPageAssert.GetHeads(page), "Without the detail the table must keep its usage columns"); + Assert.IsEmpty(page.FindAll(".dug-usage"), "Without the detail no usage panel must show"); + Assert.IsEmpty(page.FindAll(".docker-instances-table--single"), "Without the detail the table must not use the single-instance widths"); + } + } + + /// + /// Verify the table switches to cards below 960 px and labels every cell with its head + /// + /// Task + [TestMethod] + [TestCategory("AC10")] + public async Task DockerInstancesRenderTableSwitchesToCardsBelow960Px() + { + var testContext = CreateContext([CreateInstance("one", 1), CreateInstance("two", 1)]); + + await using (testContext) + { + var page = testContext.Render(); + + ListPageAssert.AssertCardLayout(page, TableClass, _columnHeads, "Latest scan", "Memory"); } } @@ -173,20 +404,84 @@ public async Task DockerInstancesDetailLoadFailureShowsNoInstanceData() } } + /// + /// Create a test context with the page's services and a list the view service returns + /// + /// Listed Docker instances + /// Test context + private static BunitContext CreateContext(IReadOnlyList instances) + { + var testContext = BlazorTestContextFactory.Create(); + var viewService = Substitute.For(); + + viewService.GetDockerInstancesAsync(Arg.Any()) + .Returns(instances); + + testContext.Services.AddSingleton(viewService); + + return testContext; + } + + /// + /// Create a test context with exactly one instance whose detail loads with the history + /// + /// Resource usage history of the instance + /// Test context + private static BunitContext CreateSingleInstanceContext(IReadOnlyList history) + { + var instance = CreateInstance("local", 1); + var testContext = CreateContext([instance]); + var viewService = testContext.Services.GetRequiredService(); + + viewService.GetDockerInstanceDetailAsync(instance.Id, Arg.Any()) + .Returns(Task.FromResult(new DockerInstanceDetailViewData + { + Id = instance.Id, + Name = "local", + EndpointUri = instance.EndpointUri, + CurrentResourceUsage = CreateUsagePoint(256, 1024), + ResourceUsageHistory = history, + })); + + return testContext; + } + + /// + /// Create an instance row with a current resource usage + /// + /// Instance name + /// Runtime container count + /// Instance row + private static DockerInstanceListItemData CreateInstance(string name, int containerCount) + { + return new DockerInstanceListItemData + { + Id = Guid.NewGuid(), + Name = name, + EndpointUri = "unix:///var/run/docker.sock", + ConnectionKind = "Socket", + LatestScanStatus = "Succeeded", + RuntimeContainerCount = containerCount, + CurrentResourceUsage = CreateUsagePoint(256, 1024), + }; + } + /// /// Create a resource usage point for the tests /// + /// Memory usage bytes + /// Host memory total bytes /// Resource usage point - private static ResourceUsagePointViewData CreateUsagePoint() + private static ResourceUsagePointViewData CreateUsagePoint(long memoryUsageBytes, long memoryLimitBytes) { return new ResourceUsagePointViewData { CpuPercent = 12.5m, - MemoryUsageBytes = 256 * 1024 * 1024, - MemoryLimitBytes = 1024 * 1024 * 1024, + MemoryUsageBytes = memoryUsageBytes, + MemoryLimitBytes = memoryLimitBytes, NetworkRxBytesPerSecond = 1024, NetworkTxBytesPerSecond = 512, - RecordedAtUtc = DateTimeOffset.UtcNow, + RecordedAtUtc = new DateTimeOffset(2026, 11, 23, 21, 0, 0, TimeSpan.Zero), }; } diff --git a/src/Tests/DockerUpdateGuard.Tests/Helper/ListPageAssert.cs b/src/Tests/DockerUpdateGuard.Tests/Helper/ListPageAssert.cs new file mode 100644 index 00000000..19eb654f --- /dev/null +++ b/src/Tests/DockerUpdateGuard.Tests/Helper/ListPageAssert.cs @@ -0,0 +1,127 @@ +using AngleSharp.Dom; + +using Bunit; + +using Microsoft.AspNetCore.Components; + +namespace DockerUpdateGuard.Tests.Helper; + +/// +/// Assertions shared by the render tests of the list pages +/// +internal static class ListPageAssert +{ + #region Static methods + + /// + /// Assert the page header carries the title and the description, and the old eyebrow and section description are gone + /// + /// Rendered page + /// Expected page title + /// Expected page description + public static void AssertHeader(IRenderedComponent page, string title, string description) + { + Assert.AreEqual(title, page.Find("h1.dug-page-header__title").TextContent.Trim(), "The header must carry the page title"); + Assert.AreEqual(description, page.Find("p.dug-page-header__description").TextContent.Trim(), "The header must carry the description sentence"); + Assert.IsEmpty(page.FindAll(".page-eyebrow"), "The eyebrow label must be gone"); + Assert.IsEmpty(page.FindAll(".section-description"), "The section description line must be gone"); + } + + /// + /// Find the panel with the title + /// + /// Rendered page + /// Panel title + /// Panel element + public static IElement FindPanel(IRenderedComponent page, string title) + { + var panel = page.FindAll("section.dug-panel") + .FirstOrDefault(candidate => candidate.QuerySelector("h2.dug-panel__title")?.TextContent.Trim() == title); + + Assert.IsNotNull(panel, $"The page must show the panel '{title}'"); + + return panel; + } + + /// + /// Assert the panel with the title shows the meta text, or no meta text when it is null + /// + /// Rendered page + /// Panel title + /// Expected meta text, or null for none + public static void AssertPanel(IRenderedComponent page, string title, string? meta) + { + var panel = FindPanel(page, title); + var metaElement = panel.QuerySelector(".dug-panel__header span.dug-panel__meta"); + + Assert.AreEqual(meta, metaElement?.TextContent.Trim(), $"The panel '{title}' must show the expected meta text"); + } + + /// + /// Read the column heads of the table + /// + /// Rendered page + /// Head texts in order + public static List GetHeads(IRenderedComponent page) + { + return [.. page.FindAll("thead th").Select(head => head.TextContent.Trim())]; + } + + /// + /// Find the cell of the row with the data label + /// + /// Rendered page + /// Zero-based row index + /// Data label of the cell + /// Cell element + public static IElement FindCell(IRenderedComponent page, int rowIndex, string label) + { + var cells = page.FindAll($"tbody tr:nth-child({rowIndex + 1}) td[data-label='{label}']"); + + Assert.HasCount(1, cells, $"Row {rowIndex} must have one cell labelled '{label}'"); + + return cells[0]; + } + + /// + /// Assert the table switches to cards below 960 px, has the shared list table class and labels every cell with its head + /// + /// Rendered page + /// Class of the page's table + /// Expected heads, which are the data labels of one row + /// Data labels of the cells that stack their lines in the card + public static void AssertCardLayout(IRenderedComponent page, string tableClass, IReadOnlyList heads, params string[] stackedLabels) + { + var labels = page.FindAll("tbody tr:first-child td").Select(cell => cell.GetAttribute("data-label")).ToList(); + + Assert.IsNotEmpty(page.FindAll(".mud-sm-table"), "The table must use the small-screen card breakpoint (class mud-sm-table)"); + Assert.IsEmpty(page.FindAll(".mud-md-table"), "The table must not use the medium breakpoint"); + Assert.IsNotEmpty(page.FindAll($".mud-table.dug-list-table.{tableClass}"), $"The table must carry the classes dug-list-table and {tableClass}"); + Assert.AreSequenceEqual(heads, labels, "Every cell must carry the label of its head"); + + foreach (var label in stackedLabels) + { + var cell = page.Find($"tbody tr:first-child td[data-label='{label}']"); + + Assert.IsTrue(cell.ClassList.Contains("dug-list-table__stacked"), $"The cell '{label}' must stack its lines in the card"); + } + } + + /// + /// Assert the cell shows the scan status as an indicator in the tone, with no chip + /// + /// Table cell + /// Status text + /// Tone CSS name + public static void AssertIndicator(IElement cell, string status, string tone) + { + var indicator = cell.QuerySelector(".dug-status"); + + Assert.IsNotNull(indicator, $"The status '{status}' must be shown as an indicator"); + Assert.IsTrue(indicator.ClassList.Contains($"dug-status--{tone}"), $"The status '{status}' must be shown in the {tone} tone"); + Assert.AreEqual(status, indicator.QuerySelector(".dug-status__text")?.TextContent, "The indicator must show the status text"); + Assert.IsEmpty(cell.QuerySelectorAll(".mud-chip, .dug-chip"), "The status must not be a chip"); + } + + #endregion // Static methods +} \ No newline at end of file diff --git a/src/Tests/DockerUpdateGuard.Tests/ListPageMetaFormatterTests.cs b/src/Tests/DockerUpdateGuard.Tests/ListPageMetaFormatterTests.cs new file mode 100644 index 00000000..051791c4 --- /dev/null +++ b/src/Tests/DockerUpdateGuard.Tests/ListPageMetaFormatterTests.cs @@ -0,0 +1,115 @@ +using DockerUpdateGuard.UI; + +namespace DockerUpdateGuard.Tests; + +/// +/// Tests for +/// +[TestClass] +public class ListPageMetaFormatterTests +{ + #region Methods + + /// + /// Verify the My Images meta counts the images and those with at least one running container + /// + /// Linked running container count per image + /// Expected meta text + [TestMethod] + [TestCategory("AC1")] + [DataRow(new[] { 0 }, "1 image · 0 running")] + [DataRow(new[] { 3 }, "1 image · 1 running")] + [DataRow(new[] { 0, 0 }, "2 images · 0 running")] + [DataRow(new[] { 4, 0, 1 }, "3 images · 2 running")] + public void ListPageMetaFormatterFormatMyImagesMetaCountsRunningImages(int[] runningCounts, string expected) + { + var images = runningCounts.Select(count => new ObservedImageListItemData + { + LinkedRuntimeContainerCount = count + }) + .ToList(); + + var meta = ListPageMetaFormatter.FormatMyImagesMeta(images); + + Assert.AreEqual(expected, meta, "The meta must count images and images with a running container, in singular and plural"); + } + + /// + /// Verify the Docker Instances meta sums the container counts of all instances + /// + /// Container count per instance + /// Expected meta text + [TestMethod] + [TestCategory("AC1")] + [DataRow(new[] { 1 }, "1 instance · 1 container")] + [DataRow(new[] { 0 }, "1 instance · 0 containers")] + [DataRow(new[] { 0, 0 }, "2 instances · 0 containers")] + [DataRow(new[] { 3, 2 }, "2 instances · 5 containers")] + public void ListPageMetaFormatterFormatDockerInstancesMetaSumsContainers(int[] containerCounts, string expected) + { + var instances = containerCounts.Select(count => new DockerInstanceListItemData + { + RuntimeContainerCount = count + }) + .ToList(); + + var meta = ListPageMetaFormatter.FormatDockerInstancesMeta(instances); + + Assert.AreEqual(expected, meta, "The meta must count instances and sum their containers, in singular and plural"); + } + + /// + /// Verify the Scan History meta lists the counts above zero in the order succeeded, running, pending, partial, failed + /// + /// Statuses of the listed runs + /// Expected meta text + [TestMethod] + [TestCategory("AC1")] + [DataRow("Failed,Partial,Pending,Running,Succeeded", "1 succeeded · 1 running · 1 pending · 1 partial · 1 failed")] + [DataRow("Failed,Succeeded,Succeeded,Partial,Succeeded,Running", "3 succeeded · 1 running · 1 partial · 1 failed")] + [DataRow("Pending", "1 pending")] + public void ListPageMetaFormatterFormatScanHistoryMetaListsCountsInOrder(string statuses, string expected) + { + var scans = CreateScans(statuses); + + var meta = ListPageMetaFormatter.FormatScanHistoryMeta(scans); + + Assert.AreEqual(expected, meta, "The meta must list the counts above zero in the fixed status order"); + } + + /// + /// Verify runs with a status outside the five run statuses are left out of the meta + /// + /// Statuses of the listed runs + /// Expected meta text + [TestMethod] + [TestCategory("AC1")] + [DataRow("Succeeded,NotScanned,NotSet,Something else", "1 succeeded")] + [DataRow("NotScanned", "")] + public void ListPageMetaFormatterFormatScanHistoryMetaLeavesOutOtherStatuses(string statuses, string expected) + { + var scans = CreateScans(statuses); + + var meta = ListPageMetaFormatter.FormatScanHistoryMeta(scans); + + Assert.AreEqual(expected, meta, "Runs with other statuses must not appear in the meta"); + } + + /// + /// Create runs from a comma separated list of statuses + /// + /// Statuses + /// Runs + private static List CreateScans(string statuses) + { + return [ + .. statuses.Split(',') + .Select(status => new ScanHistoryItemData + { + Status = status + }) + ]; + } + + #endregion // Methods +} \ No newline at end of file diff --git a/src/Tests/DockerUpdateGuard.Tests/MyImagesRenderTests.cs b/src/Tests/DockerUpdateGuard.Tests/MyImagesRenderTests.cs new file mode 100644 index 00000000..91405324 --- /dev/null +++ b/src/Tests/DockerUpdateGuard.Tests/MyImagesRenderTests.cs @@ -0,0 +1,401 @@ +using Bunit; + +using DockerUpdateGuard.Components.Common; +using DockerUpdateGuard.Components.Pages; +using DockerUpdateGuard.Configuration; +using DockerUpdateGuard.Images.Interfaces; +using DockerUpdateGuard.Tests.Data; +using DockerUpdateGuard.Tests.Helper; +using DockerUpdateGuard.UI; + +using Microsoft.Extensions.DependencyInjection; +using Microsoft.Extensions.Logging; +using Microsoft.Extensions.Options; + +using NSubstitute; + +namespace DockerUpdateGuard.Tests; + +/// +/// Render tests for the list of +/// +[TestClass] +public class MyImagesRenderTests +{ + #region Constants + + /// + /// Class of the page's table + /// + private const string TableClass = "my-images-table"; + + #endregion // Constants + + #region Fields + + /// + /// Column heads in order + /// + private static readonly string[] _columnHeads = ["Name", "Image", "Latest scan", "Running", "Base runtime", "Vulnerabilities"]; + + #endregion // Fields + + #region Methods + + /// + /// Verify the page shows one header without eyebrow and one panel with the user name as title and the meta text + /// + /// Number of listed images, of which the first one is running + /// Expected meta text + /// Task + [TestMethod] + [TestCategory("AC1")] + [DataRow(1, "1 image · 1 running")] + [DataRow(3, "3 images · 1 running")] + public async Task MyImagesRenderShowsHeaderWithoutEyebrowAndPanelMeta(int imageCount, string expectedMeta) + { + var images = Enumerable.Range(0, imageCount).Select(index => CreateImage($"image-{index}", index == 0 ? 2 : 0)).ToList(); + var testContext = CreateContext(images, "acme"); + + await using (testContext) + { + var page = testContext.Render(); + + ListPageAssert.AssertHeader(page, "My Images", "Own images discovered from the configured Docker Hub account; running ones come first."); + ListPageAssert.AssertPanel(page, "acme", expectedMeta); + Assert.HasCount(1, page.FindAll("section.dug-panel"), "The page must show exactly one panel"); + } + } + + /// + /// Verify the panel title is the trimmed Docker Hub user name, or the fallback without one + /// + /// Configured user name + /// Expected panel title + /// Task + [TestMethod] + [TestCategory("AC1")] + [DataRow("acme", "acme")] + [DataRow(" acme ", "acme")] + [DataRow(null, "Images from Docker account")] + [DataRow("", "Images from Docker account")] + [DataRow(" ", "Images from Docker account")] + public async Task MyImagesRenderPanelTitleIsUserNameOrFallback(string? userName, string expectedTitle) + { + var testContext = CreateContext([CreateImage("web", 0)], userName); + + await using (testContext) + { + var page = testContext.Render(); + + Assert.AreEqual(expectedTitle, page.Find("h2.dug-panel__title").TextContent.Trim(), "The panel title must be the user name or the fallback"); + } + } + + /// + /// Verify a pending load shows the table skeleton with the panel title, and neither table nor empty state + /// + /// Task + [TestMethod] + [TestCategory("AC1")] + public async Task MyImagesRenderLoadingShowsSkeletonWithPanelTitle() + { + var testContext = BlazorTestContextFactory.Create(); + + await using (testContext) + { + var pending = new TaskCompletionSource>(); + var viewService = Substitute.For(); + + viewService.GetDiscoveryObservedImagesAsync(Arg.Any()) + .Returns(pending.Task); + RegisterServices(testContext, viewService, "acme"); + + var page = testContext.Render(); + + Assert.AreEqual("acme", page.FindComponent().Instance.Title, "The skeleton must carry the same title as the loaded panel"); + Assert.IsNotEmpty(page.FindAll(".dug-panel__header .mud-skeleton"), "The skeleton must show a title placeholder"); + Assert.IsNotEmpty(page.FindAll(".dug-panel__body .mud-skeleton"), "The skeleton must show row placeholders"); + Assert.IsEmpty(page.FindAll("table"), "The table must not be shown while loading"); + Assert.IsEmpty(page.FindAll(".empty-state-panel"), "The empty state must not be shown while loading"); + + pending.SetResult([]); + await page.WaitForAssertionAsync(() => Assert.IsEmpty(page.FindAll(".mud-skeleton"), "The skeleton must disappear after the load"), TimeSpan.FromSeconds(DetailPageAssert.WaitSeconds)).ConfigureAwait(false); + } + } + + /// + /// Verify the table has the six column heads in order + /// + /// Task + [TestMethod] + [TestCategory("AC2")] + public async Task MyImagesRenderShowsColumnHeadsInOrder() + { + var testContext = CreateContext([CreateImage("web", 0)], "acme"); + + await using (testContext) + { + var page = testContext.Render(); + + Assert.AreSequenceEqual(_columnHeads, ListPageAssert.GetHeads(page), "The heads must be the six columns in order"); + } + } + + /// + /// Verify the running cell shows the count wording as plain text or Not running in muted text, and no chip + /// + /// Linked running containers + /// Expected cell text + /// Whether the text is muted + /// Task + [TestMethod] + [TestCategory("AC2")] + [DataRow(0, "Not running", true)] + [DataRow(1, "1 container", false)] + [DataRow(2, "2 containers", false)] + public async Task MyImagesRenderRunningCellShowsWordingWithoutChip(int runningCount, string expectedText, bool expectedMuted) + { + var testContext = CreateContext([CreateImage("web", runningCount)], "acme"); + + await using (testContext) + { + var page = testContext.Render(); + var cell = ListPageAssert.FindCell(page, 0, "Running"); + var muted = cell.QuerySelectorAll("span.table-secondary").Count(element => element.TextContent.Trim() == expectedText); + + Assert.AreEqual(expectedText, cell.TextContent.Trim(), "The cell must show the count wording"); + Assert.AreEqual(expectedMuted ? 1 : 0, muted, "Only the Not running text must be muted"); + Assert.IsEmpty(cell.QuerySelectorAll(".mud-chip, .dug-chip"), "The cell must show no chip"); + } + } + + /// + /// Verify the base runtime cell shows the alert summary as plain text, or the muted No runtime warning, and no chip + /// + /// Task + [TestMethod] + [TestCategory("AC2")] + public async Task MyImagesRenderBaseRuntimeCellWithAndWithoutWarning() + { + var warned = CreateImage("warned", 0); + var clean = CreateImage("clean", 0); + + warned.BaseRuntimeAlertSummary = "Base image debian:12 is running with an outdated tag"; + + var testContext = CreateContext([warned, clean], "acme"); + + await using (testContext) + { + var page = testContext.Render(); + var warnedCell = ListPageAssert.FindCell(page, 0, "Base runtime"); + var cleanCell = ListPageAssert.FindCell(page, 1, "Base runtime"); + + Assert.AreEqual("Base image debian:12 is running with an outdated tag", warnedCell.TextContent.Trim(), "The alert summary must be the only text of the cell"); + Assert.IsEmpty(warnedCell.QuerySelectorAll("span.table-secondary"), "The alert summary must not be muted"); + Assert.AreEqual("No runtime warning", cleanCell.TextContent.Trim(), "Without a warning the cell must say so"); + Assert.AreEqual(1, cleanCell.QuerySelectorAll("span.table-secondary").Length, "Without a warning the text must be muted"); + Assert.IsEmpty(page.FindAll("td[data-label='Base runtime'] .mud-chip, td[data-label='Base runtime'] .dug-chip"), "The cell must show no chip"); + } + } + + /// + /// Verify the latest scan cell shows the scan message in a muted line only when there is one + /// + /// Task + [TestMethod] + [TestCategory("AC2")] + public async Task MyImagesRenderLatestScanCellShowsMessageLineOnlyWhenNotEmpty() + { + var withMessage = CreateImage("with", 0); + var withoutMessage = CreateImage("without", 0); + + withMessage.LatestScanMessage = "Registry answered with 2 tags"; + withoutMessage.LatestScanMessage = null; + + var testContext = CreateContext([withMessage, withoutMessage], "acme"); + + await using (testContext) + { + var page = testContext.Render(); + var withCell = ListPageAssert.FindCell(page, 0, "Latest scan"); + var withoutCell = ListPageAssert.FindCell(page, 1, "Latest scan"); + + Assert.AreEqual("Registry answered with 2 tags", withCell.QuerySelector("span.table-secondary")?.TextContent.Trim(), "The message must be muted below the indicator"); + Assert.IsEmpty(withoutCell.QuerySelectorAll("span.table-secondary"), "Without a message no muted line must follow the indicator"); + } + } + + /// + /// Verify every row renders its vulnerability cell with the shared component and the values of the row + /// + /// Task + [TestMethod] + [TestCategory("AC4")] + public async Task MyImagesRenderVulnerabilityCellUsesSharedComponent() + { + var first = CreateImage("first", 0); + var second = CreateImage("second", 0); + + first.VulnerabilityStatus = "Failed"; + first.VulnerabilitySeveritySummary = new VulnerabilitySeveritySummaryViewData + { + HighCount = 2 + }; + first.ActiveBaseImageVulnerabilityFindingCount = 3; + first.BaseImageVulnerabilitySummary = "3 active finding(s) across 1 base image"; + + var testContext = CreateContext([first, second], "acme"); + + await using (testContext) + { + var page = testContext.Render(); + var cells = page.FindComponents(); + + Assert.HasCount(2, cells, "Every row must render the shared vulnerability cell"); + Assert.AreEqual(first.CurrentImageVersionId, cells[0].Instance.ImageVersionId, "The cell must rescan the current image version of its row"); + Assert.AreEqual("Failed", cells[0].Instance.Status, "The cell must receive the status of its row"); + Assert.AreEqual(2, cells[0].Instance.SeveritySummary?.HighCount, "The cell must receive the severity summary of its row"); + Assert.AreEqual(3, cells[0].Instance.ActiveBaseImageFindingCount, "The cell must receive the base image finding count of its row"); + Assert.AreEqual(first.BaseImageVulnerabilitySummary, cells[0].Instance.BaseImageSummary, "The cell must receive the base image summary of its row"); + Assert.IsEmpty(page.FindAll("td[data-label='Vulnerabilities'] .mud-chip"), "The old MudBlazor chips must be gone"); + } + } + + /// + /// Verify the table switches to cards below 960 px and labels every cell with its head + /// + /// Task + [TestMethod] + [TestCategory("AC10")] + public async Task MyImagesRenderTableSwitchesToCardsBelow960Px() + { + var testContext = CreateContext([CreateImage("web", 1)], "acme"); + + await using (testContext) + { + var page = testContext.Render(); + + ListPageAssert.AssertCardLayout(page, TableClass, _columnHeads, "Name", "Latest scan", "Base runtime", "Vulnerabilities"); + } + } + + /// + /// Verify an empty list shows the empty state in a panel of its own, without table and meta + /// + /// Task + [TestMethod] + [TestCategory("AC1")] + public async Task MyImagesRenderEmptyListShowsEmptyStateWithoutTable() + { + var testContext = CreateContext([], "acme"); + + await using (testContext) + { + var page = testContext.Render(); + + Assert.AreEqual("No own images from the Docker account are currently available.", page.Find(".empty-state-panel").TextContent.Trim(), "The empty state must show today's text"); + Assert.IsEmpty(page.FindAll("table"), "The table must not be shown for an empty list"); + Assert.IsEmpty(page.FindAll(".dug-panel__meta"), "The meta text must not be shown for an empty list"); + } + } + + /// + /// Verify the name cell shows the link only when the image has no description, and the description below it otherwise + /// + /// Task + [TestMethod] + [TestCategory("AC2")] + public async Task MyImagesRenderNameCellWithoutDescriptionShowsLinkOnly() + { + var described = CreateImage("described", 0); + var plain = CreateImage("plain", 0); + var blank = CreateImage("blank", 0); + var empty = CreateImage("empty", 0); + + described.Description = "Frontend of the shop"; + plain.Description = null; + blank.Description = " "; + empty.Description = string.Empty; + + var testContext = CreateContext([described, plain, blank, empty], "acme"); + + await using (testContext) + { + var page = testContext.Render(); + var describedCell = ListPageAssert.FindCell(page, 0, "Name"); + var plainCell = ListPageAssert.FindCell(page, 1, "Name"); + var blankCell = ListPageAssert.FindCell(page, 2, "Name"); + + Assert.AreEqual("Frontend of the shop", describedCell.QuerySelector("span.table-secondary")?.TextContent.Trim(), "The description must stand muted below the link"); + Assert.AreEqual($"/my-images/{plain.Id}", plainCell.QuerySelector("a")?.GetAttribute("href"), "The link must lead to the detail page"); + Assert.AreEqual("plain", plainCell.TextContent.Trim(), "Without a description the cell must show the name only"); + Assert.IsEmpty(plainCell.QuerySelectorAll("span.table-secondary"), "Without a description no muted line must follow the link"); + Assert.IsEmpty(blankCell.QuerySelectorAll("span.table-secondary"), "A blank description must show no muted line"); + Assert.IsEmpty(ListPageAssert.FindCell(page, 3, "Name").QuerySelectorAll("span.table-secondary"), "An empty description must show no muted line"); + } + } + + #endregion // Methods + + #region Helper methods + + /// + /// Create a test context with the page's services and a list the view service returns + /// + /// Listed images + /// Configured Docker Hub user name + /// Test context + private static BunitContext CreateContext(IReadOnlyList images, string? userName) + { + var testContext = BlazorTestContextFactory.Create(); + var viewService = Substitute.For(); + + viewService.GetDiscoveryObservedImagesAsync(Arg.Any()) + .Returns(images); + RegisterServices(testContext, viewService, userName); + + return testContext; + } + + /// + /// Register the services of the page + /// + /// Test context + /// View service + /// Configured Docker Hub user name + private static void RegisterServices(BunitContext testContext, IApplicationViewService viewService, string? userName) + { + var options = new DockerUpdateGuardOptions(); + + options.DockerHub.UserName = userName; + + testContext.Services.AddSingleton(viewService); + testContext.Services.AddSingleton(Substitute.For()); + testContext.Services.AddSingleton(new DashboardRefreshState()); + testContext.Services.AddSingleton(Options.Create(options)); + testContext.Services.AddSingleton>(new TestLogger()); + } + + /// + /// Create an image row without findings + /// + /// Image name + /// Linked running containers + /// Image row + private static ObservedImageListItemData CreateImage(string name, int runningCount) + { + return new ObservedImageListItemData + { + Id = Guid.NewGuid(), + Name = name, + CurrentImageVersionId = Guid.NewGuid(), + ImageReference = $"docker.io/acme/{name}:1.0", + LatestScanStatus = "Succeeded", + LinkedRuntimeContainerCount = runningCount, + VulnerabilityStatus = "No findings", + }; + } + + #endregion // Helper methods +} \ No newline at end of file diff --git a/src/Tests/DockerUpdateGuard.Tests/MyImagesTests.cs b/src/Tests/DockerUpdateGuard.Tests/MyImagesTests.cs index c963c825..a031f109 100644 --- a/src/Tests/DockerUpdateGuard.Tests/MyImagesTests.cs +++ b/src/Tests/DockerUpdateGuard.Tests/MyImagesTests.cs @@ -4,6 +4,7 @@ using DockerUpdateGuard.Components.Pages; using DockerUpdateGuard.Configuration; +using DockerUpdateGuard.Images.Interfaces; using DockerUpdateGuard.Tests.Data; using DockerUpdateGuard.Tests.Helper; using DockerUpdateGuard.UI; @@ -12,8 +13,6 @@ using Microsoft.Extensions.Logging; using Microsoft.Extensions.Options; -using MudBlazor; - using NSubstitute; namespace DockerUpdateGuard.Tests; @@ -32,27 +31,25 @@ public class MyImagesTests private static readonly MethodInfo _getSectionTitleMethod = typeof(MyImages).GetMethod("GetSectionTitle", BindingFlags.NonPublic | BindingFlags.Static) ?? throw new InvalidOperationException("MyImages must expose the non-public static GetSectionTitle method"); - /// - /// Non-public vulnerability-status chip color resolver - /// - private static readonly MethodInfo _getVulnerabilityStatusColorMethod = typeof(MyImages).GetMethod("GetVulnerabilityStatusColor", BindingFlags.NonPublic | BindingFlags.Static) - ?? throw new InvalidOperationException("MyImages must expose the non-public static GetVulnerabilityStatusColor method"); - #endregion // Fields #region Methods /// - /// Verify the section title includes the Docker Hub user name when one is configured + /// Verify the section title is the trimmed Docker Hub user name when one is configured /// + /// Configured user name [TestMethod] - public void MyImagesGetSectionTitleWithUserNameIncludesUserName() + [TestCategory("AC1")] + [DataRow("myuser")] + [DataRow(" myuser ")] + public void MyImagesGetSectionTitleWithUserNameReturnsTrimmedUserName(string userName) { - var title = (string)_getSectionTitleMethod.Invoke(null, ["myuser"])!; + var title = (string)_getSectionTitleMethod.Invoke(null, [userName])!; - Assert.AreEqual("Images from Docker account (myuser)", + Assert.AreEqual("myuser", title, - "Section title must include the Docker Hub user name in parentheses"); + "Section title must be the trimmed Docker Hub user name"); } /// @@ -60,59 +57,17 @@ public void MyImagesGetSectionTitleWithUserNameIncludesUserName() /// /// Null or blank user name [TestMethod] + [TestCategory("AC1")] [DataRow(null)] [DataRow("")] [DataRow(" ")] - public void MyImagesGetSectionTitleWithoutUserNameOmitsParentheses(string? userName) + public void MyImagesGetSectionTitleWithoutUserNameReturnsFallback(string? userName) { var title = (string)_getSectionTitleMethod.Invoke(null, [userName])!; Assert.AreEqual("Images from Docker account", title, - "Section title must not include parentheses when no user name is set"); - } - - /// - /// Verify vulnerability status chip colors map to expected MudBlazor color values - /// - /// Vulnerability assessment status string - /// Expected chip color - [TestMethod] - [DataRow("Findings Detected", Color.Warning)] - [DataRow("FINDINGS DETECTED", Color.Warning)] - [DataRow("No Findings", Color.Success)] - [DataRow("NO FINDINGS", Color.Success)] - [DataRow("Failed", Color.Error)] - [DataRow("FAILED", Color.Error)] - [DataRow("Not Configured", Color.Default)] - [DataRow("NOT CONFIGURED", Color.Default)] - [DataRow("Unsupported", Color.Default)] - [DataRow("UNSUPPORTED", Color.Default)] - [DataRow("anything-else", Color.Info)] - public void MyImagesGetVulnerabilityStatusColorKnownStatusReturnsExpectedColor(string status, Color expectedColor) - { - var color = (Color)_getVulnerabilityStatusColorMethod.Invoke(null, [status, null])!; - - Assert.AreEqual(expectedColor, - color, - $"Vulnerability status '{status}' must map to Color.{expectedColor}"); - } - - /// - /// Verify null or blank vulnerability status resolves to the default chip color - /// - /// Null or blank vulnerability status - [TestMethod] - [DataRow(null)] - [DataRow("")] - [DataRow(" ")] - public void MyImagesGetVulnerabilityStatusColorNullOrBlankReturnsDefault(string? status) - { - var color = (Color)_getVulnerabilityStatusColorMethod.Invoke(null, [status, null])!; - - Assert.AreEqual(Color.Default, - color, - "Null or blank vulnerability status must resolve to Color.Default"); + "Section title must be the fallback when no user name is set"); } /// @@ -148,16 +103,17 @@ public async Task MyImagesLoadFailureShowsFixedErrorAndLogs() } /// - /// Verify the list shows the latest scan status in a chip of its color + /// Verify the list shows the latest scan status as an indicator in its tone /// /// Scan status - /// Expected chip color class + /// Expected tone CSS name /// Task [TestMethod] - [TestCategory("AC4")] - [DataRow("Succeeded", "mud-chip-color-success")] - [DataRow("Partial", "mud-chip-color-warning")] - public async Task MyImagesLatestScanStatusChipShowsStatusColorAsync(string status, string expectedColorClass) + [TestCategory("AC3")] + [DataRow("Succeeded", "success")] + [DataRow("Partial", "warning")] + [DataRow("NotScanned", "neutral")] + public async Task MyImagesLatestScanShowsIndicatorInToneAsync(string status, string tone) { var testContext = BlazorTestContextFactory.Create(); @@ -178,16 +134,17 @@ public async Task MyImagesLatestScanStatusChipShowsStatusColorAsync(string statu .Returns(Task.FromResult(items)); testContext.Services.AddSingleton(viewService); + testContext.Services.AddSingleton(Substitute.For()); testContext.Services.AddSingleton(new DashboardRefreshState()); testContext.Services.AddSingleton(Options.Create(new DockerUpdateGuardOptions())); testContext.Services.AddSingleton>(new TestLogger()); var page = testContext.Render(); - await ScanStatusChipAssert.AssertChipAsync(page, - root => root.FindAll("td[data-label='Latest Scan'] .mud-chip"), - status, - expectedColorClass).ConfigureAwait(false); + await page.WaitForAssertionAsync(() => Assert.IsNotEmpty(page.FindAll("td[data-label='Latest scan']"), "The page must render the latest scan cell"), + TimeSpan.FromSeconds(DetailPageAssert.WaitSeconds)).ConfigureAwait(false); + + ListPageAssert.AssertIndicator(page.Find("td[data-label='Latest scan']"), status, tone); } } diff --git a/src/Tests/DockerUpdateGuard.Tests/ObservedImagesRenderTests.cs b/src/Tests/DockerUpdateGuard.Tests/ObservedImagesRenderTests.cs new file mode 100644 index 00000000..32eac496 --- /dev/null +++ b/src/Tests/DockerUpdateGuard.Tests/ObservedImagesRenderTests.cs @@ -0,0 +1,482 @@ +using Bunit; + +using DockerUpdateGuard.Components.Common; +using DockerUpdateGuard.Components.Pages; +using DockerUpdateGuard.Data.Entities; +using DockerUpdateGuard.Images.Data; +using DockerUpdateGuard.Images.Interfaces; +using DockerUpdateGuard.Tests.Data; +using DockerUpdateGuard.Tests.Helper; +using DockerUpdateGuard.UI; + +using Microsoft.AspNetCore.Components; +using Microsoft.Extensions.DependencyInjection; +using Microsoft.Extensions.Logging; + +using NSubstitute; + +namespace DockerUpdateGuard.Tests; + +/// +/// Render tests for +/// +[TestClass] +public class ObservedImagesRenderTests +{ + #region Constants + + /// + /// Class of the page's table + /// + private const string TableClass = "observed-images-table"; + + #endregion // Constants + + #region Fields + + /// + /// Column heads in order + /// + private static readonly string[] _columnHeads = ["Name", "Image", "Latest scan", "Updates", "Base runtime", "Vulnerabilities"]; + + /// + /// Expected labels of the registration form in order + /// + private static readonly string[] _formLabels = ["Name", "Image reference", "Description (optional)"]; + + #endregion // Fields + + #region Methods + + /// + /// Verify the page shows one header without eyebrow, the Register image panel without meta and the Manual images panel with the meta text + /// + /// Number of listed images + /// Expected meta text + /// Task + [TestMethod] + [TestCategory("AC1")] + [DataRow(1, "1 image")] + [DataRow(2, "2 images")] + public async Task ObservedImagesRenderShowsHeaderWithoutEyebrowAndPanelMeta(int imageCount, string expectedMeta) + { + var images = Enumerable.Range(0, imageCount).Select(index => CreateImage($"image-{index}")).ToList(); + var testContext = CreateContext(images); + + await using (testContext) + { + var page = testContext.Render(); + + ListPageAssert.AssertHeader(page, "Observed Images", "Manually tracked images. Register a registry reference to scan it right away."); + ListPageAssert.AssertPanel(page, "Register image", null); + ListPageAssert.AssertPanel(page, "Manual images", expectedMeta); + Assert.HasCount(2, page.FindAll("section.dug-panel"), "The page must show the form panel and the list panel"); + } + } + + /// + /// Verify an empty list shows the empty state in the Manual images panel, without table and meta, and keeps the form + /// + /// Task + [TestMethod] + [TestCategory("AC1")] + public async Task ObservedImagesRenderEmptyListShowsEmptyStateWithoutTable() + { + var testContext = CreateContext([]); + + await using (testContext) + { + var page = testContext.Render(); + var panel = ListPageAssert.FindPanel(page, "Manual images"); + + Assert.AreEqual("No manual observed images are registered yet.", panel.QuerySelector(".empty-state-panel")?.TextContent.Trim(), "The empty state must show today's text inside the panel"); + Assert.IsEmpty(page.FindAll("table"), "The table must not be shown for an empty list"); + Assert.IsEmpty(page.FindAll(".dug-panel__meta"), "The meta text must not be shown for an empty list"); + Assert.IsNotNull(page.Find("form"), "The registration form must stay"); + } + } + + /// + /// Verify a failed first load keeps the alert inside the Manual images panel and the registration form usable + /// + /// Task + [TestMethod] + [TestCategory("AC1")] + public async Task ObservedImagesRenderLoadFailureKeepsAlertInsidePanelAndFormUsable() + { + var testContext = BlazorTestContextFactory.Create(); + + await using (testContext) + { + var viewService = Substitute.For(); + + viewService.GetManualObservedImagesAsync(Arg.Any()) + .Returns(Task.FromException>(new InvalidOperationException("secret text"))); + RegisterServices(testContext, viewService); + + var page = testContext.Render(); + + await DetailPageAssert.AssertLoadErrorAsync(page, "Loading the observed images failed: unexpected error", "secret text").ConfigureAwait(false); + + var panel = ListPageAssert.FindPanel(page, "Manual images"); + + Assert.HasCount(1, panel.QuerySelectorAll(".mud-alert"), "The alert must stand inside the Manual images panel"); + Assert.IsNull(page.Find("button[type=submit]").GetAttribute("disabled"), "The registration button must stay usable"); + } + } + + /// + /// Verify the table has the six column heads in order + /// + /// Task + [TestMethod] + [TestCategory("AC2")] + public async Task ObservedImagesRenderShowsColumnHeadsInOrder() + { + var testContext = CreateContext([CreateImage("web")]); + + await using (testContext) + { + var page = testContext.Render(); + + Assert.AreSequenceEqual(_columnHeads, ListPageAssert.GetHeads(page), "The heads must be the six columns in order"); + } + } + + /// + /// Verify the updates cell shows the number of active update findings, or a dash for none + /// + /// Active update findings + /// Expected cell text + /// Task + [TestMethod] + [TestCategory("AC2")] + [DataRow(3, "3")] + [DataRow(1, "1")] + [DataRow(0, "—")] + public async Task ObservedImagesRenderUpdatesCellShowsCountOrDash(int count, string expected) + { + var image = CreateImage("web"); + + image.ActiveUpdateFindingCount = count; + + var testContext = CreateContext([image]); + + await using (testContext) + { + var page = testContext.Render(); + var cell = ListPageAssert.FindCell(page, 0, "Updates"); + + Assert.AreEqual(expected, cell.TextContent.Trim(), "The cell must show the count or a dash"); + Assert.IsEmpty(cell.QuerySelectorAll(".mud-chip, .dug-chip"), "The cell must show no chip"); + } + } + + /// + /// Verify the name cell shows the description in a muted line only when there is one, and the latest scan cell the message likewise + /// + /// Task + [TestMethod] + [TestCategory("AC2")] + public async Task ObservedImagesRenderNameAndScanCellsShowMutedLinesOnlyWhenNotEmpty() + { + var full = CreateImage("full"); + var empty = CreateImage("empty"); + + full.Description = "Backend of the shop"; + full.LatestScanMessage = "Registry answered with 2 tags"; + empty.Description = " "; + empty.LatestScanMessage = string.Empty; + + var testContext = CreateContext([full, empty]); + + await using (testContext) + { + var page = testContext.Render(); + + Assert.AreEqual("Backend of the shop", ListPageAssert.FindCell(page, 0, "Name").QuerySelector("span.table-secondary")?.TextContent.Trim(), "The description must stand muted below the link"); + Assert.AreEqual("Registry answered with 2 tags", ListPageAssert.FindCell(page, 0, "Latest scan").QuerySelector("span.table-secondary")?.TextContent.Trim(), "The message must stand muted below the indicator"); + Assert.IsEmpty(ListPageAssert.FindCell(page, 1, "Name").QuerySelectorAll("span.table-secondary"), "A blank description must show no muted line"); + Assert.IsEmpty(ListPageAssert.FindCell(page, 1, "Latest scan").QuerySelectorAll("span.table-secondary"), "An empty message must show no muted line"); + } + } + + /// + /// Verify a pending load shows the table skeleton with the panel title next to the usable form + /// + /// Task + [TestMethod] + [TestCategory("AC1")] + public async Task ObservedImagesRenderLoadingShowsSkeletonWithPanelTitle() + { + var testContext = BlazorTestContextFactory.Create(); + + await using (testContext) + { + var pending = new TaskCompletionSource>(); + var viewService = Substitute.For(); + + viewService.GetManualObservedImagesAsync(Arg.Any()) + .Returns(pending.Task); + RegisterServices(testContext, viewService); + + var page = testContext.Render(); + + Assert.AreEqual("Manual images", page.FindComponent().Instance.Title, "The skeleton must carry the panel title"); + Assert.IsEmpty(page.FindAll("table"), "The table must not be shown while loading"); + Assert.IsEmpty(page.FindAll(".empty-state-panel"), "The empty state must not be shown while loading"); + Assert.IsNotNull(page.Find("form"), "The registration form must stay"); + + pending.SetResult([]); + await page.WaitForAssertionAsync(() => Assert.IsEmpty(page.FindAll(".mud-skeleton"), "The skeleton must disappear after the load"), TimeSpan.FromSeconds(DetailPageAssert.WaitSeconds)).ConfigureAwait(false); + } + } + + /// + /// Verify the base runtime cell shows the hint summary in muted text, or a dash, and no chip + /// + /// Task + [TestMethod] + [TestCategory("AC2")] + public async Task ObservedImagesRenderBaseRuntimeCellShowsHintOrDash() + { + var hinted = CreateImage("hinted"); + var plain = CreateImage("plain"); + + hinted.BaseRuntimeAlertSummary = "Base image debian:12 runs in 2 containers"; + + var testContext = CreateContext([hinted, plain]); + + await using (testContext) + { + var page = testContext.Render(); + var hintedCell = ListPageAssert.FindCell(page, 0, "Base runtime"); + var plainCell = ListPageAssert.FindCell(page, 1, "Base runtime"); + + Assert.AreEqual("Base image debian:12 runs in 2 containers", hintedCell.TextContent.Trim(), "The hint summary must be the only text of the cell"); + Assert.AreEqual(1, hintedCell.QuerySelectorAll("span.table-secondary").Length, "The hint must be muted"); + Assert.AreEqual("—", plainCell.TextContent.Trim(), "Without a hint the cell must show a dash"); + Assert.IsEmpty(page.FindAll("td[data-label='Base runtime'] .mud-chip, td[data-label='Base runtime'] .dug-chip"), "The cell must show no chip"); + } + } + + /// + /// Verify every row renders its vulnerability cell with the shared component and the values of the row + /// + /// Task + [TestMethod] + [TestCategory("AC4")] + public async Task ObservedImagesRenderVulnerabilityCellUsesSharedComponent() + { + var first = CreateImage("first"); + var second = CreateImage("second"); + + first.VulnerabilityStatus = "Failed"; + first.VulnerabilitySeveritySummary = new VulnerabilitySeveritySummaryViewData + { + CriticalCount = 1 + }; + first.ActiveBaseImageVulnerabilityFindingCount = 2; + first.BaseImageVulnerabilitySummary = "2 active finding(s) across 1 base image"; + + var testContext = CreateContext([first, second]); + + await using (testContext) + { + var page = testContext.Render(); + var cells = page.FindComponents(); + + Assert.HasCount(2, cells, "Every row must render the shared vulnerability cell"); + Assert.AreEqual(first.CurrentImageVersionId, cells[0].Instance.ImageVersionId, "The cell must rescan the current image version of its row"); + Assert.AreEqual("Failed", cells[0].Instance.Status, "The cell must receive the status of its row"); + Assert.AreEqual(1, cells[0].Instance.SeveritySummary?.CriticalCount, "The cell must receive the severity summary of its row"); + Assert.AreEqual(2, cells[0].Instance.ActiveBaseImageFindingCount, "The cell must receive the base image finding count of its row"); + Assert.AreEqual(first.BaseImageVulnerabilitySummary, cells[0].Instance.BaseImageSummary, "The cell must receive the base image summary of its row"); + Assert.IsEmpty(page.FindAll("td[data-label='Vulnerabilities'] .mud-chip"), "The old MudBlazor chips must be gone"); + } + } + + /// + /// Verify the registration form shows a label above each of the three fields, tied to its input, and the button in one grid row + /// + /// Task + [TestMethod] + [TestCategory("AC6")] + public async Task ObservedImagesRenderRegistrationFormShowsLabelsFieldsAndButton() + { + var testContext = CreateContext([]); + + await using (testContext) + { + var page = testContext.Render(); + var row = page.Find("form .register-image-form"); + var labels = row.QuerySelectorAll("label[for]").ToList(); + var inputs = row.QuerySelectorAll("input").ToList(); + + Assert.AreSequenceEqual(_formLabels, labels.Select(label => string.Join(" ", label.TextContent.Split((char[]?)null, StringSplitOptions.RemoveEmptyEntries))).ToList(), "The row must show the three labels in order"); + Assert.HasCount(3, inputs, "The row must hold the three fields"); + + for (var index = 0; index < labels.Count; index++) + { + var target = labels[index].GetAttribute("for"); + + Assert.IsFalse(string.IsNullOrEmpty(target), "Every label must name its input"); + Assert.AreEqual(target, inputs[index].Id, $"The label '{_formLabels[index]}' must be tied to the input element of its field"); + } + + Assert.AreEqual("(optional)", labels[2].QuerySelector("span")?.TextContent.Trim(), "The Description label must carry a muted (optional) span"); + Assert.AreEqual("registry/repository:tag", inputs[1].GetAttribute("placeholder"), "The image reference must show its placeholder"); + Assert.IsEmpty(row.QuerySelectorAll("label.mud-input-label"), "The fields must not use MudBlazor's floating label"); + + var button = row.QuerySelector("button[type=submit]"); + + Assert.IsNotNull(button, "The primary button must end the row"); + Assert.AreEqual("Register and scan", button.TextContent.Trim(), "The button must read Register and scan"); + Assert.IsNotNull(row.QuerySelector(".mud-button-filled-primary"), "The button must be the primary button"); + + var hint = page.FindAll("form .table-secondary").FirstOrDefault(element => element.TextContent.Contains("Formats: image:tag", StringComparison.Ordinal)); + + Assert.IsNotNull(hint, "The formats hint must stay"); + Assert.IsNull(hint.Closest(".register-image-form"), "The formats hint must stand below the row, not inside it"); + } + } + + /// + /// Verify the table switches to cards below 960 px and labels every cell with its head + /// + /// Task + [TestMethod] + [TestCategory("AC10")] + public async Task ObservedImagesRenderTableSwitchesToCardsBelow960Px() + { + var testContext = CreateContext([CreateImage("web")]); + + await using (testContext) + { + var page = testContext.Render(); + + ListPageAssert.AssertCardLayout(page, TableClass, _columnHeads, "Name", "Latest scan", "Base runtime", "Vulnerabilities"); + } + } + + /// + /// Verify submitting the empty form shows the required messages, and registers nothing + /// + /// Task + [TestMethod] + [TestCategory("AC6")] + public async Task ObservedImagesRegistrationWithEmptyRequiredFieldsShowsMessages() + { + var testContext = CreateContext([]); + + await using (testContext) + { + var page = testContext.Render(); + + await page.Find("form").SubmitAsync().ConfigureAwait(false); + + Assert.Contains("The Name field is required.", page.Markup, "The empty name must be reported"); + Assert.Contains("The ImageReference field is required.", page.Markup, "The empty image reference must be reported"); + Assert.IsEmpty(page.FindAll(".mud-alert"), "A validation message is not a failed registration"); + await testContext.Services.GetRequiredService().DidNotReceive().RegisterAsync(Arg.Any(), Arg.Any()).ConfigureAwait(false); + } + } + + /// + /// Verify the button is disabled while a registration runs and usable again after it + /// + /// Task + [TestMethod] + [TestCategory("AC6")] + public async Task ObservedImagesRegistrationWhileBusyDisablesButton() + { + var testContext = CreateContext([]); + + await using (testContext) + { + var pending = new TaskCompletionSource(); + + testContext.Services.GetRequiredService() + .RegisterAsync(Arg.Any(), Arg.Any()) + .Returns(pending.Task); + + var page = testContext.Render(); + var inputs = page.FindAll("input"); + + await inputs[0].ChangeAsync(new ChangeEventArgs + { + Value = "Company API" + }).ConfigureAwait(false); + await inputs[1].ChangeAsync(new ChangeEventArgs + { + Value = "docker.io/company/api:1.0.0" + }).ConfigureAwait(false); + + Assert.IsNull(page.Find("button[type=submit]").GetAttribute("disabled"), "The button must be usable before the submit"); + + var submit = page.Find("form").SubmitAsync(); + + await page.WaitForAssertionAsync(() => Assert.IsNotNull(page.Find("button[type=submit]").GetAttribute("disabled"), "The button must be disabled while the registration runs"), TimeSpan.FromSeconds(DetailPageAssert.WaitSeconds)).ConfigureAwait(false); + + pending.SetException(new InvalidOperationException("registration failed")); + await submit.ConfigureAwait(false); + await page.WaitForAssertionAsync(() => Assert.IsNull(page.Find("button[type=submit]").GetAttribute("disabled"), "The button must be usable again after the registration"), TimeSpan.FromSeconds(DetailPageAssert.WaitSeconds)).ConfigureAwait(false); + } + } + + #endregion // Methods + + #region Helper methods + + /// + /// Create a test context with the page's services and a list the view service returns + /// + /// Listed images + /// Test context + private static BunitContext CreateContext(IReadOnlyList images) + { + var testContext = BlazorTestContextFactory.Create(); + var viewService = Substitute.For(); + + viewService.GetManualObservedImagesAsync(Arg.Any()) + .Returns(images); + RegisterServices(testContext, viewService); + + return testContext; + } + + /// + /// Register the services of the page + /// + /// Test context + /// View service + private static void RegisterServices(BunitContext testContext, IApplicationViewService viewService) + { + testContext.Services.AddSingleton(viewService); + testContext.Services.AddSingleton(Substitute.For()); + testContext.Services.AddSingleton(Substitute.For()); + testContext.Services.AddSingleton(Substitute.For()); + testContext.Services.AddSingleton(new DashboardRefreshState()); + testContext.Services.AddSingleton>(new TestLogger()); + } + + /// + /// Create an image row without findings + /// + /// Image name + /// Image row + private static ObservedImageListItemData CreateImage(string name) + { + return new ObservedImageListItemData + { + Id = Guid.NewGuid(), + Name = name, + CurrentImageVersionId = Guid.NewGuid(), + ImageReference = $"docker.io/acme/{name}:1.0", + LatestScanStatus = "Succeeded", + VulnerabilityStatus = "No findings", + }; + } + + #endregion // Helper methods +} \ No newline at end of file diff --git a/src/Tests/DockerUpdateGuard.Tests/ObservedImagesTests.cs b/src/Tests/DockerUpdateGuard.Tests/ObservedImagesTests.cs index e01b6c1b..0b8ff983 100644 --- a/src/Tests/DockerUpdateGuard.Tests/ObservedImagesTests.cs +++ b/src/Tests/DockerUpdateGuard.Tests/ObservedImagesTests.cs @@ -361,16 +361,17 @@ public async Task ObservedImagesLoadFailureShowsFixedErrorAndLogs() } /// - /// Verify the list shows the latest scan status in a chip of its color + /// Verify the list shows the latest scan status as an indicator in its tone /// /// Scan status - /// Expected chip color class + /// Expected tone CSS name /// Task [TestMethod] - [TestCategory("AC4")] - [DataRow("Succeeded", "mud-chip-color-success")] - [DataRow("Partial", "mud-chip-color-warning")] - public async Task ObservedImagesLatestScanStatusChipShowsStatusColorAsync(string status, string expectedColorClass) + [TestCategory("AC3")] + [DataRow("Succeeded", "success")] + [DataRow("Partial", "warning")] + [DataRow("NotScanned", "neutral")] + public async Task ObservedImagesLatestScanShowsIndicatorInToneAsync(string status, string tone) { var testContext = BlazorTestContextFactory.Create(); @@ -393,15 +394,16 @@ public async Task ObservedImagesLatestScanStatusChipShowsStatusColorAsync(string testContext.Services.AddSingleton(viewService); testContext.Services.AddSingleton(Substitute.For()); testContext.Services.AddSingleton(Substitute.For()); + testContext.Services.AddSingleton(Substitute.For()); testContext.Services.AddSingleton(new DashboardRefreshState()); testContext.Services.AddSingleton>(new TestLogger()); var page = testContext.Render(); - await ScanStatusChipAssert.AssertChipAsync(page, - root => root.FindAll("td[data-label='Latest Scan'] .mud-chip"), - status, - expectedColorClass).ConfigureAwait(false); + await page.WaitForAssertionAsync(() => Assert.IsNotEmpty(page.FindAll("td[data-label='Latest scan']"), "The page must render the latest scan cell"), + TimeSpan.FromSeconds(DetailPageAssert.WaitSeconds)).ConfigureAwait(false); + + ListPageAssert.AssertIndicator(page.Find("td[data-label='Latest scan']"), status, tone); } } diff --git a/src/Tests/DockerUpdateGuard.Tests/ResourceUsageChartBuilderTests.cs b/src/Tests/DockerUpdateGuard.Tests/ResourceUsageChartBuilderTests.cs deleted file mode 100644 index 0235e9e4..00000000 --- a/src/Tests/DockerUpdateGuard.Tests/ResourceUsageChartBuilderTests.cs +++ /dev/null @@ -1,53 +0,0 @@ -using DockerUpdateGuard.UI; - -namespace DockerUpdateGuard.Tests; - -/// -/// Tests for -/// -[TestClass] -public class ResourceUsageChartBuilderTests -{ - #region Methods - - /// - /// Verify chart labels are UTC: the first and last carry date and suffix, visible ones between show the time only, hidden ones stay empty - /// - [TestMethod] - [TestCategory("AC2")] - public void ResourceUsageChartBuilderGetChartLabelsWithOffsetTimestampsReturnsUtcLabels() - { - var offset = TimeSpan.FromHours(2); - var history = new List - { - new() - { - RecordedAtUtc = new DateTimeOffset(2026, 11, 24, 0, 30, 0, offset) - }, - new() - { - RecordedAtUtc = new DateTimeOffset(2026, 11, 24, 0, 45, 0, offset) - }, - new() - { - RecordedAtUtc = new DateTimeOffset(2026, 11, 24, 1, 0, 0, offset) - }, - new() - { - RecordedAtUtc = new DateTimeOffset(2026, 11, 24, 1, 15, 0, offset) - }, - new() - { - RecordedAtUtc = new DateTimeOffset(2026, 11, 24, 1, 30, 0, offset) - } - }; - - var labels = ResourceUsageChartBuilder.GetChartLabels(history, 3); - - Assert.AreSequenceEqual(["11-23 22:30 UTC", string.Empty, "23:00", string.Empty, "11-23 23:30 UTC"], - labels, - "The first and last label must carry date and UTC suffix, the visible one between them only the UTC time, hidden ones stay empty"); - } - - #endregion // Methods -} \ No newline at end of file diff --git a/src/Tests/DockerUpdateGuard.Tests/ResourceUsageFormatterTests.cs b/src/Tests/DockerUpdateGuard.Tests/ResourceUsageFormatterTests.cs new file mode 100644 index 00000000..6aca32c9 --- /dev/null +++ b/src/Tests/DockerUpdateGuard.Tests/ResourceUsageFormatterTests.cs @@ -0,0 +1,36 @@ +using DockerUpdateGuard.UI; + +namespace DockerUpdateGuard.Tests; + +/// +/// Tests for +/// +[TestClass] +public class ResourceUsageFormatterTests +{ + #region Methods + + /// + /// Verify the memory share is the usage over the limit rounded half away from zero, and missing without a positive limit + /// + /// Usage bytes + /// Limit bytes + /// Expected percentage + [TestMethod] + [TestCategory("AC7")] + [DataRow(614L, 1000L, 61)] + [DataRow(615L, 1000L, 62)] + [DataRow(0L, 1000L, 0)] + [DataRow(1000L, 1000L, 100)] + [DataRow(2000L, 1000L, 200)] + [DataRow(500L, 0L, null)] + [DataRow(500L, -1L, null)] + public void ResourceUsageFormatterGetMemoryPercentReturnsRoundedShare(long usageBytes, long limitBytes, int? expected) + { + var percent = ResourceUsageFormatter.GetMemoryPercent(usageBytes, limitBytes); + + Assert.AreEqual(expected, percent, $"The share of {usageBytes} of {limitBytes} bytes must be rounded to a whole percent"); + } + + #endregion // Methods +} \ No newline at end of file diff --git a/src/Tests/DockerUpdateGuard.Tests/RuntimeContainerListFormatterTests.cs b/src/Tests/DockerUpdateGuard.Tests/RuntimeContainerListFormatterTests.cs index f7754ce2..7b5f4189 100644 --- a/src/Tests/DockerUpdateGuard.Tests/RuntimeContainerListFormatterTests.cs +++ b/src/Tests/DockerUpdateGuard.Tests/RuntimeContainerListFormatterTests.cs @@ -37,68 +37,5 @@ public void RuntimeContainerListFormatterFormatInventoryMetaUsesSingularAndPlura Assert.AreEqual(expected, meta, "The meta text must count containers and distinct Docker instances"); } - /// - /// Verify the count line lists the counts above zero in the order critical, high, medium, low, unknown - /// - /// Critical count - /// High count - /// Medium count - /// Low count - /// Unknown count - /// Expected count line - [TestMethod] - [TestCategory("AC5")] - [DataRow(1, 2, 0, 0, 0, "3 active · 1 critical, 2 high")] - [DataRow(1, 2, 3, 4, 5, "15 active · 1 critical, 2 high, 3 medium, 4 low, 5 unknown")] - [DataRow(0, 0, 0, 0, 4, "4 active · 4 unknown")] - [DataRow(0, 0, 0, 0, 0, "")] - public void RuntimeContainerListFormatterFormatActiveFindingsListsCountsInSeverityOrder(int critical, int high, int medium, int low, int other, string expected) - { - var summary = new VulnerabilitySeveritySummaryViewData - { - CriticalCount = critical, - HighCount = high, - MediumCount = medium, - LowCount = low, - OtherCount = other, - }; - - var line = RuntimeContainerListFormatter.FormatActiveFindings(summary); - - Assert.AreEqual(expected, line, "The count line must list the counts above zero in severity order"); - } - - /// - /// Verify the status chip stands beside the severity chip only with active findings and a status other than Findings detected - /// - /// Active high findings - /// Vulnerability status - /// Expected decision - [TestMethod] - [TestCategory("AC5")] - [DataRow(2, "Failed", true)] - [DataRow(2, "Unavailable", true)] - [DataRow(2, "No findings", true)] - [DataRow(2, "Findings detected", false)] - [DataRow(2, "findings detected", false)] - [DataRow(0, "Failed", false)] - [DataRow(0, "Findings detected", false)] - public void RuntimeContainerListFormatterIsStatusShownBesideSeverityOnlyForOtherStatuses(int highCount, string status, bool expected) - { - var container = new RuntimeContainerListItemData - { - VulnerabilityStatus = status, - ActiveVulnerabilityFindingCount = highCount, - VulnerabilitySeveritySummary = new VulnerabilitySeveritySummaryViewData - { - HighCount = highCount - }, - }; - - var shown = RuntimeContainerListFormatter.IsStatusShownBesideSeverity(container); - - Assert.AreEqual(expected, shown, $"The status '{status}' with {highCount} active findings must decide the status chip as expected"); - } - #endregion // Methods } \ No newline at end of file diff --git a/src/Tests/DockerUpdateGuard.Tests/RuntimeContainersRenderTests.cs b/src/Tests/DockerUpdateGuard.Tests/RuntimeContainersRenderTests.cs index 63389a08..5ca3c75e 100644 --- a/src/Tests/DockerUpdateGuard.Tests/RuntimeContainersRenderTests.cs +++ b/src/Tests/DockerUpdateGuard.Tests/RuntimeContainersRenderTests.cs @@ -1,5 +1,6 @@ using Bunit; +using DockerUpdateGuard.Components.Common; using DockerUpdateGuard.Components.Pages; using DockerUpdateGuard.Images.Interfaces; using DockerUpdateGuard.Tests.Data; @@ -673,6 +674,41 @@ public async Task RuntimeContainersRenderEncodesExternalTexts() } } + /// + /// Verify every row renders its vulnerability cell with the shared component and the values of the row + /// + /// Task + [TestMethod] + [TestCategory("AC4")] + public async Task RuntimeContainersRenderVulnerabilityCellUsesSharedComponent() + { + var first = CreateContainer(Guid.NewGuid(), "first"); + var second = CreateContainer(Guid.NewGuid(), "second"); + + SetFindings(first, "Failed", 0, 2, 0, 0, 0); + first.ActiveBaseImageVulnerabilityFindingCount = 3; + first.BaseImageVulnerabilitySummary = "3 active finding(s) across 1 base image"; + + var testContext = CreateContext([first, second]); + + await using (testContext) + { + var page = testContext.Render(); + var cells = page.FindComponents(); + + Assert.HasCount(2, cells, "Every row must render the shared vulnerability cell"); + Assert.AreEqual(first.ImageVersionId, cells[0].Instance.ImageVersionId, "The cell must rescan the image version of its row"); + Assert.AreEqual("Failed", cells[0].Instance.Status, "The cell must receive the status of its row"); + Assert.AreEqual(2, cells[0].Instance.SeveritySummary?.HighCount, "The cell must receive the severity summary of its row"); + Assert.AreEqual(first.VulnerabilityCheckedAtUtc, cells[0].Instance.CheckedAtUtc, "The cell must receive the check time of its row"); + Assert.AreEqual(3, cells[0].Instance.ActiveBaseImageFindingCount, "The cell must receive the base image finding count of its row"); + Assert.AreEqual(first.BaseImageVulnerabilitySummary, cells[0].Instance.BaseImageSummary, "The cell must receive the base image summary of its row"); + Assert.AreEqual(second.ImageVersionId, cells[1].Instance.ImageVersionId, "The second row must pass its own image version"); + Assert.IsNotEmpty(page.FindAll(".dug-vulnerability-cell__chips"), "The cell must use the shared chip class"); + Assert.IsEmpty(page.FindAll(".runtime-containers-table__chips"), "The old inline chip class must be gone"); + } + } + /// /// Create a test context with the page's services and a list the view service returns /// diff --git a/src/Tests/DockerUpdateGuard.Tests/ScanHistoryRenderTests.cs b/src/Tests/DockerUpdateGuard.Tests/ScanHistoryRenderTests.cs new file mode 100644 index 00000000..a0fa6d49 --- /dev/null +++ b/src/Tests/DockerUpdateGuard.Tests/ScanHistoryRenderTests.cs @@ -0,0 +1,319 @@ +using Bunit; + +using DockerUpdateGuard.Components.Common; +using DockerUpdateGuard.Components.Pages; +using DockerUpdateGuard.Configuration; +using DockerUpdateGuard.Data.Entities; +using DockerUpdateGuard.Images.Interfaces; +using DockerUpdateGuard.Tests.Data; +using DockerUpdateGuard.Tests.Helper; +using DockerUpdateGuard.UI; + +using Microsoft.Extensions.DependencyInjection; +using Microsoft.Extensions.Options; + +using NSubstitute; + +namespace DockerUpdateGuard.Tests; + +/// +/// Render tests for +/// +[TestClass] +public class ScanHistoryRenderTests +{ + #region Constants + + /// + /// Class of the page's table + /// + private const string TableClass = "scan-history-table"; + + /// + /// Class of the error cell of a failed run + /// + private const string FailedErrorClass = "scan-history-table__error--failed"; + + #endregion // Constants + + #region Fields + + /// + /// Column heads in order + /// + private static readonly string[] _columnHeads = ["Type", "Status", "Trigger", "Target", "Started", "Error"]; + + #endregion // Fields + + #region Methods + + /// + /// Verify the page shows one header without eyebrow and one panel with the status counts in the fixed order as meta + /// + /// Task + [TestMethod] + [TestCategory("AC1")] + public async Task ScanHistoryRenderShowsHeaderWithoutEyebrowAndPanelMeta() + { + var testContext = CreateContext([CreateScan("Failed"), CreateScan("Succeeded"), CreateScan("Succeeded"), CreateScan("Running"), CreateScan("Partial")], false); + + await using (testContext) + { + var page = testContext.Render(); + + ListPageAssert.AssertHeader(page, "Scan History", "Image, runtime container and vulnerability scan runs with trigger, target and outcome."); + ListPageAssert.AssertPanel(page, "Latest 20 runs", "2 succeeded · 1 running · 1 partial · 1 failed"); + Assert.HasCount(1, page.FindAll("section.dug-panel"), "The page must show exactly one panel"); + } + } + + /// + /// Verify the error cell is marked as failed only for a failed run, and stays empty for a run without an error + /// + /// Task + [TestMethod] + [TestCategory("AC9")] + public async Task ScanHistoryRenderErrorCellIsDangerOnlyForFailedRun() + { + var failed = CreateScan("Failed"); + var partial = CreateScan("Partial"); + var succeeded = CreateScan("Succeeded"); + + failed.ErrorMessage = "Registry answered with 500"; + partial.ErrorMessage = "2 of 3 tags could not be read"; + + var testContext = CreateContext([failed, partial, succeeded], false); + + await using (testContext) + { + var page = testContext.Render(); + var failedCell = ListPageAssert.FindCell(page, 0, "Error"); + var partialCell = ListPageAssert.FindCell(page, 1, "Error"); + var emptyCell = ListPageAssert.FindCell(page, 2, "Error"); + + Assert.AreEqual("Registry answered with 500", failedCell.TextContent.Trim(), "The failed run must show its stored message"); + Assert.IsTrue(HasFailedMarker(failedCell), "The error of a failed run must carry the danger marker"); + Assert.AreEqual("2 of 3 tags could not be read", partialCell.TextContent.Trim(), "A partial run must show its stored message"); + Assert.IsFalse(HasFailedMarker(partialCell), "The error of a run that did not fail must not carry the danger marker"); + Assert.AreEqual(string.Empty, emptyCell.TextContent.Trim(), "A run without an error must leave the cell empty"); + Assert.IsFalse(HasFailedMarker(emptyCell), "An empty error cell must not carry the danger marker"); + } + } + + /// + /// Verify the schedule line stands before the refresh button in the header's action + /// + /// Task + [TestMethod] + [TestCategory("AC9")] + public async Task ScanHistoryRenderScheduleLineStandsBeforeButton() + { + var testContext = CreateContext([CreateScan("Succeeded")], true); + + await using (testContext) + { + var page = testContext.Render(); + var actions = page.Find("div.dug-page-header__actions"); + var markup = actions.InnerHtml; + var scheduleAt = markup.IndexOf("Next scheduled vulnerability refresh: 2026-07-29 18:30 UTC", StringComparison.Ordinal); + var buttonAt = markup.IndexOf(" + /// Verify the table switches to cards below 960 px and labels every cell with its head + /// + /// Task + [TestMethod] + [TestCategory("AC10")] + public async Task ScanHistoryRenderTableSwitchesToCardsBelow960Px() + { + var testContext = CreateContext([CreateScan("Succeeded")], false); + + await using (testContext) + { + var page = testContext.Render(); + + ListPageAssert.AssertCardLayout(page, TableClass, _columnHeads); + } + } + + /// + /// Verify an empty list shows the empty state in a panel of its own, without table and meta + /// + /// Task + [TestMethod] + [TestCategory("AC1")] + public async Task ScanHistoryRenderEmptyListShowsEmptyStateWithoutTable() + { + var testContext = CreateContext([], false); + + await using (testContext) + { + var page = testContext.Render(); + + Assert.AreEqual("No scan history exists yet.", page.Find(".empty-state-panel").TextContent.Trim(), "The empty state must show today's text"); + Assert.IsEmpty(page.FindAll("table"), "The table must not be shown for an empty list"); + Assert.IsEmpty(page.FindAll(".dug-panel__meta"), "The meta text must not be shown for an empty list"); + } + } + + /// + /// Verify the table has the six column heads in order + /// + /// Task + [TestMethod] + [TestCategory("AC2")] + public async Task ScanHistoryRenderShowsColumnHeadsInOrder() + { + var testContext = CreateContext([CreateScan("Succeeded")], false); + + await using (testContext) + { + var page = testContext.Render(); + + Assert.AreSequenceEqual(_columnHeads, ListPageAssert.GetHeads(page), "The heads must be the six columns in order"); + } + } + + /// + /// Verify a pending load shows the table skeleton with the panel title, and neither table nor empty state + /// + /// Task + [TestMethod] + [TestCategory("AC1")] + public async Task ScanHistoryRenderLoadingShowsSkeletonWithPanelTitle() + { + var testContext = CreateContext([], false); + + await using (testContext) + { + var pending = new TaskCompletionSource>(); + + testContext.Services.GetRequiredService() + .GetScanHistoryAsync(Arg.Any(), Arg.Any()) + .Returns(pending.Task); + + var page = testContext.Render(); + + Assert.AreEqual("Latest 20 runs", page.FindComponent().Instance.Title, "The skeleton must carry the panel title"); + Assert.IsEmpty(page.FindAll("table"), "The table must not be shown while loading"); + Assert.IsEmpty(page.FindAll(".empty-state-panel"), "The empty state must not be shown while loading"); + + pending.SetResult([]); + await page.WaitForAssertionAsync(() => Assert.IsEmpty(page.FindAll(".mud-skeleton"), "The skeleton must disappear after the load"), TimeSpan.FromSeconds(DetailPageAssert.WaitSeconds)).ConfigureAwait(false); + } + } + + /// + /// Verify the refresh button is disabled and names the running refresh while it runs, and reads Refresh vulnerabilities again after it + /// + /// Task + [TestMethod] + [TestCategory("AC9")] + public async Task ScanHistoryRenderRefreshWhileRunningDisablesButtonAndShowsProgress() + { + var testContext = CreateContext([CreateScan("Succeeded")], true); + + await using (testContext) + { + var pending = new TaskCompletionSource(); + + testContext.Services.GetRequiredService() + .RefreshAsync(Arg.Any(), Arg.Any()) + .Returns(pending.Task); + + var page = testContext.Render(); + var click = page.Find("div.dug-page-header__actions button").ClickAsync(); + + await page.WaitForAssertionAsync(() => + { + var button = page.Find("div.dug-page-header__actions button"); + + Assert.AreEqual("Refreshing vulnerabilities...", button.TextContent.Trim(), "The button must name the running refresh"); + Assert.IsNotNull(button.GetAttribute("disabled"), "The button must be disabled while the refresh runs"); + }, + TimeSpan.FromSeconds(DetailPageAssert.WaitSeconds)).ConfigureAwait(false); + + pending.SetResult(); + await click.ConfigureAwait(false); + await page.WaitForAssertionAsync(() => Assert.AreEqual("Refresh vulnerabilities", page.Find("div.dug-page-header__actions button").TextContent.Trim(), "The button must read Refresh vulnerabilities again"), TimeSpan.FromSeconds(DetailPageAssert.WaitSeconds)).ConfigureAwait(false); + } + } + + #endregion // Methods + + #region Helper methods + + /// + /// Determine whether the error cell or an element inside it carries the failed marker + /// + /// Error cell + /// true when marked + private static bool HasFailedMarker(AngleSharp.Dom.IElement cell) + { + return cell.ClassList.Contains(FailedErrorClass) || cell.QuerySelector($".{FailedErrorClass}") is not null; + } + + /// + /// Create a run + /// + /// Run status + /// Run + private static ScanHistoryItemData CreateScan(string status) + { + return new ScanHistoryItemData + { + Id = Guid.NewGuid(), + Type = "Registry", + Status = status, + TriggerSource = "Manual", + SubjectName = "web", + StartedAtUtc = new DateTimeOffset(2026, 11, 23, 21, 27, 0, TimeSpan.Zero), + }; + } + + /// + /// Create a test context with the page's services + /// + /// Listed runs + /// Whether vulnerability scanning is enabled + /// Test context + private static BunitContext CreateContext(IReadOnlyList scans, bool vulnerabilitiesEnabled) + { + var testContext = BlazorTestContextFactory.Create(); + var viewService = Substitute.For(); + var options = new DockerUpdateGuardOptions + { + Vulnerabilities = new VulnerabilityOptions + { + Enabled = vulnerabilitiesEnabled, + Provider = vulnerabilitiesEnabled ? VulnerabilityProviderKind.Trivy : VulnerabilityProviderKind.None, + }, + }; + + viewService.GetScanHistoryAsync(Arg.Any(), Arg.Any()) + .Returns(scans); + viewService.GetVulnerabilityScheduleAsync(Arg.Any()) + .Returns(new VulnerabilityScheduleViewData + { + VulnerabilityScanningEnabled = vulnerabilitiesEnabled, + NextVulnerabilityRefreshUtc = new DateTimeOffset(2026, 7, 29, 20, 30, 0, TimeSpan.FromHours(2)), + }); + + testContext.Services.AddSingleton(viewService); + testContext.Services.AddSingleton(Substitute.For()); + testContext.Services.AddSingleton(new DashboardRefreshState()); + testContext.Services.AddSingleton>(new TestOptionsMonitor(options)); + + return testContext; + } + + #endregion // Helper methods +} \ No newline at end of file diff --git a/src/Tests/DockerUpdateGuard.Tests/ScanHistoryTests.cs b/src/Tests/DockerUpdateGuard.Tests/ScanHistoryTests.cs index e5caaa97..edb35126 100644 --- a/src/Tests/DockerUpdateGuard.Tests/ScanHistoryTests.cs +++ b/src/Tests/DockerUpdateGuard.Tests/ScanHistoryTests.cs @@ -29,7 +29,7 @@ public class ScanHistoryTests /// /// Task [TestMethod] - [TestCategory("AC1")] + [TestCategory("AC9")] public async Task ScanHistoryPageDescriptionNamesOnlyRecordedRunTypes() { var testContext = BlazorTestContextFactory.Create(); @@ -47,10 +47,10 @@ public async Task ScanHistoryPageDescriptionNamesOnlyRecordedRunTypes() testContext.Services.AddSingleton>(CreateOptionsMonitor(enabled: false)); var component = testContext.Render(); - var description = component.Find(".page-description").TextContent.Trim(); + var description = component.Find("p.dug-page-header__description").TextContent.Trim(); var lowerCaseDescription = description.ToLowerInvariant(); - Assert.AreEqual("Operational history of observed image scans, runtime container scans and vulnerability refreshes.", + Assert.AreEqual("Image, runtime container and vulnerability scan runs with trigger, target and outcome.", description, "The description must name exactly the recorded run types"); Assert.DoesNotContain("discovery", lowerCaseDescription, "The description must not claim discovery runs"); @@ -360,16 +360,17 @@ await DetailPageAssert.AssertLoadErrorAsync(page, } /// - /// Verify the scan history table shows the scan status in a chip of its color + /// Verify the scan history table shows the scan status as an indicator in its tone /// /// Scan status - /// Expected chip color class + /// Expected tone CSS name /// Task [TestMethod] - [TestCategory("AC4")] - [DataRow("Succeeded", "mud-chip-color-success")] - [DataRow("Partial", "mud-chip-color-warning")] - public async Task ScanHistoryScanStatusChipShowsStatusColorAsync(string status, string expectedColorClass) + [TestCategory("AC3")] + [DataRow("Succeeded", "success")] + [DataRow("Partial", "warning")] + [DataRow("NotScanned", "neutral")] + public async Task ScanHistoryStatusShowsIndicatorInToneAsync(string status, string tone) { var testContext = BlazorTestContextFactory.Create(); @@ -395,10 +396,10 @@ public async Task ScanHistoryScanStatusChipShowsStatusColorAsync(string status, var page = testContext.Render(); - await ScanStatusChipAssert.AssertChipAsync(page, - root => root.FindAll("td[data-label='Status'] .mud-chip"), - status, - expectedColorClass).ConfigureAwait(false); + await page.WaitForAssertionAsync(() => Assert.IsNotEmpty(page.FindAll("td[data-label='Status']"), "The page must render the status cell"), + TimeSpan.FromSeconds(DetailPageAssert.WaitSeconds)).ConfigureAwait(false); + + ListPageAssert.AssertIndicator(page.Find("td[data-label='Status']"), status, tone); } } diff --git a/src/Tests/DockerUpdateGuard.Tests/SharedBaseImagesRenderTests.cs b/src/Tests/DockerUpdateGuard.Tests/SharedBaseImagesRenderTests.cs index 14e0ec38..7e0d22c8 100644 --- a/src/Tests/DockerUpdateGuard.Tests/SharedBaseImagesRenderTests.cs +++ b/src/Tests/DockerUpdateGuard.Tests/SharedBaseImagesRenderTests.cs @@ -1,10 +1,12 @@ using Bunit; +using DockerUpdateGuard.Components.Common; using DockerUpdateGuard.Components.Pages; using DockerUpdateGuard.Tests.Data; using DockerUpdateGuard.Tests.Helper; using DockerUpdateGuard.UI; +using Microsoft.AspNetCore.Components.Web; using Microsoft.Extensions.DependencyInjection; using Microsoft.Extensions.Logging; @@ -18,37 +20,272 @@ namespace DockerUpdateGuard.Tests; [TestClass] public class SharedBaseImagesRenderTests { + #region Constants + + /// + /// Class of the page's table + /// + private const string TableClass = "base-images-table"; + + #endregion // Constants + + #region Fields + + /// + /// Column heads in order + /// + private static readonly string[] _columnHeads = ["Base image", "Parent images", "Runtime containers", "Observed images", "Vulnerabilities"]; + + /// + /// Expected parent reference lines without digests + /// + private static readonly string[] _parentLines = ["docker.io/acme/api:1.0", "docker.io/acme/web:2.0"]; + + /// + /// Expected instance names beside the container links + /// + private static readonly string[] _instanceNames = ["prod", "stage"]; + + #endregion // Fields + #region Methods /// - /// Verify the page renders the shared base images heading and description + /// Verify the page shows the Base Images header and tab title without eyebrow and the overview panel with the meta text /// + /// Number of listed base images + /// Expected meta text /// Task [TestMethod] - [TestCategory("AC6")] - public async Task SharedBaseImagesRendersSharedBaseImagesHeadingAsync() + [TestCategory("AC1")] + [DataRow(1, "1 base image")] + [DataRow(2, "2 base images")] + public async Task SharedBaseImagesRendersSharedBaseImagesHeadingAsync(int itemCount, string expectedMeta) { var testContext = BlazorTestContextFactory.Create(); await using (testContext) { - var component = RenderPage(testContext, - [ - new() - { - BaseImageVersionId = Guid.NewGuid(), - ImageReference = "docker.io/library/debian:12", - } - ]); + RegisterViewService(testContext, [.. Enumerable.Range(0, itemCount).Select(index => CreateItem($"docker.io/library/debian:{index}"))]); + + var headOutlet = testContext.Render(); + var component = testContext.Render(); await component.WaitForAssertionAsync(() => Assert.Contains("Base image overview", component.Markup, "The page must render the overview once loaded")); - Assert.AreEqual("Shared Base Images", - component.Find("h3").TextContent.Trim(), - "The page heading must read Shared Base Images"); - Assert.AreEqual("Shared base images: bases used by two or more enabled images or containers, with the images built on them, their running containers, and vulnerability posture.", - component.Find(".page-description").TextContent.Trim(), - "The page description must state the sharing rule without calling the containers running"); + ListPageAssert.AssertHeader(component, + "Base Images", + "Base images shared by two or more enabled images or containers, with the images built on them, the containers that run them and their vulnerability status."); + ListPageAssert.AssertPanel(component, "Base image overview", expectedMeta); + Assert.Contains("Base Images", headOutlet.Markup, "The browser tab title must read Base Images"); + } + } + + /// + /// Verify the table has the five column heads in order + /// + /// Task + [TestMethod] + [TestCategory("AC2")] + public async Task SharedBaseImagesRenderShowsColumnHeadsInOrder() + { + var testContext = BlazorTestContextFactory.Create(); + + await using (testContext) + { + var page = RenderPage(testContext, [CreateItem("docker.io/library/debian:12")]); + + Assert.AreSequenceEqual(_columnHeads, ListPageAssert.GetHeads(page), "The heads must be the five columns in order"); + } + } + + /// + /// Verify the parent and container cells show plain lines, or the muted fallback without entries + /// + /// Task + [TestMethod] + [TestCategory("AC2")] + public async Task SharedBaseImagesRenderParentAndContainerCellsShowFallbacks() + { + var testContext = BlazorTestContextFactory.Create(); + + await using (testContext) + { + var withEntries = CreateItem("docker.io/library/debian:12"); + var without = CreateItem("docker.io/library/alpine:3"); + + withEntries.ParentImageReferences = ["docker.io/acme/api:1.0@sha256:0123456789abcdef", "docker.io/acme/web:2.0"]; + withEntries.RuntimeContainers = [CreateContainer("api-1", "prod")]; + + var page = RenderPage(testContext, [withEntries, without]); + var parents = ListPageAssert.FindCell(page, 0, "Parent images"); + var noParents = ListPageAssert.FindCell(page, 1, "Parent images"); + var noContainers = ListPageAssert.FindCell(page, 1, "Runtime containers"); + + Assert.AreSequenceEqual(_parentLines, + parents.QuerySelectorAll("span").Select(element => element.TextContent.Trim()).ToList(), + "The parents must be one plain reference per line without digests"); + Assert.AreEqual("No parent image recorded", noParents.TextContent.Trim(), "Without parents the cell must say so"); + Assert.AreEqual(1, noParents.QuerySelectorAll("span.table-secondary").Length, "The fallback must be muted"); + Assert.AreEqual("No linked container", noContainers.TextContent.Trim(), "Without containers the cell must say so"); + Assert.AreEqual(1, noContainers.QuerySelectorAll("span.table-secondary").Length, "The fallback must be muted"); + } + } + + /// + /// Verify the container cell links each container to its detail page with the instance name muted beside it + /// + /// Task + [TestMethod] + [TestCategory("AC2")] + public async Task SharedBaseImagesRenderContainerCellLinksToDetailWithInstance() + { + var testContext = BlazorTestContextFactory.Create(); + + await using (testContext) + { + var item = CreateItem("docker.io/library/debian:12"); + var first = CreateContainer("api-1", "prod"); + var second = CreateContainer("web-1", "stage"); + + item.RuntimeContainers = [first, second]; + + var page = RenderPage(testContext, [item]); + var cell = ListPageAssert.FindCell(page, 0, "Runtime containers"); + var links = cell.QuerySelectorAll("a").ToList(); + var instances = cell.QuerySelectorAll("span.table-secondary").Select(element => element.TextContent.Trim()).ToList(); + + Assert.HasCount(2, links, "Every container must have one link"); + Assert.AreEqual($"/runtime-containers/{first.DockerInstanceId}/{first.ContainerId}", links[0].GetAttribute("href"), "The link must lead to the container's detail page"); + Assert.AreEqual("api-1", links[0].TextContent.Trim(), "The link must show the container name"); + Assert.AreEqual($"/runtime-containers/{second.DockerInstanceId}/{second.ContainerId}", links[1].GetAttribute("href"), "The second link must lead to its detail page"); + Assert.AreSequenceEqual(_instanceNames, instances, "The instance names must stand muted beside the links"); + } + } + + /// + /// Verify the vulnerability cell shows the severity chip, the count and source line and the assessment message, without per-severity chips + /// + /// Task + [TestMethod] + [TestCategory("AC5")] + public async Task SharedBaseImagesRenderVulnerabilityCellShowsChipsCountSourceAndMessage() + { + var testContext = BlazorTestContextFactory.Create(); + + await using (testContext) + { + var item = CreateItem("docker.io/library/debian:12"); + + item.VulnerabilityAssessment = new VulnerabilityAssessmentViewData + { + Status = "Findings detected", + Source = "Trivy", + Message = "Scanned 3 minutes ago", + ActiveFindingCount = 3, + SeveritySummary = new VulnerabilitySeveritySummaryViewData + { + CriticalCount = 1, + HighCount = 2 + }, + }; + + var page = RenderPage(testContext, [item]); + var cell = ListPageAssert.FindCell(page, 0, "Vulnerabilities"); + var chips = cell.QuerySelectorAll("span.dug-chip").ToList(); + + Assert.IsNotNull(page.FindComponent(), "The cell must use the shared chips"); + Assert.HasCount(1, chips, "Findings detected must show only the severity chip"); + Assert.AreEqual("Critical", chips[0].TextContent.Trim(), "The chip must name the highest severity without a count"); + Assert.IsTrue(chips[0].ClassList.Contains("dug-chip--critical"), "The chip must be in the severity's tone"); + Assert.Contains("3 active · Trivy", cell.TextContent, "The count and source line must be shown"); + Assert.Contains("Scanned 3 minutes ago", cell.TextContent, "The assessment message must be shown"); + Assert.IsEmpty(cell.QuerySelectorAll(".mud-chip"), "The compact per-severity chips must be gone"); + } + } + + /// + /// Verify a failed check with earlier findings shows the status chip beside the severity chip + /// + /// Task + [TestMethod] + [TestCategory("AC5")] + public async Task SharedBaseImagesRenderFailedCheckShowsStatusBesideSeverity() + { + var testContext = BlazorTestContextFactory.Create(); + + await using (testContext) + { + var item = CreateItem("docker.io/library/debian:12"); + + item.VulnerabilityAssessment = new VulnerabilityAssessmentViewData + { + Status = "Failed", + ActiveFindingCount = 2, + SeveritySummary = new VulnerabilitySeveritySummaryViewData + { + HighCount = 2 + }, + }; + + var page = RenderPage(testContext, [item]); + var chips = ListPageAssert.FindCell(page, 0, "Vulnerabilities").QuerySelectorAll("span.dug-chip").ToList(); + + Assert.HasCount(2, chips, "The severity chip and the status chip must both be shown"); + Assert.AreEqual("High", chips[0].TextContent.Trim(), "The severity chip must come first"); + Assert.AreEqual("Failed", chips[1].TextContent.Trim(), "The status chip must stand beside it"); + Assert.IsTrue(chips[1].ClassList.Contains("dug-chip--danger"), "The failed status must be in the danger tone"); + } + } + + /// + /// Verify the vulnerability cell of the read-only Base Images list has no rescan button + /// + /// Task + [TestMethod] + [TestCategory("AC5")] + public async Task SharedBaseImagesRenderVulnerabilityCellHasNoRescanButton() + { + var testContext = BlazorTestContextFactory.Create(); + + await using (testContext) + { + var item = CreateItem("docker.io/library/debian:12"); + + item.VulnerabilityAssessment = new VulnerabilityAssessmentViewData + { + Status = "Findings detected", + ActiveFindingCount = 1, + SeveritySummary = new VulnerabilitySeveritySummaryViewData + { + HighCount = 1 + }, + }; + + var page = RenderPage(testContext, [item]); + var cell = ListPageAssert.FindCell(page, 0, "Vulnerabilities"); + + Assert.IsEmpty(page.FindComponents(), "The page must not render the rescan control"); + Assert.IsEmpty(cell.QuerySelectorAll("button"), "The cell must have no button"); + Assert.IsEmpty(cell.QuerySelectorAll(".vulnerability-rescan-control"), "The cell must have no rescan control markup"); + } + } + + /// + /// Verify the table switches to cards below 960 px and labels every cell with its head + /// + /// Task + [TestMethod] + [TestCategory("AC10")] + public async Task SharedBaseImagesRenderTableSwitchesToCardsBelow960Px() + { + var testContext = BlazorTestContextFactory.Create(); + + await using (testContext) + { + var page = RenderPage(testContext, [CreateItem("docker.io/library/debian:12")]); + + ListPageAssert.AssertCardLayout(page, TableClass, _columnHeads, "Parent images", "Runtime containers", "Vulnerabilities"); } } @@ -102,6 +339,37 @@ public async Task SharedBaseImagesLoadFailureShowsFixedErrorAndLogs() } } + /// + /// Create a base image entry without parents, containers or findings + /// + /// Base image reference + /// Entry + private static SharedBaseImageListItemData CreateItem(string imageReference) + { + return new SharedBaseImageListItemData + { + BaseImageVersionId = Guid.NewGuid(), + ImageReference = imageReference, + }; + } + + /// + /// Create a linked runtime container + /// + /// Container name + /// Docker instance name + /// Linked container + private static LinkedRuntimeContainerViewData CreateContainer(string name, string instanceName) + { + return new LinkedRuntimeContainerViewData + { + DockerInstanceId = Guid.NewGuid(), + ContainerId = $"id-{name}", + ContainerName = name, + DockerInstanceName = instanceName, + }; + } + /// /// Render the page for the entries the view service returns /// @@ -109,6 +377,18 @@ public async Task SharedBaseImagesLoadFailureShowsFixedErrorAndLogs() /// Entries returned by the view service /// Rendered page private static IRenderedComponent RenderPage(BunitContext testContext, IReadOnlyList items) + { + RegisterViewService(testContext, items); + + return testContext.Render(); + } + + /// + /// Register a view service that returns the entries + /// + /// bUnit test context + /// Entries returned by the view service + private static void RegisterViewService(BunitContext testContext, IReadOnlyList items) { var viewService = Substitute.For(); @@ -116,8 +396,6 @@ private static IRenderedComponent RenderPage(BunitContext test .Returns(items); testContext.Services.AddSingleton(viewService); - - return testContext.Render(); } #endregion // Methods diff --git a/src/Tests/DockerUpdateGuard.Tests/VulnerabilityCellFormatterTests.cs b/src/Tests/DockerUpdateGuard.Tests/VulnerabilityCellFormatterTests.cs new file mode 100644 index 00000000..a653873b --- /dev/null +++ b/src/Tests/DockerUpdateGuard.Tests/VulnerabilityCellFormatterTests.cs @@ -0,0 +1,73 @@ +using DockerUpdateGuard.UI; + +namespace DockerUpdateGuard.Tests; + +/// +/// Tests for +/// +[TestClass] +public class VulnerabilityCellFormatterTests +{ + #region Methods + + /// + /// Verify the count line lists the counts above zero in the order critical, high, medium, low, unknown + /// + /// Critical count + /// High count + /// Medium count + /// Low count + /// Unknown count + /// Expected count line + [TestMethod] + [TestCategory("AC4")] + [DataRow(1, 2, 0, 0, 0, "3 active · 1 critical, 2 high")] + [DataRow(1, 2, 3, 4, 5, "15 active · 1 critical, 2 high, 3 medium, 4 low, 5 unknown")] + [DataRow(0, 0, 0, 0, 4, "4 active · 4 unknown")] + [DataRow(0, 0, 0, 0, 0, "")] + public void VulnerabilityCellFormatterFormatActiveFindingsListsCountsInSeverityOrder(int critical, int high, int medium, int low, int other, string expected) + { + var summary = new VulnerabilitySeveritySummaryViewData + { + CriticalCount = critical, + HighCount = high, + MediumCount = medium, + LowCount = low, + OtherCount = other, + }; + + var line = VulnerabilityCellFormatter.FormatActiveFindings(summary); + + Assert.AreEqual(expected, line, "The count line must list the counts above zero in severity order"); + } + + /// + /// Verify the status chip stands beside the severity chip only with active findings and a status other than Findings detected + /// + /// Active high findings + /// Vulnerability status + /// Expected decision + [TestMethod] + [TestCategory("AC4")] + [DataRow(2, "Failed", true)] + [DataRow(2, "Unavailable", true)] + [DataRow(2, "No findings", true)] + [DataRow(2, "Findings detected", false)] + [DataRow(2, "findings detected", false)] + [DataRow(2, null, true)] + [DataRow(0, "Failed", false)] + [DataRow(0, "Findings detected", false)] + public void VulnerabilityCellFormatterIsStatusShownBesideSeverityOnlyForOtherStatuses(int highCount, string? status, bool expected) + { + var summary = new VulnerabilitySeveritySummaryViewData + { + HighCount = highCount + }; + + var shown = VulnerabilityCellFormatter.IsStatusShownBesideSeverity(summary, status); + + Assert.AreEqual(expected, shown, $"The status '{status}' with {highCount} active findings must decide the status chip as expected"); + } + + #endregion // Methods +} \ No newline at end of file diff --git a/src/Tests/DockerUpdateGuard.Tests/VulnerabilityListCellTests.cs b/src/Tests/DockerUpdateGuard.Tests/VulnerabilityListCellTests.cs new file mode 100644 index 00000000..80d439e3 --- /dev/null +++ b/src/Tests/DockerUpdateGuard.Tests/VulnerabilityListCellTests.cs @@ -0,0 +1,239 @@ +using Bunit; + +using DockerUpdateGuard.Components.Common; +using DockerUpdateGuard.Images.Interfaces; +using DockerUpdateGuard.Infrastructure; +using DockerUpdateGuard.Tests.Helper; +using DockerUpdateGuard.UI; + +using Microsoft.Extensions.DependencyInjection; + +using NSubstitute; + +namespace DockerUpdateGuard.Tests; + +/// +/// Tests for +/// +[TestClass] +public class VulnerabilityListCellTests +{ + #region Constants + + /// + /// Selector of the details part of the rescan control + /// + private const string DetailsPart = "div.vulnerability-rescan-control__details"; + + #endregion // Constants + + #region Fields + + /// + /// Lines of the details part in their expected order + /// + private static readonly string[] _detailLines = [">High<", "3 active · 3 high", "Checked 2026-11-23 21:27 UTC", "Base images affected", "4 active finding(s) across 1 base image"]; + + #endregion // Fields + + #region Methods + + /// + /// Verify findings show the highest severity chip and the count line + /// + /// Task + [TestMethod] + [TestCategory("AC4")] + public async Task VulnerabilityListCellFindingsShowSeverityChipAndCountLine() + { + var testContext = CreateContext(); + + await using (testContext) + { + var summary = CreateSummary(1, 2); + var cell = RenderCell(testContext, "Findings detected", summary); + var chips = cell.FindAll("span.dug-chip").ToList(); + + Assert.HasCount(1, chips, "Findings with the status Findings detected must show one chip"); + Assert.AreEqual("Critical", chips[0].TextContent.Trim(), "The chip must name the highest severity"); + Assert.IsTrue(chips[0].ClassList.Contains("dug-chip--critical"), "The chip must be in the severity's tone"); + Assert.Contains("3 active · 1 critical, 2 high", cell.Markup, "The count line must list the breakdown"); + } + } + + /// + /// Verify a failed check with earlier findings shows the status chip beside the severity chip + /// + /// Task + [TestMethod] + [TestCategory("AC4")] + public async Task VulnerabilityListCellFailedCheckShowsStatusBesideSeverity() + { + var testContext = CreateContext(); + + await using (testContext) + { + var cell = RenderCell(testContext, "Failed", CreateSummary(0, 2)); + var chips = cell.FindAll("span.dug-chip").ToList(); + + Assert.HasCount(2, chips, "The severity chip and the status chip must both be shown"); + Assert.AreEqual("High", chips[0].TextContent.Trim(), "The severity chip must come first"); + Assert.AreEqual("Failed", chips[1].TextContent.Trim(), "The status chip must stand beside it"); + Assert.IsTrue(chips[1].ClassList.Contains("dug-chip--danger"), "The failed status must be in the danger tone"); + Assert.Contains("2 active · 2 high", cell.Markup, "The count line must still be shown"); + } + } + + /// + /// Verify without active findings the status chip shows in its tone and no count line follows + /// + /// Vulnerability status + /// Expected tone CSS name + /// Task + [TestMethod] + [TestCategory("AC4")] + [DataRow("No findings", "success")] + [DataRow("Failed", "danger")] + [DataRow("Not scanned", "neutral")] + [DataRow("Unavailable", "neutral")] + public async Task VulnerabilityListCellWithoutFindingsShowsStatusChipInTone(string status, string tone) + { + var testContext = CreateContext(); + + await using (testContext) + { + var cell = RenderCell(testContext, status, new VulnerabilitySeveritySummaryViewData()); + var chips = cell.FindAll("span.dug-chip").ToList(); + + Assert.HasCount(1, chips, "Without findings only the status chip must be shown"); + Assert.AreEqual(status, chips[0].TextContent.Trim(), "The chip must show the status"); + Assert.IsTrue(chips[0].ClassList.Contains($"dug-chip--{tone}"), $"The status '{status}' must be shown in the {tone} tone"); + Assert.DoesNotContain(" active", cell.Markup, "Without findings there must be no count line"); + } + } + + /// + /// Verify the check time shows in UTC, or Never scanned without a check + /// + /// Task + [TestMethod] + [TestCategory("AC4")] + public async Task VulnerabilityListCellNeverScannedShowsNeverScanned() + { + var testContext = CreateContext(); + + await using (testContext) + { + var never = RenderCell(testContext, "Not scanned", new VulnerabilitySeveritySummaryViewData(), null); + var checkedCell = RenderCell(testContext, "No findings", new VulnerabilitySeveritySummaryViewData(), new DateTimeOffset(2026, 11, 23, 23, 27, 0, TimeSpan.FromHours(2))); + + Assert.Contains("Never scanned", never.Find(DetailsPart).TextContent, "An image never checked must show Never scanned"); + Assert.Contains("Checked 2026-11-23 21:27 UTC", checkedCell.Find(DetailsPart).TextContent, "A checked image must show its check time in UTC"); + Assert.DoesNotContain("Never scanned", checkedCell.Markup, "A checked image must not read Never scanned"); + } + } + + /// + /// Verify the base image warning shows only when base images have active findings + /// + /// Task + [TestMethod] + [TestCategory("AC4")] + public async Task VulnerabilityListCellBaseImageWarningOnlyWithAffectedBaseImages() + { + var testContext = CreateContext(); + + await using (testContext) + { + var affected = RenderCell(testContext, "No findings", new VulnerabilitySeveritySummaryViewData(), null, 1, "1 active finding(s) across 1 base image"); + var clean = RenderCell(testContext, "No findings", new VulnerabilitySeveritySummaryViewData(), null, 0, "must not be shown"); + + Assert.Contains("Base images affected", affected.Find(DetailsPart).TextContent, "The warning must show in the details part"); + Assert.Contains("1 active finding(s) across 1 base image", affected.Find(DetailsPart).TextContent, "The base image summary must show"); + Assert.DoesNotContain("Base images affected", clean.Markup, "Without affected base images there must be no warning"); + Assert.DoesNotContain("must not be shown", clean.Markup, "Without affected base images there must be no summary"); + } + } + + /// + /// Verify the lines come in the specified order and the rescan button stays outside the details part + /// + /// Task + [TestMethod] + [TestCategory("AC4")] + public async Task VulnerabilityListCellOrdersLinesAndKeepsButtonOutside() + { + var testContext = CreateContext(); + + await using (testContext) + { + var cell = RenderCell(testContext, "Findings detected", CreateSummary(0, 3), new DateTimeOffset(2026, 11, 23, 21, 27, 0, TimeSpan.Zero), 4, "4 active finding(s) across 1 base image"); + var details = cell.Find(DetailsPart); + + Assert.IsNull(details.QuerySelector("button"), "The rescan button must be outside the details part"); + Assert.IsNotNull(cell.Find("button[aria-label='Rescan vulnerabilities']"), "The rescan button must stay in the cell"); + + var markup = details.InnerHtml; + var positions = _detailLines.Select(text => markup.IndexOf(text, StringComparison.Ordinal)) + .ToList(); + + Assert.DoesNotContain(-1, positions, "Every line must be inside the details part"); + Assert.AreSequenceEqual(positions.Order().ToList(), positions, "The lines must come in the order chip, count, check time, base image chip, base image summary"); + } + } + + /// + /// Create a test context with the rescan control's service + /// + /// Test context + private static BunitContext CreateContext() + { + var testContext = BlazorTestContextFactory.Create(); + + testContext.Services.AddSingleton(Substitute.For()); + + return testContext; + } + + /// + /// Create a severity summary + /// + /// Critical count + /// High count + /// Summary + private static VulnerabilitySeveritySummaryViewData CreateSummary(int critical, int high) + { + return new VulnerabilitySeveritySummaryViewData + { + CriticalCount = critical, + HighCount = high, + }; + } + + /// + /// Render the cell + /// + /// Test context + /// Vulnerability status + /// Severity summary + /// Check time + /// Active base image findings + /// Base image summary + /// Rendered cell + private static IRenderedComponent RenderCell(BunitContext testContext, + string status, + VulnerabilitySeveritySummaryViewData summary, + DateTimeOffset? checkedAtUtc = null, + int baseImageFindings = 0, + string? baseImageSummary = null) + { + return testContext.Render(parameters => parameters.Add(cell => cell.ImageVersionId, Guid.NewGuid()) + .Add(cell => cell.Status, status) + .Add(cell => cell.SeveritySummary, summary) + .Add(cell => cell.CheckedAtUtc, checkedAtUtc) + .Add(cell => cell.ActiveBaseImageFindingCount, baseImageFindings) + .Add(cell => cell.BaseImageSummary, baseImageSummary)); + } + + #endregion // Methods +} \ No newline at end of file diff --git a/src/Tests/DockerUpdateGuard.Tests/VulnerabilityStatusChipsTests.cs b/src/Tests/DockerUpdateGuard.Tests/VulnerabilityStatusChipsTests.cs new file mode 100644 index 00000000..00234697 --- /dev/null +++ b/src/Tests/DockerUpdateGuard.Tests/VulnerabilityStatusChipsTests.cs @@ -0,0 +1,72 @@ +using Bunit; + +using DockerUpdateGuard.Components.Common; +using DockerUpdateGuard.Tests.Helper; +using DockerUpdateGuard.UI; + +namespace DockerUpdateGuard.Tests; + +/// +/// Tests for +/// +[TestClass] +public class VulnerabilityStatusChipsTests +{ + #region Constants + + /// + /// Prefix of the tone class of a chip + /// + private const string ToneClassPrefix = "dug-chip--"; + + #endregion // Constants + + #region Methods + + /// + /// Verify the chips show the highest active severity, the status beside it when it adds information, and the status alone otherwise + /// + /// Whether a severity summary is given + /// Active critical findings + /// Active high findings + /// Vulnerability status + /// Expected chip texts and tone names, comma separated + /// Task + [TestMethod] + [TestCategory("AC4")] + [DataRow(true, 0, 2, "Findings detected", "High:high")] + [DataRow(true, 1, 2, "Findings detected", "Critical:critical")] + [DataRow(true, 0, 2, "Failed", "High:high,Failed:danger")] + [DataRow(true, 0, 0, "No findings", "No findings:success")] + [DataRow(true, 0, 0, "Failed", "Failed:danger")] + [DataRow(false, 0, 0, "Not scanned", "Not scanned:neutral")] + public async Task VulnerabilityStatusChipsShowsSeverityAndStatusChips(bool hasSummary, int criticalCount, int highCount, string status, string expectedChips) + { + var testContext = BlazorTestContextFactory.Create(); + + await using (testContext) + { + VulnerabilitySeveritySummaryViewData? summary = null; + + if (hasSummary) + { + summary = new VulnerabilitySeveritySummaryViewData + { + CriticalCount = criticalCount, + HighCount = highCount + }; + } + + var component = testContext.Render(parameters => parameters.Add(chips => chips.Status, status) + .Add(chips => chips.SeveritySummary, summary)); + var chips = component.FindAll("span.dug-chip") + .Select(chip => $"{chip.TextContent.Trim()}:{chip.ClassList.First(name => name.StartsWith(ToneClassPrefix, StringComparison.Ordinal))[ToneClassPrefix.Length..]}") + .ToList(); + + Assert.AreEqual(expectedChips, string.Join(",", chips), $"The status '{status}' must produce the expected chips"); + Assert.IsEmpty(component.FindAll(".mud-chip"), "The chips must not be MudBlazor chips"); + } + } + + #endregion // Methods +} \ No newline at end of file