Skip to content

The easy-to-use open source Business Intelligence and Embedded Analytics tool that lets everyone work with data :bar_chart:

PoC: Performance tests e2e refinement (#73595)

Nemanja Glumacdf410d7c0edf
diff --git a/e2e/support/helpers/e2e-caching-helpers.ts b/e2e/support/helpers/e2e-caching-helpers.ts
new file mode 100644
index 00000000000..211e5753da8
--- /dev/null
+++ b/e2e/support/helpers/e2e-caching-helpers.ts
@@ -0,0 +1,7 @@
+export const cacheStrategySidesheet = () =>
+ cy.findByRole("dialog", { name: /Caching settings/ }).should("be.visible");
+
+export const durationRadioButton = () =>
+ cy
+ .findByRole("form", { name: "Select the cache invalidation policy" })
+ .findByRole("radio", { name: /Duration/ });
diff --git a/e2e/support/helpers/index.ts b/e2e/support/helpers/index.ts
index fb1a7a1cd77..dcea1ddab90 100644
--- a/e2e/support/helpers/index.ts
+++ b/e2e/support/helpers/index.ts
@@ -5,6 +5,7 @@ export * from "./e2e-api-key-helpers";
export * from "./e2e-bi-basics-helpers";
export * from "./e2e-boolean-helpers";
export * from "./e2e-browser-helpers";
+export * from "./e2e-caching-helpers";
export * from "./e2e-cloud-helpers";
export * from "./e2e-codemirror-helpers";
export * from "./e2e-collection-helpers";
diff --git a/e2e/test/scenarios/admin/database-routing/database-routing-admin.cy.spec.ts b/e2e/test/scenarios/admin/database-routing/database-routing-admin.cy.spec.ts
index 75ef4c71371..feb0352f728 100644
--- a/e2e/test/scenarios/admin/database-routing/database-routing-admin.cy.spec.ts
+++ b/e2e/test/scenarios/admin/database-routing/database-routing-admin.cy.spec.ts
@@ -8,8 +8,6 @@ import {
} from "e2e/support/cypress_data";
import type { DatabaseId } from "metabase-types/api";
-import { interceptPerformanceRoutes } from "../performance/helpers/e2e-performance-helpers";
-
import {
BASE_POSTGRES_DESTINATION_DB_INFO,
configureDbRoutingViaAPI,
@@ -652,7 +650,7 @@ function assertDbRoutingDisabled() {
}
function setupModelPersistence() {
- interceptPerformanceRoutes();
+ cy.intercept("POST", "/api/persist/enable").as("enablePersistence");
cy.visit("/admin/performance/models");
cy.findByTestId("admin-layout-content").findByLabelText("Disabled").click();
cy.wait("@enablePersistence");
diff --git a/e2e/test/scenarios/admin/database-routing/database-routing-usage.cy.spec.ts b/e2e/test/scenarios/admin/database-routing/database-routing-usage.cy.spec.ts
index 75fbc7e15f0..72b934bfafb 100644
--- a/e2e/test/scenarios/admin/database-routing/database-routing-usage.cy.spec.ts
+++ b/e2e/test/scenarios/admin/database-routing/database-routing-usage.cy.spec.ts
@@ -4,8 +4,6 @@ import _ from "underscore";
import { USER_GROUPS } from "e2e/support/cypress_data";
import { DataPermissionValue } from "metabase/admin/permissions/types";
-import { interceptPerformanceRoutes } from "../performance/helpers/e2e-performance-helpers";
-
import {
BASE_POSTGRES_DESTINATION_DB_INFO,
DB_ROUTER_USERS,
@@ -221,7 +219,6 @@ describe("admin > database > database routing", { tags: ["@external"] }, () => {
query: "SELECT name FROM db_identifier;",
},
}).then(({ body: { id: questionId } }) => {
- interceptPerformanceRoutes();
cy.request("PUT", "api/cache", {
model: "question",
model_id: questionId,
@@ -237,20 +234,16 @@ describe("admin > database > database routing", { tags: ["@external"] }, () => {
cy.log("User A");
signInAs(DB_ROUTER_USERS.userA);
H.visitQuestion(questionId);
- cy.get('[data-column-id="name"]').should("contain", "destination_one");
- cy.get('[data-column-id="name"]').should(
- "not.contain",
- "destination_two",
- );
+ cy.get('[data-column-id="name"]')
+ .should("contain", "destination_one")
+ .and("not.contain", "destination_two");
cy.log("User B");
signInAs(DB_ROUTER_USERS.userB);
H.visitQuestion(questionId);
- cy.get('[data-column-id="name"]').should("contain", "destination_two");
- cy.get('[data-column-id="name"]').should(
- "not.contain",
- "destination_one",
- );
+ cy.get('[data-column-id="name"]')
+ .should("contain", "destination_two")
+ .and("not.contain", "destination_one");
});
});
diff --git a/e2e/test/scenarios/admin/performance/caching.cy.spec.ts b/e2e/test/scenarios/admin/performance/caching.cy.spec.ts
new file mode 100644
index 00000000000..9b77164015f
--- /dev/null
+++ b/e2e/test/scenarios/admin/performance/caching.cy.spec.ts
@@ -0,0 +1,244 @@
+import {
+ ORDERS_COUNT_QUESTION_ID,
+ ORDERS_QUESTION_ID,
+} from "e2e/support/cypress_sample_instance_data";
+
+const { H } = cy;
+
+const adaptiveRadioButton = () =>
+ cy
+ .findByRole("form", { name: "Select the cache invalidation policy" })
+ .findByRole("radio", { name: /Adaptive/ });
+
+const preemptiveCachingSwitch = () =>
+ cy.findByTestId("preemptive-caching-switch");
+
+const saveCacheStrategyForm = () => {
+ cy.intercept("PUT", "/api/cache").as("putCacheConfig");
+ cy.findByRole("form", { name: "Select the cache invalidation policy" })
+ .button(/Save/)
+ .click();
+ cy.wait("@putCacheConfig");
+};
+
+const openSidebarCacheStrategyForm = (type: "question" | "dashboard") => {
+ cy.intercept("GET", "/api/cache?model=*&id=*").as("getCacheConfig");
+ if (type === "dashboard") {
+ H.openDashboardSettingsSidebar();
+ } else {
+ H.openQuestionActions("Edit settings");
+ }
+ cy.wait("@getCacheConfig");
+ cy.findByLabelText("When to get new results").click();
+ return H.cacheStrategySidesheet();
+};
+
+const cancelConfirmationModal = () =>
+ cy
+ .findByTestId("confirm-modal")
+ .should("be.visible")
+ .button("Cancel")
+ .click();
+
+/**
+ * Smoke tests for the caching feature.
+ *
+ * The bar for what lives here: the test must catch something neither
+ * backend tests nor Jest component tests can. That means real HTTP
+ * round-trips whose composition (frontend -> backend -> frontend) isn't
+ * verifiable at either layer alone, cross-page flows that exercise
+ * RTK-query cache invalidation across distinct UI surfaces, or
+ * real-browser UX (modal portal stacking, ESC handling, history listeners).
+ *
+ * Coverage that lives elsewhere — and what's deliberately NOT here:
+ *
+ * - Strategy resolution / inheritance ladder, TTL behavior, schedule
+ * invalidation timing, refresh task: backend tests in
+ * metabase.query-processor.middleware.cache-test,
+ * metabase-enterprise.cache.{strategies,cache,config,task.refresh-cache-configs}-test.
+ * - Cron transform and the Schedule UI -> cron mapping (28+ permutations),
+ * per-frequency conditional render, AM/PM 12-hour boundary,
+ * monthly-frame variants:
+ * frontend/.../Schedule/{cron,Schedule}.unit.spec.{ts,tsx}.
+ * - Strategy form input binding (typing into Min Duration / Multiplier),
+ * strategy-switch flows (Adaptive <-> Duration <-> No caching),
+ * strategy -> launcher-label mapping, policy-options counts,
+ * preemptive caching switch availability for root/database targets:
+ * frontend/.../StrategyEditorForDatabases.unit.spec.tsx and
+ * enterprise/.../caching/components/StrategyEditorForDatabases.unit.spec.tsx.
+ */
+describe("scenarios > admin > performance > caching", () => {
+ describe("oss", { tags: "@OSS" }, () => {
+ beforeEach(() => {
+ H.restore();
+ cy.signInAsAdmin();
+ });
+
+ it("saves the default-policy strategy and reflects the saved state", () => {
+ cy.visit("/admin/performance");
+ adaptiveRadioButton().click();
+ saveCacheStrategyForm();
+ adaptiveRadioButton().should("be.checked");
+ });
+ });
+
+ describe("ee", () => {
+ beforeEach(() => {
+ H.restore();
+ cy.signInAsAdmin();
+ H.activateToken("pro-self-hosted");
+ });
+
+ it("can configure a database cache strategy, save, and clear the cache", () => {
+ cy.visit("/admin/performance");
+ cy.findByTestId("admin-layout-content")
+ .findByLabelText(/Edit.*Sample Database.*currently.*No caching/)
+ .click();
+
+ cy.log("Clear-cache button is absent before the database has a cache");
+ cy.button(/Clear cache/).should("not.exist");
+
+ cy.log("Set Sample Database to Duration and save");
+ H.durationRadioButton().click();
+ saveCacheStrategyForm();
+ cy.findByTestId("admin-layout-content").findByLabelText(
+ /Edit.*Sample Database.*currently.*Duration/,
+ );
+
+ cy.intercept(
+ "POST",
+ "/api/cache/invalidate?include=overrides&database=*",
+ ).as("invalidateCacheForSampleDatabase");
+
+ cy.log("Clear-cache button is now visible — click it");
+ cy.button(/Clear cache for this database/).click();
+
+ cy.log("Confirm in the dialog");
+ cy.findByRole("dialog")
+ .button(/Clear cache/)
+ .click();
+ cy.wait("@invalidateCacheForSampleDatabase");
+
+ cy.button(/Cache cleared/).should("exist");
+ });
+
+ it("preemptive caching toggles persist across the question sidebar and the admin tab", () => {
+ cy.log("Enable preemptive caching from the question sidebar");
+ H.visitQuestion(ORDERS_QUESTION_ID);
+ openSidebarCacheStrategyForm("question");
+ H.durationRadioButton().click();
+ preemptiveCachingSwitch().within(() => {
+ cy.findByRole("switch").should("not.be.checked");
+ cy.findByRole("switch").parent("label").click();
+ cy.findByRole("switch").should("be.checked");
+ });
+ saveCacheStrategyForm();
+ cy.findByLabelText("When to get new results").click();
+ preemptiveCachingSwitch().findByRole("switch").should("be.checked");
+
+ cy.log(
+ "Toggle is reflected on the admin Dashboard and question caching tab",
+ );
+ cy.visit("/admin/performance/dashboards-and-questions");
+ cy.findByTestId("cache-config-table").contains("Duration: 24h").click();
+ preemptiveCachingSwitch().findByRole("switch").should("be.checked");
+
+ cy.log("Disable from the admin tab");
+ preemptiveCachingSwitch().within(() => {
+ cy.findByRole("switch").should("be.checked");
+ cy.findByRole("switch").parent("label").click();
+ cy.findByRole("switch").should("not.be.checked");
+ });
+ saveCacheStrategyForm();
+ preemptiveCachingSwitch().findByRole("switch").should("not.be.checked");
+
+ cy.log("Toggle is reflected back in the question sidebar");
+ H.visitQuestion(ORDERS_QUESTION_ID);
+ openSidebarCacheStrategyForm("question");
+ preemptiveCachingSwitch().findByRole("switch").should("not.be.checked");
+ });
+
+ /**
+ * The dirty-form modal guards four independent close paths, each backed
+ * by a different listener (Mantine close button, keyboard ESC handler,
+ * outside-click detector, react-router history listener). This test
+ * exercises all four against the question sidebar's cache strategy form.
+ */
+ it("guards closing a dirty cache form across all four close paths", () => {
+ cy.log("Populate browser history so cy.go('back') has somewhere to go");
+ cy.visit("/");
+ cy.findByTestId("main-navbar-root").findByText("Our analytics").click();
+ cy.findByTestId("collection-table").findByText("Orders").click();
+
+ openSidebarCacheStrategyForm("question");
+ H.cacheStrategySidesheet().within(() => {
+ cy.findByText(/Caching settings/).should("be.visible");
+ H.durationRadioButton().click();
+ });
+
+ cy.log("Action 1 — click the close (×) button");
+ H.cacheStrategySidesheet()
+ .findByRole("button", { name: /Close/ })
+ .click();
+ cancelConfirmationModal();
+
+ cy.log("Action 2 — press ESC");
+ cy.get("body").type("{esc}");
+ cancelConfirmationModal();
+
+ cy.log("Action 3 — click outside (modal overlay)");
+ cy.findAllByTestId("modal-overlay")
+ .should("have.length.gte", 1)
+ .last()
+ .click();
+ cancelConfirmationModal();
+
+ cy.log("Action 4 — browser back button");
+ cy.go("back");
+ cancelConfirmationModal();
+ });
+
+ /**
+ * When the admin tab has multiple cache-config rows, clicking each must
+ * open the form initialized from that row's config — not a stale shared
+ * state, not the first row regardless of which was clicked. The table
+ * itself + per-row click handlers + form initialization from RTK-query
+ * cache only line up correctly in the assembled app.
+ */
+ it("opens the right form when clicking distinct entries on the admin tab", () => {
+ cy.log("Configure Orders with Duration: 99h");
+ H.visitQuestion(ORDERS_QUESTION_ID);
+ openSidebarCacheStrategyForm("question");
+ H.durationRadioButton().click();
+ cy.findByLabelText(/Cache results for this many hours/).type("99");
+ saveCacheStrategyForm();
+
+ cy.log("Configure Orders, Count with Adaptive");
+ H.visitQuestion(ORDERS_COUNT_QUESTION_ID);
+ openSidebarCacheStrategyForm("question");
+ adaptiveRadioButton().click();
+ saveCacheStrategyForm();
+
+ cy.log("Both entries are visible on the admin tab");
+ cy.visit("/admin/performance/dashboards-and-questions");
+ cy.findByTestId("cache-config-table")
+ .should("contain", "Duration: 99h")
+ .and("contain", "Adaptive");
+
+ cy.log("Clicking Duration: 99h opens its form with duration selected");
+ cy.findByTestId("cache-config-table").contains("Duration: 99h").click();
+ H.durationRadioButton().should("be.checked");
+ cy.findByLabelText(/Cache results for this many hours/).should(
+ "have.value",
+ "99",
+ );
+
+ cy.log("Close the sidesheet via ESC");
+ cy.get("body").type("{esc}");
+
+ cy.log("Clicking Adaptive opens its form with adaptive selected");
+ cy.findByTestId("cache-config-table").contains("Adaptive").click();
+ adaptiveRadioButton().should("be.checked");
+ });
+ });
+});
diff --git a/e2e/test/scenarios/admin/performance/clock.cy.spec.ts b/e2e/test/scenarios/admin/performance/clock.cy.spec.ts
deleted file mode 100644
index 7de069990c8..00000000000
--- a/e2e/test/scenarios/admin/performance/clock.cy.spec.ts
+++ /dev/null
@@ -1,72 +0,0 @@
-import dayjs from "dayjs";
-import timezone from "dayjs/plugin/timezone";
-
-const { H } = cy;
-dayjs.extend(timezone);
-
-import {
- freezeServerTime,
- resetServerTime,
-} from "./helpers/e2e-performance-helpers";
-
-/** Some caching tests need to be able to advance the server clock manually.
- * There's an endpoint that supports this: /api/testing/set-time.
- * These tests guarantee that this endpoint works as expected. */
-describe("server clock", () => {
- beforeEach(() => {
- H.restore();
- resetServerTime();
- cy.signInAsAdmin();
- });
-
- it("can advance the server clock by one day", () => {
- cy.request("GET", "/api/setting/report-timezone-long").then((response) => {
- cy.wrap(response.body).as("serverTimeZone");
- });
-
- cy.then(function () {
- const oneDayInMilliseconds = 86400000;
-
- const utcFormatter = new Intl.DateTimeFormat("en-US", {
- timeZone: "UTC",
- hour: "2-digit",
- minute: "2-digit",
- second: "2-digit",
- year: "numeric",
- month: "2-digit",
- day: "2-digit",
- });
- const nowInUTC = utcFormatter.format(Date.now());
-
- const tomorrowInUTC: string = dayjs(nowInUTC)
- .add(1, "day")
- .format("YYYY-MM-DD");
-
- freezeServerTime({
- addMilliseconds: oneDayInMilliseconds,
- wrapServerTimeAs: "serverTimeInUTC",
- });
-
- cy.then(function () {
- const serverDate = this.serverTimeInUTC.split("T")[0];
- expect(serverDate).to.eq(tomorrowInUTC);
- });
- });
- });
-
- it("server clock remains stopped once manually set", () => {
- const oneDayInMilliseconds = 86400000;
- freezeServerTime({
- addMilliseconds: oneDayInMilliseconds,
- wrapServerTimeAs: "previousServerTime",
- });
- cy.wait(500);
- freezeServerTime({ addMilliseconds: 0, wrapServerTimeAs: "newServerTime" });
- cy.then(function () {
- expect(
- this.newServerTime,
- "Even though 500ms of real time have elapsed, the server's clock is the same as before",
- ).to.eq(this.previousServerTime);
- });
- });
-});
diff --git a/e2e/test/scenarios/admin/performance/dashboardsAndQuestions.cy.spec.ts b/e2e/test/scenarios/admin/performance/dashboardsAndQuestions.cy.spec.ts
deleted file mode 100644
index 1a70d56dd88..00000000000
--- a/e2e/test/scenarios/admin/performance/dashboardsAndQuestions.cy.spec.ts
+++ /dev/null
@@ -1,296 +0,0 @@
-const { H } = cy;
-
-import {
- TEST_TABLE,
- instanceDefault,
- sampleAdaptiveStrategy,
- sampleDashboard,
- sampleDatabase,
- sampleDurationStrategy,
- sampleQuestion,
-} from "./helpers/constants";
-import {
- advanceServerClockBy,
- getExpectedCacheDuration,
- interceptPerformanceRoutes,
- resetServerTime,
- setupDashboardTest,
- setupQuestionTest,
-} from "./helpers/e2e-performance-helpers";
-import {
- cacheStrategyForm,
- disableCaching,
- selectCacheStrategy,
-} from "./helpers/e2e-strategy-form-helpers";
-import type { CacheTestParameters } from "./helpers/types";
-
-const itFunction = it;
-
-const testCacheStrategy = ({
- strategy,
- item,
- inheritsStrategyFrom,
- description,
- it = itFunction,
- oss = false,
-}: CacheTestParameters) => {
- it(description, () => {
- const { visitItem } =
- item.model === "question"
- ? setupQuestionTest(sampleQuestion)
- : setupDashboardTest(sampleDashboard, sampleQuestion);
-
- const itemToConfigure = inheritsStrategyFrom ?? item;
-
- cy.then(function () {
- selectCacheStrategy({
- item: itemToConfigure,
- strategy,
- oss,
- });
- });
-
- const expectedCacheDuration = getExpectedCacheDuration(strategy);
- H.queryWritableDB(`UPDATE ${TEST_TABLE} SET my_text='Old Value';`);
-
- // first visit causes us to cache it
- visitItem();
- cy.findByTestId("visualization-root").findByText("Old Value");
-
- // value changes in the DB
- H.queryWritableDB(`UPDATE ${TEST_TABLE} SET my_text='New Value';`);
-
- // check that old value is still cached
- advanceServerClockBy(expectedCacheDuration - 1000);
- visitItem();
- cy.findByTestId("visualization-root").findByText("Old Value");
-
- // check that the cache expires when expected
- advanceServerClockBy(2000);
- visitItem();
- cy.findByTestId("visualization-root").findByText("New Value");
- });
-};
-
-const testDoNotCachePolicy = ({
- description,
- item,
- inheritsStrategyFrom,
- it = itFunction,
-}: CacheTestParameters) => {
- it(description, () => {
- const { visitItem } =
- item.model === "question"
- ? setupQuestionTest(sampleQuestion)
- : setupDashboardTest(sampleDashboard, sampleQuestion);
- visitItem();
-
- // Don't try to disable caching on the root since it's disabled by default
- const shouldDisableCaching = inheritsStrategyFrom?.model !== "root";
- if (shouldDisableCaching) {
- cy.then(function () {
- disableCaching({ item: inheritsStrategyFrom ?? item });
- visitItem();
- });
- }
-
- H.queryWritableDB(`UPDATE ${TEST_TABLE} SET my_text='Value 2';`).then(
- () => {
- visitItem();
- cy.findByTestId("visualization-root").findByText("Value 2");
- H.queryWritableDB(`UPDATE ${TEST_TABLE} SET my_text='Value 3';`).then(
- () => {
- visitItem();
- cy.findByTestId("visualization-root").findByText("Value 3");
- },
- );
- },
- );
- });
-};
-
-/**
- * These tests check that dashboards and questions can use different cache invalidation strategies.
- *
- * Each test applies a certain cache invalidation strategy to a certain item - a question or
- * dashboard. The strategy is either applied directly, or the item is made to inherit the
- * strategy, either from the underlying database or from the global default policy.
- *
- * Since all the tests are similar, we can think of this as the same test
- * run repeatedly with different parameters. */
-describe(
- "Cache invalidation for dashboards and questions",
- { tags: "@external" },
- () => {
- describe("ee", () => {
- beforeEach(() => {
- resetServerTime();
- interceptPerformanceRoutes();
- H.restore("postgres-writable");
- H.resetTestTable({ type: "postgres", table: TEST_TABLE });
- cy.signInAsAdmin();
- H.activateToken("pro-self-hosted");
- });
-
- describe("adaptive and duration strategies", () => {
- /** Each item in this array contains parameters for a test.
- *
- * You can add "it: it.only" or "it: it.skip" to any of the objects below
- * to control which tests run
- */
- (
- [
- {
- description: "questions can use adaptive strategy",
- strategy: sampleAdaptiveStrategy,
- item: sampleQuestion,
- },
- {
- description:
- "questions can inherit adaptive strategy from database",
- strategy: sampleAdaptiveStrategy,
- item: sampleQuestion,
- inheritsStrategyFrom: sampleDatabase,
- },
- {
- description:
- "questions can inherit adaptive strategy from instance-wide default policy",
- strategy: sampleAdaptiveStrategy,
- item: sampleQuestion,
- inheritsStrategyFrom: instanceDefault,
- },
- {
- description: "questions can use duration strategy",
- strategy: sampleDurationStrategy,
- item: sampleQuestion,
- },
- {
- description:
- "questions can inherit duration strategy from database",
- strategy: sampleDurationStrategy,
- item: sampleQuestion,
- inheritsStrategyFrom: sampleDatabase,
- },
- {
- description:
- "questions can inherit duration strategy from instance-wide default policy",
- strategy: sampleDurationStrategy,
- item: sampleQuestion,
- inheritsStrategyFrom: instanceDefault,
- },
- {
- description: "dashboards can use adaptive strategy",
- strategy: sampleAdaptiveStrategy,
- item: sampleDashboard,
- },
- {
- description:
- "dashboards can inherit adaptive strategy from database",
- strategy: sampleAdaptiveStrategy,
- item: sampleDashboard,
- inheritsStrategyFrom: sampleDatabase,
- },
- {
- description:
- "dashboards can inherit adaptive strategy from instance-wide default policy",
- strategy: sampleAdaptiveStrategy,
- item: sampleDashboard,
- inheritsStrategyFrom: instanceDefault,
- },
- {
- description: "dashboards can use duration strategy",
- strategy: sampleDurationStrategy,
- item: sampleDashboard,
- },
- {
- description:
- "dashboards can inherit duration strategy from database",
- strategy: sampleDurationStrategy,
- item: sampleDashboard,
- inheritsStrategyFrom: sampleDatabase,
- },
- {
- description:
- "dashboards can inherit duration strategy from instance-wide default policy",
- strategy: sampleDurationStrategy,
- item: sampleDashboard,
- inheritsStrategyFrom: instanceDefault,
- },
- ] as CacheTestParameters[]
- ).forEach(testCacheStrategy);
- });
-
- describe("no-caching policy", () => {
- (
- [
- {
- description: "questions can use no-caching policy",
- item: sampleQuestion,
- },
- {
- description:
- "questions can inherit no-caching policy from database",
- item: sampleQuestion,
- inheritsStrategyFrom: sampleDatabase,
- },
- {
- description:
- "questions can inherit no-caching policy from instance-wide default policy",
- item: sampleQuestion,
- inheritsStrategyFrom: instanceDefault,
- },
- {
- description: "dashboards can use no-caching policy",
- item: sampleDashboard,
- },
- {
- description:
- "dashboards can inherit no-caching policy from database",
- item: sampleDashboard,
- inheritsStrategyFrom: sampleDatabase,
- },
- {
- description:
- "dashboards can inherit no-caching policy from instance-wide default policy",
- item: sampleDashboard,
- inheritsStrategyFrom: instanceDefault,
- },
- ] as CacheTestParameters[]
- ).forEach(testDoNotCachePolicy);
- });
- });
-
- describe("oss", { tags: "@OSS" }, () => {
- beforeEach(() => {
- resetServerTime();
- interceptPerformanceRoutes();
- H.restore("postgres-writable");
- H.resetTestTable({ type: "postgres", table: TEST_TABLE });
- cy.signInAsAdmin();
- cy.visit("/admin/performance");
- cacheStrategyForm();
- });
-
- (
- [
- {
- description:
- "questions can inherit adaptive strategy from instance-wide default policy",
- strategy: sampleAdaptiveStrategy,
- item: sampleQuestion,
- inheritsStrategyFrom: instanceDefault,
- oss: true,
- },
- {
- description:
- "dashboards can inherit adaptive strategy from instance-wide default policy",
- strategy: sampleAdaptiveStrategy,
- item: sampleDashboard,
- inheritsStrategyFrom: instanceDefault,
- oss: true,
- },
- ] as CacheTestParameters[]
- ).forEach(testCacheStrategy);
- });
- },
-);
diff --git a/e2e/test/scenarios/admin/performance/helpers/constants.ts b/e2e/test/scenarios/admin/performance/helpers/constants.ts
deleted file mode 100644
index e05e0b04dbc..00000000000
--- a/e2e/test/scenarios/admin/performance/helpers/constants.ts
+++ /dev/null
@@ -1,60 +0,0 @@
-import { WRITABLE_DB_ID } from "e2e/support/cypress_data";
-import type { NativeQuestionDetails } from "e2e/support/helpers";
-import {
- type AdaptiveStrategy,
- CacheDurationUnit,
- type DoNotCacheStrategy,
- type DurationStrategy,
- type ScheduleStrategy,
-} from "metabase-types/api";
-
-import type { StrategyBearer } from "./types";
-
-export const TEST_TABLE = "cached_table";
-
-export const sampleAdaptiveStrategy: AdaptiveStrategy = {
- type: "ttl",
- multiplier: 5,
- min_duration_ms: 0,
-};
-export const sampleDurationStrategy: DurationStrategy = {
- type: "duration",
- duration: 48,
- unit: CacheDurationUnit.Hours,
- refresh_automatically: false,
-};
-export const sampleScheduleStrategy: ScheduleStrategy = {
- type: "schedule",
- schedule: "0 0 * * * ?", // Invalidate hourly at the start of the hour
- refresh_automatically: false,
-};
-export const sampleDoNotCacheStrategy: DoNotCacheStrategy = { type: "nocache" };
-
-/** In milliseconds */
-export const questionRuntime = 1000;
-
-export const sampleQuestion: StrategyBearer & {
- name: string;
-} & NativeQuestionDetails = {
- model: "question",
- name: "Slow question",
- database: WRITABLE_DB_ID,
- native: {
- query: `SELECT * FROM ${TEST_TABLE}, pg_sleep(${questionRuntime / 1000})`,
- },
-};
-
-export const sampleDashboard: StrategyBearer & { name: string } = {
- model: "dashboard",
- name: "Dashboard with a slow question",
-};
-
-export const sampleDatabase: StrategyBearer = {
- model: "database",
- name: "Writable Postgres12",
-};
-
-export const instanceDefault: StrategyBearer = {
- model: "root",
- name: "Default policy",
-};
diff --git a/e2e/test/scenarios/admin/performance/helpers/e2e-performance-helpers.ts b/e2e/test/scenarios/admin/performance/helpers/e2e-performance-helpers.ts
deleted file mode 100644
index 658d83db7e0..00000000000
--- a/e2e/test/scenarios/admin/performance/helpers/e2e-performance-helpers.ts
+++ /dev/null
@@ -1,185 +0,0 @@
-import { WRITABLE_DB_ID } from "e2e/support/cypress_data";
-import type { NativeQuestionDetails } from "e2e/support/helpers";
-import {
- createNativeQuestion,
- createNativeQuestionAndDashboard,
- modal,
- visitDashboard,
- visitQuestion,
-} from "e2e/support/helpers";
-import type { CacheStrategy } from "metabase-types/api";
-
-import { questionRuntime } from "./constants";
-import type { DashboardDetails } from "./types";
-
-/** Intercept routes for caching tests */
-export const interceptPerformanceRoutes = () => {
- cy.intercept("POST", "/api/dataset").as("dataset");
- cy.intercept("POST", "/api/card/*/query").as("cardQuery");
- cy.intercept("PUT", "/api/cache").as("putCacheConfig");
- cy.intercept("DELETE", "/api/cache").as("deleteCacheConfig");
- cy.intercept("GET", "/api/cache?model=*&id=*").as("getCacheConfig");
- cy.intercept("POST", "/api/dashboard/*/dashcard/*/card/*/query").as(
- "dashcardQuery",
- );
- cy.intercept("POST", "/api/persist/enable").as("enablePersistence");
- cy.intercept("POST", "/api/persist/disable").as("disablePersistence");
- cy.intercept("POST", "/api/cache/invalidate?include=overrides&database=*").as(
- "invalidateCacheForSampleDatabase",
- );
- cy.intercept("POST", "/api/cache/invalidate?*").as("invalidateCache");
-};
-
-/** Cypress log messages sometimes occur out of order so it is helpful to log to the console as well. */
-export const log = (message: string) => {
- cy.log(message);
- console.log(message);
-};
-
-export const goToPerformancePage = (
- name:
- | "Database caching"
- | "Dashboard and question caching"
- | "Model persistence",
-) => {
- cy.findByTestId("admin-layout-sidebar").findByText(name).click();
-};
-
-export const setupQuestionTest = (
- nativeQuestionDetails: NativeQuestionDetails,
-) => {
- log(`Create a question that takes ${questionRuntime} milliseconds to run`);
- createNativeQuestion(nativeQuestionDetails, {
- visitQuestion: true,
- wrapId: true,
- });
- const visitItem = () =>
- cy.then(function () {
- log("Visiting the question");
- visitQuestion("@questionId");
- });
- return { visitItem };
-};
-
-export const setupDashboardTest = (
- dashboardDetails: DashboardDetails,
- questionDetails: NativeQuestionDetails,
-) => {
- createNativeQuestionInDashboard({
- questionDetails,
- dashboardDetails,
- visitDashboard: true,
- });
-
- const waitForQuery = () => cy.wait("@dashcardQuery");
- const visitItem = () =>
- cy.then(function () {
- visitDashboard(this.dashboardId);
- });
- return { visitItem, waitForQuery };
-};
-
-export const saveQuestion = ({ withName }: { withName: string }) => {
- log("Save the question");
- cy.intercept("POST", "/api/card").as("saveQuestion");
- cy.findByTestId("qb-header").button(/^Save/).click();
- cy.findByLabelText("Name").type(withName);
- modal().button("Save").click();
-
- cy.wait("@saveQuestion");
-};
-
-export const getDetailsForQuestionWithFixedRuntime = ({
- runtime,
-}: {
- /** Runtime in milliseconds */
- runtime: number;
-}) => ({
- name: "Question with fixed runtime",
- database: WRITABLE_DB_ID,
- native: {
- query: `select (MD5(random()::text)), pg_sleep(${runtime / 1000})`,
- },
-});
-
-export const createNativeQuestionInDashboard = ({
- questionDetails,
- dashboardDetails,
- visitDashboard: shouldVisitDashboard = true,
-}: {
- questionDetails: NativeQuestionDetails;
- dashboardDetails: DashboardDetails;
- visitDashboard: boolean;
-}) =>
- createNativeQuestionAndDashboard({
- questionDetails,
- dashboardDetails,
- }).then(({ body }) => {
- const { dashboard_id } = body;
- cy.wrap(dashboard_id).as("dashboardId");
- if (shouldVisitDashboard) {
- visitDashboard(dashboard_id);
- }
- });
-
-/** Sets the server clock, which then stops advancing automatically */
-export const freezeServerTime = ({
- addMilliseconds,
- time,
- wrapServerTimeAs,
-}: {
- addMilliseconds?: number;
- time?: string;
- wrapServerTimeAs?: string;
-}) =>
- cy
- .request("POST", "/api/testing/set-time", {
- "add-ms": addMilliseconds,
- time,
- })
- .then((response) => {
- if (wrapServerTimeAs) {
- cy.wrap(response.body.time).as(wrapServerTimeAs);
- }
- });
-
-export const resetServerTime = () => freezeServerTime({});
-
-/** Get the number of milliseconds until the moment when the cache should
- * expire */
-export const getExpectedCacheDuration = (strategy: CacheStrategy) => {
- if (strategy.type === "ttl") {
- return strategy.multiplier * questionRuntime;
- }
-
- if (strategy.type === "duration") {
- return strategy.duration * 60 * 60 * 1000;
- }
-
- if (strategy.type === "schedule") {
- return millisecondsUntilEndOfHour();
- }
-
- throw new Error(`Unsupported strategy type: ${strategy.type}`);
-};
-
-export const millisecondsUntilEndOfHour = () => {
- const now = new Date();
- const nextHour = new Date(
- now.getFullYear(),
- now.getMonth(),
- now.getDate(),
- now.getHours() + 1,
- 0,
- 0,
- 0,
- );
- return nextHour.getTime() - now.getTime();
-};
-
-export const advanceServerClockBy = (milliseconds: number) => {
- log(`Advancing clock by ${milliseconds}ms`);
- return cy.request("POST", "/api/testing/set-time", {
- "add-ms": milliseconds,
- });
-};
diff --git a/e2e/test/scenarios/admin/performance/helpers/e2e-strategy-form-helpers.ts b/e2e/test/scenarios/admin/performance/helpers/e2e-strategy-form-helpers.ts
deleted file mode 100644
index 6c460c22c3a..00000000000
--- a/e2e/test/scenarios/admin/performance/helpers/e2e-strategy-form-helpers.ts
+++ /dev/null
@@ -1,235 +0,0 @@
-import { match } from "ts-pattern";
-
-import { popover } from "e2e/support/helpers";
-import {
- type ScheduleComponentType,
- getScheduleComponentLabel,
-} from "metabase/common/components/Schedule/strings";
-import type {
- CacheStrategyType,
- CacheableModel,
- DoNotCacheStrategy,
- InheritStrategy,
-} from "metabase-types/api";
-
-import { log } from "./e2e-performance-helpers";
-import type { SelectCacheStrategyOptions, StrategyBearer } from "./types";
-
-/** Save the cache strategy form and wait for a response from the relevant endpoint */
-export const saveCacheStrategyForm = (options?: {
- strategyType?: CacheStrategyType;
- /** 'Model' as in 'type of object' */
- model?: CacheableModel;
-}) => {
- let expectedRoute: string;
- if (options?.strategyType === "nocache" && options?.model === "root") {
- // When setting the default policy to "Don't cache", we delete the policy in the BE
- expectedRoute = "@deleteCacheConfig";
- } else if (options?.strategyType === "inherit") {
- // When setting a database's policy to "Use default", we delete the policy in the BE
- expectedRoute = "@deleteCacheConfig";
- } else {
- // Otherwise we update the cache config
- expectedRoute = "@putCacheConfig";
- }
- cy.log("Save the cache strategy form");
- cacheStrategyForm().button(/Save/).click();
- return cy.wait(expectedRoute);
-};
-
-export const cacheStrategyForm = () =>
- cy.findByRole("form", { name: "Select the cache invalidation policy" });
-
-export const cacheStrategyRadioButton = (name: RegExp) =>
- cacheStrategyForm().findByRole("radio", { name });
-
-export const durationRadioButton = () => cacheStrategyRadioButton(/Duration/);
-export const adaptiveRadioButton = () => cacheStrategyRadioButton(/Adaptive/);
-export const scheduleRadioButton = () => cacheStrategyRadioButton(/Schedule/);
-export const dontCacheResultsRadioButton = () =>
- cacheStrategyRadioButton(/Don.t cache results/);
-export const useDefaultRadioButton = () =>
- cacheStrategyRadioButton(/Use default/);
-
-export const preemptiveCachingSwitch = () =>
- cy.findByTestId("preemptive-caching-switch");
-export const enablePreemptiveCaching = () =>
- preemptiveCachingSwitch().within(() => {
- cy.findByRole("switch").should("not.be.checked");
- cy.findByRole("switch").parent("label").click();
- cy.findByRole("switch").should("be.checked");
- });
-export const disablePreemptiveCaching = () =>
- preemptiveCachingSwitch().within(() => {
- cy.findByRole("switch").should("be.checked");
- cy.findByRole("switch").parent("label").click();
- cy.findByRole("switch").should("not.be.checked");
- });
-export const checkPreemptiveCachingEnabled = () =>
- preemptiveCachingSwitch().within(() => {
- cy.findByRole("switch").should("be.checked");
- });
-export const checkPreemptiveCachingDisabled = () =>
- preemptiveCachingSwitch().within(() => {
- cy.findByRole("switch").should("not.be.checked");
- });
-
-export const formLauncher = (
- itemName: string,
- preface:
- | "currently"
- | "currently inheriting"
- | "currently inheriting the default policy",
- strategyLabel = "",
-) => {
- const regExp = new RegExp(`Edit.*${itemName}.*${preface}.*${strategyLabel}`);
- cy.log(`Finding strategy for launcher for regular expression: ${regExp}`);
- const launcher = () =>
- cy.findByTestId("admin-layout-content").findByLabelText(regExp);
- launcher().should("exist");
- return launcher();
-};
-
-/** Opens the strategy form on 'Database caching' tab */
-export const openStrategyFormForDatabaseOrDefaultPolicy = (
- /** To open the form for the default policy, set this parameter to "default policy" */
- databaseNameOrDefaultPolicy: string,
- currentStrategyLabel?: string,
-) => {
- cy.visit("/admin/performance");
- cy.log(`Open strategy form for ${databaseNameOrDefaultPolicy}`);
- formLauncher(
- databaseNameOrDefaultPolicy,
- "currently",
- currentStrategyLabel,
- ).click();
-};
-
-export const getScheduleComponent = (componentType: ScheduleComponentType) =>
- cacheStrategyForm().findByLabelText(getScheduleComponentLabel(componentType));
-
-export const openSidebar = (type: "question" | "dashboard") => {
- if (type === "dashboard") {
- cy.findByTestId("dashboard-header").icon("ellipsis").click();
- }
-
- if (type === "question") {
- cy.findByTestId("qb-header").icon("ellipsis").click();
- }
- popover().findByText("Edit settings").click();
-};
-
-export const closeSidebar = () => {
- cy.findByLabelText("Close").click();
-};
-
-/** Open the sidebar form that lets you set the caching strategy.
- * This works on dashboards and questions */
-export const openSidebarCacheStrategyForm = (
- type: "question" | "dashboard",
-) => {
- cy.log("Open the cache strategy form in the sidebar");
- openSidebar(type);
- cy.wait("@getCacheConfig");
- cy.findByLabelText("When to get new results").click();
- return cacheStrategySidesheet();
-};
-
-export const cacheStrategySidesheet = () =>
- cy.findByRole("dialog", { name: /Caching settings/ }).should("be.visible");
-
-export const questionSettingsSidesheet = () =>
- cy.findByRole("dialog", { name: /Question settings/ }).should("be.visible");
-
-export const getRadioButtonForStrategyType = (
- strategyType: CacheStrategyType,
-) =>
- match(strategyType)
- .with("duration", () => durationRadioButton())
- .with("ttl", () => adaptiveRadioButton())
- .with("schedule", () => scheduleRadioButton())
- .with("inherit", () => useDefaultRadioButton())
- .with("nocache", () => dontCacheResultsRadioButton())
- .exhaustive();
-
-/** Select a cache invalidation strategy for an item.
- * The item can be a question, dashboard, database,
- * or the instance-wide default policy (the "root"). */
-export const selectCacheStrategy = ({
- item,
- strategy,
- oss = false,
-}: SelectCacheStrategyOptions) => {
- log(`Selecting ${strategy.type} strategy for ${item.model}`);
-
- // On OSS, you can only set the root policy, so there's no need to open a
- // specific strategy form
- if (oss) {
- cy.visit("/admin/performance");
- cacheStrategyForm();
- } else {
- openStrategyFormFor(item);
- }
-
- getRadioButtonForStrategyType(strategy.type).click();
-
- if ("multiplier" in strategy && strategy.multiplier) {
- cy.findByLabelText(/Multiplier/).type(`${strategy.multiplier}`);
- }
-
- if ("min_duration_ms" in strategy && strategy.min_duration_ms) {
- cy.findByLabelText(/Minimum query duration/).type(
- `${strategy.min_duration_ms / 1000}`,
- );
- }
-
- if ("duration" in strategy && strategy.duration) {
- cy.findByLabelText("Cache results for this many hours").type(
- `${strategy.duration}`,
- );
- }
-
- if ("schedule" in strategy && strategy.schedule) {
- if (strategy.schedule !== "0 0 * * * ?") {
- throw new Error(
- `The schedule ${strategy.schedule} is not supported in this test. Only an hourly schedule ("0 0 * * * ?") is supported`,
- );
- }
- }
-
- saveCacheStrategyForm({ strategyType: strategy.type, model: item?.model });
-};
-
-export const disableCaching = (
- options: Omit<SelectCacheStrategyOptions<DoNotCacheStrategy>, "strategy">,
-) =>
- selectCacheStrategy({
- ...options,
- strategy: { type: "nocache" },
- });
-
-/** Set the cache invalidation strategy to 'Use default' */
-export const useDefaultCacheStrategy = (
- options: Omit<SelectCacheStrategyOptions<InheritStrategy>, "strategy">,
-) =>
- selectCacheStrategy({
- ...options,
- strategy: { type: "inherit" },
- });
-
-const openStrategyFormFor = (item: StrategyBearer) => {
- return match(item)
- .with({ model: "database" }, ({ name }) => {
- openStrategyFormForDatabaseOrDefaultPolicy(name);
- })
- .with({ model: "root" }, () => {
- openStrategyFormForDatabaseOrDefaultPolicy("default policy");
- })
- .with({ model: "question" }, () => {
- openSidebarCacheStrategyForm("question");
- })
- .with({ model: "dashboard" }, () => {
- openSidebarCacheStrategyForm("dashboard");
- })
- .exhaustive();
-};
diff --git a/e2e/test/scenarios/admin/performance/helpers/modals-helpers.ts b/e2e/test/scenarios/admin/performance/helpers/modals-helpers.ts
deleted file mode 100644
index dc108eead5c..00000000000
--- a/e2e/test/scenarios/admin/performance/helpers/modals-helpers.ts
+++ /dev/null
@@ -1,7 +0,0 @@
-export const confirmModal = () =>
- cy.findByTestId("confirm-modal").should("be.visible");
-
-export const cancelConfirmationModal = () =>
- confirmModal()
- .findByRole("button", { name: /Cancel/ })
- .click();
diff --git a/e2e/test/scenarios/admin/performance/helpers/types.ts b/e2e/test/scenarios/admin/performance/helpers/types.ts
deleted file mode 100644
index 83d65831538..00000000000
--- a/e2e/test/scenarios/admin/performance/helpers/types.ts
+++ /dev/null
@@ -1,31 +0,0 @@
-import type { CacheStrategy, CacheableModel } from "metabase-types/api";
-
-export type CacheTestParameters = {
- description: string;
- strategy: CacheStrategy;
- /** Item whose cache we are testing */
- item: StrategyBearer;
- inheritsStrategyFrom?: StrategyBearer;
- /** Function that runs the test. Set to it, it.only, or it.skip */
- it?: Mocha.TestFunction;
- /** Whether the test is being run in OSS */
- oss?: boolean;
-};
-
-/** Something with a configurable cache strategy */
-export type StrategyBearer = {
- model: CacheableModel;
- name: string;
-};
-
-export type SelectCacheStrategyOptions<Strategy = CacheStrategy> = {
- /** The item to be configured */
- item: StrategyBearer;
- strategy: Strategy;
- /** Whether the test is being run in OSS */
- oss?: boolean;
-};
-
-export type DashboardDetails = {
- name: string;
-};
diff --git a/e2e/test/scenarios/admin/performance/preemptiveCaching.cy.spec.ts b/e2e/test/scenarios/admin/performance/preemptiveCaching.cy.spec.ts
deleted file mode 100644
index b70ee2e9c38..00000000000
--- a/e2e/test/scenarios/admin/performance/preemptiveCaching.cy.spec.ts
+++ /dev/null
@@ -1,129 +0,0 @@
-const { H } = cy;
-
-import { WRITABLE_DB_ID } from "e2e/support/cypress_data";
-
-import {
- advanceServerClockBy,
- interceptPerformanceRoutes,
- resetServerTime,
-} from "./helpers/e2e-performance-helpers";
-import {
- durationRadioButton,
- enablePreemptiveCaching,
- openSidebarCacheStrategyForm,
- saveCacheStrategyForm,
-} from "./helpers/e2e-strategy-form-helpers";
-
-const CACHE_DURATION_MS = 24 * 60 * 60 * 1000;
-
-const WRITABLE_TEST_TABLE = "scoreboard_actions";
-
-describe(
- "Preemptive caching for MBQL and native queries",
- { tags: "@external" },
- () => {
- describe("ee", () => {
- beforeEach(() => {
- resetServerTime();
- interceptPerformanceRoutes();
- H.restore("postgres-writable");
- cy.signInAsAdmin();
- H.activateToken("pro-self-hosted");
-
- H.resetTestTable({ type: "postgres", table: WRITABLE_TEST_TABLE });
- H.resyncDatabase({
- dbId: WRITABLE_DB_ID,
- tableName: WRITABLE_TEST_TABLE,
- });
- });
-
- after(() => {
- resetServerTime();
- });
-
- function runPreemptiveCachingTest(questionId: string) {
- function visitCachedQuestion(questionId: string) {
- cy.log("Visiting the question");
- H.visitQuestion(questionId);
- }
-
- visitCachedQuestion(questionId);
- cy.findByTestId("visualization-root").findByText("Amorous Aardvarks");
- openSidebarCacheStrategyForm("question");
- cy.findByLabelText(/Use default/).click();
- durationRadioButton().click();
- enablePreemptiveCaching();
- saveCacheStrategyForm({
- strategyType: "duration",
- model: "question",
- });
-
- // Refreshing the question causes us to cache it
- visitCachedQuestion(questionId);
- cy.findByTestId("visualization-root").findByText("Amorous Aardvarks");
-
- // Value changes in the DB
- H.queryWritableDB(
- `UPDATE ${WRITABLE_TEST_TABLE} SET team_name = 'New Value' where id = 1;`,
- );
-
- // Check that old value is still cached
- visitCachedQuestion(questionId);
- cy.findByTestId("visualization-root").findByText("Amorous Aardvarks");
-
- // Advance server clock more, and then trigger automatic cache refresh
- advanceServerClockBy(CACHE_DURATION_MS + 5000);
- cy.log("Triggering cache refresh task");
- cy.request("POST", "/api/testing/refresh-caches");
-
- // Wait to ensure we're fetching the refreshed cache
- cy.wait(500);
-
- visitCachedQuestion(questionId);
- cy.findByTestId("visualization-root").findByText("New Value");
- }
-
- it("Returns matching results when an MBQL query is cached preemptively", () => {
- H.getTableId({
- databaseId: WRITABLE_DB_ID,
- name: WRITABLE_TEST_TABLE,
- }).then((tableId) => {
- H.createQuestion(
- {
- name: "Cached question",
- database: WRITABLE_DB_ID,
- query: {
- "source-table": tableId,
- },
- type: "question",
- },
- {
- wrapId: true,
- idAlias: "mbqlQuestionId",
- },
- );
- });
-
- runPreemptiveCachingTest("@mbqlQuestionId");
- });
-
- it("Returns matching results when a native query is cached preemptively", () => {
- H.createNativeQuestion(
- {
- name: "Cached question",
- database: WRITABLE_DB_ID,
- native: {
- query: `SELECT * FROM ${WRITABLE_TEST_TABLE};`,
- },
- },
- {
- wrapId: true,
- idAlias: "nativeQuestionId",
- },
- );
-
- runPreemptiveCachingTest("@nativeQuestionId");
- });
- });
- },
-);
diff --git a/e2e/test/scenarios/admin/performance/schedule.cy.spec.ts b/e2e/test/scenarios/admin/performance/schedule.cy.spec.ts
deleted file mode 100644
index 53ac61948d4..00000000000
--- a/e2e/test/scenarios/admin/performance/schedule.cy.spec.ts
+++ /dev/null
@@ -1,159 +0,0 @@
-import type { ScheduleComponentType } from "metabase/common/components/Schedule/strings";
-import { checkNotNull } from "metabase/utils/types";
-import type { CacheableModel } from "metabase-types/api";
-
-import { interceptPerformanceRoutes } from "./helpers/e2e-performance-helpers";
-import {
- cacheStrategyForm,
- getScheduleComponent,
- openStrategyFormForDatabaseOrDefaultPolicy,
- saveCacheStrategyForm,
- scheduleRadioButton,
-} from "./helpers/e2e-strategy-form-helpers";
-
-const { H } = cy;
-
-/** These tests check that the schedule strategy form fields (in Admin /
- * Performance) send the correct cron expressions to the API. They do not check
- * that configuring the schedule strategy causes the cache to be invalidated at
- * the appointed time. Nor do they check that the cron expression retrieved
- * from the API is displayed in the UI. */
-describe("scenarios > admin > performance > schedule strategy", () => {
- beforeEach(() => {
- H.restore();
- interceptPerformanceRoutes();
- cy.signInAsAdmin();
- H.activateToken("pro-self-hosted");
- });
-
- /** An object describing the values to enter in the schedule strategy configuration form. */
- type FormValues = Partial<Record<ScheduleComponentType, string>>;
-
- type ScheduleTestOptions = [
- FormValues,
- /** The cron expression we expect to be sent to the API. */
- string,
- ];
-
- // prettier-ignore
- const schedules: ScheduleTestOptions[] = [
- [ {}, "0 0 * * * ? *" ], // The default schedule is 'every hour, on the hour'
-
- [ { frequency: "daily" }, "0 0 8 * * ? *" ], // 8 am is the default time for a daily schedule
-
- [ { frequency: "hourly" }, "0 0 * * * ? *" ], // Check that switching back to hourly works
-
- [ { frequency: "daily", time: "9:00" }, "0 0 9 * * ? *" ], // AM is the default choice between AM and PM
- [ { frequency: "daily", time: "9:00", amPm: "PM" }, "0 0 21 * * ? *" ],
- [ { frequency: "daily", time: "12:00", amPm: "AM" }, "0 0 0 * * ? *" ],
-
- [ { frequency: "weekly", weekday: "Monday", time: "12:00", amPm: "AM" }, "0 0 0 ? * 2 *" ],
- [ { frequency: "weekly", weekday: "Monday", time: "1:00", amPm: "AM" }, "0 0 1 ? * 2 *" ],
-
- [ { frequency: "weekly", weekday: "Tuesday", time: "2:00", amPm: "AM" }, "0 0 2 ? * 3 *" ],
- [ { frequency: "weekly", weekday: "Tuesday", time: "3:00", amPm: "AM" }, "0 0 3 ? * 3 *" ],
-
- [ { frequency: "weekly", weekday: "Wednesday", time: "4:00", amPm: "AM" }, "0 0 4 ? * 4 *" ],
- [ { frequency: "weekly", weekday: "Wednesday", time: "5:00", amPm: "AM" }, "0 0 5 ? * 4 *" ],
-
- [ { frequency: "weekly", weekday: "Thursday", time: "6:00", amPm: "AM" }, "0 0 6 ? * 5 *" ],
- [ { frequency: "weekly", weekday: "Thursday", time: "7:00", amPm: "AM" }, "0 0 7 ? * 5 *" ],
-
- [ { frequency: "weekly", weekday: "Friday", time: "8:00", amPm: "AM" }, "0 0 8 ? * 6 *" ],
- [ { frequency: "weekly", weekday: "Friday", time: "9:00", amPm: "AM" }, "0 0 9 ? * 6 *" ],
-
- [ { frequency: "weekly", weekday: "Saturday", time: "10:00", amPm: "AM" }, "0 0 10 ? * 7 *" ],
- [ { frequency: "weekly", weekday: "Saturday", time: "11:00", amPm: "AM" }, "0 0 11 ? * 7 *" ],
-
- [ { frequency: "weekly", weekday: "Sunday", time: "12:00", amPm: "PM" }, "0 0 12 ? * 1 *" ],
- [ { frequency: "weekly", weekday: "Sunday", time: "1:00", amPm: "PM" }, "0 0 13 ? * 1 *" ],
-
- [ { frequency: "monthly", frame: "first", weekdayOfMonth: "Sunday", time: "12:00", amPm: "AM" }, "0 0 0 ? * 1#1 *" ],
- [ { frequency: "monthly", frame: "first", weekdayOfMonth: "Monday", time: "2:00", amPm: "AM" }, "0 0 2 ? * 2#1 *" ],
-
- [ { frequency: "monthly", frame: "last", weekdayOfMonth: "Tuesday", time: "12:00", amPm: "AM" }, "0 0 0 ? * 3L *" ],
- [ { frequency: "monthly", frame: "last", weekdayOfMonth: "Wednesday", time: "12:00", amPm: "AM" }, "0 0 0 ? * 4L *" ],
-
- [ { frequency: "monthly", frame: "15th", time: "12:00", amPm: "AM" }, "0 0 0 15 * ? *" ],
- [ { frequency: "monthly", frame: "15th", time: "11:00", amPm: "PM" }, "0 0 23 15 * ? *" ],
- [ { frequency: "monthly", frame: "first", weekdayOfMonth: "calendar day", time: "3:00", amPm: "PM" }, "0 0 15 1 * ? *" ],
-
- ];
-
- (["root", "database"] as CacheableModel[]).forEach((model) => {
- schedules.forEach(([schedule, cronExpression]) => {
- it(`can set on ${model}: ${
- Object.values(schedule).join(" ") || "default values"
- }, yielding a cron of ${cronExpression}`, () => {
- openStrategyFormForDatabaseOrDefaultPolicy(
- model === "root" ? "default policy" : "Sample Database",
- "No caching",
- );
- scheduleRadioButton().click();
- Object.entries(schedule).forEach(([componentType, optionToClick]) => {
- if (componentType === "amPm") {
- // AM/PM is a segmented control, not a select
- cacheStrategyForm()
- .findByLabelText("AM/PM")
- .findByText(checkNotNull(optionToClick))
- .click();
- } else {
- getScheduleComponent(componentType).click();
-
- H.popover().within(() => {
- cy.findByText(checkNotNull(optionToClick)).click();
- });
- }
- });
- saveCacheStrategyForm().then((xhr) => {
- const { body } = xhr.request;
- expect(body.model).to.eq(model);
- expect(body.strategy.schedule).to.eq(cronExpression);
- });
- cy.log(
- "Ensure there are no unexpected components among the schedule strategy form fields",
- );
- const expectedFieldLabels: string[] = [];
- expectedFieldLabels.push("Frequency");
- switch (schedule.frequency) {
- case undefined:
- // This means the frequency was not changed; the default frequency (hourly) is selected
- break;
- case "hourly":
- break;
- case "daily":
- expectedFieldLabels.push("Time", "AM/PM", "Your Metabase timezone");
- break;
- case "weekly":
- expectedFieldLabels.push(
- "Day of the week",
- "Time",
- "AM/PM",
- "Your Metabase timezone",
- );
- break;
- case "monthly":
- expectedFieldLabels.push("First, 15th, or last of the month");
- if (schedule.frame !== "15th") {
- expectedFieldLabels.push("Day of the month");
- }
- expectedFieldLabels.push("Time", "AM/PM", "Your Metabase timezone");
- break;
- default:
- throw new Error(
- `Unexpected schedule frequency: ${schedule.frequency}`,
- );
- }
- cacheStrategyForm()
- .findByLabelText("Describe how often the cache should be invalidated")
- .find("[aria-label]")
- .then(($labels) => {
- const labels = $labels
- .get()
- .map(($el) => $el.getAttribute("aria-label"));
- expect(labels).to.deep.equal(expectedFieldLabels);
- });
- });
- });
- });
-});
diff --git a/e2e/test/scenarios/admin/performance/strategyForm.cy.spec.ts b/e2e/test/scenarios/admin/performance/strategyForm.cy.spec.ts
deleted file mode 100644
index 007f4c5f0c0..00000000000
--- a/e2e/test/scenarios/admin/performance/strategyForm.cy.spec.ts
+++ /dev/null
@@ -1,513 +0,0 @@
-const { H } = cy;
-import {
- ORDERS_COUNT_QUESTION_ID,
- ORDERS_QUESTION_ID,
-} from "e2e/support/cypress_sample_instance_data";
-
-import {
- goToPerformancePage,
- interceptPerformanceRoutes,
-} from "./helpers/e2e-performance-helpers";
-import {
- adaptiveRadioButton,
- cacheStrategyForm,
- checkPreemptiveCachingDisabled,
- checkPreemptiveCachingEnabled,
- disablePreemptiveCaching,
- dontCacheResultsRadioButton,
- durationRadioButton,
- enablePreemptiveCaching,
- formLauncher,
- openSidebarCacheStrategyForm,
- openStrategyFormForDatabaseOrDefaultPolicy,
- preemptiveCachingSwitch,
- saveCacheStrategyForm,
- scheduleRadioButton,
-} from "./helpers/e2e-strategy-form-helpers";
-
-/** NOTE: These tests do not check whether caches are actually invalidated at the specified times. */
-describe("scenarios > admin > performance > strategy form", () => {
- describe("oss", { tags: "@OSS" }, () => {
- beforeEach(() => {
- H.restore();
- interceptPerformanceRoutes();
- cy.signInAsAdmin();
- cy.visit("/admin");
- cy.findByRole("link", { name: "Performance" }).click();
- });
-
- it("can enable and disable model persistence", () => {
- goToPerformancePage("Model persistence");
- cy.findByRole("switch", { name: "Disabled" }).click({ force: true });
- cy.wait("@enablePersistence");
- cy.findByTestId("toast-undo").contains("Saved");
- cy.findByTestId("toast-undo")
- .findByRole("img", { name: /close icon/ })
- .click();
-
- cy.findByRole("switch", { name: "Enabled" }).click({ force: true });
- cy.wait("@disablePersistence");
- cy.findByTestId("toast-undo").contains("Saved");
- });
-
- it("can change when models are refreshed", () => {
- goToPerformancePage("Model persistence");
- cy.findByRole("switch", { name: "Disabled" }).click({ force: true });
- cy.wait("@enablePersistence");
- cy.findByTestId("toast-undo").contains("Saved");
- cy.findByTestId("toast-undo")
- .findByRole("img", { name: /close icon/ })
- .click();
- cy.findByRole("textbox").click();
- H.popover().findByText("2 hours").click();
- cy.findByTestId("toast-undo").contains("Saved");
- });
-
- it("there are two policy options for the default policy, Adaptive and Don't cache results", () => {
- cacheStrategyForm().findAllByRole("radio").should("have.length", 2);
- adaptiveRadioButton().should("exist");
- dontCacheResultsRadioButton().should("exist");
- });
-
- it("can set default policy to Don't cache results", () => {
- cy.log("Set default policy to Adaptive first");
- adaptiveRadioButton().click();
- saveCacheStrategyForm({ strategyType: "ttl", model: "root" });
- adaptiveRadioButton().should("be.checked");
-
- cy.log("Then set default policy to Don't cache results");
- dontCacheResultsRadioButton().click();
- saveCacheStrategyForm({ strategyType: "nocache", model: "root" });
- dontCacheResultsRadioButton().should("be.checked");
- });
-
- it("has the correct nav items", () => {
- cy.findByTestId("admin-layout-sidebar").within(() => {
- cy.findAllByRole("link").should("have.length", 2);
- cy.findByText("Database caching").should("be.visible");
- cy.findByText("Model persistence").should("be.visible");
- cy.findByText("Dashboard and question caching").should("not.exist");
- });
- });
-
- describe("adaptive strategy", () => {
- it("can set default policy to adaptive", () => {
- adaptiveRadioButton().click();
- saveCacheStrategyForm({ strategyType: "ttl", model: "root" });
- adaptiveRadioButton().should("be.checked");
- });
-
- it("can configure both a minimum query duration and a multiplier for the default adaptive policy", () => {
- adaptiveRadioButton().click();
- cy.findByLabelText(/Minimum query duration/).type("1234");
- cy.findByLabelText(/Multiplier/).type("4");
- saveCacheStrategyForm({ strategyType: "ttl", model: "root" });
- adaptiveRadioButton().should("be.checked");
- cy.findByLabelText(/Minimum query duration/).should(
- "have.value",
- "1234",
- );
- cy.findByLabelText(/Multiplier/).should("have.value", "4");
- });
- });
- });
-
- describe("ee", () => {
- beforeEach(() => {
- H.restore();
- interceptPerformanceRoutes();
- cy.signInAsAdmin();
- H.activateToken("pro-self-hosted");
- });
-
- it("has the correct nav items", () => {
- cy.visit("/admin");
- cy.findByRole("link", { name: "Performance" }).click();
- cy.findByTestId("admin-layout-sidebar").within(() => {
- cy.findAllByRole("link").should("have.length", 3);
- cy.findByText("Database caching").should("be.visible");
- cy.findByText("Dashboard and question caching").should("be.visible");
- cy.findByText("Model persistence").should("be.visible");
- });
- });
-
- it("can call cache invalidation endpoint for Sample Database", () => {
- openStrategyFormForDatabaseOrDefaultPolicy(
- "default policy",
- "No caching",
- );
- cy.log('A "Clear cache" button is not present for the default policy');
- cy.button(/Clear cache/).should("not.exist");
-
- openStrategyFormForDatabaseOrDefaultPolicy(
- "Sample Database",
- "No caching",
- );
- cy.log(
- 'A "Clear cache" button is not yet present because the database does not use a cache',
- );
- cy.button(/Clear cache/).should("not.exist");
-
- cy.log("Set Sample Database's caching policy to Duration");
- durationRadioButton().click();
-
- cy.log("Save the caching strategy form");
- saveCacheStrategyForm({ strategyType: "duration", model: "database" });
-
- cy.log("Now there's a 'Clear cache' button. Click it");
- cy.button(/Clear cache for this database/).click();
-
- cy.log('Confirm via the "Clear cache" dialog');
- cy.findByRole("dialog")
- .button(/Clear cache/)
- .click();
-
- cy.wait("@invalidateCacheForSampleDatabase");
-
- cy.log("The cache has been cleared");
- cy.button(/Cache cleared/);
- });
-
- const checkInheritanceIfNeeded = (
- itemName: string,
- strategyName: string,
- ) => {
- if (itemName === "default policy") {
- cy.log(
- `Sample Database is now inheriting a default policy of ${strategyName}`,
- );
- formLauncher(
- "Sample Database",
- "currently inheriting the default policy",
- strategyName,
- );
- }
- };
-
- ["default policy", "Sample Database"].forEach((itemName) => {
- const model = itemName === "default policy" ? "root" : "database";
- const expectedNumberOfOptions = itemName === "default policy" ? 4 : 5;
-
- it(`there are ${expectedNumberOfOptions} policy options for ${itemName}`, () => {
- openStrategyFormForDatabaseOrDefaultPolicy(itemName, "No caching");
- cacheStrategyForm()
- .findAllByRole("radio")
- .should("have.length", expectedNumberOfOptions);
- });
-
- it(`can set ${itemName} to Don't cache results`, () => {
- openStrategyFormForDatabaseOrDefaultPolicy(itemName, "No caching");
- cy.log(`Set ${itemName} to Duration first`);
- durationRadioButton().click();
- saveCacheStrategyForm({ strategyType: "duration", model });
- formLauncher(itemName, "currently", "Duration");
-
- cy.log(`Then set ${itemName} to Don't cache results`);
- dontCacheResultsRadioButton().click();
- saveCacheStrategyForm({ strategyType: "nocache", model });
- formLauncher(itemName, "currently", "No caching");
- checkInheritanceIfNeeded(itemName, "No caching");
- });
-
- it(`can set ${itemName} to a duration-based cache invalidation policy`, () => {
- openStrategyFormForDatabaseOrDefaultPolicy(itemName, "No caching");
- cy.log(`Set ${itemName} to Duration`);
- durationRadioButton().click();
- saveCacheStrategyForm({ strategyType: "duration", model });
- cy.log(`${itemName} is now set to Duration`);
- formLauncher(itemName, "currently", "Duration");
- checkInheritanceIfNeeded(itemName, "Duration");
- });
-
- describe("adaptive strategy", () => {
- beforeEach(() => {
- openStrategyFormForDatabaseOrDefaultPolicy(itemName, "No caching");
- adaptiveRadioButton().click();
- });
-
- it(`can set ${itemName} to adaptive`, () => {
- saveCacheStrategyForm({ strategyType: "ttl", model });
- formLauncher(itemName, "currently", "Adaptive");
- checkInheritanceIfNeeded(itemName, "Adaptive");
- });
-
- it(`can configure a minimum query duration for ${itemName}'s adaptive policy`, () => {
- cy.findByLabelText(/Minimum query duration/).type("1000");
- saveCacheStrategyForm({ strategyType: "ttl", model });
- formLauncher(itemName, "currently", "Adaptive");
- cy.findByLabelText(/Minimum query duration/).should(
- "have.value",
- "1000",
- );
- });
-
- it(`can configure a multiplier for ${itemName}'s adaptive policy`, () => {
- cy.findByLabelText(/Multiplier/).type("3");
- saveCacheStrategyForm({ strategyType: "ttl", model });
- formLauncher(itemName, "currently", "Adaptive");
- cy.findByLabelText(/Multiplier/).should("have.value", "3");
- });
-
- it(`can configure both a minimum query duration and a multiplier for ${itemName}'s adaptive policy`, () => {
- cy.findByLabelText(/Minimum query duration/).type("1234");
- cy.findByLabelText(/Multiplier/).type("4");
- saveCacheStrategyForm({ strategyType: "ttl", model });
- formLauncher(itemName, "currently", "Adaptive");
- cy.findByLabelText(/Minimum query duration/).should(
- "have.value",
- "1234",
- );
- cy.findByLabelText(/Multiplier/).should("have.value", "4");
- });
- });
-
- describe(`can set ${itemName} to a schedule-based cache invalidation policy`, () => {
- beforeEach(() => {
- cy.visit("/admin");
- cy.findByRole("link", { name: "Performance" }).click();
- cy.log(`Open caching strategy form for ${itemName}`);
- formLauncher(
- itemName,
- itemName === "default policy"
- ? "currently"
- : "currently inheriting the default policy",
- "No caching",
- ).click();
- cy.log("View schedule options");
- scheduleRadioButton().click();
- });
-
- const selectScheduleType = (type: string) => {
- cy.log(`Set schedule to "${type}"`);
- cy.findByRole("textbox", { name: "Frequency" }).click();
- cy.findByRole("listbox").findByText(type).click();
- };
-
- it(`can save a new hourly schedule policy for ${itemName}`, () => {
- selectScheduleType("hourly");
- saveCacheStrategyForm({ strategyType: "schedule", model });
- formLauncher(itemName, "currently", "Scheduled: hourly");
- });
-
- it(`can save a new daily schedule policy - for ${itemName}`, () => {
- [12, 1, 11].forEach((time) => {
- ["AM", "PM"].forEach((amPm) => {
- cy.log(`Test daily at ${time} ${amPm}`);
- selectScheduleType("daily");
- cy.findAllByRole("textbox").eq(1).click();
- cy.findByRole("listbox").findByText(`${time}:00`).click();
- cy.findByLabelText(amPm).next().click();
- saveCacheStrategyForm({ strategyType: "schedule", model });
- formLauncher("Sample Database", "currently", "Scheduled: daily");
-
- // reset for next iteration of loop
- dontCacheResultsRadioButton().click();
- saveCacheStrategyForm({ strategyType: "nocache", model });
- scheduleRadioButton().click();
- });
- });
- });
-
- it(`can save a new weekly schedule policy - for ${itemName}`, () => {
- [
- ["Sunday", "12:00 AM"],
- ["Monday", "1:00 AM"],
- ["Tuesday", "11:00 AM"],
- ["Wednesday", "12:00 PM"],
- ["Thursday", "1:00 PM"],
- ["Friday", "7:00 PM"],
- ["Saturday", "11:00 PM"],
- ].forEach(([day, time]) => {
- cy.log(`testing on ${day} at ${time}`);
- selectScheduleType("weekly");
- cy.findAllByRole("textbox").eq(1).click();
- cy.findByRole("listbox").findByText(day).click();
- cy.findAllByRole("textbox").eq(2).click();
- const [hour, amPm] = time.split(" ");
- cy.findByRole("listbox").findByText(hour).click();
- cy.findByLabelText(amPm).next().click();
- saveCacheStrategyForm({ strategyType: "schedule", model });
- formLauncher(itemName, "currently", "Scheduled: weekly");
- cy.findAllByRole("textbox").then((searchBoxes) => {
- const values = Cypress._.map(
- searchBoxes,
- (box) => (box as HTMLInputElement).value,
- );
- expect(values).to.deep.equal(["weekly", day, hour]);
- });
- cy.findByRole("radio", { name: amPm }).should("be.checked");
-
- // reset for next iteration of loop
- dontCacheResultsRadioButton().click();
- saveCacheStrategyForm({ strategyType: "nocache", model });
- scheduleRadioButton().click();
- });
- });
- });
- });
-
- describe("Dashboard and question caching tab", () => {
- it("can configure Sample Database on the 'Dashboard and question caching' tab", () => {
- interceptPerformanceRoutes();
- cy.visit("/admin/performance/dashboards-and-questions");
- cy.findByTestId("cache-config-table")
- .should("be.visible")
- .contains(
- "No dashboards or questions have their own caching policies yet.",
- );
- H.visitQuestion(ORDERS_QUESTION_ID);
- openSidebarCacheStrategyForm("question");
- durationRadioButton().click();
- cy.findByLabelText(/Cache results for this many hours/).type("99");
- saveCacheStrategyForm({ strategyType: "duration", model: "database" });
- cy.visit("/admin/performance/dashboards-and-questions");
- cy.findByTestId("cache-config-table")
- .contains("Duration: 99h")
- .within(() => {
- cy.findByText("Duration: 99h").click();
- });
- adaptiveRadioButton().click();
- saveCacheStrategyForm({ strategyType: "ttl", model: "database" });
- });
-
- it("confirmation modal appears before dirty form is abandoned", () => {
- interceptPerformanceRoutes();
- cy.visit("/admin/performance/dashboards-and-questions");
- cy.findByTestId("cache-config-table")
- .should("be.visible")
- .contains(
- "No dashboards or questions have their own caching policies yet.",
- );
- H.visitQuestion(ORDERS_QUESTION_ID);
- openSidebarCacheStrategyForm("question");
- durationRadioButton().click();
- cy.findByLabelText(/Cache results for this many hours/).type("99");
- saveCacheStrategyForm({ strategyType: "duration", model: "database" });
- cy.visit("/admin/performance/dashboards-and-questions");
- cy.findByTestId("cache-config-table")
- .contains("Duration: 99h")
- .within(() => {
- cy.findByText("Duration: 99h").click();
- });
- adaptiveRadioButton().click();
- saveCacheStrategyForm({ strategyType: "ttl", model: "database" });
-
- H.visitQuestion(ORDERS_COUNT_QUESTION_ID);
- openSidebarCacheStrategyForm("question");
- durationRadioButton().click();
- cy.findByLabelText(/Cache results for this many hours/).type("24");
- saveCacheStrategyForm({ strategyType: "duration", model: "database" });
- cy.visit("/admin/performance/dashboards-and-questions");
- cy.findByTestId("cache-config-table").contains("Adaptive");
- cy.findByTestId("cache-config-table")
- .contains("Duration: 24h")
- .within(() => {
- cy.findByText("Duration: 24h").click();
- });
-
- cy.log("Make form dirty");
- scheduleRadioButton().click();
-
- cy.log("Modal appears when the user tries to close the sidesheet");
- cy.findByTestId("modal-overlay").click();
-
- H.modal()
- .should("have.length", 2) // sidesheet and confirm modal are both modals
- .last()
- .findByText("Discard your changes?");
- });
- });
-
- describe("Preemptive caching", () => {
- it("Preemptive caching can be enabled and disabled for duration-based caches", () => {
- // Enable preemptive caching in question settings sidebar
- H.visitQuestion(ORDERS_QUESTION_ID);
- openSidebarCacheStrategyForm("question");
- durationRadioButton().click();
- enablePreemptiveCaching();
- saveCacheStrategyForm({ strategyType: "duration", model: "database" });
- cy.findByLabelText("When to get new results").click();
- checkPreemptiveCachingEnabled();
-
- // Check that it's also enabled on the "Dashboard and question caching" admin page
- cy.visit("/admin/performance/dashboards-and-questions");
- cy.findByTestId("cache-config-table")
- .contains("Duration: 24h")
- .within(() => {
- cy.findByText("Duration: 24h").click();
- });
- checkPreemptiveCachingEnabled();
-
- // Disable preemptive caching on the admin page
- disablePreemptiveCaching();
- saveCacheStrategyForm({ strategyType: "duration", model: "database" });
- checkPreemptiveCachingDisabled();
-
- // Check that it's also disabled in the question sidebar
- H.visitQuestion(ORDERS_QUESTION_ID);
- openSidebarCacheStrategyForm("question");
- checkPreemptiveCachingDisabled();
- });
-
- it("Preemptive caching can be enabled and disabled for schedule-based caches", () => {
- // Enable preemptive caching in question settings sidebar
- H.visitQuestion(ORDERS_QUESTION_ID);
- openSidebarCacheStrategyForm("question");
- scheduleRadioButton().click();
- enablePreemptiveCaching();
- saveCacheStrategyForm({ strategyType: "schedule", model: "database" });
- cy.findByLabelText("When to get new results").click();
- checkPreemptiveCachingEnabled();
-
- // Check that it's also enabled on the "Dashboard and question caching" admin page
- cy.visit("/admin/performance/dashboards-and-questions");
- cy.findByTestId("cache-config-table")
- .contains("Scheduled: hourly")
- .within(() => {
- cy.findByText("Scheduled: hourly").click();
- });
- checkPreemptiveCachingEnabled();
-
- // Disable preemptive caching on the admin page
- disablePreemptiveCaching();
- saveCacheStrategyForm({ strategyType: "schedule", model: "database" });
- checkPreemptiveCachingDisabled();
-
- // Check that it's also disabled in the question sidebar
- H.visitQuestion(ORDERS_QUESTION_ID);
- openSidebarCacheStrategyForm("question");
- checkPreemptiveCachingDisabled();
- });
-
- it("Preemptive caching is not available for other caching policies, or for databases", () => {
- H.visitQuestion(ORDERS_QUESTION_ID);
- openSidebarCacheStrategyForm("question");
- preemptiveCachingSwitch().should("not.exist");
-
- adaptiveRadioButton().click();
- preemptiveCachingSwitch().should("not.exist");
-
- dontCacheResultsRadioButton().click();
- preemptiveCachingSwitch().should("not.exist");
-
- openStrategyFormForDatabaseOrDefaultPolicy(
- "default policy",
- "No caching",
- );
- durationRadioButton().click();
- preemptiveCachingSwitch().should("not.exist");
- scheduleRadioButton().click();
- preemptiveCachingSwitch().should("not.exist");
-
- openStrategyFormForDatabaseOrDefaultPolicy(
- "Sample Database",
- "No caching",
- );
- durationRadioButton().click();
- preemptiveCachingSwitch().should("not.exist");
- scheduleRadioButton().click();
- preemptiveCachingSwitch().should("not.exist");
- });
- });
- });
-});
diff --git a/e2e/test/scenarios/dashboard/dashboard.cy.spec.js b/e2e/test/scenarios/dashboard/dashboard.cy.spec.js
index 128ddd46ca0..cd1611c5f81 100644
--- a/e2e/test/scenarios/dashboard/dashboard.cy.spec.js
+++ b/e2e/test/scenarios/dashboard/dashboard.cy.spec.js
@@ -9,21 +9,12 @@ import {
ORDERS_DASHBOARD_ID,
ORDERS_QUESTION_ID,
} from "e2e/support/cypress_sample_instance_data";
-import { cancelConfirmationModal } from "e2e/test/scenarios/admin/performance/helpers/modals-helpers";
import { GRID_WIDTH } from "metabase/utils/dashboard_grid";
import {
createMockVirtualCard,
createMockVirtualDashCard,
} from "metabase-types/api/mocks";
-import { interceptPerformanceRoutes } from "../admin/performance/helpers/e2e-performance-helpers";
-import {
- adaptiveRadioButton,
- cacheStrategySidesheet,
- durationRadioButton,
- openSidebarCacheStrategyForm,
-} from "../admin/performance/helpers/e2e-strategy-form-helpers";
-
const { H } = cy;
const { ORDERS, ORDERS_ID, PRODUCTS, PEOPLE, PEOPLE_ID } = SAMPLE_DATABASE;
@@ -1589,111 +1580,6 @@ describe("LOCAL TESTING ONLY > dashboard", () => {
);
});
-describe("scenarios > dashboard > caching", () => {
- beforeEach(() => {
- H.restore();
- cy.signInAsAdmin();
- H.activateToken("pro-self-hosted");
- });
-
- /**
- * @note There is a similar test for the cache config form that appears in the question sidebar.
- * It's in the Cypress describe block labeled "scenarios > question > caching"
- */
- it("can configure cache for a dashboard, on an enterprise instance", () => {
- interceptPerformanceRoutes();
- H.visitDashboard(ORDERS_DASHBOARD_ID);
-
- openSidebarCacheStrategyForm("dashboard");
-
- H.sidesheet().within(() => {
- cy.findByText(/Caching settings/).should("be.visible");
- durationRadioButton().click();
- cy.findByLabelText("Cache results for this many hours").type("48");
- cy.findByRole("button", { name: /Save/ }).click();
- cy.wait("@putCacheConfig");
- cy.log(
- "Check that the newly chosen cache invalidation policy - Duration - is now visible in the sidebar",
- );
- cy.findByLabelText(/When to get new results/).should(
- "contain",
- "Duration",
- );
- cy.findByLabelText(/When to get new results/).click();
- adaptiveRadioButton().click();
- cy.findByLabelText(/Minimum query duration/).type("999");
- cy.findByRole("button", { name: /Save/ }).click();
- cy.wait("@putCacheConfig");
- cy.findByLabelText(/When to get new results/).should(
- "contain",
- "Adaptive",
- );
- });
- });
-
- /**
- * @note There is a similar test for closing the cache form when it's dirty
- * It's in the Cypress describe block labeled "scenarios > question > caching"
- */
- it("should guard closing caching form if it's dirty on different actions", () => {
- interceptPerformanceRoutes();
- /**
- * we need to populate the history via react router by clicking route's links
- * in order to imitate a user who clicks "back" and "forward" button
- */
- cy.visit("/");
- cy.findByTestId("main-navbar-root").findByText("Our analytics").click();
- cy.findByTestId("collection-table")
- .findByText("Orders in a dashboard")
- .click();
-
- openSidebarCacheStrategyForm("dashboard");
-
- cacheStrategySidesheet().within(() => {
- cy.findByText(/Caching settings/).should("be.visible");
- durationRadioButton().click();
- });
- // Action 1: clicking on cross button
- cacheStrategySidesheet().findByRole("button", { name: /Close/ }).click();
- cancelConfirmationModal();
- // Action 2: ESC button
- cy.get("body").type("{esc}");
- cancelConfirmationModal();
- // Action 3: click outside
- // When a user clicks somewhere outside he basically clicks on the top one
- cy.findAllByTestId("modal-overlay")
- .should("have.length.gte", 1)
- .last()
- .click();
- cancelConfirmationModal();
- // Action 4: browser's Back action
- cy.go("back");
- cancelConfirmationModal();
- });
-
- it("can click 'Clear cache' for a dashboard", () => {
- interceptPerformanceRoutes();
- H.visitDashboard(ORDERS_DASHBOARD_ID);
-
- openSidebarCacheStrategyForm("dashboard");
-
- H.sidesheet().within(() => {
- cy.findByText(/Caching settings/).should("be.visible");
- cy.findByRole("button", {
- name: /Clear cache for this dashboard/,
- }).click();
- });
-
- cy.findByTestId("confirm-modal").within(() => {
- cy.findByRole("button", { name: /Clear cache/ }).click();
- });
- cy.wait("@invalidateCache");
- H.sidesheet().within(() => {
- cy.findByText("Cache cleared").should("be.visible");
- });
- });
-});
-
describe("scenarios > dashboard > permissions", () => {
let dashboardId;
diff --git a/e2e/test/scenarios/permissions/impersonated.cy.spec.js b/e2e/test/scenarios/permissions/impersonated.cy.spec.js
index 2b8c15b11f0..4cabe904864 100644
--- a/e2e/test/scenarios/permissions/impersonated.cy.spec.js
+++ b/e2e/test/scenarios/permissions/impersonated.cy.spec.js
@@ -1,6 +1,5 @@
const { H } = cy;
import { USER_GROUPS } from "e2e/support/cypress_data";
-import * as PH from "e2e/test/scenarios/admin/performance/helpers/e2e-strategy-form-helpers";
const { ALL_USERS_GROUP, COLLECTION_GROUP } = USER_GROUPS;
@@ -112,12 +111,12 @@ describe("impersonated permission", { tags: "@external" }, () => {
});
cy.log("configure caching");
- PH.openSidebar("question");
+ H.openQuestionActions("Edit settings");
cy.findByLabelText("When to get new results").click();
- PH.cacheStrategySidesheet().within(() => {
+ H.cacheStrategySidesheet().within(() => {
cy.findByText(/Use default/).click();
cy.findByText(/Caching settings/).should("be.visible");
- PH.durationRadioButton().click();
+ H.durationRadioButton().click();
cy.findByRole("button", { name: /Save/ }).click();
});
diff --git a/e2e/test/scenarios/question/caching.cy.spec.js b/e2e/test/scenarios/question/caching.cy.spec.js
deleted file mode 100644
index 3074cde6357..00000000000
--- a/e2e/test/scenarios/question/caching.cy.spec.js
+++ /dev/null
@@ -1,125 +0,0 @@
-import { ORDERS_QUESTION_ID } from "e2e/support/cypress_sample_instance_data";
-import { cancelConfirmationModal } from "e2e/test/scenarios/admin/performance/helpers/modals-helpers";
-
-import { interceptPerformanceRoutes } from "../admin/performance/helpers/e2e-performance-helpers";
-import {
- adaptiveRadioButton,
- cacheStrategySidesheet,
- durationRadioButton,
- openSidebarCacheStrategyForm,
- questionSettingsSidesheet,
-} from "../admin/performance/helpers/e2e-strategy-form-helpers";
-
-const { H } = cy;
-
-describe("scenarios > question > caching", () => {
- beforeEach(() => {
- H.restore();
- cy.signInAsAdmin();
- H.activateToken("pro-self-hosted");
- });
-
- /**
- * @note There is a similar test for the cache config form that appears in the dashboard sidebar.
- * It's in the Cypress describe block labeled "scenarios > dashboard > caching"
- */
- it("can configure cache for a question, on an enterprise instance", () => {
- interceptPerformanceRoutes();
- H.visitQuestion(ORDERS_QUESTION_ID);
-
- openSidebarCacheStrategyForm("question");
-
- cacheStrategySidesheet().within(() => {
- cy.findByText(/Caching settings/).should("be.visible");
- durationRadioButton().click();
- cy.findByLabelText("Cache results for this many hours").type("48");
- cy.findByRole("button", { name: /Save/ }).click();
- });
- cy.wait("@putCacheConfig");
-
- questionSettingsSidesheet().within(() => {
- cy.log(
- "Check that the newly chosen cache invalidation policy - Duration - is now visible in the sidebar",
- );
- cy.findByLabelText(/When to get new results/).should(
- "contain",
- "Duration",
- );
- cy.findByLabelText(/When to get new results/).click();
- });
-
- cacheStrategySidesheet().within(() => {
- adaptiveRadioButton().click();
- cy.findByLabelText(/Minimum query duration/).type("999");
- cy.findByRole("button", { name: /Save/ }).click();
- cy.wait("@putCacheConfig");
- });
-
- questionSettingsSidesheet().within(() => {
- cy.log(
- "Check that the newly chosen cache invalidation policy - Adaptive - is now visible in the sidebar",
- );
- cy.findByLabelText(/When to get new results/).should(
- "contain",
- "Adaptive",
- );
- });
- });
-
- /**
- * @note There is a similar test for closing the cache form when it's dirty
- * It's in the Cypress describe block labeled "scenarios > dashboard > caching"
- */
- it("should guard closing caching form if it's dirty on different actions", () => {
- interceptPerformanceRoutes();
- /**
- * we need to populate the history via react router by clicking route's links
- * in order to imitate a user who clicks "back" button
- */
- cy.visit("/");
- cy.findByTestId("main-navbar-root").findByText("Our analytics").click();
- cy.findByTestId("collection-table").findByText("Orders").click();
-
- openSidebarCacheStrategyForm("question");
-
- cacheStrategySidesheet().within(() => {
- cy.findByText(/Caching settings/).should("be.visible");
- durationRadioButton().click();
- });
- // Action 1: clicking on cross button
- cacheStrategySidesheet().findByRole("button", { name: /Close/ }).click();
- cancelConfirmationModal();
- // Action 2: ESC button
- cy.get("body").type("{esc}");
- cancelConfirmationModal();
- // Action 3: click outside
- // When a user clicks somewhere outside he basically clicks on the top one
- cy.findAllByTestId("modal-overlay")
- .should("have.length.gte", 1)
- .last()
- .click();
- cancelConfirmationModal();
- // Action 4: browser's Back action
- cy.go("back");
- cancelConfirmationModal();
- });
-
- it("can click 'Clear cache' for a question", () => {
- interceptPerformanceRoutes();
- H.visitQuestion(ORDERS_QUESTION_ID);
-
- openSidebarCacheStrategyForm("question");
-
- cacheStrategySidesheet().within(() => {
- cy.findByText(/Caching settings/).should("be.visible");
- cy.findByRole("button", {
- name: /Clear cache for this question/,
- }).click();
- });
-
- cy.findByTestId("confirm-modal").button("Clear cache").click();
- cy.wait("@invalidateCache");
-
- cacheStrategySidesheet().findByText("Cache cleared").should("be.visible");
- });
-});
diff --git a/e2e/test/scenarios/search/recently-viewed.cy.spec.js b/e2e/test/scenarios/search/recently-viewed.cy.spec.js
index 3efc6dec3c6..522670ff5ee 100644
--- a/e2e/test/scenarios/search/recently-viewed.cy.spec.js
+++ b/e2e/test/scenarios/search/recently-viewed.cy.spec.js
@@ -4,7 +4,8 @@ import {
ORDERS_QUESTION_ID,
} from "e2e/support/cypress_sample_instance_data";
-import { advanceServerClockBy } from "../admin/performance/helpers/e2e-performance-helpers";
+const advanceServerClockBy = (milliseconds) =>
+ cy.request("POST", "/api/testing/set-time", { "add-ms": milliseconds });
describe("search > recently viewed", () => {
beforeEach(() => {
diff --git a/enterprise/frontend/src/metabase-enterprise/caching/components/StrategyEditorForDatabases.unit.spec.tsx b/enterprise/frontend/src/metabase-enterprise/caching/components/StrategyEditorForDatabases.unit.spec.tsx
index d19ada4de60..b58b7455d15 100644
--- a/enterprise/frontend/src/metabase-enterprise/caching/components/StrategyEditorForDatabases.unit.spec.tsx
+++ b/enterprise/frontend/src/metabase-enterprise/caching/components/StrategyEditorForDatabases.unit.spec.tsx
@@ -1,6 +1,6 @@
import userEvent from "@testing-library/user-event";
-import { act, screen } from "__support__/ui";
+import { act, screen, within } from "__support__/ui";
import type { SetupOpts } from "metabase/admin/performance/components/test-utils";
import {
setupStrategyEditorForDatabases as baseSetup,
@@ -33,6 +33,21 @@ describe("StrategyEditorForDatabases", () => {
expect(PLUGIN_CACHING.canOverrideRootStrategy).toBe(true);
});
+ it("shows four policy options for the default policy", async () => {
+ await userEvent.click(await screen.findByLabelText(/Edit default policy/));
+ expect(await screen.findAllByRole("radio")).toHaveLength(4);
+ });
+
+ it("shows five policy options for a database (adds 'Use default')", async () => {
+ await userEvent.click(
+ await screen.findByLabelText(/Edit policy for database 'Database 1'/),
+ );
+ expect(await screen.findAllByRole("radio")).toHaveLength(5);
+ expect(
+ screen.getByRole("radio", { name: /Use default/i }),
+ ).toBeInTheDocument();
+ });
+
it("should show strategy form launchers", async () => {
const rootStrategyHeading = await screen.findByText("Default policy");
expect(rootStrategyHeading).toBeInTheDocument();
@@ -209,6 +224,45 @@ describe("StrategyEditorForDatabases", () => {
).toBeInTheDocument();
});
+ // The Schedule UI -> cron mapping is exhaustively unit-tested in
+ // Schedule.unit.spec.tsx. This case is the integration: picking a
+ // frequency/day/time in the Schedule fields must flow through Formik's
+ // `setFieldValue("schedule", ...)` and end up in the saved strategy, which
+ // the launcher label then reads back.
+ it("saves a weekly Monday 8 AM schedule and round-trips it through the launcher label", async () => {
+ await userEvent.click(
+ await screen.findByLabelText(
+ `Edit policy for database 'Database 1' (currently: Adaptive)`,
+ ),
+ );
+
+ await userEvent.click(
+ await screen.findByRole("radio", { name: /Schedule/i }),
+ );
+
+ const pickOption = async (testId: string, optionName: string) => {
+ await userEvent.click(screen.getByTestId(testId));
+ const listbox = await screen.findByRole("listbox");
+ await userEvent.click(
+ within(listbox).getByRole("option", { name: optionName }),
+ );
+ };
+
+ await pickOption("select-frequency", "weekly");
+ await pickOption("select-weekday", "Monday");
+ await pickOption("select-time", "8:00");
+
+ await userEvent.click(
+ await screen.findByTestId("strategy-form-submit-button"),
+ );
+
+ expect(
+ await screen.findByLabelText(
+ `Edit policy for database 'Database 1' (currently: Scheduled: weekly)`,
+ ),
+ ).toBeInTheDocument();
+ });
+
it("can abbreviate a 'Schedule' strategy", () => {
const strategy: ScheduleStrategy = {
type: "schedule",
@@ -230,3 +284,34 @@ describe("StrategyEditorForDatabases", () => {
expect(result).toBe("Duration: 5h");
});
});
+
+describe("StrategyEditorForDatabases (cache_preemptive enabled)", () => {
+ beforeEach(() => {
+ setup({
+ tokenFeatures: createMockTokenFeatures({
+ cache_granular_controls: true,
+ cache_preemptive: true,
+ }),
+ });
+ });
+
+ // The preemptive caching switch only renders for question/dashboard targets.
+ // Root and database forms must not show it, regardless of strategy.
+ it.each([
+ ["default policy", /Edit default policy/, /Duration/i],
+ ["default policy", /Edit default policy/, /Schedule/i],
+ ["a database", /Edit policy for database 'Database 1'/, /Duration/i],
+ ["a database", /Edit policy for database 'Database 1'/, /Schedule/i],
+ ])(
+ "does not show the preemptive caching switch for %s with %p strategy",
+ async (_label, launcherLabel, strategyName) => {
+ await userEvent.click(await screen.findByLabelText(launcherLabel));
+ await userEvent.click(
+ await screen.findByRole("radio", { name: strategyName }),
+ );
+ expect(
+ screen.queryByTestId("preemptive-caching-switch"),
+ ).not.toBeInTheDocument();
+ },
+ );
+});
diff --git a/frontend/src/metabase/admin/performance/components/ModelPersistenceConfiguration.unit.spec.tsx b/frontend/src/metabase/admin/performance/components/ModelPersistenceConfiguration.unit.spec.tsx
new file mode 100644
index 00000000000..78bfa0ee55b
--- /dev/null
+++ b/frontend/src/metabase/admin/performance/components/ModelPersistenceConfiguration.unit.spec.tsx
@@ -0,0 +1,152 @@
+import userEvent from "@testing-library/user-event";
+import fetchMock from "fetch-mock";
+
+import {
+ setupPropertiesEndpoints,
+ setupSettingsEndpoints,
+} from "__support__/server-mocks";
+import { mockSettings } from "__support__/settings";
+import { renderWithProviders, screen, waitFor } from "__support__/ui";
+import { createMockState } from "metabase/redux/store/mocks";
+import { createMockSettings } from "metabase-types/api/mocks";
+
+import { ModelPersistenceConfiguration } from "./ModelPersistenceConfiguration";
+
+const ENABLE_URL = "path:/api/persist/enable";
+const DISABLE_URL = "path:/api/persist/disable";
+const SET_SCHEDULE_URL = "path:/api/persist/set-refresh-schedule";
+const SESSION_PROPERTIES_URL = "path:/api/session/properties";
+
+interface SetupOpts {
+ persistedModelsEnabled?: boolean;
+ cronSchedule?: string;
+}
+
+const setup = ({
+ persistedModelsEnabled = false,
+ cronSchedule = "0 0 0/1 * * ? *",
+}: SetupOpts = {}) => {
+ const settings = createMockSettings({
+ "persisted-models-enabled": persistedModelsEnabled,
+ "persisted-model-refresh-cron-schedule": cronSchedule,
+ });
+
+ setupPropertiesEndpoints(settings);
+ setupSettingsEndpoints([]);
+ fetchMock.post(ENABLE_URL, 204);
+ fetchMock.post(DISABLE_URL, 204);
+ fetchMock.post(SET_SCHEDULE_URL, 204);
+
+ const state = createMockState({ settings: mockSettings(settings) });
+
+ return renderWithProviders(<ModelPersistenceConfiguration />, {
+ storeInitialState: state,
+ });
+};
+
+describe("ModelPersistenceConfiguration", () => {
+ afterEach(() => {
+ fetchMock.removeRoutes();
+ fetchMock.clearHistory();
+ });
+
+ describe("initial render", () => {
+ it("shows the switch as disabled when persistence is off", () => {
+ setup({ persistedModelsEnabled: false });
+ expect(screen.getByText("Disabled")).toBeInTheDocument();
+ expect(screen.getByRole("switch")).not.toBeChecked();
+ });
+
+ it("shows the switch as enabled when persistence is on", () => {
+ setup({ persistedModelsEnabled: true });
+ expect(screen.getByText("Enabled")).toBeInTheDocument();
+ expect(screen.getByRole("switch")).toBeChecked();
+ });
+
+ it("hides the refresh-interval picker when persistence is off", () => {
+ setup({ persistedModelsEnabled: false });
+ expect(
+ screen.queryByText("Refresh models every…"),
+ ).not.toBeInTheDocument();
+ });
+
+ it("shows the refresh-interval picker when persistence is on", () => {
+ setup({ persistedModelsEnabled: true });
+ expect(screen.getByText("Refresh models every…")).toBeInTheDocument();
+ });
+ });
+
+ describe("toggle wiring", () => {
+ it("calls POST /api/persist/enable when the switch is turned on", async () => {
+ setup({ persistedModelsEnabled: false });
+
+ await userEvent.click(screen.getByRole("switch"));
+
+ await waitFor(() => {
+ expect(fetchMock.callHistory.called(ENABLE_URL)).toBe(true);
+ });
+ expect(fetchMock.callHistory.called(DISABLE_URL)).toBe(false);
+ });
+
+ it("calls POST /api/persist/disable when the switch is turned off", async () => {
+ setup({ persistedModelsEnabled: true });
+
+ await userEvent.click(screen.getByRole("switch"));
+
+ await waitFor(() => {
+ expect(fetchMock.callHistory.called(DISABLE_URL)).toBe(true);
+ });
+ expect(fetchMock.callHistory.called(ENABLE_URL)).toBe(false);
+ });
+
+ it("refetches site settings after toggling", async () => {
+ setup({ persistedModelsEnabled: false });
+
+ await userEvent.click(screen.getByRole("switch"));
+
+ await waitFor(() => {
+ expect(fetchMock.callHistory.called(SESSION_PROPERTIES_URL)).toBe(true);
+ });
+ });
+ });
+
+ describe("refresh-interval picker", () => {
+ it("calls POST /api/persist/set-refresh-schedule with the chosen cron when a preset is selected", async () => {
+ setup({
+ persistedModelsEnabled: true,
+ cronSchedule: "0 0 0/2 * * ? *",
+ });
+
+ await userEvent.click(screen.getByDisplayValue("2 hours"));
+ await userEvent.click(
+ await screen.findByRole("option", { name: "6 hours" }),
+ );
+
+ await waitFor(() => {
+ expect(fetchMock.callHistory.called(SET_SCHEDULE_URL)).toBe(true);
+ });
+ const lastCall = fetchMock.callHistory.lastCall(SET_SCHEDULE_URL);
+ expect(JSON.parse(lastCall?.options?.body as string)).toEqual({
+ cron: "0 0 0/6 * * ? *",
+ });
+ });
+
+ it("reveals the cron input when 'Custom…' is selected", async () => {
+ setup({
+ persistedModelsEnabled: true,
+ cronSchedule: "0 0 0/2 * * ? *",
+ });
+
+ // Cron input is not present before Custom… is chosen.
+ expect(screen.queryByDisplayValue("0 * * * ?")).not.toBeInTheDocument();
+
+ await userEvent.click(screen.getByDisplayValue("2 hours"));
+ await userEvent.click(
+ await screen.findByRole("option", { name: "Custom…" }),
+ );
+
+ // The custom cron input is now visible, populated with the default.
+ expect(await screen.findByDisplayValue("0 * * * ?")).toBeInTheDocument();
+ });
+ });
+});
diff --git a/frontend/src/metabase/admin/performance/components/StrategyEditorForDatabases.unit.spec.tsx b/frontend/src/metabase/admin/performance/components/StrategyEditorForDatabases.unit.spec.tsx
index e35a38ecb12..e3e7baa0e67 100644
--- a/frontend/src/metabase/admin/performance/components/StrategyEditorForDatabases.unit.spec.tsx
+++ b/frontend/src/metabase/admin/performance/components/StrategyEditorForDatabases.unit.spec.tsx
@@ -8,11 +8,22 @@ import {
setupStrategyEditorForDatabases as setup,
} from "./test-utils";
-describe("StrategyEditorForDatabases", () => {
+describe("StrategyEditorForDatabases (OSS)", () => {
beforeEach(() => {
setup();
});
+ it("shows two policy options for the default policy: Adaptive and Don't cache", async () => {
+ const radios = await screen.findAllByRole("radio");
+ expect(radios).toHaveLength(2);
+ expect(
+ screen.getByRole("radio", { name: /Adaptive/i }),
+ ).toBeInTheDocument();
+ expect(
+ screen.getByRole("radio", { name: /Don.t cache/i }),
+ ).toBeInTheDocument();
+ });
+
it("lets user change the default policy to 'Adaptive', then 'No caching'", async () => {
expect(
screen.queryByRole("button", { name: "Save changes" }),
diff --git a/frontend/src/metabase/common/components/Schedule/Schedule.unit.spec.tsx b/frontend/src/metabase/common/components/Schedule/Schedule.unit.spec.tsx
index f53253d67d5..34bc3bf513e 100644
--- a/frontend/src/metabase/common/components/Schedule/Schedule.unit.spec.tsx
+++ b/frontend/src/metabase/common/components/Schedule/Schedule.unit.spec.tsx
@@ -2,7 +2,11 @@ import { within } from "@testing-library/react";
import userEvent from "@testing-library/user-event";
import { screen } from "__support__/ui";
-import { setup } from "metabase/common/components/Schedule/test-utils";
+import type { ScheduleComponentType } from "metabase/common/components/Schedule/strings";
+import {
+ setup,
+ setupHarness,
+} from "metabase/common/components/Schedule/test-utils";
const getInputValues = () => {
const inputs = screen.getAllByRole("textbox");
@@ -106,4 +110,268 @@ describe("Schedule", () => {
});
expect(getInputValues()).toEqual(["custom", "0/5 * * * ?"]);
});
+
+ describe("rendered fields per frequency", () => {
+ const ALL_SCHEDULE_FIELD_LABELS = [
+ "Frequency",
+ "First, 15th, or last of the month",
+ "Day of the week",
+ "Day of the month",
+ "Time",
+ "AM/PM",
+ "Your Metabase timezone",
+ ];
+
+ it.each([
+ ["hourly", "0 0 * * * ? *", ["Frequency"]],
+ [
+ "daily",
+ "0 0 8 * * ? *",
+ ["Frequency", "Time", "AM/PM", "Your Metabase timezone"],
+ ],
+ [
+ "weekly",
+ "0 0 8 ? * 2 *",
+ [
+ "Frequency",
+ "Day of the week",
+ "Time",
+ "AM/PM",
+ "Your Metabase timezone",
+ ],
+ ],
+ [
+ "monthly first weekday",
+ "0 0 8 ? * 2#1 *",
+ [
+ "Frequency",
+ "First, 15th, or last of the month",
+ "Day of the month",
+ "Time",
+ "AM/PM",
+ "Your Metabase timezone",
+ ],
+ ],
+ [
+ "monthly mid (15th)",
+ "0 0 8 15 * ? *",
+ [
+ "Frequency",
+ "First, 15th, or last of the month",
+ "Time",
+ "AM/PM",
+ "Your Metabase timezone",
+ ],
+ ],
+ ])("renders the right fields for %s", (_label, cronString, expected) => {
+ setup({ cronString });
+ expected.forEach((label) => {
+ expect(screen.getByLabelText(label)).toBeInTheDocument();
+ });
+ ALL_SCHEDULE_FIELD_LABELS.filter(
+ (label) => !expected.includes(label),
+ ).forEach((label) => {
+ expect(screen.queryByLabelText(label)).not.toBeInTheDocument();
+ });
+ });
+ });
+
+ describe("write path", () => {
+ const pickField = async (
+ componentType: ScheduleComponentType,
+ optionToClick: string,
+ ) => {
+ if (componentType === "amPm") {
+ await userEvent.click(
+ screen.getByRole("radio", { name: optionToClick }),
+ );
+ return;
+ }
+ const testIdMap: Record<
+ Exclude<ScheduleComponentType, "amPm">,
+ string
+ > = {
+ frequency: "select-frequency",
+ frame: "select-frame",
+ weekdayOfMonth: "select-weekday-of-month",
+ weekday: "select-weekday",
+ time: "select-time",
+ minute: "select-minute",
+ };
+ const testId = testIdMap[componentType];
+ await userEvent.click(screen.getByTestId(testId));
+ const listbox = await screen.findByRole("listbox");
+ await userEvent.click(
+ within(listbox).getByRole("option", { name: optionToClick }),
+ );
+ };
+
+ type WriteCase = [
+ label: string,
+ initialCronString: string,
+ clicks: Partial<Record<ScheduleComponentType, string>>,
+ expectedCron: string,
+ ];
+
+ const cases: WriteCase[] = [
+ // Switching back to hourly from daily
+ [
+ "switch to hourly",
+ "0 0 8 * * ? *",
+ { frequency: "hourly" },
+ "0 0 * * * ? *",
+ ],
+ // Daily defaults
+ [
+ "daily default time",
+ "0 0 * * * ? *",
+ { frequency: "daily" },
+ "0 0 8 * * ? *",
+ ],
+ // Daily with explicit time/AM-PM, including 12-hour boundary
+ [
+ "daily 9 AM (default)",
+ "0 0 * * * ? *",
+ { frequency: "daily", time: "9:00" },
+ "0 0 9 * * ? *",
+ ],
+ [
+ "daily 9 PM",
+ "0 0 * * * ? *",
+ { frequency: "daily", time: "9:00", amPm: "PM" },
+ "0 0 21 * * ? *",
+ ],
+ [
+ "daily 12 AM",
+ "0 0 * * * ? *",
+ { frequency: "daily", time: "12:00", amPm: "AM" },
+ "0 0 0 * * ? *",
+ ],
+ // Weekly across all weekdays + AM/PM boundary cases
+ [
+ "weekly Monday 12 AM",
+ "0 0 * * * ? *",
+ { frequency: "weekly", weekday: "Monday", time: "12:00", amPm: "AM" },
+ "0 0 0 ? * 2 *",
+ ],
+ [
+ "weekly Tuesday 2 AM",
+ "0 0 * * * ? *",
+ { frequency: "weekly", weekday: "Tuesday", time: "2:00", amPm: "AM" },
+ "0 0 2 ? * 3 *",
+ ],
+ [
+ "weekly Wednesday 4 AM",
+ "0 0 * * * ? *",
+ { frequency: "weekly", weekday: "Wednesday", time: "4:00", amPm: "AM" },
+ "0 0 4 ? * 4 *",
+ ],
+ [
+ "weekly Thursday 6 AM",
+ "0 0 * * * ? *",
+ { frequency: "weekly", weekday: "Thursday", time: "6:00", amPm: "AM" },
+ "0 0 6 ? * 5 *",
+ ],
+ [
+ "weekly Friday 8 AM",
+ "0 0 * * * ? *",
+ { frequency: "weekly", weekday: "Friday", time: "8:00", amPm: "AM" },
+ "0 0 8 ? * 6 *",
+ ],
+ [
+ "weekly Saturday 10 AM",
+ "0 0 * * * ? *",
+ { frequency: "weekly", weekday: "Saturday", time: "10:00", amPm: "AM" },
+ "0 0 10 ? * 7 *",
+ ],
+ [
+ "weekly Sunday 12 PM",
+ "0 0 * * * ? *",
+ { frequency: "weekly", weekday: "Sunday", time: "12:00", amPm: "PM" },
+ "0 0 12 ? * 1 *",
+ ],
+ [
+ "weekly Sunday 1 PM",
+ "0 0 * * * ? *",
+ { frequency: "weekly", weekday: "Sunday", time: "1:00", amPm: "PM" },
+ "0 0 13 ? * 1 *",
+ ],
+ // Monthly variants
+ [
+ "monthly first Sunday 12 AM",
+ "0 0 * * * ? *",
+ {
+ frequency: "monthly",
+ frame: "first",
+ weekdayOfMonth: "Sunday",
+ time: "12:00",
+ amPm: "AM",
+ },
+ "0 0 0 ? * 1#1 *",
+ ],
+ [
+ "monthly first Monday 2 AM",
+ "0 0 * * * ? *",
+ {
+ frequency: "monthly",
+ frame: "first",
+ weekdayOfMonth: "Monday",
+ time: "2:00",
+ amPm: "AM",
+ },
+ "0 0 2 ? * 2#1 *",
+ ],
+ [
+ "monthly last Tuesday 12 AM",
+ "0 0 * * * ? *",
+ {
+ frequency: "monthly",
+ frame: "last",
+ weekdayOfMonth: "Tuesday",
+ time: "12:00",
+ amPm: "AM",
+ },
+ "0 0 0 ? * 3L *",
+ ],
+ [
+ "monthly 15th 12 AM",
+ "0 0 * * * ? *",
+ { frequency: "monthly", frame: "15th", time: "12:00", amPm: "AM" },
+ "0 0 0 15 * ? *",
+ ],
+ [
+ "monthly 15th 11 PM",
+ "0 0 * * * ? *",
+ { frequency: "monthly", frame: "15th", time: "11:00", amPm: "PM" },
+ "0 0 23 15 * ? *",
+ ],
+ [
+ "monthly first calendar day 3 PM",
+ "0 0 * * * ? *",
+ {
+ frequency: "monthly",
+ frame: "first",
+ weekdayOfMonth: "calendar day",
+ time: "3:00",
+ amPm: "PM",
+ },
+ "0 0 15 1 * ? *",
+ ],
+ ];
+
+ it.each(cases)(
+ "%s",
+ async (_label, initialCronString, clicks, expectedCron) => {
+ const { onScheduleChange } = setupHarness({ initialCronString });
+ for (const entry of Object.entries(clicks) as [
+ ScheduleComponentType,
+ string,
+ ][]) {
+ await pickField(entry[0], entry[1]);
+ }
+ expect(onScheduleChange).toHaveBeenCalled();
+ expect(onScheduleChange.mock.calls.at(-1)?.[0]).toBe(expectedCron);
+ },
+ );
+ });
});
diff --git a/frontend/src/metabase/common/components/Schedule/test-utils.tsx b/frontend/src/metabase/common/components/Schedule/test-utils.tsx
index 09efaaa3c6b..03328095a50 100644
--- a/frontend/src/metabase/common/components/Schedule/test-utils.tsx
+++ b/frontend/src/metabase/common/components/Schedule/test-utils.tsx
@@ -1,9 +1,15 @@
+import { useState } from "react";
+
import { setupEnterpriseOnlyPlugin } from "__support__/enterprise";
import { mockSettings } from "__support__/settings";
import { createMockEntitiesState } from "__support__/store";
import { renderWithProviders } from "__support__/ui";
import { createMockState } from "metabase/redux/store/mocks";
-import type { ScheduleType, TokenFeatures } from "metabase-types/api";
+import type {
+ ScheduleSettings,
+ ScheduleType,
+ TokenFeatures,
+} from "metabase-types/api";
import {
createMockSettings,
createMockTokenFeatures,
@@ -26,14 +32,11 @@ const mockScheduleOptions: ScheduleType[] = [
];
const mockVerb = "Send";
const mockTimezone = "America/New_York";
-const mockOnScheduleChange = jest.fn();
-export const setup = ({
- enterprisePlugins,
+const buildStoreState = ({
tokenFeatures = {},
- ...props
-}: SetupOpts & Partial<ScheduleProps> = {}) => {
- const storeInitialState = createMockState({
+}: Pick<SetupOpts, "tokenFeatures">) =>
+ createMockState({
entities: createMockEntitiesState({}),
settings: mockSettings(
createMockSettings({
@@ -42,20 +45,76 @@ export const setup = ({
),
});
+export const setup = ({
+ enterprisePlugins,
+ tokenFeatures = {},
+ ...props
+}: SetupOpts & Partial<ScheduleProps> = {}) => {
+ const onScheduleChange = jest.fn();
+
if (enterprisePlugins) {
enterprisePlugins.forEach(setupEnterpriseOnlyPlugin);
}
- const propsWithDefaults = {
+ const propsWithDefaults: ScheduleProps = {
cronString: props.cronString ?? "0 0 8 * * ? *",
scheduleOptions: mockScheduleOptions,
- onScheduleChange: mockOnScheduleChange,
+ onScheduleChange,
timezone: mockTimezone,
verb: mockVerb,
...props,
};
- return renderWithProviders(<Schedule {...propsWithDefaults} />, {
- storeInitialState,
+ const renderResult = renderWithProviders(
+ <Schedule {...propsWithDefaults} />,
+ { storeInitialState: buildStoreState({ tokenFeatures }) },
+ );
+
+ return { ...renderResult, onScheduleChange };
+};
+
+/**
+ * Stateful wrapper that holds the cron string in React state and re-renders
+ * `<Schedule>` after every change. Required for tests that drive multiple
+ * sequential clicks — `<Schedule>` derives its settings from `cronString` on
+ * each render, so the parent must update `cronString` for subsequent clicks
+ * to see the new state.
+ */
+export const setupHarness = ({
+ enterprisePlugins,
+ tokenFeatures = {},
+ initialCronString = "0 0 * * * ? *",
+ ...props
+}: SetupOpts &
+ Omit<Partial<ScheduleProps>, "cronString" | "onScheduleChange"> & {
+ initialCronString?: string;
+ } = {}) => {
+ const onScheduleChange = jest.fn<void, [string, ScheduleSettings]>();
+
+ if (enterprisePlugins) {
+ enterprisePlugins.forEach(setupEnterpriseOnlyPlugin);
+ }
+
+ const Harness = () => {
+ const [cron, setCron] = useState(initialCronString);
+ return (
+ <Schedule
+ cronString={cron}
+ scheduleOptions={mockScheduleOptions}
+ timezone={mockTimezone}
+ verb={mockVerb}
+ {...props}
+ onScheduleChange={(next, settings) => {
+ onScheduleChange(next, settings);
+ setCron(next);
+ }}
+ />
+ );
+ };
+
+ const renderResult = renderWithProviders(<Harness />, {
+ storeInitialState: buildStoreState({ tokenFeatures }),
});
+
+ return { ...renderResult, onScheduleChange };
};