The easy-to-use open source Business Intelligence and Embedded Analytics tool that lets everyone work with data :bar_chart:
TypeScript analyticsbibusiness-intelligencebusinessintelligenceclojuredashboarddatadata-analysisdata-visualizationdatabasemetabasemysqlpostgrespostgresqlreportingslacksql-editorvisualization
e2e2unit: binning reproductions (#85301)
Nemanja Glumacc015d7a85d86
diff --git a/e2e/test/scenarios/binning/binning-reproductions.cy.spec.js b/e2e/test/scenarios/binning/binning-reproductions.cy.spec.jsindex 11d5dedb379..df8b48f8c6f 100644--- a/e2e/test/scenarios/binning/binning-reproductions.cy.spec.js+++ b/e2e/test/scenarios/binning/binning-reproductions.cy.spec.js@@ -10,244 +10,59 @@ describe("binning related reproductions", () => {cy.signInAsAdmin();});- it("shouldn't render double binning options when question is based on the saved native question (metabase#16327)", () => {- H.createNativeQuestion({- name: "16327",- native: { query: "select * from products limit 5" },- });-- H.startNewQuestion();- H.miniPicker().within(() => {- cy.findByText("Our analytics").click();- cy.findByText("16327").click();- });-- // eslint-disable-next-line metabase/no-unscoped-text-selectors -- deprecated usage- cy.findByText("Pick a function or metric").click();- // eslint-disable-next-line metabase/no-unscoped-text-selectors -- deprecated usage- cy.findByText("Count of rows").click();-- // eslint-disable-next-line metabase/no-unscoped-text-selectors -- deprecated usage- cy.findByText("Pick a column to group by").click();- // eslint-disable-next-line metabase/no-unscoped-text-selectors -- deprecated usage- cy.findByText(/CREATED_AT/i).realHover();- // eslint-disable-next-line metabase/no-unscoped-text-selectors -- deprecated usage- cy.findByText("by month").click({ force: true });+ it("should run a query that breaks out by a temporal column of a joined native question (metabase#18646)", () => {+ cy.log("Reproduces metabase#18646");+ const joinAlias = "18646 - Product";- // Implicit assertion - it fails if there is more than one instance of the string, which is exactly what we need for this repro- // eslint-disable-next-line metabase/no-unscoped-text-selectors -- deprecated usage- cy.findByText("Day");- });-- it("should be able to update the bucket size / granularity on a field that has sorting applied to it (metabase#16770)", () => {- H.visitQuestionAdhoc({- dataset_query: {- database: SAMPLE_DB_ID,- query: {- "source-table": ORDERS_ID,- aggregation: [["count"]],- breakout: [- ["field", ORDERS.CREATED_AT, { "temporal-unit": "month" }],- ],- "order-by": [- ["asc", ["field", ORDERS.CREATED_AT, { "temporal-unit": "month" }]],- ],- },- type: "query",- },- display: "line",- });-- H.summarize();-- H.changeBinningForDimension({- name: "Created At",- fromBinning: "by month",- toBinning: "Year",- isSelected: true,- });-- cy.wait("@dataset").then((xhr) => {- expect(xhr.response.body.error).not.to.exist;- });-- // eslint-disable-next-line metabase/no-unscoped-text-selectors -- deprecated usage- cy.findByText("Count by Created At: Year");- // eslint-disable-next-line metabase/no-unscoped-text-selectors -- deprecated usage- cy.findByText("2027");- });-- it("should not remove order-by (sort) when changing the breakout field on an SQL saved question (metabase#17975)", () => {- H.createNativeQuestion(- {- name: "17975",- native: {- query: "SELECT * FROM ORDERS",- },- },- { loadMetadata: true },- );-- H.startNewQuestion();- H.miniPicker().within(() => {- cy.findByText("Our analytics").click();- cy.findByText("17975").click();- });-- H.getNotebookStep("summarize")- .findByText("Pick a function or metric")- .click();- H.popover().findByText("Count of rows").click();- H.getNotebookStep("summarize")- .findByText("Pick a column to group by")- .click();- H.popover().findByText("CREATED_AT").click();-- cy.findByRole("button", { name: "Sort" }).click();- H.popover().findByText("CREATED_AT: Month").click();-- H.getNotebookStep("summarize").findByText("CREATED_AT: Month").click();- H.popover()- .findByRole("option", { name: "CREATED_AT" })- .findByLabelText("Temporal bucket")- .realHover()- .click();- // eslint-disable-next-line metabase/no-unsafe-element-filtering- H.popover().last().findByText("Quarter").click();-- H.getNotebookStep("sort").findByText("CREATED_AT: Quarter");- });-- it("should render binning options when joining on the saved native question (metabase#18646)", () => {H.createNativeQuestion({name: "18646",native: { query: "select * from products" },},- { loadMetadata: true },+ { loadMetadata: true, wrapId: true },);- H.openOrdersTable({ mode: "notebook" });-- cy.icon("join_left_outer").click();-- H.miniPicker().within(() => {- cy.findByText("Our analytics").click();- cy.findByText("18646").click();- });-- H.popover().findByText("Product ID").click();-- H.popover().within(() => {- cy.findByText("ID").click();- });-- // eslint-disable-next-line metabase/no-unscoped-text-selectors -- deprecated usage- cy.findByText("Summarize").click();- H.popover().findByText("Count of rows").click();-- H.getNotebookStep("summarize")- .findByText("Pick a column to group by")- .click();- H.popover().findByText("18646").click();-- H.popover().within(() => {- cy.findByRole("option", { name: /CREATED_AT/ })- .findByText("by month")- .should("exist");- cy.findByRole("option", { name: /CREATED_AT/ }).click({- position: "left",+ cy.get("@questionId").then((cardId) => {+ H.visitQuestionAdhoc({+ dataset_query: {+ database: SAMPLE_DB_ID,+ type: "query",+ query: {+ "source-table": ORDERS_ID,+ joins: [+ {+ alias: joinAlias,+ "source-table": `card__${cardId}`,+ fields: "all",+ condition: [+ "=",+ ["field", ORDERS.PRODUCT_ID, null],+ [+ "field",+ "ID",+ { "base-type": "type/BigInteger", "join-alias": joinAlias },+ ],+ ],+ },+ ],+ aggregation: [["count"]],+ breakout: [+ [+ "field",+ "CREATED_AT",+ {+ "base-type": "type/DateTimeWithLocalTZ",+ "join-alias": joinAlias,+ "temporal-unit": "month",+ },+ ],+ ],+ },+ },+ display: "line",});});- H.getNotebookStep("summarize").findByText(- "18646 - Product → CREATED_AT: Month",- );-- H.visualize();- H.cartesianChartCircle();- });-- it("should display date granularity on Summarize when opened from saved question (metabase#10441, metabase#11439)", () => {- H.createQuestion({- name: "11439",- query: { "source-table": ORDERS_ID },- });-- // it is essential for this repro to find question following these exact steps- // (for example, visiting `/collection/root` would yield different result)- H.startNewQuestion();- H.miniPicker().within(() => {- cy.findByText("Our analytics").click();- cy.findByText("11439").click();- });-- H.visualize();- H.summarize();-- H.rightSidebar().within(() => {- cy.findAllByRole("listitem", { name: "Created At" })- .eq(0)- .findByLabelText("Temporal bucket")- .realHover()- .click();- });-- H.popover().within(() => {- cy.button("More…").click();- cy.findByText("Hour of day").should("exist");- });- });-- it("shouldn't duplicate the breakout field (metabase#22382)", () => {- const questionDetails = {- name: "22382",- query: {- "source-table": ORDERS_ID,- aggregation: [["count"]],- breakout: [["field", ORDERS.CREATED_AT, { "temporal-unit": "month" }]],- },- };-- cy.intercept("POST", "/api/dataset").as("dataset");-- H.createQuestion(questionDetails, { visitQuestion: true });-- // Open settings through viz type picker to ensure "Table Options" is in the sidebar.- H.openVizTypeSidebar();- cy.findByTestId("sidebar-left").within(() => {- cy.findByTestId("Table-button").click();- cy.findByTextEnsureVisible("Table options");- cy.findByTestId("draggable-item-Created At: Month")- .findByText("Created At: Month")- .should("be.visible");- cy.findByTestId("draggable-item-Created At: Month")- .icon("eye_outline")- .click({ force: true });- cy.button("Done").click();- });-- H.summarize();-- cy.findByTestId("pinned-dimensions")- .should("contain", "Created At")- .find(".Icon-close")- .click();- cy.wait("@dataset");-- cy.findByTestId("query-visualization-root").findByText("Count");-- cy.findByTestId("sidebar-right")- .findAllByText("Created At")- .first()- .click();- cy.wait("@dataset");-- cy.findByTestId("query-visualization-root").within(() => {- // All of these are implicit assertions and will fail if there's more than one string- cy.findByText("Count");- cy.findByText("Created At: Month");- cy.findByText("June 2025");- });+ H.cartesianChartCircle().should("have.length.greaterThan", 1);});});diff --git a/frontend/src/metabase/query_builder/components/view/sidebars/SummarizeSidebar/SummarizeSidebar.unit.spec.tsx b/frontend/src/metabase/query_builder/components/view/sidebars/SummarizeSidebar/SummarizeSidebar.unit.spec.tsxindex 8af2f71fa6b..b58b1fc427e 100644--- a/frontend/src/metabase/query_builder/components/view/sidebars/SummarizeSidebar/SummarizeSidebar.unit.spec.tsx+++ b/frontend/src/metabase/query_builder/components/view/sidebars/SummarizeSidebar/SummarizeSidebar.unit.spec.tsx@@ -1,6 +1,7 @@import userEvent from "@testing-library/user-event";import { useState } from "react";+import { createMockMetadata } from "__support__/metadata";import { setupDatabaseEndpoints } from "__support__/server-mocks";import {createMockQueryBuilderState,@@ -8,12 +9,18 @@ import {} from "__support__/state";import { renderWithProviders, screen, waitFor, within } from "__support__/ui";import * as Lib from "metabase-lib";-import { DEFAULT_TEST_QUERY, SAMPLE_PROVIDER } from "metabase-lib/test-helpers";+import {+ DEFAULT_TEST_QUERY,+ SAMPLE_PROVIDER,+ createMetadataProvider,+} from "metabase-lib/test-helpers";import { createMockCard } from "metabase-types/api/mocks";import {ORDERS,ORDERS_ID,+ createOrdersTable,createSampleDatabase,+ createSavedStructuredCard,} from "metabase-types/api/mocks/presets";import { SummarizeSidebar } from "./SummarizeSidebar";@@ -462,6 +469,69 @@ describe("SummarizeSidebar", () => {expect(getNextBreakouts()).toHaveLength(1);});+ it("should update the sort when changing the temporal bucket of a sorted breakout (metabase#16770)", async () => {+ const { onQueryChange } = await setup({+ query: Lib.createTestQuery(SAMPLE_PROVIDER, {+ stages: [+ {+ source: { type: "table", id: ORDERS_ID },+ aggregations: [{ type: "operator", operator: "count", args: [] }],+ breakouts: [{ type: "column", name: "CREATED_AT", unit: "month" }],+ orderBys: [{ type: "column", name: "CREATED_AT", unit: "month" }],+ },+ ],+ }),+ });++ const createdAt = within(getPinnedColumnList()).getByLabelText(+ "Created At",+ );+ await userEvent.click(within(createdAt).getByText("by month"));+ await userEvent.click(await screen.findByText("Year"));++ await waitFor(() => expect(onQueryChange).toHaveBeenCalled());+ const [nextQuery] = onQueryChange.mock.lastCall;+ expect(+ Lib.breakouts(nextQuery, -1).map(+ (breakout) => Lib.displayInfo(nextQuery, -1, breakout).displayName,+ ),+ ).toEqual(["Created At: Year"]);+ expect(+ Lib.orderBys(nextQuery, -1).map(+ (orderBy) => Lib.displayInfo(nextQuery, -1, orderBy).displayName,+ ),+ ).toEqual(["Created At: Year"]);+ });++ it("should offer all temporal buckets for a column of a saved question source (metabase#10441, metabase#11439)", async () => {+ const card = createSavedStructuredCard({+ id: 2,+ name: "11439",+ result_metadata: (createOrdersTable().fields ?? []).map((field) => ({+ ...field,+ field_ref: ["field", Number(field.id), null],+ })),+ });+ const provider = createMetadataProvider({+ metadata: createMockMetadata({+ databases: [createSampleDatabase()],+ questions: [card],+ }),+ });+ await setup({+ query: Lib.createTestQuery(provider, {+ stages: [{ source: { type: "card", id: card.id } }],+ }),+ });++ const [createdAt] = screen.getAllByLabelText("Created At");+ await userEvent.hover(createdAt);+ await userEvent.click(within(createdAt).getByText("by month"));+ await userEvent.click(await screen.findByText("More…"));++ expect(await screen.findByText("Hour of day")).toBeInTheDocument();+ });+it("should allow picking a binning strategy for breakout columns", async () => {const { getNextBreakouts } = await setup();diff --git a/frontend/src/metabase/query_builder/utils/viz-settings.unit.spec.ts b/frontend/src/metabase/query_builder/utils/viz-settings.unit.spec.tsindex a067ca6b1c8..2d45e09b2b9 100644--- a/frontend/src/metabase/query_builder/utils/viz-settings.unit.spec.ts+++ b/frontend/src/metabase/query_builder/utils/viz-settings.unit.spec.ts@@ -1,15 +1,26 @@import { createMockMetadata } from "__support__/metadata";import { registerVisualizations } from "metabase/visualizations/register";import { registerVisualization } from "metabase/viz-core";+import * as Lib from "metabase-lib";import Question from "metabase-lib/v1/Question";import type { VisualizationSettings } from "metabase-types/api";import {createMockCard,createMockSingleSeries,+ createMockTableColumnOrderSetting,} from "metabase-types/api/mocks";-import { createSampleDatabase } from "metabase-types/api/mocks/presets";+import {+ ORDERS,+ ORDERS_ID,+ SAMPLE_DB_ID,+ createAdHocCard,+ createSampleDatabase,+} from "metabase-types/api/mocks/presets";-import { getQuestionWithDefaultVisualizationSettings } from "./viz-settings";+import {+ getAdHocQuestionWithVizSettings,+ getQuestionWithDefaultVisualizationSettings,+} from "./viz-settings";registerVisualizations();@@ -70,3 +81,47 @@ describe("getQuestionWithDefaultVisualizationSettings", () => {});});});++describe("getAdHocQuestionWithVizSettings", () => {+ it("should sync table columns with the query of the current question (metabase#22382)", () => {+ const currentQuestion = new Question(+ createAdHocCard({+ dataset_query: {+ type: "query",+ database: SAMPLE_DB_ID,+ query: {+ "source-table": ORDERS_ID,+ aggregation: [["count"]],+ breakout: [+ ["field", ORDERS.CREATED_AT, { "temporal-unit": "month" }],+ ],+ },+ },+ visualization_settings: {+ "table.columns": [+ createMockTableColumnOrderSetting({+ name: "CREATED_AT",+ enabled: false,+ }),+ createMockTableColumnOrderSetting({ name: "count", enabled: true }),+ ],+ },+ }),+ METADATA,+ );+ const query = Lib.removeClause(+ currentQuestion.query(),+ -1,+ Lib.breakouts(currentQuestion.query(), -1)[0],+ );++ const question = getAdHocQuestionWithVizSettings({+ question: currentQuestion.setQuery(query),+ currentQuestion,+ });++ expect(question.settings()["table.columns"]).toEqual([+ { name: "count", enabled: true },+ ]);+ });+});diff --git a/frontend/src/metabase/querying/notebook/components/BreakoutStep/BreakoutStep.unit.spec.tsx b/frontend/src/metabase/querying/notebook/components/BreakoutStep/BreakoutStep.unit.spec.tsxindex 0d276d75989..eaf089d5b4b 100644--- a/frontend/src/metabase/querying/notebook/components/BreakoutStep/BreakoutStep.unit.spec.tsx+++ b/frontend/src/metabase/querying/notebook/components/BreakoutStep/BreakoutStep.unit.spec.tsx@@ -10,11 +10,17 @@ import {within,} from "__support__/ui";import * as Lib from "metabase-lib";-import { SAMPLE_PROVIDER } from "metabase-lib/test-helpers";+import {+ SAMPLE_PROVIDER,+ createMetadataProvider,+} from "metabase-lib/test-helpers";import Question from "metabase-lib/v1/Question";-import type { TemporalUnit } from "metabase-types/api";+import type { FieldReference, TemporalUnit } from "metabase-types/api";import {createMockCard,+ createMockField,+ createMockNativeDatasetQuery,+ createMockNativeQuery,createMockStructuredDatasetQuery,} from "metabase-types/api/mocks";import {@@ -23,6 +29,7 @@ import {createOrdersIdField,createOrdersTable,createSampleDatabase,+ createSavedNativeCard,} from "metabase-types/api/mocks/presets";import { DEFAULT_QUESTION, createMockNotebookStep } from "../../test-utils";@@ -146,6 +153,24 @@ function createQueryWithMultipleBreakoutsAndTemporalBucket() {});}+type NativeCardFieldOpts = {+ name: string;+ baseType: string;+};++function createNativeCardField({ name, baseType }: NativeCardFieldOpts) {+ const fieldRef: FieldReference = ["field", name, { "base-type": baseType }];+ // Native result columns have no field id; the column ref stands in for it.+ return createMockField({+ id: fieldRef,+ field_ref: fieldRef,+ name,+ display_name: name,+ base_type: baseType,+ effective_type: baseType,+ });+}+interface SetupOpts {step?: NotebookStep;readOnly?: boolean;@@ -541,6 +566,134 @@ describe("BreakoutStep", () => {});});+ describe("saved native question source", () => {+ const NATIVE_CARD = createSavedNativeCard({+ id: 2,+ name: "Native products",+ dataset_query: createMockNativeDatasetQuery({+ database: SAMPLE_DB_ID,+ native: createMockNativeQuery({ query: "select * from products" }),+ }),+ result_metadata: [+ createNativeCardField({ name: "ID", baseType: "type/BigInteger" }),+ createNativeCardField({+ name: "CREATED_AT",+ baseType: "type/DateTimeWithLocalTZ",+ }),+ ],+ });++ const NATIVE_CARD_PROVIDER = createMetadataProvider({+ metadata: createMockMetadata({+ databases: [createSampleDatabase()],+ questions: [NATIVE_CARD],+ }),+ });++ it("should not render duplicate temporal buckets (metabase#16327)", async () => {+ const query = Lib.createTestQuery(NATIVE_CARD_PROVIDER, {+ stages: [{ source: { type: "card", id: NATIVE_CARD.id } }],+ });+ setup({ step: createMockNotebookStep({ query }) });++ await userEvent.click(screen.getByText("Pick a column to group by"));+ const option = await screen.findByRole("option", { name: "CREATED_AT" });+ await userEvent.click(within(option).getByLabelText("Temporal bucket"));++ // userEvent.click closes the popover+ fireEvent.click(await screen.findByText("More…"));++ const itemNames = screen+ .getAllByRole("menuitem")+ .map((item) => item.textContent);+ expect(itemNames).toContain("Day");+ expect(itemNames).toContain("Hour of day");+ expect(new Set(itemNames).size).toBe(itemNames.length);+ });++ it("should keep the sort in sync when changing the temporal bucket of a breakout (metabase#17975)", async () => {+ const query = Lib.createTestQuery(NATIVE_CARD_PROVIDER, {+ stages: [+ {+ source: { type: "card", id: NATIVE_CARD.id },+ aggregations: [{ type: "operator", operator: "count", args: [] }],+ breakouts: [{ type: "column", name: "CREATED_AT", unit: "month" }],+ orderBys: [{ type: "column", name: "CREATED_AT", unit: "month" }],+ },+ ],+ });+ const { getNextQuery } = setup({+ step: createMockNotebookStep({ query }),+ });++ await userEvent.click(screen.getByText("CREATED_AT: Month"));+ const option = await screen.findByRole("option", { name: "CREATED_AT" });+ await userEvent.click(within(option).getByLabelText("Temporal bucket"));+ fireEvent.click(await screen.findByRole("menuitem", { name: "Quarter" }));++ const nextQuery = getNextQuery();+ const orderBys = Lib.orderBys(nextQuery, 0).map(+ (orderBy) => Lib.displayInfo(nextQuery, 0, orderBy).displayName,+ );+ expect(orderBys).toEqual(["CREATED_AT: Quarter"]);+ });++ it("should apply the default temporal bucket to a column of a joined native question (metabase#10441, metabase#18646)", async () => {+ const query = Lib.createTestQuery(NATIVE_CARD_PROVIDER, {+ stages: [+ {+ source: { type: "table", id: ORDERS_ID },+ joins: [+ {+ source: { type: "card", id: NATIVE_CARD.id },+ strategy: "left-join",+ conditions: [+ {+ operator: "=",+ left: { type: "column", name: "PRODUCT_ID" },+ right: { type: "column", name: "ID" },+ },+ ],+ },+ ],+ },+ ],+ });+ const { getNextQuery, getNextBreakouts } = setup({+ step: createMockNotebookStep({ query }),+ });++ await userEvent.click(screen.getByText("Pick a column to group by"));+ await userEvent.click(await screen.findByText("Native products"));+ const option = await screen.findByRole("option", {+ name: "Native products - Product → CREATED_AT",+ });+ expect(within(option).getByText("by month")).toBeInTheDocument();++ await userEvent.click(+ within(option).getByText("Native products - Product → CREATED_AT"),+ );+ expect(getNextBreakouts()).toMatchObject([+ { longDisplayName: "Native products - Product → CREATED_AT: Month" },+ ]);+ expect(Lib.toLegacyQuery(getNextQuery())).toMatchObject({+ query: {+ breakout: [+ [+ "field",+ "CREATED_AT",+ {+ "base-type": "type/DateTimeWithLocalTZ",+ "join-alias": "Native products - Product",+ "temporal-unit": "month",+ },+ ],+ ],+ },+ });+ });+ });+describe("metrics", () => {it("should allow selecting breakoutable columns", async () => {const question = DEFAULT_QUESTION.setType("metric");diff --git a/frontend/src/metabase/querying/viz-settings/utils/sync-viz-settings.unit.spec.tsx b/frontend/src/metabase/querying/viz-settings/utils/sync-viz-settings.unit.spec.tsxindex 1b90c817a9b..5113ad12043 100644--- a/frontend/src/metabase/querying/viz-settings/utils/sync-viz-settings.unit.spec.tsx+++ b/frontend/src/metabase/querying/viz-settings/utils/sync-viz-settings.unit.spec.tsx@@ -1,6 +1,6 @@import * as Lib from "metabase-lib";import { SAMPLE_METADATA, SAMPLE_PROVIDER } from "metabase-lib/test-helpers";-import type { Series } from "metabase-types/api";+import type { Series, TestBreakoutSpec } from "metabase-types/api";import {createMockCard,createMockColumn,@@ -552,6 +552,51 @@ describe("syncVizSettings", () => {describe("syncVizSettingsWithQuery", () => {describe("table.columns", () => {+ it("should not duplicate a hidden breakout column when it is removed and added again (metabase#22382)", () => {+ const createQuery = (breakouts: TestBreakoutSpec[]) =>+ Lib.createTestQuery(SAMPLE_PROVIDER, {+ stages: [+ {+ source: { type: "table", id: ORDERS_ID },+ aggregations: [{ type: "operator", operator: "count", args: [] }],+ breakouts,+ },+ ],+ });+ const queryWithBreakout = createQuery([+ { type: "column", name: "CREATED_AT", unit: "month" },+ ]);+ const queryWithoutBreakout = createQuery([]);+ const settingsWithHiddenBreakout = createMockVisualizationSettings({+ "table.columns": [+ createMockTableColumnOrderSetting({+ name: "CREATED_AT",+ enabled: false,+ }),+ createMockTableColumnOrderSetting({ name: "count", enabled: true }),+ ],+ });++ const settingsWithoutBreakout = syncVizSettingsWithQuery(+ settingsWithHiddenBreakout,+ queryWithoutBreakout,+ queryWithBreakout,+ );+ expect(settingsWithoutBreakout["table.columns"]).toEqual([+ { name: "count", enabled: true },+ ]);++ const settingsWithBreakout = syncVizSettingsWithQuery(+ settingsWithoutBreakout,+ queryWithBreakout,+ queryWithoutBreakout,+ );+ expect(settingsWithBreakout["table.columns"]).toEqual([+ { name: "count", enabled: true },+ { name: "CREATED_AT", enabled: true },+ ]);+ });+it("should handle adding new columns with column.name changes", () => {const oldQuery = Lib.createTestQuery(SAMPLE_PROVIDER, {stages: [