diff --git a/resources/js/vue/components/BuildSummaryPage.vue b/resources/js/vue/components/BuildSummaryPage.vue
index bcd2b86bb4..e40046c537 100644
--- a/resources/js/vue/components/BuildSummaryPage.vue
+++ b/resources/js/vue/components/BuildSummaryPage.vue
@@ -422,20 +422,33 @@
-
@@ -455,11 +468,13 @@ import BuildSidebar from './shared/BuildSidebar.vue';
import BuildTimelineCard from './BuildSummaryPage/BuildTimelineCard.vue';
import gql from 'graphql-tag';
import BuildTimeChart from './BuildSummaryPage/BuildTimeChart.vue';
+import TrendFilterBar from './shared/TrendFilterBar.vue';
+import { loadTrendFilters, saveTrendFilters, trendBuildConditions, trendHistoryFilterParams } from './shared/TrendFilters';
import { DateTime, Duration } from 'luxon';
export default {
name: 'BuildSummaryPage',
- components: { BuildTimelineCard, BuildTimeChart, BuildSummaryCard, LoadingIndicator, BuildSidebar, FontAwesomeIcon },
+ components: { BuildTimelineCard, BuildTimeChart, BuildSummaryCard, LoadingIndicator, BuildSidebar, FontAwesomeIcon, TrendFilterBar },
props: {
projectId: {
@@ -495,6 +510,7 @@ export default {
cdash: {},
loading: true,
errored: false,
+ trendFilters: loadTrendFilters('build'),
};
},
@@ -523,6 +539,7 @@ export default {
}
subProject {
id
+ name
}
project {
id
@@ -604,10 +621,6 @@ export default {
id: build.id,
nerrors: Math.max(0, build.buildErrorsCount),
nwarnings: Math.max(0, build.buildWarningsCount),
- name_encoded: encodeURIComponent(build.name),
- type_encoded: encodeURIComponent(build.buildType),
- starttime_encoded: encodeURIComponent(build.startTime),
- sitename_encoded: encodeURIComponent(build.site.name),
};
this.cdash.configure = {
@@ -620,8 +633,6 @@ export default {
nnotrun: Math.max(0, build.notRunTestsCount),
npassed: Math.max(0, build.passedTestsCount),
};
-
- this.cdash.projectname_encoded = encodeURIComponent(build.project.name);
},
error(error) {
this.errored = true;
@@ -631,11 +642,11 @@ export default {
},
buildHistory: {
query: gql`
- query($projectId: ID, $filters: ProjectBuildsFiltersMultiFilterInput, $onlyParents: Boolean) {
+ query($projectId: ID, $limit: Int!, $filters: ProjectBuildsFiltersMultiFilterInput, $onlyParents: Boolean) {
project(id: $projectId) {
id
builds(
- first: 100,
+ first: $limit,
orderBy: [{column: START_TIME, order: DESC}],
filters: $filters
onlyParents: $onlyParents
@@ -643,7 +654,13 @@ export default {
edges {
node {
id
+ name
+ buildType
startTime
+ site {
+ id
+ name
+ }
configureDuration
buildDuration
testDuration
@@ -660,6 +677,7 @@ export default {
variables() {
return {
projectId: this.projectId,
+ limit: this.trendFilters.limit,
filters: this.buildHistoryFilters,
onlyParents: this.isParentBuild,
};
@@ -687,9 +705,11 @@ export default {
}
const build = this.buildData;
const conditions = [
- { eq: { name: build.name } },
- { eq: { buildType: build.buildType } },
- { has: { site: { eq: { id: build.site.id } } } },
+ ...trendBuildConditions(this.historyFilters, {
+ name: build.name,
+ buildType: build.buildType,
+ siteId: build.site.id,
+ }),
{ le: { startTime: build.startTime } },
];
if (build.subProject) {
@@ -698,6 +718,42 @@ export default {
return { all: conditions };
},
+ /**
+ * The build history is the history of builds with this build's name, so that filter is always applied.
+ */
+ historyFilters() {
+ return {
+ ...this.trendFilters,
+ sameName: true,
+ };
+ },
+
+ trendFilterBuild() {
+ return {
+ siteName: this.buildData?.site.name ?? '',
+ name: this.buildData?.name ?? '',
+ group: this.buildData?.buildType ?? '',
+ };
+ },
+
+ /**
+ * The builds page, filtered to the builds in the build history chart.
+ */
+ buildHistoryUrl() {
+ if (!this.buildData || !this.buildHistory || this.buildHistory.length === 0) {
+ return '';
+ }
+ const build = this.buildData;
+ const params = trendHistoryFilterParams(this.historyFilters, {
+ name: build.name,
+ buildType: build.buildType,
+ siteName: build.site.name,
+ startTime: build.startTime,
+ }, this.buildHistory.at(-1).node.startTime);
+ const subproject = build.subProject ? `&subproject=${encodeURIComponent(build.subProject.name)}` : '';
+ return `${this.$baseURL}/index.php?project=${encodeURIComponent(build.project.name)}${subproject}&${params}`;
+ },
+
buildTimeData() {
if (!this.buildHistory) {
return [];
@@ -706,6 +762,9 @@ export default {
const build = edge.node;
return {
buildId: build.id,
+ buildName: build.name,
+ buildType: build.buildType,
+ siteName: build.site.name,
configureTime: Duration.fromObject({ seconds: Math.max(build.configureDuration, 0) }),
buildTime: Duration.fromObject({ seconds: Math.max(build.buildDuration, 0) }),
testTime: Duration.fromObject({ seconds: Math.max(build.testDuration, 0) }),
@@ -718,6 +777,12 @@ export default {
},
},
+ watch: {
+ trendFilters(filters) {
+ saveTrendFilters('build', filters);
+ },
+ },
+
methods: {
},
};
diff --git a/resources/js/vue/components/BuildSummaryPage/BuildTimeChart.vue b/resources/js/vue/components/BuildSummaryPage/BuildTimeChart.vue
index 000b8b60f5..49c1def53b 100644
--- a/resources/js/vue/components/BuildSummaryPage/BuildTimeChart.vue
+++ b/resources/js/vue/components/BuildSummaryPage/BuildTimeChart.vue
@@ -3,6 +3,8 @@
class="tw-w-full tw-h-60 tw-cursor-pointer"
:option="chartOption"
autoresize
+ data-test="build-time-chart"
+ :data-test-point-count="data.length"
@click="handleChartClick"
>
@@ -11,6 +13,12 @@
class="tw-text-sm"
>
Start: {{ tooltipTimestamp(params[0].dataIndex) }}
+
+ {{ field.label }}: {{ data[params[0].dataIndex]?.[field.key] }}
+
Configure Time: {{ tooltipDuration(params[0].dataIndex, 'configureTime') }}
Build Time: {{ tooltipDuration(params[0].dataIndex, 'buildTime') }}
Test Time: {{ tooltipDuration(params[0].dataIndex, 'testTime') }}
@@ -22,6 +30,7 @@
diff --git a/resources/js/vue/components/shared/TrendFilters.js b/resources/js/vue/components/shared/TrendFilters.js
new file mode 100644
index 0000000000..715108bc8c
--- /dev/null
+++ b/resources/js/vue/components/shared/TrendFilters.js
@@ -0,0 +1,159 @@
+/**
+ * The choices which control which builds a trend chart compares the current build with. Each chart
+ * remembers the user's last choices in the browser's local storage.
+ */
+
+import { DateTime } from 'luxon';
+import { filterParams } from './legacy/filters/filterUrls';
+
+/**
+ * The numbers of builds a trend chart can show.
+ */
+export const TREND_LIMITS = [25, 50, 100, 200];
+
+/**
+ * @typedef {Object} TrendFilters
+ * @property {boolean} sameSite Only show builds from the current build's site.
+ * @property {boolean} sameName Only show builds with the current build's name.
+ * @property {boolean} sameGroup Only show builds in the current build's group.
+ * @property {number} limit The maximum number of builds to show, one of TREND_LIMITS.
+ */
+
+/**
+ * @type {Readonly}
+ */
+export const DEFAULT_TREND_FILTERS = Object.freeze({
+ sameSite: true,
+ sameName: true,
+ sameGroup: true,
+ limit: 100,
+});
+
+/**
+ * @param {string} chart e.g. "build" or "test"
+ * @returns {string}
+ */
+function storageKey(chart) {
+ return `cdash.trendFilters.${chart}`;
+}
+
+/**
+ * The choices the user last made for a chart. Missing or invalid choices are replaced by the defaults.
+ *
+ * @param {string} chart e.g. "build" or "test"
+ * @returns {TrendFilters}
+ */
+export function loadTrendFilters(chart) {
+ let stored = null;
+ try {
+ stored = JSON.parse(localStorage.getItem(storageKey(chart)));
+ } catch {
+ // Local storage is blocked by the browser, or holds something other than JSON.
+ }
+
+ const filters = { ...DEFAULT_TREND_FILTERS };
+ if (stored !== null && typeof stored === 'object') {
+ for (const key of ['sameSite', 'sameName', 'sameGroup']) {
+ if (typeof stored[key] === 'boolean') {
+ filters[key] = stored[key];
+ }
+ }
+ if (TREND_LIMITS.includes(stored.limit)) {
+ filters.limit = stored.limit;
+ }
+ }
+ return filters;
+}
+
+/**
+ * Remember the user's choices for a chart. Only the choices which differ from the defaults are kept, so
+ * that users get any new defaults for the choices they haven't changed.
+ *
+ * @param {string} chart e.g. "build" or "test"
+ * @param {TrendFilters} filters
+ */
+export function saveTrendFilters(chart, filters) {
+ const changed = Object.fromEntries(Object.keys(DEFAULT_TREND_FILTERS)
+ .filter((key) => filters[key] !== DEFAULT_TREND_FILTERS[key])
+ .map((key) => [key, filters[key]]));
+ try {
+ if (Object.keys(changed).length === 0) {
+ localStorage.removeItem(storageKey(chart));
+ } else {
+ localStorage.setItem(storageKey(chart), JSON.stringify(changed));
+ }
+ } catch {
+ // The choices just won't be remembered.
+ }
+}
+
+/**
+ * The conditions which limit a builds query to the builds the user chose to compare with a build.
+ *
+ * @param {TrendFilters} filters
+ * @param {{name: string, buildType: string, siteId: number|string}} build
+ * @returns {Object[]} Conditions for a `ProjectBuildsFiltersMultiFilterInput` `all` filter.
+ */
+export function trendBuildConditions(filters, build) {
+ const conditions = [];
+ if (filters.sameSite) {
+ conditions.push({ has: { site: { eq: { id: build.siteId } } } });
+ }
+ if (filters.sameName) {
+ conditions.push({ eq: { name: build.name } });
+ }
+ if (filters.sameGroup) {
+ conditions.push({ eq: { buildType: build.buildType } });
+ }
+ return conditions;
+}
+
+/**
+ * The filter parameters for the index.php and queryTests.php pages which select the same builds as a
+ * trend chart: those matching the chosen details of the current build, which started between the
+ * oldest plotted build and the current build. Builds which started in the same second as either of
+ * those are included too, even if the chart has no room for them. The legacy pages match sites by
+ * name rather than by id, so they also include builds from other sites with the same name. Likewise,
+ * index.php finds a SubProject by name, so it lists parent builds instead if the SubProject has been
+ * removed or its name contains HTML special characters.
+ *
+ * @param {TrendFilters} filters
+ * @param {{name: string, buildType: string, siteName: string, startTime: string}} build
+ * @param {string} oldestStartTime The start time of the oldest plotted build.
+ * @param {Array<[string, number, string]>} extraFilters Other [field, compare, value] filters.
+ * @returns {string} e.g. "filtercount=2&showfilters=1&filtercombine=and&field1=..."
+ */
+export function trendHistoryFilterParams(filters, build, oldestStartTime, extraFilters = []) {
+ const conditions = [...extraFilters];
+ if (filters.sameSite) {
+ conditions.push(['site', 61, build.siteName]);
+ }
+ if (filters.sameName) {
+ conditions.push(['buildname', 61, build.name]);
+ }
+ if (filters.sameGroup) {
+ conditions.push(['buildtype', 61, build.buildType]);
+ }
+ // The date comparisons are exclusive, and start times are stored to the second.
+ const toISO = (time) => time.toISO({ suppressMilliseconds: true });
+ conditions.push(['buildstarttime', 83, toISO(DateTime.fromISO(oldestStartTime, { setZone: true }).minus({ seconds: 1 }))]);
+ conditions.push(['buildstarttime', 84, toISO(DateTime.fromISO(build.startTime, { setZone: true }).plus({ seconds: 1 }))]);
+
+ const params = conditions.map(([field, compare, value], index) => filterParams('', { field, compare, value }, index + 1));
+ return `filtercount=${conditions.length}&showfilters=1&filtercombine=and${params.join('')}`;
+}
+
+/**
+ * The build details which differ between the builds plotted in a trend chart, and so are needed to
+ * tell them apart.
+ *
+ * @param {Array<{siteName: string, buildName: string, buildType: string}>} dataPoints
+ * @returns {Array<{key: string, label: string}>}
+ */
+export function variedBuildFields(dataPoints) {
+ return [
+ { key: 'siteName', label: 'Site' },
+ { key: 'buildName', label: 'Build name' },
+ { key: 'buildType', label: 'Group' },
+ ].filter((field) => new Set(dataPoints.map((dataPoint) => dataPoint[field.key])).size > 1);
+}
diff --git a/resources/js/vue/components/shared/legacy/filters/filterUrls.js b/resources/js/vue/components/shared/legacy/filters/filterUrls.js
index f8eb1453fc..1a6396feb6 100644
--- a/resources/js/vue/components/shared/legacy/filters/filterUrls.js
+++ b/resources/js/vue/components/shared/legacy/filters/filterUrls.js
@@ -2,7 +2,8 @@
* URL handling for the legacy filters. The filters are encoded in the query string as
* "filtercount=2&field1=...&compare1=..." and so on, which the legacy APIs parse.
*
- * Remove this once the pages which use it use the GraphQL filters.
+ * Remove this once the pages which use it use the GraphQL filters. The trend charts' links to the
+ * legacy pages also use filterParams().
*/
/**
@@ -34,7 +35,15 @@ export function showFiltersUrl(href, show) {
return show ? href.replace('&showfilters=0', '&showfilters=1') : href.replace('&showfilters=1', '&showfilters=0');
}
-function filterParams(prefix, filter, i) {
+/**
+ * The parameters for one filter.
+ *
+ * @param {string} prefix "" for a top-level filter, or e.g. "field2" for a filter in the second block.
+ * @param {{field: string, compare: number|string, value: string}} filter
+ * @param {number} i The filter's position, starting from 1.
+ * @returns {string} e.g. "&field1=site&compare1=61&value1=..."
+ */
+export function filterParams(prefix, filter, i) {
return `&${prefix}field${i}=${encodeURIComponent(filter.field)}`
+ `&${prefix}compare${i}=${encodeURIComponent(filter.compare)}`
+ `&${prefix}value${i}=${encodeURIComponent(filter.value)}`;
diff --git a/tests/Browser/Pages/BuildSummaryPageTest.php b/tests/Browser/Pages/BuildSummaryPageTest.php
index 6767d2ca9f..5eea78f3b1 100644
--- a/tests/Browser/Pages/BuildSummaryPageTest.php
+++ b/tests/Browser/Pages/BuildSummaryPageTest.php
@@ -7,6 +7,7 @@
use App\Models\Project;
use App\Models\Site;
use App\Models\SiteInformation;
+use App\Models\SubProject;
use App\Services\SiteService;
use Illuminate\Support\Carbon;
use Illuminate\Support\Str;
@@ -21,6 +22,13 @@ class BuildSummaryPageTest extends BrowserTestCase
private Project $project;
private Site $site;
+ /**
+ * Records which aren't deleted along with the project.
+ *
+ * @var array
+ */
+ private array $cleanup = [];
+
public function setUp(): void
{
parent::setUp();
@@ -34,6 +42,10 @@ public function setUp(): void
public function tearDown(): void
{
$this->project->delete();
+ foreach ($this->cleanup as $model) {
+ $model->delete();
+ }
+ $this->cleanup = [];
$this->site->delete();
parent::tearDown();
@@ -71,14 +83,16 @@ public function testShowsHistoryLink(): void
'uuid' => Str::uuid()->toString(),
]);
- $this->browse(function (Browser $browser) use ($build, $buildName, $buildType, $startTime): void {
+ $this->browse(function (Browser $browser) use ($build, $buildName, $buildType): void {
$browser->visit("/builds/{$build->id}")
- ->waitForText('Show History')
+ ->waitFor('[data-test="build-history-link"][href]')
->assertAttributeContains('@build-history-link', 'href', 'project=' . urlencode($this->project->name))
->assertAttributeContains('@build-history-link', 'href', 'value1=' . urlencode($this->site->name))
->assertAttributeContains('@build-history-link', 'href', 'value2=' . rawurlencode($buildName))
->assertAttributeContains('@build-history-link', 'href', 'value3=' . rawurlencode($buildType))
- ->assertAttributeContains('@build-history-link', 'href', 'value4=' . rawurlencode($startTime))
+ // Builds which started between the oldest build in the chart (this one) and this build.
+ ->assertAttributeContains('@build-history-link', 'href', 'field4=buildstarttime&compare4=83&value4=' . rawurlencode('2024-03-15T08:29:59Z'))
+ ->assertAttributeContains('@build-history-link', 'href', 'field5=buildstarttime&compare5=84&value5=' . rawurlencode('2024-03-15T08:30:01Z'))
;
});
}
@@ -323,4 +337,171 @@ public function testBuildTimelineZeroDuration(): void
->assertSeeIn('@build-timeline', '0 sec');
});
}
+
+ public function testBuildHistoryFilters(): void
+ {
+ $startTime = Carbon::now()->subHour();
+ $attributes = [
+ 'siteid' => $this->site->id,
+ 'name' => 'Linux-' . Str::uuid()->toString(),
+ 'type' => 'Nightly',
+ ];
+
+ /** @var Build $build */
+ $build = $this->project->builds()->create(array_merge($attributes, [
+ 'uuid' => Str::uuid()->toString(),
+ 'starttime' => $startTime,
+ ]));
+ // The builds page only lists builds in a build group.
+ $build->buildGroups()->attach($this->project->buildgroups()->where('name', 'Nightly')->firstOrFail());
+
+ $otherSite = Site::factory()->create();
+ $this->cleanup[] = $otherSite;
+
+ // An earlier build like the current one, and earlier builds which differ from it in its site (one
+ // build) or group (three), so that the number of builds shown tells which filters are applied. A
+ // later build and builds with another name are never shown. The build like the current one is the
+ // oldest, so that the history page's time range includes all the others.
+ $builds = [
+ ['starttime' => $startTime->copy()->subMinutes(8)],
+ ['starttime' => $startTime->copy()->addMinute()],
+ ['starttime' => $startTime->copy()->subMinutes(2), 'siteid' => $otherSite->id],
+ ['starttime' => $startTime->copy()->subMinutes(3), 'name' => 'Other Build'],
+ ['starttime' => $startTime->copy()->subMinutes(4), 'name' => 'Other Build'],
+ ['starttime' => $startTime->copy()->subMinutes(5), 'type' => 'Experimental'],
+ ['starttime' => $startTime->copy()->subMinutes(6), 'type' => 'Experimental'],
+ ['starttime' => $startTime->copy()->subMinutes(7), 'type' => 'Experimental'],
+ ];
+ foreach ($builds as $differences) {
+ /** @var Build $otherBuild */
+ $otherBuild = $this->project->builds()->create(array_merge($attributes, ['uuid' => Str::uuid()->toString()], $differences));
+ $otherBuild->buildGroups()->attach($this->project->buildgroups()->where('name', $otherBuild->type)->firstOrFail());
+ }
+
+ $this->browse(function (Browser $browser) use ($build): void {
+ try {
+ $browser->visit("/builds/{$build->id}")
+ ->waitFor('[data-test="build-time-chart"][data-test-point-count="2"]')
+ ->assertAttributeContains('@trend-filter-site', 'title', $this->site->name)
+ ->assertSelected('@trend-filter-site', 'this')
+ ->assertSelected('@trend-filter-group', 'this')
+ // The build history only includes builds with this build's name.
+ ->assertMissing('@trend-filter-name')
+ ->waitFor('[data-test="build-history-link"][href]')
+ ->assertAttributeContains('@build-history-link', 'href', 'filtercount=5&showfilters=1&filtercombine=and&field1=site&compare1=61')
+ ->select('@trend-filter-site', 'all')
+ ->waitFor('[data-test="build-time-chart"][data-test-point-count="3"]')
+ // The history link lists the same builds as the chart.
+ ->waitFor('[data-test="build-history-link"][href]')
+ ->waitForReload(fn (Browser $browser) => $browser->click('@build-history-link'))
+ ->waitFor('@build-row');
+ self::assertCount(3, $browser->elements('@build-row'));
+
+ $browser->visit("/builds/{$build->id}")
+ ->waitFor('[data-test="build-time-chart"][data-test-point-count="3"]')
+ ->select('@trend-filter-group', 'all')
+ ->waitFor('[data-test="build-time-chart"][data-test-point-count="6"]')
+ ->waitFor('[data-test="build-history-link"][href]')
+ ->assertAttributeContains('@build-history-link', 'href', 'filtercount=3&showfilters=1&filtercombine=and&field1=buildname&compare1=61')
+ // The choices are remembered.
+ ->refresh()
+ ->waitFor('[data-test="build-time-chart"][data-test-point-count="6"]')
+ ->assertSelected('@trend-filter-site', 'all')
+ ->assertSelected('@trend-filter-group', 'all')
+ ->select('@trend-filter-site', 'this')
+ ->waitFor('[data-test="build-time-chart"][data-test-point-count="5"]')
+ ->assertSelected('@trend-filter-site', 'this');
+ } finally {
+ $browser->script("try { localStorage.removeItem('cdash.trendFilters.build'); } catch {}");
+ }
+ });
+ }
+
+ /**
+ * The history of a SubProject's build only includes that SubProject's builds.
+ */
+ public function testBuildHistoryForSubProjectBuild(): void
+ {
+ $nightly = $this->project->buildgroups()->where('name', 'Nightly')->firstOrFail();
+ $subprojects = array_map(fn (): SubProject => $this->project->subprojects()->create([
+ 'name' => Str::uuid()->toString(),
+ 'groupid' => -1,
+ ]), [0, 1]);
+
+ $children = [];
+ foreach ([20, 10] as $minutesAgo) {
+ $attributes = [
+ 'siteid' => $this->site->id,
+ 'name' => 'Linux',
+ 'type' => 'Nightly',
+ 'starttime' => Carbon::now()->subMinutes($minutesAgo),
+ ];
+ /** @var Build $parent */
+ $parent = $this->project->builds()->create(array_merge($attributes, ['uuid' => Str::uuid()->toString()]));
+ $parent->buildGroups()->attach($nightly);
+ foreach ($subprojects as $subproject) {
+ /** @var Build $child */
+ $child = $this->project->builds()->create(array_merge($attributes, [
+ 'uuid' => Str::uuid()->toString(),
+ 'parentid' => $parent->id,
+ 'subprojectid' => $subproject->id,
+ ]));
+ $child->buildGroups()->attach($nightly);
+ $children[] = $child;
+ }
+ }
+
+ $this->browse(function (Browser $browser) use ($children, $subprojects): void {
+ $browser->visit("/builds/{$children[2]->id}")
+ ->waitFor('[data-test="build-time-chart"][data-test-point-count="2"]')
+ ->waitFor('[data-test="build-history-link"][href]')
+ ->assertAttributeContains('@build-history-link', 'href', '&subproject=' . rawurlencode($subprojects[0]->name) . '&')
+ ->waitForReload(fn (Browser $browser) => $browser->click('@build-history-link'))
+ ->waitFor('@build-row');
+ self::assertCount(2, $browser->elements('@build-row'));
+ });
+ }
+
+ public function testBuildHistoryLimit(): void
+ {
+ $startTime = Carbon::parse('2024-03-15T08:30:00Z');
+ $attributes = [
+ 'siteid' => $this->site->id,
+ 'name' => Str::uuid()->toString(),
+ 'type' => 'Nightly',
+ ];
+
+ /** @var Build $build */
+ $build = $this->project->builds()->create(array_merge($attributes, [
+ 'uuid' => Str::uuid()->toString(),
+ 'starttime' => $startTime,
+ ]));
+ for ($i = 1; $i <= 25; $i++) {
+ $this->project->builds()->create(array_merge($attributes, [
+ 'uuid' => Str::uuid()->toString(),
+ 'starttime' => $startTime->copy()->subMinutes($i),
+ ]));
+ }
+
+ $this->browse(function (Browser $browser) use ($build): void {
+ try {
+ $browser->visit("/builds/{$build->id}")
+ ->waitFor('[data-test="build-time-chart"][data-test-point-count="26"]')
+ ->assertSelected('@trend-filter-limit', '100')
+ ->waitFor('[data-test="build-history-link"][href]')
+ ->assertAttributeContains('@build-history-link', 'href', 'compare4=83&value4=' . rawurlencode('2024-03-15T08:04:59Z'))
+ ->select('@trend-filter-limit', '25')
+ ->waitFor('[data-test="build-time-chart"][data-test-point-count="25"]')
+ // The history link starts at the oldest build in the chart.
+ ->waitFor('[data-test="build-history-link"][href]')
+ ->assertAttributeContains('@build-history-link', 'href', 'compare4=83&value4=' . rawurlencode('2024-03-15T08:05:59Z'))
+ // The choice is remembered.
+ ->refresh()
+ ->waitFor('[data-test="build-time-chart"][data-test-point-count="25"]')
+ ->assertSelected('@trend-filter-limit', '25');
+ } finally {
+ $browser->script("try { localStorage.removeItem('cdash.trendFilters.build'); } catch {}");
+ }
+ });
+ }
}
diff --git a/tests/Browser/Pages/TestsIdPageTest.php b/tests/Browser/Pages/TestsIdPageTest.php
index 230d57142c..858131cad4 100644
--- a/tests/Browser/Pages/TestsIdPageTest.php
+++ b/tests/Browser/Pages/TestsIdPageTest.php
@@ -32,7 +32,7 @@ class TestsIdPageTest extends BrowserTestCase
/**
* Records which aren't deleted along with the project.
*
- * @var array
+ * @var array
*/
private array $cleanup = [];
@@ -435,6 +435,118 @@ public function testTrendChartShowsDataForSubprojectBuilds(): void
});
}
+ public function testTrendChartFilters(): void
+ {
+ /** @var Test $test */
+ $test = $this->createTest([
+ 'testname' => (string) Str::uuid(),
+ 'status' => 'passed',
+ ]);
+
+ $otherSite = Site::factory()->create();
+ $this->cleanup[] = $otherSite;
+
+ // An earlier build like the current one, a later build, which is never shown, and earlier builds
+ // which differ from the current one in its site (one build), name (two) or type (three), so that
+ // the number of builds shown tells which filters are applied. The build like the current one is
+ // the oldest, so that the history pages' time ranges include all the others.
+ $builds = [
+ ['starttime' => $this->build->starttime->copy()->subMinutes(8)],
+ ['starttime' => $this->build->starttime->copy()->addMinute()],
+ ['starttime' => $this->build->starttime->copy()->subMinutes(2), 'siteid' => $otherSite->id],
+ ['starttime' => $this->build->starttime->copy()->subMinutes(3), 'name' => 'Other Build'],
+ ['starttime' => $this->build->starttime->copy()->subMinutes(4), 'name' => 'Other Build'],
+ ['starttime' => $this->build->starttime->copy()->subMinutes(5), 'type' => 'Debug'],
+ ['starttime' => $this->build->starttime->copy()->subMinutes(6), 'type' => 'Debug'],
+ ['starttime' => $this->build->starttime->copy()->subMinutes(7), 'type' => 'Debug'],
+ ];
+ foreach ($builds as $attributes) {
+ $build = $this->project->builds()->create(array_merge([
+ 'siteid' => $this->site->id,
+ 'name' => $this->build->name,
+ 'type' => $this->build->type,
+ 'uuid' => Str::uuid()->toString(),
+ ], $attributes));
+ $this->createTest(['testname' => $test->testname, 'status' => 'passed'], $build);
+ }
+
+ $this->browse(function (Browser $browser) use ($test): void {
+ try {
+ $browser->visit("/tests/{$test->id}")
+ ->waitFor('[data-test="trend-chart"][data-test-point-count="2"]')
+ ->assertAttributeContains('@trend-filter-site', 'title', $this->site->name)
+ ->assertSelected('@trend-filter-site', 'this')
+ ->assertSelected('@trend-filter-name', 'this')
+ ->assertSelected('@trend-filter-group', 'this')
+ ->select('@trend-filter-site', 'all')
+ ->waitFor('[data-test="trend-chart"][data-test-point-count="3"]')
+ // The history page lists the same builds as the chart.
+ ->waitFor('[data-test="test-history-link"][href]')
+ ->waitForReload(fn (Browser $browser) => $browser->click('@test-history-link'))
+ ->waitFor('@test-count');
+ self::assertSame('3', $browser->text('@test-count'));
+
+ $browser->visit("/tests/{$test->id}")
+ ->waitFor('[data-test="trend-chart"][data-test-point-count="3"]')
+ ->select('@trend-filter-name', 'all')
+ ->waitFor('[data-test="trend-chart"][data-test-point-count="5"]')
+ ->select('@trend-filter-group', 'all')
+ ->waitFor('[data-test="trend-chart"][data-test-point-count="8"]')
+ // The choices are remembered.
+ ->refresh()
+ ->waitFor('[data-test="trend-chart"][data-test-point-count="8"]')
+ ->assertSelected('@trend-filter-site', 'all')
+ ->assertSelected('@trend-filter-name', 'all')
+ ->assertSelected('@trend-filter-group', 'all')
+ ->select('@trend-filter-site', 'this')
+ ->waitFor('[data-test="trend-chart"][data-test-point-count="7"]')
+ ->assertSelected('@trend-filter-site', 'this');
+ } finally {
+ $browser->script("try { localStorage.removeItem('cdash.trendFilters.test'); } catch {}");
+ }
+ });
+ }
+
+ public function testTrendChartLimit(): void
+ {
+ /** @var Test $test */
+ $test = $this->createTest([
+ 'testname' => (string) Str::uuid(),
+ 'status' => 'passed',
+ ]);
+ for ($i = 1; $i <= 25; $i++) {
+ $build = $this->project->builds()->create([
+ 'siteid' => $this->site->id,
+ 'name' => $this->build->name,
+ 'type' => $this->build->type,
+ 'uuid' => Str::uuid()->toString(),
+ 'starttime' => $this->build->starttime->copy()->subMinutes($i),
+ ]);
+ $this->createTest(['testname' => $test->testname, 'status' => 'passed'], $build);
+ }
+
+ $this->browse(function (Browser $browser) use ($test): void {
+ try {
+ $browser->visit("/tests/{$test->id}")
+ ->waitFor('[data-test="trend-chart"][data-test-point-count="26"]')
+ ->assertSelected('@trend-filter-limit', '100')
+ ->select('@trend-filter-limit', '25')
+ ->waitFor('[data-test="trend-chart"][data-test-point-count="25"]')
+ // The choice is remembered.
+ ->refresh()
+ ->waitFor('[data-test="trend-chart"][data-test-point-count="25"]')
+ ->assertSelected('@trend-filter-limit', '25')
+ // The history page lists the same builds as the chart.
+ ->waitFor('[data-test="test-history-link"][href]')
+ ->waitForReload(fn (Browser $browser) => $browser->click('@test-history-link'))
+ ->waitFor('@test-count');
+ self::assertSame('25', $browser->text('@test-count'));
+ } finally {
+ $browser->script("try { localStorage.removeItem('cdash.trendFilters.test'); } catch {}");
+ }
+ });
+ }
+
public static function validImageRoleProvider(): array
{
return [
diff --git a/tests/Spec/CMakeLists.txt b/tests/Spec/CMakeLists.txt
index e76e8ddd72..2fbe76a9ea 100644
--- a/tests/Spec/CMakeLists.txt
+++ b/tests/Spec/CMakeLists.txt
@@ -17,4 +17,5 @@ add_js_unit_test(legacy-timeline)
add_js_unit_test(project-builds)
add_js_unit_test(repository-integrations)
add_js_unit_test(testing-day)
+add_js_unit_test(trend-filters)
add_js_unit_test(utils)
diff --git a/tests/Spec/trend-filters.spec.js b/tests/Spec/trend-filters.spec.js
new file mode 100644
index 0000000000..d6b27044f9
--- /dev/null
+++ b/tests/Spec/trend-filters.spec.js
@@ -0,0 +1,102 @@
+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
+import {
+ DEFAULT_TREND_FILTERS,
+ loadTrendFilters,
+ saveTrendFilters,
+ trendBuildConditions,
+ trendHistoryFilterParams,
+ variedBuildFields,
+} from '../../resources/js/vue/components/shared/TrendFilters';
+
+describe('trend filters', () => {
+ let storage;
+
+ beforeEach(() => {
+ storage = new Map();
+ vi.stubGlobal('localStorage', {
+ getItem: (key) => storage.get(key) ?? null,
+ setItem: (key, value) => storage.set(key, String(value)),
+ removeItem: (key) => storage.delete(key),
+ });
+ });
+
+ afterEach(() => {
+ vi.unstubAllGlobals();
+ });
+
+ it('remembers each chart\'s filters separately', () => {
+ expect(loadTrendFilters('test')).toEqual(DEFAULT_TREND_FILTERS);
+
+ const filters = { sameSite: false, sameName: true, sameGroup: false, limit: 25 };
+ saveTrendFilters('test', filters);
+ expect(loadTrendFilters('test')).toEqual(filters);
+ expect(loadTrendFilters('build')).toEqual(DEFAULT_TREND_FILTERS);
+ });
+
+ it('only remembers the filters which differ from the defaults', () => {
+ saveTrendFilters('test', { ...DEFAULT_TREND_FILTERS, limit: 25 });
+ expect(JSON.parse(storage.get('cdash.trendFilters.test'))).toEqual({ limit: 25 });
+ saveTrendFilters('test', { ...DEFAULT_TREND_FILTERS });
+ expect(storage.size).toBe(0);
+ });
+
+ it('uses the defaults for invalid stored filters', () => {
+ storage.set('cdash.trendFilters.test', JSON.stringify({ sameSite: 'no', sameName: false, limit: 30 }));
+ expect(loadTrendFilters('test')).toEqual({ ...DEFAULT_TREND_FILTERS, sameName: false });
+
+ for (const value of ['not json', 'null', '7', '[]']) {
+ storage.set('cdash.trendFilters.test', value);
+ expect(loadTrendFilters('test')).toEqual(DEFAULT_TREND_FILTERS);
+ }
+ });
+
+ it('uses the defaults when local storage is unavailable', () => {
+ const unavailable = () => {
+ throw new DOMException('The operation is insecure.', 'SecurityError');
+ };
+ vi.stubGlobal('localStorage', { getItem: unavailable, setItem: unavailable, removeItem: unavailable });
+
+ expect(() => saveTrendFilters('test', { ...DEFAULT_TREND_FILTERS, limit: 25 })).not.toThrow();
+ expect(loadTrendFilters('test')).toEqual(DEFAULT_TREND_FILTERS);
+ });
+
+ it('only matches the chosen build details', () => {
+ const build = { name: 'Linux', buildType: 'Nightly', siteId: '7' };
+ expect(trendBuildConditions(DEFAULT_TREND_FILTERS, build)).toEqual([
+ { has: { site: { eq: { id: '7' } } } },
+ { eq: { name: 'Linux' } },
+ { eq: { buildType: 'Nightly' } },
+ ]);
+ expect(trendBuildConditions({ ...DEFAULT_TREND_FILTERS, sameSite: false, sameGroup: false }, build)).toEqual([
+ { eq: { name: 'Linux' } },
+ ]);
+ });
+
+ it('filters the history pages to the plotted builds', () => {
+ const build = { name: 'Linux gcc', buildType: 'Nightly', siteName: 'a&b', startTime: '2026-11-18T10:00:00-05:00' };
+ expect(trendHistoryFilterParams(DEFAULT_TREND_FILTERS, build, '2026-11-01T09:30:00-04:00', [['testname', 61, 'my test']])).toBe(
+ 'filtercount=6&showfilters=1&filtercombine=and'
+ + '&field1=testname&compare1=61&value1=my%20test'
+ + '&field2=site&compare2=61&value2=a%26b'
+ + '&field3=buildname&compare3=61&value3=Linux%20gcc'
+ + '&field4=buildtype&compare4=61&value4=Nightly'
+ + '&field5=buildstarttime&compare5=83&value5=2026-11-01T09%3A29%3A59-04%3A00'
+ + '&field6=buildstarttime&compare6=84&value6=2026-11-18T10%3A00%3A01-05%3A00',
+ );
+ // The API's UTC times are like "+00:00".
+ expect(trendHistoryFilterParams({ ...DEFAULT_TREND_FILTERS, sameSite: false, sameGroup: false }, build, '2026-11-01T09:30:00+00:00')).toBe(
+ 'filtercount=3&showfilters=1&filtercombine=and'
+ + '&field1=buildname&compare1=61&value1=Linux%20gcc'
+ + '&field2=buildstarttime&compare2=83&value2=2026-11-01T09%3A29%3A59Z'
+ + '&field3=buildstarttime&compare3=84&value3=2026-11-18T10%3A00%3A01-05%3A00',
+ );
+ });
+
+ it('lists the build details which differ between data points', () => {
+ const point = { siteName: 'a', buildName: 'Linux', buildType: 'Nightly' };
+ expect(variedBuildFields([])).toEqual([]);
+ expect(variedBuildFields([point, { ...point }])).toEqual([]);
+ expect(variedBuildFields([point, { ...point, siteName: 'b', buildType: 'Continuous' }]).map((field) => field.key))
+ .toEqual(['siteName', 'buildType']);
+ });
+});