Skip to content

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

e2e2unit: Filters (#85744)

Nemanja Glumac1618d4c55c2c
diff --git a/e2e/test/scenarios/filters/filter.cy.spec.js b/e2e/test/scenarios/filters/filter.cy.spec.js
deleted file mode 100644
index a0373af8676..00000000000
--- a/e2e/test/scenarios/filters/filter.cy.spec.js
+++ /dev/null
@@ -1,803 +0,0 @@
-const { H } = cy;
-import { SAMPLE_DB_ID } from "e2e/support/cypress_data";
-import { SAMPLE_DATABASE } from "e2e/support/cypress_sample_database";
-
-const { ORDERS, ORDERS_ID, PRODUCTS, PRODUCTS_ID, REVIEWS, REVIEWS_ID } =
- SAMPLE_DATABASE;
-
-describe("scenarios > question > filter", () => {
- beforeEach(() => {
- H.restore();
- cy.signInAsAdmin();
- });
-
- it("should filter a joined table by 'Is not' filter (metabase#13534)", () => {
- H.openOrdersTable({ mode: "notebook" });
-
- H.join();
- H.joinTable("Products");
-
- H.filter({ mode: "notebook" });
- H.popover().within(() => {
- cy.findByText("Products").click();
- cy.findByText("Category").click();
- cy.findByText("Is").click();
- });
- cy.findByRole("menu").findByText("Is not").click();
- H.popover().within(() => {
- cy.findByText("Gizmo").click();
- cy.button("Add filter").click();
- });
- H.getNotebookStep("filter")
- .findByText("Products → Category is not Gizmo")
- .should("be.visible");
-
- H.visualize((response) => {
- expect(response.body.error).to.not.exist;
- });
-
- H.queryBuilderMain().within(() => {
- cy.contains("37.65").should("exist");
- cy.findByText("3621077291879").should("not.exist"); // one of the "Gizmo" EANs
- });
-
- H.summarize();
- H.rightSidebar().button("Done").click();
- cy.wait("@dataset");
- H.queryBuilderMain()
- .findByTestId("scalar-value")
- .should("have.text", "13,976");
- });
-
- it("should filter based on remapped values (metabase#13235)", () => {
- // set "Filtering on this field" = "A list of all values"
- cy.request("PUT", `/api/field/${ORDERS.PRODUCT_ID}`, {
- has_field_values: "list",
- });
- // "Display values" = "Use foreign key" as `Product.Title`
- cy.request("POST", `/api/field/${ORDERS.PRODUCT_ID}/dimension`, {
- name: "Product ID",
- type: "external",
- human_readable_field_id: PRODUCTS.TITLE,
- });
-
- // Add filter as remapped Product ID (Product name)
- H.openOrdersTable();
- H.filter();
- H.popover().within(() => {
- cy.findByText("Product ID").click();
- cy.findByText("Aerodynamic Linen Coat").click();
- cy.button("Apply filter").click();
- });
-
- cy.log("Reported failing on v0.36.4 and v0.36.5.1");
- cy.findByTestId("loading-indicator").should("not.exist");
- cy.findAllByText("148.23"); // one of the subtotals for this product
- cy.findAllByText("Fantastic Wool Shirt").should("not.exist");
- });
-
- it("should not drop aggregated filters (metabase#11957)", () => {
- const AGGREGATED_FILTER = "Count is less than or equal to 20";
-
- H.createQuestion(
- {
- name: "11957",
- query: {
- "source-query": {
- "source-table": ORDERS_ID,
- filter: [">", ["field", ORDERS.CREATED_AT, null], "2029-01-01"],
- aggregation: [["count"]],
- breakout: [
- ["field", ORDERS.CREATED_AT, { "temporal-unit": "day" }],
- ],
- },
- filter: [
- "<=",
- ["field", "count", { "base-type": "type/Integer" }],
- 20,
- ],
- },
- },
- { visitQuestion: true },
- );
-
- // Test shows two filter collapsed - click on number 2 to expand and show filter names
- cy.findByTestId("filters-visibility-control")
- .should("have.text", "2")
- .click();
-
- // eslint-disable-next-line metabase/no-unscoped-text-selectors -- deprecated usage
- cy.findByText(AGGREGATED_FILTER);
-
- cy.intercept("POST", "/api/dataset").as("dataset");
- // eslint-disable-next-line metabase/no-unscoped-text-selectors -- deprecated usage
- cy.findByText(/^Created At is after/i)
- .find(".Icon-close")
- .click();
- cy.wait("@dataset");
-
- cy.log(
- "**Removing or changing filters shouldn't remove aggregated filter**",
- );
- // eslint-disable-next-line metabase/no-unscoped-text-selectors -- deprecated usage
- cy.findByText(AGGREGATED_FILTER).should("exist");
- // eslint-disable-next-line metabase/no-unscoped-text-selectors -- deprecated usage
- cy.findByText(/^Created At is after/i).should("not.exist");
- });
-
- it("should display original custom expression filter with dates on subsequent click (metabase#12492)", () => {
- H.visitQuestionAdhoc({
- dataset_query: {
- type: "query",
- query: {
- "source-table": ORDERS_ID,
- filter: [
- ">",
- ["field", ORDERS.CREATED_AT, null],
- [
- "field",
- PRODUCTS.CREATED_AT,
- { "source-field": ORDERS.PRODUCT_ID },
- ],
- ],
- },
- database: SAMPLE_DB_ID,
- },
- display: "table",
- });
-
- cy.findByTestId("qb-filters-panel")
- .findByText("Created At is greater than Product → Created At")
- .click();
-
- H.popover()
- .contains("[Created At] > [Product → Created At]")
- .should("be.visible");
- });
-
- it("should reject Enter when the filter expression is invalid", () => {
- H.openReviewsTable({ mode: "notebook" });
- H.filter({ mode: "notebook" });
- // eslint-disable-next-line metabase/no-unscoped-text-selectors -- deprecated usage
- cy.findByText("Custom Expression").click();
-
- H.enterCustomColumnDetails({ formula: "[Rating] > 2E{enter}" }); // there should numbers after 'E'
-
- // eslint-disable-next-line metabase/no-unscoped-text-selectors -- deprecated usage
- cy.findByText("Missing exponent");
- // eslint-disable-next-line metabase/no-unscoped-text-selectors -- deprecated usage
- cy.findByText("Rating is greater than 2").should("not.exist");
- });
-
- it("should offer case in the suggestions and highlight them with keyboard up and down arrows (metabase#16210)", () => {
- openExpressionEditorFromFreshlyLoadedPage();
-
- H.enterCustomColumnDetails({ formula: "c", blur: false });
-
- H.CustomExpressionEditor.completions().should("contain", "case");
- H.CustomExpressionEditor.completion("case")
- .parent()
- .should("have.attr", "aria-selected", "true");
-
- // Avoid flakiness caused by CodeMirror not accepting the keypress
- // immediately
- cy.wait(200);
- cy.realPress("ArrowDown");
-
- H.CustomExpressionEditor.completion("ceil")
- .parent()
- .should("have.attr", "aria-selected", "true");
-
- H.CustomExpressionEditor.completion("case")
- .parent()
- .should("have.attr", "aria-selected", "false");
-
- H.CustomExpressionEditor.type("a");
-
- // "case" is still there after typing a bit
- H.CustomExpressionEditor.completions().should("contain", "case");
- });
-
- it("should highlight the correct matching for suggestions", () => {
- openExpressionEditorFromFreshlyLoadedPage();
-
- H.enterCustomColumnDetails({ formula: "[B", blur: false });
-
- H.CustomExpressionEditor.completion("Body").should("be.visible");
-
- H.CustomExpressionEditor.type("{backspace}p", { focus: false });
-
- H.CustomExpressionEditor.completion("Product ID").should("be.visible");
- H.CustomExpressionEditor.completion("Product ID")
- .findByText("P")
- .should("be.visible");
- H.CustomExpressionEditor.completion("Product ID")
- .findByText("roduct ID")
- .should("be.visible");
- });
-
- it("should provide accurate auto-complete custom-expression suggestions based on the aggregated column name (metabase#14776)", () => {
- cy.viewport(1400, 1000); // We need a bit taller window for this repro to see all custom filter options in the popover
- H.createQuestion({
- name: "14776",
- query: {
- "source-table": ORDERS_ID,
- aggregation: [["sum", ["field", ORDERS.TOTAL, null]]],
- breakout: [["field", ORDERS.CREATED_AT, { "temporal-unit": "month" }]],
- },
- }).then(({ body: { id: QUESTION_ID } }) => {
- cy.visit(`/question/${QUESTION_ID}/notebook`);
- });
- // eslint-disable-next-line metabase/no-unscoped-text-selectors -- deprecated usage
- cy.findByText("Filter").click();
- // eslint-disable-next-line metabase/no-unscoped-text-selectors -- deprecated usage
- cy.findByText("Custom Expression").click();
- H.enterCustomColumnDetails({ formula: "[su", blur: false });
-
- H.CustomExpressionEditor.completion("Sum of Total").should("be.visible");
-
- H.CustomExpressionEditor.type("m", { focus: false });
-
- H.CustomExpressionEditor.completion("Sum of Total").should("be.visible");
- });
-
- it("should filter using IsNull() and IsEmpty()", () => {
- H.openReviewsTable({ mode: "notebook" });
- H.filter({ mode: "notebook" });
- // eslint-disable-next-line metabase/no-unscoped-text-selectors -- deprecated usage
- cy.findByText("Custom Expression").click();
-
- H.enterCustomColumnDetails({ formula: "NOT IsNull([Rating])" });
-
- cy.button("Done").should("not.be.disabled").click();
-
- cy.findByTestId("query-builder-root").icon("add").click();
-
- // eslint-disable-next-line metabase/no-unscoped-text-selectors -- deprecated usage
- cy.findByText("Custom Expression").click();
-
- H.enterCustomColumnDetails({
- formula: "NOT IsEmpty([Reviewer])",
- });
-
- cy.button("Done").should("not.be.disabled").click();
-
- H.getNotebookStep("filter").within(() => {
- cy.findByText(/Rating/).should("be.visible");
- cy.findByText(/Reviewer/).should("be.visible");
- });
-
- // check that filter is applied and rows displayed
- H.visualize();
- H.assertQueryBuilderRowCount(1112);
- });
-
- it("should convert 'is empty' on a text column to a custom expression using IsEmpty()", () => {
- H.openReviewsTable();
- H.tableHeaderClick("Reviewer");
- // eslint-disable-next-line metabase/no-unscoped-text-selectors -- deprecated usage
- cy.findByText("Filter by this column").click();
- H.selectFilterOperator("Is empty");
- // eslint-disable-next-line metabase/no-unscoped-text-selectors -- deprecated usage
- cy.findByText("Add filter").click();
-
- // filter out everything
- // eslint-disable-next-line metabase/no-unscoped-text-selectors -- deprecated usage
- cy.contains("Showing 0 rows");
-
- // change the corresponding custom expression
- // eslint-disable-next-line metabase/no-unscoped-text-selectors -- deprecated usage
- cy.findByText("Reviewer is empty").click();
- cy.get(".Icon-chevronleft").click();
- // eslint-disable-next-line metabase/no-unscoped-text-selectors -- deprecated usage
- cy.findByText("Custom Expression").click();
- // eslint-disable-next-line metabase/no-unscoped-text-selectors -- deprecated usage
- cy.contains("isEmpty([Reviewer])");
- H.CustomExpressionEditor.clear().type("NOT IsEmpty([Reviewer])").blur();
-
- cy.button("Update").click();
- // eslint-disable-next-line metabase/no-unscoped-text-selectors -- deprecated usage
- cy.contains("Showing 1,112 rows");
- });
-
- it("should convert 'is empty' on a numeric column to a custom expression using IsNull()", () => {
- H.openReviewsTable();
- H.tableHeaderClick("Rating");
- // eslint-disable-next-line metabase/no-unscoped-text-selectors -- deprecated usage
- cy.findByText("Filter by this column").click();
- H.selectFilterOperator("Is empty");
- // eslint-disable-next-line metabase/no-unscoped-text-selectors -- deprecated usage
- cy.findByText("Add filter").click();
-
- // filter out everything
- // eslint-disable-next-line metabase/no-unscoped-text-selectors -- deprecated usage
- cy.contains("Showing 0 rows");
-
- // change the corresponding custom expression
- // eslint-disable-next-line metabase/no-unscoped-text-selectors -- deprecated usage
- cy.findByText("Rating is empty").click();
- cy.get(".Icon-chevronleft").click();
- // eslint-disable-next-line metabase/no-unscoped-text-selectors -- deprecated usage
- cy.findByText("Custom Expression").click();
- // eslint-disable-next-line metabase/no-unscoped-text-selectors -- deprecated usage
- cy.contains("isNull([Rating])");
- H.CustomExpressionEditor.clear()
- .type("NOT IsNull([Rating])", { delay: 50 })
- .blur();
- cy.button("Update").should("not.be.disabled").click();
- // eslint-disable-next-line metabase/no-unscoped-text-selectors -- deprecated usage
- cy.contains("Showing 1,112 rows");
- });
-
- it("should convert negative filter to custom expression (metabase#14880)", () => {
- H.visitQuestionAdhoc({
- dataset_query: {
- type: "query",
- query: {
- "source-table": PRODUCTS_ID,
- filter: [
- "does-not-contain",
- ["field", PRODUCTS.TITLE, null],
- "Wallet",
- { "case-sensitive": false },
- ],
- },
- database: SAMPLE_DB_ID,
- },
- display: "table",
- });
-
- // eslint-disable-next-line metabase/no-unscoped-text-selectors -- deprecated usage
- cy.findByText("Title does not contain Wallet").click();
- cy.get(".Icon-chevronleft").click();
- // eslint-disable-next-line metabase/no-unscoped-text-selectors -- deprecated usage
- cy.findByText("Custom Expression").click();
- // eslint-disable-next-line metabase/no-unscoped-text-selectors -- deprecated usage
- cy.contains('doesNotContain([Title], "Wallet", "case-insensitive")');
- });
-
- it("should be able to convert time interval filter to custom expression (metabase#12457)", () => {
- H.openOrdersTable({ mode: "notebook" });
-
- H.filter({ mode: "notebook" });
- H.popover().within(() => {
- cy.findByText("Created At").click();
- cy.findByText("Relative date range…").click();
- cy.findByText("Previous").click();
- cy.findByLabelText(/^Include/).click();
- cy.button("Add filter").click();
- });
-
- H.getNotebookStep("filter")
- .findByText("Created At is in the previous 30 days or today")
- .click();
-
- H.clauseStepPopover().within(() => {
- cy.button("Back").click();
- cy.button("Back").click();
- cy.findByText("Custom Expression").click();
- cy.button("Update").click();
- });
-
- // Back to GUI and "Include today" should be still checked
- H.getNotebookStep("filter")
- .findByText("Created At is in the previous 30 days or today")
- .click();
-
- H.popover()
- .findByTestId("include-current-interval-option")
- .should("have.attr", "aria-checked", "true");
- });
-
- it("should be able to convert case-insensitive filter to custom expression (metabase#14959)", () => {
- H.visitQuestionAdhoc({
- dataset_query: {
- type: "query",
- query: {
- "source-table": REVIEWS_ID,
- filter: [
- "contains",
- ["field", REVIEWS.REVIEWER, null],
- "MULLER",
- { "case-sensitive": false },
- ],
- },
- database: SAMPLE_DB_ID,
- },
- display: "table",
- });
-
- // eslint-disable-next-line metabase/no-unscoped-text-selectors -- deprecated usage
- cy.findByText("wilma-muller");
- // eslint-disable-next-line metabase/no-unscoped-text-selectors -- deprecated usage
- cy.findByText("Reviewer contains MULLER").click();
- cy.get(".Icon-chevronleft").click();
- // eslint-disable-next-line metabase/no-unscoped-text-selectors -- deprecated usage
- cy.findByText("Custom Expression").click();
- // eslint-disable-next-line metabase/no-unscoped-text-selectors -- deprecated usage
- cy.contains('contains([Reviewer], "MULLER", "case-insensitive")');
- cy.button("Update").click();
- cy.wait("@dataset").then((xhr) => {
- expect(xhr.response.body.data.rows).to.have.lengthOf(1);
- });
- // eslint-disable-next-line metabase/no-unscoped-text-selectors -- deprecated usage
- cy.findByText("wilma-muller");
- });
-
- it("should reject number and string literals", () => {
- H.openProductsTable({ mode: "notebook" });
- H.filter({ mode: "notebook" });
- H.popover().findByText("Custom Expression").click();
- H.enterCustomColumnDetails({ formula: "3.14159" });
- H.popover().within(() => {
- cy.button("Done").should("be.disabled");
- cy.findByText("Types are incompatible.").should("be.visible");
- });
-
- H.enterCustomColumnDetails({ formula: "[Price] > 1" });
- H.popover().within(() => {
- cy.button("Done").should("be.enabled");
- cy.findByText("Types are incompatible.").should("not.exist");
- });
-
- H.enterCustomColumnDetails({ formula: '"TheAnswer"' });
- H.popover().within(() => {
- cy.button("Done").should("be.disabled");
- cy.findByText("Types are incompatible.").should("be.visible");
- });
- });
-
- it("custom expression filter should reference fields by their name, not by their id (metabase#15748)", () => {
- H.openOrdersTable({ mode: "notebook" });
-
- H.filter({ mode: "notebook" });
- H.popover().within(() => {
- cy.findByText("Custom Expression").click();
- H.enterCustomColumnDetails({ formula: "[Total] < [Subtotal]" });
- cy.button("Done").click();
- });
-
- H.getNotebookStep("filter")
- .findByText("Total is less than Subtotal")
- .should("be.visible");
- });
-
- it("custom expression filter should allow parentheses with logical operators and refuse a numeric value before an operator (metabase#15754, metabase#15893)", () => {
- H.openOrdersTable({ mode: "notebook" });
-
- H.filter({ mode: "notebook" });
- H.popover().findByText("Custom Expression").click();
-
- H.CustomExpressionEditor.focus()
- .type("([ID] > 2 OR [Subtotal] = 100) and [Tax] < 4")
- .blur();
-
- H.expressionEditorWidget()
- .findByText(/^Expected closing parenthesis but found/)
- .should("not.exist");
-
- H.expressionEditorWidget().button("Done").should("not.be.disabled");
-
- cy.log("should refuse a numeric value before an operator (metabase#15893)");
- H.CustomExpressionEditor.clear();
- H.CustomExpressionEditor.focus().type("0 < [ID]").blur();
-
- H.expressionEditorWidget()
- .findByText("Expecting field but found 0")
- .should("be.visible");
-
- H.expressionEditorWidget().button("Done").should("be.disabled");
- });
-
- it("should allow choosing a suggestion with Tab", () => {
- H.openOrdersTable({ mode: "notebook" });
-
- H.filter({ mode: "notebook" });
- H.popover().findByText("Custom Expression").click();
-
- // Try to auto-complete Tax
- H.CustomExpressionEditor.focus().type("[Ta");
-
- // Suggestion popover shows up and this select the first one ([Tax])
- H.CustomExpressionEditor.acceptCompletion("tab");
-
- // Focus remains on the expression editor
- cy.focused().should("have.attr", "role", "textbox");
-
- // Finish to complete a valid expression, i.e. [Tax] > 42
- H.CustomExpressionEditor.type("> 42");
-
- // Tab indents instead of moving the focus
- cy.realPress("Tab");
-
- cy.focused().should("have.attr", "role", "textbox");
- H.CustomExpressionEditor.value().should("equal", "[Tax]> 42 ");
- });
-
- it("should allow hiding the suggestion list with Escape", () => {
- H.openOrdersTable({ mode: "notebook" });
- H.filter({ mode: "notebook" });
- // eslint-disable-next-line metabase/no-unscoped-text-selectors -- deprecated usage
- cy.findByText("Custom Expression").click();
-
- // Try to auto-complete Tax
- H.CustomExpressionEditor.focus().type("Disc");
-
- H.CustomExpressionEditor.completions().should("be.visible");
-
- // Esc closes the suggestion popover
- cy.realPress("Escape");
-
- H.CustomExpressionEditor.completions().should("not.be.visible");
- });
-
- it("should work on twice summarized questions and preserve both summaries (metabase#15620)", () => {
- H.visitQuestionAdhoc({
- dataset_query: {
- database: SAMPLE_DB_ID,
- type: "query",
- query: {
- "source-query": {
- "source-table": PRODUCTS_ID,
- aggregation: [["count"]],
- breakout: [
- ["field", PRODUCTS.CREATED_AT, { "temporal-unit": "month" }],
- ],
- },
- aggregation: [
- ["avg", ["field", "count", { "base-type": "type/Integer" }]],
- ],
- },
- },
- });
-
- cy.findByTestId("scalar-value").contains("5.41");
- H.filter();
- H.popover().within(() => {
- cy.findByText("Category").click();
- cy.findByText("Gizmo").click();
- cy.button("Apply filter").click();
- });
- H.openNotebook();
-
- H.verifyNotebookQuery("Products", [
- {
- filters: ["Category is Gizmo"],
- aggregations: ["Count"],
- breakouts: ["Created At: Month"],
- },
- {
- aggregations: ["Average of Count"],
- },
- ]);
- });
-
- it("user shouldn't need to scroll to add filter (metabase#14307)", () => {
- cy.viewport(1280, 720);
- H.openPeopleTable({ mode: "notebook" });
- H.filter({ mode: "notebook" });
- H.popover().findByText("State").click({ force: true });
- // eslint-disable-next-line metabase/no-unscoped-text-selectors -- deprecated usage
- cy.findByText("AL").click();
- cy.button("Add filter").isVisibleInPopover();
- });
-
- it("should retain all data series after saving a question where custom expression formula is the first metric (metabase#15882)", () => {
- H.visitQuestionAdhoc({
- dataset_query: {
- database: SAMPLE_DB_ID,
- query: {
- "source-table": ORDERS_ID,
- aggregation: [
- [
- "aggregation-options",
- [
- "/",
- ["sum", ["field", ORDERS.DISCOUNT, null]],
- ["sum", ["field", ORDERS.SUBTOTAL, null]],
- ],
- { "display-name": "Discount %" },
- ],
- ["count"],
- ["avg", ["field", ORDERS.TOTAL, null]],
- ],
- breakout: [
- ["field", ORDERS.CREATED_AT, { "temporal-unit": "month" }],
- ],
- },
- type: "query",
- },
- display: "line",
- });
-
- assertOnLegendLabels();
- H.cartesianChartCircleWithColors(["#88BF4D", "#509EE3", "#A989C5"]);
- // eslint-disable-next-line metabase/no-unscoped-text-selectors -- deprecated usage
- cy.findByText("Save").click();
- cy.findByTestId("save-question-modal")
- .findByLabelText(/Where do you want to save this/)
- .click();
- H.pickEntity({
- path: ["Our analytics"],
- });
- H.entityPickerModal().findByText("Select this collection").click();
- cy.findByTestId("save-question-modal").button("Save").click();
-
- assertOnLegendLabels();
-
- H.cartesianChartCircleWithColors(["#88BF4D", "#509EE3", "#A989C5"]);
-
- function assertOnLegendLabels() {
- cy.findAllByTestId("legend-item")
- .should("contain", "Discount %")
- .and("contain", "Count")
- .and("contain", "Average of Total");
- }
- });
-
- describe("specific combination of filters can cause frontend reload or blank screen (metabase#16198)", () => {
- it("shouldn't display chosen category in a breadcrumb (metabase#16198-1)", () => {
- const chosenCategory = "Gizmo";
-
- H.visitQuestionAdhoc({
- dataset_query: {
- database: SAMPLE_DB_ID,
- query: {
- "source-table": PRODUCTS_ID,
- filter: [
- "and",
- ["=", ["field", PRODUCTS.CATEGORY, null], chosenCategory],
- ["=", ["field", PRODUCTS.ID, null], 1],
- ],
- },
- type: "query",
- },
- });
-
- cy.findByTestId("head-crumbs-container").should(
- "not.contain",
- chosenCategory,
- );
- });
-
- it("adding an ID filter shouldn't cause page error and page reload (metabase#16198-2)", () => {
- H.openOrdersTable({ mode: "notebook" });
- H.filter({ mode: "notebook" });
- // eslint-disable-next-line metabase/no-unscoped-text-selectors -- deprecated usage
- cy.findByText("Custom Expression").click();
- H.CustomExpressionEditor.type("[Total] < [Product → Price]").blur();
- H.CustomExpressionEditor.format();
- cy.button("Done").click();
- // Filter currently says "Total is less than..." but it can change in https://github.com/metabase/metabase/pull/16174 to "Total < Price"
- // See: https://github.com/metabase/metabase/pull/16209#discussion_r638129099
- // eslint-disable-next-line metabase/no-unscoped-text-selectors -- deprecated usage
- cy.findByText(/^Total/);
- // eslint-disable-next-line metabase/no-unsafe-element-filtering
- cy.icon("add").last().click();
- H.popover().findByText(/^ID$/i).click();
- cy.findByPlaceholderText("Enter an ID").type("1");
- cy.button("Add filter").click();
- // eslint-disable-next-line metabase/no-unscoped-text-selectors -- deprecated usage
- cy.findByText(/^Total/);
- // eslint-disable-next-line metabase/no-unscoped-text-selectors -- deprecated usage
- cy.findByText("Something went wrong").should("not.exist");
- });
-
- it("removing first filter in a sequence shouldn't result in an empty page (metabase#16198-3)", () => {
- H.openOrdersTable({ mode: "notebook" });
-
- H.filter({ mode: "notebook" });
- H.clauseStepPopover().findByText("Total").click();
- H.selectFilterOperator("Equal to");
- H.clauseStepPopover().within(() => {
- cy.findByPlaceholderText("Enter a number").type("123");
- cy.button("Add filter").click();
- });
-
- H.getNotebookStep("filter").icon("add").click();
-
- H.clauseStepPopover().within(() => {
- cy.findByText("Custom Expression").click();
- H.CustomExpressionEditor.type("[Total] < [Product → Price]", {
- allowFastSet: true,
- }).blur();
- cy.button("Done").click();
- });
-
- // eslint-disable-next-line metabase/no-unsafe-element-filtering
- cy.icon("add").last().click();
- H.clauseStepPopover().findByText(/^ID$/i).click();
- cy.findByPlaceholderText("Enter an ID").type("1");
- cy.button("Add filter").click();
- // eslint-disable-next-line metabase/no-unscoped-text-selectors -- deprecated usage
- cy.findByText("Total is equal to 123")
- .parent()
- .find(".Icon-close")
- .click();
-
- H.getNotebookStep("filter").within(() => {
- cy.findByText("Total is equal to 123").should("not.exist");
- cy.findByText(/^Total is less than/).should("be.visible");
- cy.findByText("ID is 1").should("be.visible");
- });
-
- H.visualize((response) => {
- expect(response.body.error).to.not.exist;
- });
- });
- });
-
- it("should close the dropdown but not the popover on escape when the combobox is opened", () => {
- const optionName = "Abbey Satterfield";
- H.openPeopleTable({ mode: "notebook" });
- H.filter({ mode: "notebook" });
- H.popover().within(() => {
- cy.findByText("Name").click();
- cy.findByLabelText("Filter value").type("ab");
- cy.findByRole("option", { name: optionName }).should("be.visible");
-
- cy.findByLabelText("Filter value").type("{esc}");
- cy.findByRole("option", { name: optionName }).should("not.exist");
- cy.findByLabelText("Filter value").should("be.visible");
- });
- });
-
- it("should render the selected item in view", () => {
- cy.viewport(1280, 320);
- H.openReviewsTable({ mode: "notebook" });
- H.filter({ mode: "notebook" });
-
- cy.realPress("ArrowDown");
- cy.realPress("ArrowDown");
- cy.realPress("ArrowDown");
- cy.realPress("ArrowDown");
- cy.realPress("ArrowDown");
- cy.realPress("ArrowDown");
- cy.realPress("ArrowDown");
-
- H.popover()
- .findByRole("tree")
- .then((el) => {
- cy.wrap(el[0].scrollTop).should("be.greaterThan", 0);
- });
-
- H.popover().findByText("Created At").should("be.visible");
- });
-
- it("should allow picking custom expressions in filter picker", () => {
- H.openOrdersTable({ mode: "notebook" });
- H.filter({ mode: "notebook" });
- H.popover().within(() => {
- cy.findByPlaceholderText("Find...").clear().type("coalesce");
- cy.findByText("Custom Expressions").should("be.visible");
- cy.findByText("coalesce").should("be.visible").click();
-
- H.CustomExpressionEditor.value().should(
- "equal",
- "coalesce(value1, value2)",
- );
- });
- });
-
- it("should allow selecting custom expressions in filter picker with (", () => {
- H.openOrdersTable({ mode: "notebook" });
- H.filter({ mode: "notebook" });
- H.popover().within(() => {
- cy.log("typing a non-existing clause does nothing");
- cy.findByPlaceholderText("Find...").clear().type("foo(");
- H.CustomExpressionEditor.get().should("not.exist");
-
- cy.findByPlaceholderText("Find...").clear().type("case(");
- H.CustomExpressionEditor.value().should(
- "equal",
- "case(condition, output)",
- );
- });
- });
-});
-
-function openExpressionEditorFromFreshlyLoadedPage() {
- H.openReviewsTable({ mode: "notebook" });
- H.filter({ mode: "notebook" });
- cy.findByText("Custom Expression").click();
-}
diff --git a/e2e/test/scenarios/filters/filter.cy.spec.ts b/e2e/test/scenarios/filters/filter.cy.spec.ts
new file mode 100644
index 00000000000..a72c299bf59
--- /dev/null
+++ b/e2e/test/scenarios/filters/filter.cy.spec.ts
@@ -0,0 +1,1045 @@
+import {
+ SAMPLE_DB_ID,
+ SAMPLE_DB_SCHEMA_ID,
+ WRITABLE_DB_ID,
+} from "e2e/support/cypress_data";
+import { SAMPLE_DATABASE } from "e2e/support/cypress_sample_database";
+
+const { H } = cy;
+
+const {
+ ORDERS,
+ ORDERS_ID,
+ PRODUCTS,
+ PRODUCTS_ID,
+ PEOPLE,
+ PEOPLE_ID,
+ REVIEWS,
+ REVIEWS_ID,
+} = SAMPLE_DATABASE;
+
+describe("scenarios > filters", () => {
+ beforeEach(() => {
+ H.restore();
+ cy.signInAsAdmin();
+ });
+
+ it("should filter a joined, summarized question before and after the aggregation (metabase#13534, metabase#11957, metabase#24994)", () => {
+ H.visitQuestionAdhoc({
+ dataset_query: {
+ database: SAMPLE_DB_ID,
+ type: "query",
+ query: {
+ "source-table": ORDERS_ID,
+ joins: [
+ {
+ fields: "all",
+ alias: "Products",
+ "source-table": PRODUCTS_ID,
+ condition: [
+ "=",
+ ["field", ORDERS.PRODUCT_ID, null],
+ ["field", PRODUCTS.ID, { "join-alias": "Products" }],
+ ],
+ },
+ ],
+ aggregation: [["count"]],
+ breakout: [
+ ["field", PRODUCTS.CATEGORY, { "join-alias": "Products" }],
+ ],
+ },
+ },
+ display: "table",
+ });
+ H.assertQueryBuilderRowCount(4);
+
+ cy.log("filter the joined column before the aggregation");
+ H.filter();
+ H.popover().within(() => {
+ cy.findByText("Products").click();
+ cy.findByText("Category").click();
+ cy.findByText("Is").click();
+ });
+ cy.findByRole("menu").findByText("Is not").click();
+ H.popover().within(() => {
+ cy.findByText("Gizmo").click();
+ cy.button("Apply filter").click();
+ });
+ H.queryBuilderFiltersPanel()
+ .findByText("Products → Category is not Gizmo")
+ .should("be.visible");
+ H.assertQueryBuilderRowCount(3);
+ H.tableInteractiveBody().within(() => {
+ cy.findByText("3,976").should("be.visible"); // Doohickey
+ cy.findByText("4,939").should("be.visible"); // Gadget
+ cy.findByText("5,061").should("be.visible"); // Widget
+ cy.findByText("Gizmo").should("not.exist");
+ });
+
+ cy.log("filter the aggregation, in a new stage");
+ H.filter();
+ H.popover().within(() => {
+ cy.findByText("Summaries").click();
+ cy.findByText("Count").click();
+ });
+ H.selectFilterOperator("Greater than");
+ H.popover().within(() => {
+ cy.findByPlaceholderText("Enter a number").type("4000");
+ cy.button("Apply filter").click();
+ });
+ H.queryBuilderFiltersPanel()
+ .findByText(/^Count is greater than 4,?000$/)
+ .should("be.visible");
+ H.assertQueryBuilderRowCount(2);
+ H.tableInteractiveBody().findByText("Doohickey").should("not.exist");
+
+ cy.log(
+ "edit the first-stage filter of a question with an aggregation filter",
+ );
+ H.queryBuilderFiltersPanel()
+ .findByText("Products → Category is not Gizmo")
+ .click();
+ H.popover().within(() => {
+ cy.findByRole("checkbox", { name: "Gizmo" }).should("be.checked");
+ cy.findByText("Widget").click();
+ cy.button("Update filter").click();
+ });
+ H.queryBuilderFiltersPanel()
+ .findByText("Products → Category is not 2 selections")
+ .should("be.visible");
+ H.assertQueryBuilderRowCount(1);
+ H.tableInteractiveBody().findByText("Gadget").should("be.visible");
+
+ cy.log("removing the first-stage filter keeps the aggregation filter");
+ H.queryBuilderFiltersPanel()
+ .findByText("Products → Category is not 2 selections")
+ .icon("close")
+ .click();
+ H.queryBuilderFiltersPanel().within(() => {
+ cy.findByText(/^Count is greater than 4,?000$/).should("be.visible");
+ cy.findByText("Products → Category is not 2 selections").should(
+ "not.exist",
+ );
+ });
+ H.assertQueryBuilderRowCount(3);
+ H.tableInteractiveBody().within(() => {
+ cy.findByText("4,784").should("be.visible"); // Gizmo
+ cy.findByText("Doohickey").should("not.exist");
+ });
+
+ cy.log("filter the aggregation from its column header");
+ H.tableHeaderClick("Count");
+ H.popover().findByText("Filter by this column").click();
+ H.selectFilterOperator("Equal to");
+ H.clickActionsPopover().within(() => {
+ cy.findByPlaceholderText("Enter a number").type("4939");
+ cy.realPress("Tab");
+ cy.button("Add filter").should("be.enabled").click();
+ });
+ H.queryBuilderFiltersPanel()
+ .findByText(/^Count is equal to 4,?939$/)
+ .should("be.visible");
+ H.assertQueryBuilderRowCount(1);
+ H.tableInteractiveBody().findByText("Gadget").should("be.visible");
+ });
+
+ it("should filter an aggregation from its column header on a question with one stage (metabase#30312)", () => {
+ H.createQuestion(
+ {
+ query: {
+ "source-table": ORDERS_ID,
+ aggregation: [["count"]],
+ breakout: [
+ [
+ "field",
+ ORDERS.CREATED_AT,
+ { "base-type": "type/DateTime", "temporal-unit": "month" },
+ ],
+ ],
+ limit: 5,
+ },
+ display: "table",
+ },
+ { visitQuestion: true },
+ );
+
+ H.tableHeaderClick("Count");
+ H.popover().findByText("Filter by this column").click();
+ H.selectFilterOperator("Equal to");
+ H.clickActionsPopover().within(() => {
+ cy.findByPlaceholderText("Enter a number").type("10");
+ cy.realPress("Tab");
+ cy.button("Add filter").should("be.enabled").click();
+ });
+
+ H.queryBuilderFiltersPanel()
+ .findByTestId("filter-pill")
+ .should("have.text", "Count is equal to 10");
+ H.queryBuilderMain().findByText("No results").should("be.visible");
+ });
+
+ it("should add a filter to the first stage of a question summarized twice (metabase#15620)", () => {
+ H.visitQuestionAdhoc({
+ dataset_query: {
+ database: SAMPLE_DB_ID,
+ type: "query",
+ query: {
+ "source-query": {
+ "source-table": PRODUCTS_ID,
+ aggregation: [["count"]],
+ breakout: [
+ ["field", PRODUCTS.CREATED_AT, { "temporal-unit": "month" }],
+ ],
+ },
+ aggregation: [
+ ["avg", ["field", "count", { "base-type": "type/Integer" }]],
+ ],
+ },
+ },
+ });
+
+ cy.findByTestId("scalar-value").contains("5.41");
+ H.filter();
+ H.popover().within(() => {
+ cy.findByText("Category").click();
+ cy.findByText("Gizmo").click();
+ cy.button("Apply filter").click();
+ });
+ H.openNotebook();
+
+ H.verifyNotebookQuery("Products", [
+ {
+ filters: ["Category is Gizmo"],
+ aggregations: ["Count"],
+ breakouts: ["Created At: Month"],
+ },
+ {
+ aggregations: ["Average of Count"],
+ },
+ ]);
+ });
+
+ it("post-aggregation filter shouldn't affect the drill-through options (metabase#18770)", () => {
+ H.createQuestion(
+ {
+ name: "18770",
+ query: {
+ "source-query": {
+ aggregation: [["count"]],
+ "source-table": ORDERS_ID,
+ breakout: [
+ ["field", PRODUCTS.TITLE, { "source-field": ORDERS.PRODUCT_ID }],
+ ],
+ },
+ filter: [">", ["field", "count", { "base-type": "type/Integer" }], 0],
+ },
+ },
+ { visitQuestion: true },
+ );
+
+ H.openNotebook();
+ // It is important to manually trigger "visualize" in order to generate the `result_metadata`
+ // Otherwise, we might get false negative even when this issue gets resolved.
+ // In order to do that, we have to change the breakout field first or it will never generate and send POST /api/dataset request.
+ cy.findAllByTestId("notebook-cell-item")
+ .contains(/Products? → Title/)
+ .click();
+ H.popover().findByText("Category").click();
+ cy.findAllByTestId("notebook-cell-item").contains(/Products? → Category/);
+
+ H.visualize();
+
+ cy.findAllByTestId("cell-data")
+ .filter(":contains(4,784)")
+ .should("have.length", 1);
+
+ // Querying the cell again to ensure the dom node stability
+ H.tableInteractiveBody().findByText("4,784").click();
+ H.popover().within(() => {
+ cy.findByText("Filter by this value").should("be.visible");
+ cy.findAllByRole("button")
+ .should("have.length", 7)
+ .and("contain", "See these Orders")
+ .and("contain", "Break out by")
+ .and("contain", "Copy value")
+ .and("contain", "<")
+ .and("contain", ">")
+ .and("contain", "=")
+ .and("contain", "≠");
+ });
+ });
+
+ it("should combine GUI and custom expression filters in the notebook and remove one of them (metabase#16198)", () => {
+ H.openOrdersTable({ mode: "notebook" });
+
+ H.filter({ mode: "notebook" });
+ H.clauseStepPopover().findByText("Total").click();
+ H.selectFilterOperator("Equal to");
+ H.clauseStepPopover().within(() => {
+ cy.findByPlaceholderText("Enter a number").type("123");
+ cy.button("Add filter").click();
+ });
+
+ H.getNotebookStep("filter").icon("add").click();
+ H.clauseStepPopover().within(() => {
+ cy.findByText("Custom Expression").click();
+ H.CustomExpressionEditor.type("[Total] < [Product → Price]", {
+ allowFastSet: true,
+ }).blur();
+ cy.button("Done").click();
+ });
+
+ H.getNotebookStep("filter").icon("add").click();
+ H.clauseStepPopover().findByText(/^ID$/i).click();
+ cy.findByPlaceholderText("Enter an ID").type("1");
+ cy.button("Add filter").click();
+
+ H.getNotebookStep("filter")
+ .findByText("Total is equal to 123")
+ .parent()
+ .find(".Icon-close")
+ .click();
+
+ H.getNotebookStep("filter").within(() => {
+ cy.findByText("Total is equal to 123").should("not.exist");
+ cy.findByText(/^Total is less than/).should("be.visible");
+ cy.findByText("ID is 1").should("be.visible");
+ });
+
+ H.visualize((response) => {
+ expect(response.body.error).to.not.exist;
+ });
+ H.queryBuilderMain().findByText("Something went wrong").should("not.exist");
+ });
+
+ it("should add and edit filters from a column header without replacing other filters (metabase#16621, metabase#24664)", () => {
+ H.openProductsTable({ limit: 3 });
+
+ H.tableHeaderClick("Category");
+ H.popover().within(() => {
+ cy.findByText("Filter by this column").click();
+ cy.findByPlaceholderText("Search the list").type("Gadget");
+ cy.findByText("Gadget").click();
+ cy.button("Add filter").click();
+ });
+ H.queryBuilderFiltersPanel().findByText("Category is Gadget").click();
+ H.popover().within(() => {
+ cy.findByText("Gizmo").click();
+ cy.button("Update filter").click();
+ });
+ H.queryBuilderFiltersPanel()
+ .findByText("Category is 2 selections")
+ .should("be.visible");
+
+ H.tableHeaderClick("Category");
+ H.popover().within(() => {
+ cy.findByText("Filter by this column").click();
+ cy.findByText("Doohickey").click();
+ cy.button("Add filter").click();
+ });
+ H.queryBuilderFiltersPanel().findByText("Category is Doohickey").click();
+ H.popover().within(() => {
+ cy.findByText("Widget").click();
+ cy.button("Update filter").click();
+ });
+
+ H.queryBuilderFiltersPanel()
+ .findAllByTestId("filter-pill")
+ .should("have.length", 2)
+ .and("contain", "Category is 2 selections");
+
+ assertPillValues({
+ index: 0,
+ checked: ["Gadget", "Gizmo"],
+ unchecked: ["Doohickey", "Widget"],
+ });
+ assertPillValues({
+ index: 1,
+ checked: ["Doohickey", "Widget"],
+ unchecked: ["Gadget", "Gizmo"],
+ });
+ });
+
+ it("should filter by excluded and relative dates (metabase#21979, metabase#12457)", () => {
+ H.openProductsTable({ mode: "notebook" });
+
+ H.filter({ mode: "notebook" });
+ H.popover().within(() => {
+ cy.findByText("Created At").click();
+ cy.findByText("Exclude…").click();
+ cy.findByText("Days of the week…").click();
+ cy.findByLabelText("Monday").click();
+ cy.button("Add filter").click();
+ });
+ H.getNotebookStep("filter")
+ .findByText("Created At excludes Mondays")
+ .should("be.visible");
+
+ H.visualize();
+ // "Practical Bronze Computer" is created on a Monday
+ H.assertQueryBuilderRowCount(170);
+ H.queryBuilderMain()
+ .findByText("Practical Bronze Computer")
+ .should("not.exist");
+
+ H.queryBuilderFiltersPanel()
+ .findByText("Created At excludes Mondays")
+ .click();
+ H.popover().within(() => {
+ cy.findByLabelText("Monday").click();
+ cy.findByLabelText("Thursday").click();
+ cy.button("Update filter").click();
+ });
+ H.assertQueryBuilderRowCount(180);
+ H.queryBuilderMain()
+ .findByText("Practical Bronze Computer")
+ .should("be.visible");
+ H.queryBuilderFiltersPanel()
+ .findByText("Created At excludes Thursdays")
+ .should("be.visible");
+
+ cy.log(
+ "a relative date filter survives a round trip through a custom expression",
+ );
+ H.openOrdersTable({ mode: "notebook" });
+ H.filter({ mode: "notebook" });
+ H.popover().within(() => {
+ cy.findByText("Created At").click();
+ cy.findByText("Relative date range…").click();
+ cy.findByText("Previous").click();
+ cy.findByLabelText(/^Include/).click();
+ cy.button("Add filter").click();
+ });
+
+ H.getNotebookStep("filter")
+ .findByText("Created At is in the previous 30 days or today")
+ .click();
+ H.clauseStepPopover().within(() => {
+ cy.button("Back").click();
+ cy.button("Back").click();
+ cy.findByText("Custom Expression").click();
+ cy.button("Update").click();
+ });
+
+ H.getNotebookStep("filter")
+ .findByText("Created At is in the previous 30 days or today")
+ .click();
+ H.popover()
+ .findByTestId("include-current-interval-option")
+ .should("have.attr", "aria-checked", "true");
+ });
+
+ it("should convert GUI filters to custom expressions and keep the results (metabase#14959)", () => {
+ H.openReviewsTable();
+ H.tableHeaderClick("Reviewer");
+ H.popover().findByText("Filter by this column").click();
+ H.selectFilterOperator("Is empty");
+ H.popover().button("Add filter").click();
+ H.queryBuilderMain().contains("Showing 0 rows");
+
+ H.queryBuilderFiltersPanel().findByText("Reviewer is empty").click();
+ H.popover().within(() => {
+ cy.icon("chevronleft").click();
+ cy.findByText("Custom Expression").click();
+ });
+ H.popover().contains("isEmpty([Reviewer])");
+ H.CustomExpressionEditor.clear().type("NOT IsEmpty([Reviewer])").blur();
+ cy.button("Update").click();
+ H.queryBuilderMain().contains("Showing 1,112 rows");
+
+ cy.log("is empty on a numeric column converts to isNull");
+ H.tableHeaderClick("Rating");
+ H.popover().findByText("Filter by this column").click();
+ H.selectFilterOperator("Is empty");
+ H.popover().button("Add filter").click();
+ H.queryBuilderMain().contains("Showing 0 rows");
+
+ H.queryBuilderFiltersPanel().findByText("Rating is empty").click();
+ H.popover().within(() => {
+ cy.icon("chevronleft").click();
+ cy.findByText("Custom Expression").click();
+ });
+ H.popover().contains("isNull([Rating])");
+ H.CustomExpressionEditor.clear()
+ .type("NOT IsNull([Rating])", { delay: 50 })
+ .blur();
+ cy.button("Update").should("not.be.disabled").click();
+ H.queryBuilderMain().contains("Showing 1,112 rows");
+
+ cy.log("case-insensitive filters keep their option");
+ H.visitQuestionAdhoc({
+ dataset_query: {
+ type: "query",
+ query: {
+ "source-table": REVIEWS_ID,
+ filter: [
+ "contains",
+ ["field", REVIEWS.REVIEWER, null],
+ "MULLER",
+ { "case-sensitive": false },
+ ],
+ },
+ database: SAMPLE_DB_ID,
+ },
+ display: "table",
+ });
+ H.queryBuilderMain().findByText("wilma-muller").should("be.visible");
+
+ H.queryBuilderFiltersPanel().findByText("Reviewer contains MULLER").click();
+ H.popover().within(() => {
+ cy.icon("chevronleft").click();
+ cy.findByText("Custom Expression").click();
+ });
+ H.popover().contains('contains([Reviewer], "MULLER", "case-insensitive")');
+ cy.intercept("POST", "/api/dataset").as("caseInsensitiveQuery");
+ cy.button("Update").click();
+ cy.wait("@caseInsensitiveQuery")
+ .its("response.body.data.rows")
+ .should("have.length", 1);
+ H.assertQueryBuilderRowCount(1);
+ H.queryBuilderMain().findByText("wilma-muller").should("be.visible");
+ });
+
+ it("should filter remapped, coerced and custom datetime columns (metabase#13235, QUE-2567)", () => {
+ cy.request("PUT", `/api/field/${ORDERS.PRODUCT_ID}`, {
+ has_field_values: "list",
+ });
+ cy.request("POST", `/api/field/${ORDERS.PRODUCT_ID}/dimension`, {
+ name: "Product ID",
+ type: "external",
+ human_readable_field_id: PRODUCTS.TITLE,
+ });
+ cy.request("PUT", `/api/field/${ORDERS.QUANTITY}`, {
+ coercion_strategy: "Coercion/UNIXSeconds->DateTime",
+ semantic_type: null,
+ });
+
+ cy.log("filter by a remapped value");
+ H.openOrdersTable();
+ H.filter();
+ H.popover().within(() => {
+ cy.findByText("Product ID").click();
+ cy.findByText("Aerodynamic Linen Coat").click();
+ cy.intercept("POST", "/api/dataset").as("remappedFilterQuery");
+ cy.button("Apply filter").click();
+ });
+ cy.wait("@remappedFilterQuery");
+ H.queryBuilderMain().within(() => {
+ cy.findAllByText("148.23").should("have.length.at.least", 1); // one of the subtotals for this product
+ cy.findAllByText("Fantastic Wool Shirt").should("not.exist");
+ });
+
+ cy.log("edit date filters on a coerced column and on custom expressions");
+ H.createQuestion(
+ {
+ query: {
+ "source-table": ORDERS_ID,
+ expressions: {
+ Foo: [
+ "datetime-add",
+ [
+ "field",
+ ORDERS.CREATED_AT,
+ {
+ "base-type": "type/DateTime",
+ "effective-type": "type/DateTime",
+ },
+ ],
+ 5,
+ "day",
+ ],
+ Bar: ["datetime", "2028-12-24"],
+ },
+ },
+ },
+ { visitQuestion: true },
+ );
+ ["Foo", "Bar", "Quantity"].forEach((columnName) => {
+ H.filter();
+ H.popover().within(() => {
+ cy.findByText(columnName).click();
+ cy.findByText("Previous 12 months").click();
+ });
+ });
+
+ cy.findAllByTestId("filter-pill").should("have.length", 3);
+ ["Foo", "Bar", "Quantity"].forEach((columnName) => {
+ H.queryBuilderFiltersPanel()
+ .findByText(`${columnName} is in the previous 12 months`)
+ .click();
+ H.popover().within(() => {
+ cy.findByText("Previous").should("be.visible");
+ cy.findByText("Current").should("be.visible");
+ cy.findByText("Next").should("be.visible");
+ });
+ });
+ });
+
+ it("should search the values of a key that points to a large text column without crashing (metabase#32985)", () => {
+ cy.request("PUT", `/api/field/${REVIEWS.REVIEWER}`, {
+ semantic_type: "type/PK",
+ });
+ cy.request("PUT", `/api/field/${PEOPLE.EMAIL}`, {
+ semantic_type: "type/FK",
+ });
+ cy.request("PUT", `/api/field/${PEOPLE.EMAIL}`, {
+ fk_target_field_id: REVIEWS.REVIEWER,
+ });
+ H.createQuestion(
+ { query: { "source-table": PEOPLE_ID, limit: 2 } },
+ { visitQuestion: true },
+ );
+
+ H.tableHeaderClick("Email");
+ H.popover().within(() => {
+ cy.findByText("Filter by this column").click();
+ cy.findByPlaceholderText("Search by Email or enter an ID").type("foo");
+ });
+ H.popover()
+ .should("have.length", 2)
+ .last()
+ .findByText("No matching Email found.")
+ .should("be.visible");
+ });
+
+ it("should filter a native question by a time column (metabase#22730)", () => {
+ H.createNativeQuestion(
+ {
+ name: "22730",
+ native: {
+ query:
+ "select '14:02:13'::time \"time\", 'before-row' \"name\" union all select '14:06:13'::time \"time\", 'after-row' ",
+ },
+ },
+ { visitQuestion: true },
+ );
+
+ cy.findByTestId("qb-header-action-panel")
+ .findByText("Explore results")
+ .click();
+
+ H.tableHeaderClick("time");
+ H.popover().within(() => {
+ cy.findByText("Filter by this column").click();
+ cy.findByDisplayValue("00:00").clear().type("14:03");
+ cy.button("Add filter").click();
+ });
+
+ H.assertQueryBuilderRowCount(1);
+ H.tableInteractiveBody().within(() => {
+ cy.findByText("before-row").should("be.visible");
+ cy.findByText("after-row").should("not.exist");
+ });
+ });
+
+ it("should handle the keyboard in the custom expression editor (metabase#16210)", () => {
+ H.openReviewsTable({ mode: "notebook" });
+ H.filter({ mode: "notebook" });
+ H.popover().findByText("Custom Expression").click();
+
+ cy.log("Enter does not submit an invalid expression");
+ H.enterCustomColumnDetails({ formula: "[Rating] > 2E{enter}" });
+ H.expressionEditorWidget()
+ .findByText("Missing exponent")
+ .should("be.visible");
+ H.getNotebookStep("filter")
+ .findByText("Rating is greater than 2")
+ .should("not.exist");
+
+ cy.log("arrow keys move the highlighted suggestion");
+ H.enterCustomColumnDetails({ formula: "c", blur: false });
+ H.CustomExpressionEditor.completions().should("contain", "case");
+ H.CustomExpressionEditor.completion("case")
+ .parent()
+ .should("have.attr", "aria-selected", "true");
+ // Avoid flakiness caused by CodeMirror not accepting the keypress
+ // immediately
+ cy.wait(200);
+ cy.realPress("ArrowDown");
+ H.CustomExpressionEditor.completion("ceil")
+ .parent()
+ .should("have.attr", "aria-selected", "true");
+ H.CustomExpressionEditor.completion("case")
+ .parent()
+ .should("have.attr", "aria-selected", "false");
+
+ cy.log("suggestions highlight the matching characters");
+ H.enterCustomColumnDetails({ formula: "[B", blur: false });
+ H.CustomExpressionEditor.completion("Body").should("be.visible");
+ H.CustomExpressionEditor.type("{backspace}p", { focus: false });
+ H.CustomExpressionEditor.completion("Product ID")
+ .findByText("P")
+ .should("be.visible");
+ H.CustomExpressionEditor.completion("Product ID")
+ .findByText("roduct ID")
+ .should("be.visible");
+
+ cy.log("a function searched in the filter picker opens with its template");
+ H.openOrdersTable({ mode: "notebook" });
+ H.filter({ mode: "notebook" });
+ H.popover().findByPlaceholderText("Find...").type("case(");
+ H.CustomExpressionEditor.value().should("equal", "case(condition, output)");
+
+ cy.log("Tab accepts a suggestion and then indents");
+ H.CustomExpressionEditor.clear();
+ H.CustomExpressionEditor.focus().type("[Ta");
+ H.CustomExpressionEditor.acceptCompletion("tab");
+ cy.focused().should("have.attr", "role", "textbox");
+ H.CustomExpressionEditor.type("> 42");
+ cy.realPress("Tab");
+ cy.focused().should("have.attr", "role", "textbox");
+ H.CustomExpressionEditor.value().should("equal", "[Tax]> 42 ");
+
+ cy.log("Escape hides the suggestions");
+ H.CustomExpressionEditor.clear();
+ H.CustomExpressionEditor.focus().type("Disc");
+ H.CustomExpressionEditor.completions().should("be.visible");
+ cy.realPress("Escape");
+ H.CustomExpressionEditor.completions().should("not.be.visible");
+ });
+
+ describe("layout", () => {
+ it("filter pill should not overflow the window width when the filter string is very long (metabase#44435)", () => {
+ // The string must not contain spaces.
+ const longString = "ABCDEFGHIJKLMNOPQRSTUVWXYZ".repeat(10);
+
+ H.visitQuestionAdhoc({
+ dataset_query: {
+ database: SAMPLE_DB_ID,
+ type: "query",
+ query: {
+ "source-table": REVIEWS_ID,
+ fields: [
+ ["field", REVIEWS.REVIEWER, { "base-type": "type/Text" }],
+ ["field", REVIEWS.RATING, { "base-type": "type/Integer" }],
+ ],
+ filter: [
+ "=",
+ ["field", REVIEWS.BODY, { "base-type": "type/Text" }],
+ longString,
+ ],
+ },
+ parameters: [],
+ },
+ });
+
+ cy.findByTestId("filter-pill").then(($pill) => {
+ const pillWidth = $pill[0].getBoundingClientRect().width;
+ cy.window().its("innerWidth").should("be.gt", pillWidth);
+ });
+ });
+
+ it("user shouldn't need to scroll to add filter (metabase#14307)", () => {
+ cy.viewport(1280, 720);
+ H.openPeopleTable({ mode: "notebook" });
+ H.filter({ mode: "notebook" });
+ H.popover().findByText("State").click({ force: true });
+ H.popover().findByText("AL").click();
+ cy.button("Add filter").isVisibleInPopover();
+ });
+
+ it("should render the item selected with the keyboard in view", () => {
+ cy.viewport(1280, 320);
+ H.openReviewsTable({ mode: "notebook" });
+ H.filter({ mode: "notebook" });
+
+ Cypress._.times(7, () => cy.realPress("ArrowDown"));
+
+ H.popover()
+ .findByRole("tree")
+ .then((el) => {
+ cy.wrap(el[0].scrollTop).should("be.greaterThan", 0);
+ });
+
+ H.popover().findByText("Created At").should("be.visible");
+ });
+
+ it("should render an outline on the custom expression item in the filter popover (QUE-1359)", () => {
+ H.openReviewsTable({ mode: "notebook" });
+ H.filter({ mode: "notebook" });
+
+ Cypress._.times(10, () => cy.realPress("ArrowDown"));
+
+ H.popover()
+ .findByText("Custom Expression")
+ .parent()
+ .then((el) => {
+ cy.wrap(window.getComputedStyle(el[0]).outline).should(
+ "contain",
+ "solid",
+ );
+ });
+ });
+
+ it("tooltip content should not overflow the tooltip (metabase#50731)", () => {
+ cy.viewport(800, 800);
+ H.openOrdersTable();
+ cy.icon("filter").click();
+ cy.icon("label").realHover();
+
+ H.popover()
+ .should("be.visible")
+ .and(($element) => {
+ const [container] = $element;
+ const descendants = container.querySelectorAll("*");
+
+ descendants.forEach((descendant) => {
+ H.assertDescendantNotOverflowsContainer(descendant, container);
+ });
+ });
+ });
+
+ it("should keep the popover width while typing (metabase#49321)", () => {
+ H.openProductsTable({ mode: "notebook" });
+ H.filter({ mode: "notebook" });
+
+ H.popover().within(() => {
+ cy.findByText("Title").click();
+ cy.findByText("Is").click();
+ });
+ // eslint-disable-next-line metabase/no-unsafe-element-filtering
+ H.popover().last().findByText("Contains").click();
+
+ H.popover().then(($popover) => {
+ const { width } = $popover[0].getBoundingClientRect();
+ cy.wrap(width).as("initialWidth");
+ });
+
+ H.popover()
+ .findByPlaceholderText("Enter some text")
+ .type("aaaaaaaaaa, bbbbbbbbbbb,");
+
+ cy.get<number>("@initialWidth").then((initialWidth) => {
+ H.popover().should(($popover) => {
+ const { width } = $popover[0].getBoundingClientRect();
+ expect(width).to.eq(initialWidth);
+ });
+ });
+ });
+
+ it("should not overflow the filter popover, even when there are a lot of values (metabase#48851)", () => {
+ const manyValues = Array(20)
+ .fill(0)
+ .map(() => Math.round(Math.random() * 1000_000_000_000).toString(36))
+ .join(", ");
+
+ cy.viewport(1050, 500);
+ H.openProductsTable();
+ H.tableHeaderClick("Title");
+
+ H.popover().within(() => {
+ cy.findByText("Filter by this column").click();
+ cy.findByText("Is").click();
+ });
+
+ H.popover().eq(1).findByText("Contains").click();
+ H.popover().should("have.length", 1);
+ H.popover()
+ .findByPlaceholderText("Enter some text")
+ .type(manyValues, { force: true, timeout: 0 });
+
+ H.popover().button("Add filter").should("be.visible");
+ });
+
+ it("it should not lose padding when switching filter types (metabase#58923)", () => {
+ cy.viewport(800, 800);
+ H.openPeopleTable();
+ H.tableHeaderClick("Name");
+
+ H.popover().findByText("Filter by this column").click();
+ H.popover().findByText("Is").click();
+ H.popover()
+ .should("have.length", 2)
+ .last()
+ .findByText("Contains")
+ .click();
+
+ H.popover().findByText("Contains").click();
+ H.popover().should("have.length", 2).last().findByText("Is").click();
+
+ H.popover()
+ .first()
+ .within(() => {
+ cy.findByPlaceholderText("Search by Name").then((input) => {
+ cy.button("Add filter")
+ .parent()
+ .then((footer) => {
+ const { bottom } = input[0].getBoundingClientRect();
+ const { top } = footer[0].getBoundingClientRect();
+
+ cy.wrap(top - bottom).should("be.gt", 16);
+ });
+ });
+ });
+ });
+
+ it("should not overflow the last filter value with the info icon (metabase#45410)", () => {
+ H.openPeopleTable({ mode: "notebook" });
+ H.filter({ mode: "notebook" });
+ H.clauseStepPopover().within(() => {
+ cy.findByText("Email").click();
+ cy.findByPlaceholderText("Search by Email")
+ .blur();
+ cy.findByText("[email protected]")
+ .next("button")
+ .then(([removeButton]) => {
+ cy.icon("info").then(([infoIcon]) => {
+ const removeButtonRect = removeButton.getBoundingClientRect();
+ const infoIconRect = infoIcon.getBoundingClientRect();
+ expect(removeButtonRect.right).to.be.lte(infoIconRect.left);
+ });
+ });
+ });
+ });
+
+ it("should display long column names in search results (metabase#31340)", () => {
+ const LONG_COLUMN_NAME =
+ "Some very very very very long column name that should have a line break";
+
+ cy.intercept("PUT", "/api/field/*").as("fieldUpdate");
+ cy.intercept("GET", `/api/field/${PEOPLE.PASSWORD}/search/*`).as(
+ "search",
+ );
+
+ H.DataModel.visit({
+ databaseId: SAMPLE_DB_ID,
+ schemaId: SAMPLE_DB_SCHEMA_ID,
+ tableId: PEOPLE_ID,
+ fieldId: PEOPLE.PASSWORD,
+ });
+ H.DataModel.FieldSection.getNameInput()
+ .focus()
+ .clear()
+ .type(LONG_COLUMN_NAME)
+ .blur();
+ cy.wait("@fieldUpdate");
+
+ H.createQuestion(
+ { query: { "source-table": PEOPLE_ID, limit: 2 } },
+ { visitQuestion: true },
+ );
+
+ H.tableHeaderClick(LONG_COLUMN_NAME);
+ H.popover().findByText("Filter by this column").click();
+ H.selectFilterOperator("Is");
+ H.popover().within(() => {
+ cy.findByPlaceholderText(`Search by ${LONG_COLUMN_NAME}`).type(
+ "nonexistingvalue",
+ );
+ cy.wait("@search");
+ });
+
+ H.popover()
+ .should("have.length", 2)
+ .last()
+ .findByText(`No matching ${LONG_COLUMN_NAME} found.`)
+ .should("be.visible")
+ .and(([message]) => {
+ expect(message.scrollWidth).to.be.lte(message.clientWidth);
+ });
+ });
+ });
+});
+
+describe(
+ "scenarios > filters > unsupported column types",
+ { tags: "@external" },
+ () => {
+ beforeEach(() => {
+ H.restore("postgres-writable");
+ H.resetTestTable({ type: "postgres", table: "many_data_types" });
+ cy.signInAsAdmin();
+ H.resyncDatabase({ dbId: WRITABLE_DB_ID, tableName: "many_data_types" });
+ cy.intercept("POST", "/api/dataset").as("dataset");
+ });
+
+ it("should allow using is-null and not-null operators with unsupported data types (metabase#45252,metabase#38111)", () => {
+ H.startNewQuestion();
+
+ cy.log("filter picker - new filter");
+ H.miniPicker().within(() => {
+ cy.findByText("Writable Postgres12").click();
+ cy.findByText("Many Data Types").click();
+ });
+ H.getNotebookStep("filter")
+ .findByText("Add filters to narrow your answer")
+ .click();
+ H.popover().within(() => {
+ cy.findByText("Binary").scrollIntoView().click();
+ cy.findByLabelText("Is empty").click();
+ cy.button("Add filter").click();
+ });
+ H.visualize();
+ cy.wait("@dataset");
+ H.assertQueryBuilderRowCount(0);
+
+ cy.log("filter picker - existing filter");
+ cy.findByTestId("qb-filters-panel").findByText("Binary is empty").click();
+ H.popover().within(() => {
+ cy.findByLabelText("Not empty").click();
+ cy.button("Update filter").click();
+ cy.wait("@dataset");
+ });
+ cy.findByTestId("qb-filters-panel")
+ .findByText("Binary is not empty")
+ .should("be.visible");
+ H.assertQueryBuilderRowCount(2);
+
+ cy.log("filter picker - existing filter");
+ H.queryBuilderHeader()
+ .button(/Filter/)
+ .click();
+ H.popover().within(() => {
+ cy.findByText("Binary").click();
+ cy.findByLabelText("Is empty").click();
+ cy.button("Apply filter").click();
+ });
+ cy.wait("@dataset");
+ H.assertQueryBuilderRowCount(0);
+
+ cy.log("filter picker - json column");
+ H.queryBuilderFiltersPanel()
+ .findByText("Binary is empty")
+ .icon("close")
+ .click();
+ cy.wait("@dataset");
+ H.queryBuilderHeader()
+ .button(/Filter/)
+ .click();
+ H.popover().within(() => {
+ cy.findByText("Jsonb").click();
+ cy.findByLabelText("Not empty").click();
+ cy.button("Apply filter").click();
+ });
+ cy.wait("@dataset");
+ H.assertQueryBuilderRowCount(2);
+ });
+ },
+);
+
+function assertPillValues({
+ index,
+ checked,
+ unchecked,
+}: {
+ index: number;
+ checked: string[];
+ unchecked: string[];
+}) {
+ H.queryBuilderFiltersPanel()
+ .findAllByTestId("filter-pill")
+ .should("have.length", 2)
+ .eq(index)
+ .click();
+ H.popover().within(() => {
+ checked.forEach((value) =>
+ cy.findByRole("checkbox", { name: value }).should("be.checked"),
+ );
+ unchecked.forEach((value) =>
+ cy.findByRole("checkbox", { name: value }).should("not.be.checked"),
+ );
+ });
+ cy.realPress("Escape");
+ cy.get(H.POPOVER_ELEMENT).should("not.exist");
+}
diff --git a/e2e/test/scenarios/filters/filters-reproductions.cy.spec.js b/e2e/test/scenarios/filters/filters-reproductions.cy.spec.js
deleted file mode 100644
index 55a8114afa5..00000000000
--- a/e2e/test/scenarios/filters/filters-reproductions.cy.spec.js
+++ /dev/null
@@ -1,949 +0,0 @@
-const { H } = cy;
-
-import {
- SAMPLE_DB_ID,
- SAMPLE_DB_SCHEMA_ID,
- WRITABLE_DB_ID,
-} from "e2e/support/cypress_data";
-import { SAMPLE_DATABASE } from "e2e/support/cypress_sample_database";
-
-const {
- ORDERS_ID,
- PRODUCTS,
- PRODUCTS_ID,
- ORDERS,
- REVIEWS,
- REVIEWS_ID,
- PEOPLE,
- PEOPLE_ID,
-} = SAMPLE_DATABASE;
-
-describe("issue 9339 + 27123", () => {
- beforeEach(() => {
- H.restore();
- cy.signInAsAdmin();
- });
-
- it("should not paste non-numeric values into single-value numeric filters and should open the chosen exclude granularity (metabase#9339, metabase#27123)", () => {
- H.openOrdersTable();
-
- H.tableHeaderClick("Total");
- // eslint-disable-next-line metabase/no-unscoped-text-selectors -- deprecated usage
- cy.findByText("Filter by this column").click();
- H.selectFilterOperator("Greater than");
- cy.findByPlaceholderText("Enter a number").type("9339,1234").blur();
- cy.findByDisplayValue("9339").should("be.visible");
- // eslint-disable-next-line metabase/no-unscoped-text-selectors -- deprecated usage
- cy.findByText("1,234").should("not.exist");
- cy.button("Add filter").should("be.enabled");
-
- cy.log(
- "exclude filter should not resolve to 'Days of the week' regardless of the chosen granularity (metabase#27123)",
- );
- cy.findByDisplayValue("9339").type("{esc}");
- cy.get(H.POPOVER_ELEMENT).should("not.exist");
-
- H.tableHeaderClick("Created At");
- H.popover().within(() => {
- cy.findByText("Filter by this column").click();
- cy.findByText("Exclude…").click();
- cy.findByText("Months of the year…").click();
- });
-
- H.popover()
- .should("contain", "Months of the year…")
- .and("contain", "January");
- });
-});
-
-describe("issue 16621 + 24664", () => {
- beforeEach(() => {
- H.restore();
- cy.signInAsAdmin();
- H.openProductsTable({ limit: 3 });
- });
-
- it("should add values to a filter and edit a second filter without replacing the first (metabase#16621, metabase#24664)", () => {
- H.tableHeaderClick("Category");
- H.popover().within(() => {
- cy.findByText("Filter by this column").click();
- cy.findByPlaceholderText("Search the list").type("Gadget");
- cy.findByText("Gadget").click();
- cy.button("Add filter").click();
- });
- cy.findByTestId("qb-filters-panel").within(() => {
- cy.findByText("Category is Gadget").click();
- });
- H.popover().within(() => {
- cy.findByText("Gizmo").click();
- cy.button("Update filter").click();
- });
- cy.findByTestId("qb-filters-panel")
- .findByText("Category is 2 selections")
- .should("be.visible");
-
- cy.log(
- "editing a second filter should not replace the first (metabase#24664)",
- );
- H.tableHeaderClick("Category");
- H.popover().within(() => {
- cy.findByText("Filter by this column").click();
- cy.findByText("Doohickey").click();
- cy.button("Add filter").click();
- });
-
- cy.findByTestId("qb-filters-panel")
- .findByText("Category is Doohickey")
- .click();
- H.popover().within(() => {
- cy.findByText("Widget").click();
- cy.button("Update filter").click();
- });
-
- cy.findByTestId("qb-filters-panel")
- .findAllByTestId("filter-pill")
- .should("have.length", 2)
- .and("contain", "Category is 2 selections");
-
- assertPillValues({
- index: 0,
- checked: ["Gadget", "Gizmo"],
- unchecked: ["Doohickey", "Widget"],
- });
- assertPillValues({
- index: 1,
- checked: ["Doohickey", "Widget"],
- unchecked: ["Gadget", "Gizmo"],
- });
- });
-
- function assertPillValues({ index, checked, unchecked }) {
- cy.findByTestId("qb-filters-panel")
- .findAllByTestId("filter-pill")
- .should("have.length", 2)
- .eq(index)
- .click();
- H.popover().within(() => {
- checked.forEach((value) => assertFilterValueIsSelected(value));
- unchecked.forEach((value) =>
- cy.findByRole("checkbox", { name: value }).should("not.be.checked"),
- );
- });
- cy.realPress("Escape");
- cy.get(H.POPOVER_ELEMENT).should("not.exist");
- }
-});
-
-describe("issue 18770", () => {
- const questionDetails = {
- name: "18770",
- query: {
- "source-query": {
- aggregation: [["count"]],
- "source-table": ORDERS_ID,
- breakout: [
- ["field", PRODUCTS.TITLE, { "source-field": ORDERS.PRODUCT_ID }],
- ],
- },
- filter: [">", ["field", "count", { "base-type": "type/Integer" }], 0],
- },
- };
-
- beforeEach(() => {
- H.restore();
- cy.signInAsAdmin();
-
- H.createQuestion(questionDetails, { visitQuestion: true });
- });
-
- it("post-aggregation filter shouldn't affect the drill-through options (metabase#18770)", () => {
- H.openNotebook();
- // It is important to manually trigger "visualize" in order to generate the `result_metadata`
- // Otherwise, we might get false negative even when this issue gets resolved.
- // In order to do that, we have to change the breakout field first or it will never generate and send POST /api/dataset request.
- cy.findAllByTestId("notebook-cell-item")
- .contains(/Products? → Title/)
- .click();
- H.popover().findByText("Category").click();
- cy.findAllByTestId("notebook-cell-item").contains(/Products? → Category/);
-
- H.visualize();
-
- cy.findAllByTestId("cell-data")
- .filter(":contains(4,784)")
- .should("have.length", 1);
-
- // Querying the cell again to ensure the dom node stability
- H.tableInteractiveBody().findByText("4,784").click();
- H.popover().within(() => {
- cy.findByText("Filter by this value").should("be.visible");
- cy.findAllByRole("button")
- .should("have.length", 7)
- .and("contain", "See these Orders")
- .and("contain", "Break out by")
- .and("contain", "Copy value")
- .and("contain", "<")
- .and("contain", ">")
- .and("contain", "=")
- .and("contain", "≠");
- });
- });
-});
-
-describe("issue 20551 + 49321", () => {
- beforeEach(() => {
- H.restore();
- cy.signInAsNormalUser();
- });
-
- it("should search values by includes and keep the popover width while typing (metabase#20551, metabase#49321)", () => {
- H.openProductsTable({ mode: "notebook" });
- H.filter({ mode: "notebook" });
-
- H.popover().within(() => {
- cy.findByText("Category").click();
- cy.findByText("Gadget").should("be.visible");
- cy.findByPlaceholderText("Search the list").type("i");
-
- cy.findByText("Doohickey").should("be.visible");
- cy.findByText("Gizmo").should("be.visible");
- cy.findByText("Widget").should("be.visible");
- cy.findByText("Gadget").should("not.exist");
-
- cy.icon("chevronleft").click();
- });
-
- cy.log(
- "should not require multiple clicks to apply a filter (metabase#49321)",
- );
- H.popover().within(() => {
- cy.findByText("Title").click();
- cy.findByText("Is").click();
- });
- // eslint-disable-next-line metabase/no-unsafe-element-filtering
- H.popover().last().findByText("Contains").click();
-
- H.popover().then(($popover) => {
- const { width } = $popover[0].getBoundingClientRect();
- cy.wrap(width).as("initialWidth");
- });
-
- H.popover()
- .findByPlaceholderText("Enter some text")
- .type("aaaaaaaaaa, bbbbbbbbbbb,");
-
- cy.get("@initialWidth").then((initialWidth) => {
- H.popover().should(($popover) => {
- const { width } = $popover[0].getBoundingClientRect();
- expect(width).to.eq(initialWidth);
- });
- });
- });
-});
-describe("issue 21979", () => {
- beforeEach(() => {
- H.restore();
- cy.signInAsAdmin();
- cy.intercept("POST", "/api/dataset").as("dataset");
- });
-
- it("exclude 'day of the week' should show the correct day reference in the UI (metabase#21979)", () => {
- H.openProductsTable({ mode: "notebook" });
-
- H.filter({ mode: "notebook" });
- H.popover().within(() => {
- cy.findByText("Created At").click();
- cy.findByText("Exclude…").click();
- cy.findByText("Days of the week…").click();
- cy.findByLabelText("Monday").click();
- cy.button("Add filter").click();
- });
-
- H.getNotebookStep("filter")
- .findByText("Created At excludes Mondays")
- .should("be.visible");
-
- H.visualize();
-
- // "Practical Bronze Computer" is created on a Monday
- H.assertQueryBuilderRowCount(170);
- H.queryBuilderMain()
- .findByText("Practical Bronze Computer")
- .should("not.exist");
-
- cy.findByTestId("qb-filters-panel")
- .findByText("Created At excludes Mondays")
- .click();
-
- H.popover().within(() => {
- cy.findByLabelText("Monday").click();
- cy.findByLabelText("Thursday").click();
- cy.button("Update filter").click();
- });
- cy.wait("@dataset");
-
- H.assertQueryBuilderRowCount(180);
- H.queryBuilderMain()
- .findByText("Practical Bronze Computer")
- .should("be.visible");
-
- cy.findByTestId("qb-filters-panel")
- .findByText("Created At excludes Thursdays")
- .should("be.visible");
- });
-});
-describe("issue 22730", () => {
- beforeEach(() => {
- H.restore();
- cy.signInAsAdmin();
-
- H.createNativeQuestion(
- {
- name: "22730",
- native: {
- query:
- "select '14:02:13'::time \"time\", 'before-row' \"name\" union all select '14:06:13'::time \"time\", 'after-row' ",
- },
- },
- { visitQuestion: true },
- );
-
- cy.intercept("POST", "/api/dataset").as("dataset");
- });
-
- it("allows filtering by time column (metabase#22730)", () => {
- // eslint-disable-next-line metabase/no-unscoped-text-selectors -- deprecated usage
- cy.findByText("Explore results").click();
- cy.wait("@dataset");
-
- H.tableHeaderClick("time");
-
- H.popover().within(() => {
- cy.findByText("Filter by this column").click();
- cy.findByDisplayValue("00:00").clear().type("14:03");
- cy.button("Add filter").click();
- });
- cy.wait("@dataset");
-
- H.assertQueryBuilderRowCount(1);
- H.tableInteractiveBody().within(() => {
- cy.findByText("before-row").should("be.visible");
- cy.findByText("after-row").should("not.exist");
- });
- });
-});
-
-describe("issue 24994", () => {
- const questionDetails = {
- query: {
- "source-query": {
- "source-table": PRODUCTS_ID,
- filter: [
- "and",
- ["=", ["field", PRODUCTS.CATEGORY, null], "Gadget", "Gizmo"],
- [
- "time-interval",
- ["field", PRODUCTS.CREATED_AT, null],
- -30,
- "year",
- {
- include_current: false,
- },
- ],
- ],
- aggregation: [["count"]],
- breakout: [["field", PRODUCTS.CATEGORY, null]],
- },
- filter: [
- ">",
- [
- "field",
- "count",
- {
- "base-type": "type/Integer",
- },
- ],
- 0,
- ],
- },
- };
-
- beforeEach(() => {
- H.restore();
- cy.signInAsAdmin();
- });
-
- it("should allow updating filters (metabase#24994)", () => {
- H.createQuestion(questionDetails, { visitQuestion: true });
-
- // Three filters
- cy.findByTestId("filters-visibility-control").contains("3").click();
-
- // eslint-disable-next-line metabase/no-unscoped-text-selectors -- deprecated usage
- cy.findByText("Category is 2 selections").click();
- assertFilterValueIsSelected("Gadget");
- assertFilterValueIsSelected("Gizmo");
- // eslint-disable-next-line metabase/no-unscoped-text-selectors -- deprecated usage
- cy.findByText("Doohickey").click();
- assertFilterValueIsSelected("Doohickey");
- cy.button("Update filter").should("not.be.disabled").click();
- // eslint-disable-next-line metabase/no-unscoped-text-selectors -- deprecated usage
- cy.findByText("Category is 3 selections");
- });
-});
-
-function assertFilterValueIsSelected(value) {
- cy.findByRole("checkbox", { name: value }).should("be.checked");
-}
-
-describe("issue 45410", () => {
- beforeEach(() => {
- H.restore();
- cy.signInAsNormalUser();
- });
-
- it("should not overflow the last filter value with the info icon (metabase#45410)", () => {
- H.openPeopleTable({ mode: "notebook" });
- H.filter({ mode: "notebook" });
- H.clauseStepPopover().within(() => {
- cy.findByText("Email").click();
- cy.findByPlaceholderText("Search by Email")
- .blur();
- cy.findByText("[email protected]")
- .next("button")
- .then(([removeButton]) => {
- cy.icon("info").then(([infoIcon]) => {
- const removeButtonRect = removeButton.getBoundingClientRect();
- const infoIconRect = infoIcon.getBoundingClientRect();
- expect(removeButtonRect.right).to.be.lte(infoIconRect.left);
- });
- });
- });
- });
-});
-
-describe("issue 30312", () => {
- const CREATED_AT_BREAKOUT = [
- "field",
- ORDERS.CREATED_AT,
- {
- "base-type": "type/DateTime",
- "temporal-unit": "month",
- },
- ];
-
- beforeEach(() => {
- H.restore();
- cy.signInAsNormalUser();
- });
-
- it("can use a drill filter on an aggregated column (metabase#30312)", () => {
- H.createQuestion(
- {
- query: {
- "source-table": ORDERS_ID,
- aggregation: [["count"]],
- breakout: [CREATED_AT_BREAKOUT],
- limit: 5, // optimization
- },
- display: "table",
- },
- { visitQuestion: true },
- );
-
- cy.findAllByTestId("header-cell").eq(1).should("have.text", "Count");
-
- H.tableHeaderClick("Count");
-
- H.popover().findByText("Filter by this column").click();
- H.selectFilterOperator("Equal to");
- H.clickActionsPopover().within(() => {
- cy.findByPlaceholderText("Enter a number").type("10");
- cy.realPress("Tab");
- cy.button("Add filter").should("be.enabled").click();
- });
-
- cy.findByTestId("filter-pill").should("have.text", "Count is equal to 10");
- H.queryBuilderMain().findByText("No results").should("be.visible");
- });
-});
-
-describe("issue 31340 + 32985", () => {
- const LONG_COLUMN_NAME =
- "Some very very very very long column name that should have a line break";
-
- beforeEach(() => {
- H.restore();
- cy.signInAsAdmin();
-
- cy.intercept("PUT", "/api/field/*").as("fieldUpdate");
- cy.intercept("GET", `/api/field/${PEOPLE.PASSWORD}/search/*`).as("search");
-
- H.DataModel.visit({
- databaseId: SAMPLE_DB_ID,
- schemaId: SAMPLE_DB_SCHEMA_ID,
- tableId: PEOPLE_ID,
- fieldId: PEOPLE.PASSWORD,
- });
-
- H.DataModel.FieldSection.getNameInput()
- .focus()
- .clear()
- .type(LONG_COLUMN_NAME)
- .blur();
- cy.wait("@fieldUpdate");
-
- // we need to mess with the field metadata to make the field values crazy
- cy.request("PUT", `/api/field/${REVIEWS.REVIEWER}`, {
- semantic_type: "type/PK",
- });
- cy.request("PUT", `/api/field/${PEOPLE.EMAIL}`, {
- semantic_type: "type/FK",
- });
- cy.request("PUT", `/api/field/${PEOPLE.EMAIL}`, {
- fk_target_field_id: REVIEWS.REVIEWER,
- });
-
- H.createQuestion(
- { query: { "source-table": PEOPLE_ID, limit: 2 } },
- { wrapId: true, visitQuestion: true },
- );
- });
-
- it("should search field values without crashing and display long column names (metabase#32985, metabase#31340)", () => {
- cy.log(
- "should not crash when searching large field values sets (metabase#32985)",
- );
- H.tableHeaderClick("Email");
-
- H.popover().within(() => {
- cy.findByText("Filter by this column").click();
- cy.findByPlaceholderText("Search by Email or enter an ID").type("foo");
- });
- H.popover()
- .should("have.length", 2)
- .last()
- .findByText("No matching Email found.")
- .should("be.visible");
-
- cy.log(
- "should display long column names in search results (metabase#31340)",
- );
- H.visitQuestion("@questionId");
- H.tableHeaderClick(LONG_COLUMN_NAME);
-
- H.popover().findByText("Filter by this column").click();
- H.selectFilterOperator("Is");
- H.popover().within(() => {
- cy.findByPlaceholderText(`Search by ${LONG_COLUMN_NAME}`).type(
- "nonexistingvalue",
- );
- cy.wait("@search");
- });
-
- H.popover()
- .should("have.length", 2)
- .last()
- .findByText(`No matching ${LONG_COLUMN_NAME} found.`)
- .should("be.visible")
- .and(([message]) => {
- expect(message.scrollWidth).to.be.lte(message.clientWidth);
- });
- });
-});
-
-describe("issue 29094 + 34794", () => {
- beforeEach(() => {
- H.restore();
- cy.signInAsNormalUser();
- });
-
- it("should reach the custom expression section after going back and reject non-boolean expressions (metabase#29094, metabase#34794)", () => {
- H.openOrdersTable({ mode: "notebook" });
-
- H.filter({ mode: "notebook" });
- H.popover().within(() => {
- cy.findByText("Created At").click();
- cy.icon("chevronleft").click(); // go back to the main filter popover
- cy.findByText("Custom Expression").click();
-
- H.enterCustomColumnDetails({ formula: "[Tax] * 22" });
- cy.realPress("Tab");
- cy.button("Done").should("be.disabled");
- cy.findByText("Types are incompatible.").should("exist");
-
- H.CustomExpressionEditor.clear();
- H.CustomExpressionEditor.type("[Total] > 10").format();
- cy.findByText("Types are incompatible.").should("not.exist");
- cy.button("Done").click();
- });
-
- H.getNotebookStep("filter")
- .findByText("Total is greater than 10")
- .should("be.visible");
- });
-});
-
-describe("issue 35043", () => {
- beforeEach(() => {
- H.restore();
- cy.signInAsAdmin();
- });
-
- it("should prevent illogical ranges - from newer to older (metabase#35043)", () => {
- const questionDetails = {
- database: SAMPLE_DB_ID,
- query: {
- "source-table": ORDERS_ID,
- filter: [
- "between",
- [
- "field",
- ORDERS.CREATED_AT,
- {
- "base-type": "type/DateTime",
- },
- ],
- "2027-04-15",
- "2027-05-22",
- ],
- limit: 5,
- },
- type: "query",
- };
-
- H.createQuestion(questionDetails, { visitQuestion: true });
-
- cy.findByTestId("filters-visibility-control").click();
- cy.findByTestId("filter-pill")
- .should("have.text", "Created At is Apr 15 – May 22, 2027")
- .click();
-
- cy.findByTestId("date-filter-picker").within(() => {
- cy.intercept("POST", "/api/dataset").as("dataset");
- cy.findByDisplayValue("May 22, 2027").type("{backspace}2").blur();
- cy.findByDisplayValue("May 22, 2022").should("exist");
-
- cy.button("Update filter").click();
- cy.wait("@dataset");
- });
-
- cy.findByTestId("filter-pill").should(
- "have.text",
- "Created At is May 22, 2022 – Apr 15, 2027",
- );
- });
-});
-
-describe("issue 45252", { tags: "@external" }, () => {
- beforeEach(() => {
- H.restore("postgres-writable");
- H.resetTestTable({ type: "postgres", table: "many_data_types" });
- cy.signInAsAdmin();
- H.resyncDatabase({ dbId: WRITABLE_DB_ID, tableName: "many_data_types" });
- cy.intercept("POST", "/api/dataset").as("dataset");
- });
-
- it("should allow using is-null and not-null operators with unsupported data types (metabase#45252,metabase#38111)", () => {
- H.startNewQuestion();
-
- cy.log("filter picker - new filter");
- H.miniPicker().within(() => {
- cy.findByText("Writable Postgres12").click();
- cy.findByText("Many Data Types").click();
- });
- H.getNotebookStep("filter")
- .findByText("Add filters to narrow your answer")
- .click();
- H.popover().within(() => {
- cy.findByText("Binary").scrollIntoView().click();
- cy.findByLabelText("Is empty").click();
- cy.button("Add filter").click();
- });
- H.visualize();
- cy.wait("@dataset");
- H.assertQueryBuilderRowCount(0);
-
- cy.log("filter picker - existing filter");
- cy.findByTestId("qb-filters-panel").findByText("Binary is empty").click();
- H.popover().within(() => {
- cy.findByLabelText("Not empty").click();
- cy.button("Update filter").click();
- cy.wait("@dataset");
- });
- cy.findByTestId("qb-filters-panel")
- .findByText("Binary is not empty")
- .should("be.visible");
- H.assertQueryBuilderRowCount(2);
-
- cy.log("filter picker - existing filter");
- H.queryBuilderHeader()
- .button(/Filter/)
- .click();
- H.popover().within(() => {
- cy.findByText("Binary").click();
- cy.findByLabelText("Is empty").click();
- cy.button("Apply filter").click();
- });
- cy.wait("@dataset");
- H.assertQueryBuilderRowCount(0);
-
- cy.log("filter picker - json column");
- H.queryBuilderFiltersPanel()
- .findByText("Binary is empty")
- .icon("close")
- .click();
- cy.wait("@dataset");
- H.queryBuilderHeader()
- .button(/Filter/)
- .click();
- H.popover().within(() => {
- cy.findByText("Jsonb").click();
- cy.findByLabelText("Not empty").click();
- cy.button("Apply filter").click();
- });
- cy.wait("@dataset");
- H.assertQueryBuilderRowCount(2);
- });
-});
-
-describe("issue 44435", () => {
- // It is crucial that the string is without spaces!
- const alphabet = "ABCDEFGHIJKLMNOPQRSTUVWXYZ";
- const longString = alphabet.repeat(10);
-
- beforeEach(() => {
- H.restore();
- cy.signInAsAdmin();
- });
-
- it("filter pill should not overflow the window width when the filter string is very long (metabase#44435)", () => {
- H.visitQuestionAdhoc({
- dataset_query: {
- database: SAMPLE_DB_ID,
- type: "query",
- query: {
- "source-table": REVIEWS_ID,
- fields: [
- ["field", REVIEWS.REVIEWER, { "base-type": "type/Text" }],
- ["field", REVIEWS.RATING, { "base-type": "type/Integer" }],
- ],
- filter: [
- "=",
- ["field", REVIEWS.BODY, { "base-type": "type/Text" }],
- longString,
- ],
- },
- parameters: [],
- },
- });
-
- cy.findByTestId("filter-pill").then(($pill) => {
- const pillWidth = $pill[0].getBoundingClientRect().width;
- cy.window().its("innerWidth").should("be.gt", pillWidth);
- });
- });
-});
-
-describe("Issue 48851", () => {
- beforeEach(() => {
- H.restore();
- cy.signInAsNormalUser();
- cy.viewport(1050, 500);
- });
-
- const manyValues = Array(20)
- .fill(0)
- .map(() => Math.round(Math.random() * 1000_000_000_000).toString(36))
- .join(", ");
-
- it("should not overflow the filter popover, even when there are a lot of values (metabase#48851)", () => {
- H.openProductsTable();
- H.tableHeaderClick("Title");
-
- H.popover().within(() => {
- cy.findByText("Filter by this column").click();
- cy.findByText("Is").click();
- });
-
- H.popover().eq(1).findByText("Contains").click();
- H.popover().should("have.length", 1);
- H.popover()
- .findByPlaceholderText("Enter some text")
- .type(manyValues, { force: true, timeout: 0 });
-
- H.popover().button("Add filter").should("be.visible");
- });
-});
-
-describe("issue 50731", () => {
- beforeEach(() => {
- H.restore();
- cy.signInAsNormalUser();
- cy.viewport(800, 800);
- });
-
- it("tooltip content should not overflow the tooltip (metabase#50731)", () => {
- H.openOrdersTable();
- cy.icon("filter").click();
- cy.icon("label").realHover();
-
- H.popover()
- .should("be.visible")
- .and(($element) => {
- const [container] = $element;
- const descendants = container.querySelectorAll("*");
-
- descendants.forEach((descendant) => {
- H.assertDescendantNotOverflowsContainer(descendant, container);
- });
- });
- });
-});
-
-describe("issue 58923", () => {
- beforeEach(() => {
- H.restore();
- cy.signInAsNormalUser();
- cy.viewport(800, 800);
- });
-
- it("it should not lose padding when switching filter types (metabase#58923)", () => {
- H.openPeopleTable();
- H.tableHeaderClick("Name");
-
- H.popover().findByText("Filter by this column").click();
- H.popover().findByText("Is").click();
- H.popover().should("have.length", 2).last().findByText("Contains").click();
-
- H.popover().findByText("Contains").click();
- H.popover().should("have.length", 2).last().findByText("Is").click();
-
- H.popover()
- .first()
- .within(() => {
- cy.findByPlaceholderText("Search by Name").then((input) => {
- cy.button("Add filter")
- .parent()
- .then((footer) => {
- const { bottom } = input[0].getBoundingClientRect();
- const { top } = footer[0].getBoundingClientRect();
-
- cy.wrap(top - bottom).should("be.gt", 16);
- });
- });
- });
- });
-});
-
-describe("issue QUE-1359", () => {
- beforeEach(() => {
- H.restore();
- cy.signInAsNormalUser();
- });
-
- it("should render an outline on the custom expression item in the filter popover (QUE-1359)", () => {
- H.openReviewsTable({ mode: "notebook" });
- H.filter({ mode: "notebook" });
-
- Cypress._.times(10, () => cy.realPress("ArrowDown"));
-
- H.popover()
- .findByText("Custom Expression")
- .parent()
- .then((el) => {
- cy.wrap(window.getComputedStyle(el[0]).outline).should(
- "contain",
- "solid",
- );
- });
- });
-});
-
-describe("issue QUE-2567", () => {
- beforeEach(() => {
- H.restore();
- cy.signInAsAdmin();
- cy.request("PUT", `/api/field/${ORDERS.QUANTITY}`, {
- coercion_strategy: "Coercion/UNIXSeconds->DateTime",
- semantic_type: null,
- });
- cy.signInAsNormalUser();
-
- H.createQuestion(
- {
- query: {
- "source-table": ORDERS_ID,
- expressions: {
- Foo: [
- "datetime-add",
- [
- "field",
- ORDERS.CREATED_AT,
- {
- "base-type": "type/DateTime",
- "effective-type": "type/DateTime",
- },
- ],
- 5,
- "day",
- ],
- Bar: ["datetime", "2028-12-24"],
- },
- },
- },
- { visitQuestion: true },
- );
-
- H.filter();
- H.popover().within(() => {
- cy.findByText("Foo").click();
- cy.findByText("Previous 12 months").click();
- });
-
- H.filter();
- H.popover().within(() => {
- cy.findByText("Bar").click();
- cy.findByText("Previous 12 months").click();
- });
- });
-
- it("should be possible to edit a datetime filter that is based on a custom expression or a coerced column (QUE-2567)", () => {
- cy.log("Editing the filter should show the date picker");
- cy.findAllByTestId("filter-pill").should("have.length", 2).eq(0).click();
- H.popover().within(() => {
- cy.findByText("Previous").should("be.visible");
- cy.findByText("Current").should("be.visible");
- cy.findByText("Next").should("be.visible");
- });
-
- cy.log(
- "Editing the filter should show the date picker for coerced datetime",
- );
- cy.findAllByTestId("filter-pill").should("have.length", 2).eq(1).click();
- H.popover().within(() => {
- cy.findByText("Previous").should("be.visible");
- cy.findByText("Current").should("be.visible");
- cy.findByText("Next").should("be.visible");
- });
-
- cy.log(
- "Editing the filter should show the date picker for coerced columns",
- );
- H.openOrdersTable();
-
- H.filter();
- H.popover().within(() => {
- cy.findByText("Quantity").click();
- cy.findByText("Previous 12 months").click();
- });
-
- cy.findByTestId("filter-pill").click();
- H.popover().within(() => {
- cy.findByText("Previous").should("be.visible");
- cy.findByText("Current").should("be.visible");
- cy.findByText("Next").should("be.visible");
- });
- });
-});
diff --git a/frontend/src/metabase/query_builder/components/view/ViewHeader/components/QuestionDataSource/QuestionDataSource.unit.spec.tsx b/frontend/src/metabase/query_builder/components/view/ViewHeader/components/QuestionDataSource/QuestionDataSource.unit.spec.tsx
index 9feffd1c141..5100c123f37 100644
--- a/frontend/src/metabase/query_builder/components/view/ViewHeader/components/QuestionDataSource/QuestionDataSource.unit.spec.tsx
+++ b/frontend/src/metabase/query_builder/components/view/ViewHeader/components/QuestionDataSource/QuestionDataSource.unit.spec.tsx
@@ -627,6 +627,29 @@ describe("QuestionDataSource", () => {
});
});
+ it("should not display a filter value in the breadcrumbs (metabase#16198)", async () => {
+ setup({
+ card: {
+ ...BASE_GUI_QUESTION,
+ dataset_query: createMockStructuredDatasetQuery({
+ database: SAMPLE_DB_ID,
+ query: {
+ "source-table": PRODUCTS_ID,
+ filter: [
+ "and",
+ ["=", ["field", PRODUCTS.CATEGORY, null], "Gizmo"],
+ ["=", ["field", PRODUCTS.ID, null], 1],
+ ],
+ },
+ }),
+ },
+ });
+
+ const breadcrumbs = await screen.findByTestId("head-crumbs-container");
+ await waitFor(() => expect(breadcrumbs).toHaveTextContent("Products"));
+ expect(breadcrumbs).not.toHaveTextContent("Gizmo");
+ });
+
it("should show info icon on an ad-hoc question header", async () => {
setup({ card: SOURCE_CARD });
expect(await screen.findByLabelText("More info")).toBeInTheDocument();
diff --git a/frontend/src/metabase/querying/components/expressions/Editor/utils.unit.spec.ts b/frontend/src/metabase/querying/components/expressions/Editor/utils.unit.spec.ts
new file mode 100644
index 00000000000..3b4bf1caa16
--- /dev/null
+++ b/frontend/src/metabase/querying/components/expressions/Editor/utils.unit.spec.ts
@@ -0,0 +1,34 @@
+import { EditorView } from "@codemirror/view";
+import { renderHook } from "@testing-library/react";
+
+import type * as Lib from "metabase-lib";
+
+import { useInitialClause } from "./utils";
+
+type SetupOpts = {
+ initialExpressionClause: Lib.DefinedClauseName | null;
+};
+
+function setup({ initialExpressionClause }: SetupOpts) {
+ const view = new EditorView({ doc: "" });
+ const { result } = renderHook(() =>
+ useInitialClause({ initialExpressionClause }),
+ );
+ result.current(view);
+ return { source: view.state.doc.toString() };
+}
+
+describe("useInitialClause", () => {
+ it.each<[Lib.DefinedClauseName, string]>([
+ ["coalesce", "coalesce(value1, value2)"],
+ ["case", "case(condition, output)"],
+ ])("should insert the %s template", (clause, expectedSource) => {
+ expect(setup({ initialExpressionClause: clause }).source).toBe(
+ expectedSource,
+ );
+ });
+
+ it("should insert nothing without an initial clause", () => {
+ expect(setup({ initialExpressionClause: null }).source).toBe("");
+ });
+});
diff --git a/frontend/src/metabase/querying/expressions/diagnostics/diagnostics.unit.spec.ts b/frontend/src/metabase/querying/expressions/diagnostics/diagnostics.unit.spec.ts
index 742b735731e..62b8028fb46 100644
--- a/frontend/src/metabase/querying/expressions/diagnostics/diagnostics.unit.spec.ts
+++ b/frontend/src/metabase/querying/expressions/diagnostics/diagnostics.unit.spec.ts
@@ -136,6 +136,22 @@ describe("diagnostics", () => {
).toBeUndefined();
});
+ it("should accept a parenthesized OR inside an AND in filter mode", () => {
+ expect(
+ err("([ID] > 2 OR [Subtotal] = 100) and [Tax] < 4", "filter"),
+ ).toBeUndefined();
+ expect(err("([ID] > 2 OR [Subtotal] = 100) and", "filter")).toBe(
+ "Expected expression",
+ );
+ });
+
+ it("should reject non-boolean expressions in filter mode", () => {
+ expect(err("[Tax] * 22", "filter")).toBe("Types are incompatible.");
+ expect(err("3.14159", "filter")).toBe("Types are incompatible.");
+ expect(err('"TheAnswer"', "filter")).toBe("Types are incompatible.");
+ expect(err("[Total] > 10", "filter")).toBeUndefined();
+ });
+
it.each(["in", "notIn"])(
"should reject multi-arg function calls without options when there is not enough arguments",
(fn) => {
diff --git a/frontend/src/metabase/querying/expressions/formatter/formatter.unit.spec.ts b/frontend/src/metabase/querying/expressions/formatter/formatter.unit.spec.ts
index 3e7affa7208..eefaf59a036 100644
--- a/frontend/src/metabase/querying/expressions/formatter/formatter.unit.spec.ts
+++ b/frontend/src/metabase/querying/expressions/formatter/formatter.unit.spec.ts
@@ -607,6 +607,61 @@ describe("if printWidth = Infinity, it should return the same results as the sin
});
});
+ it("should format is-empty and not-empty", async () => {
+ await all({
+ "isEmpty([User → Name])": op("is-empty", fields.people.NAME),
+ "notEmpty([User → Name])": op("not-empty", fields.people.NAME),
+ "NOT isEmpty([User → Name])": op(
+ "not",
+ op("is-empty", fields.people.NAME),
+ ),
+ });
+ });
+
+ it("should format single-value string filters with options", async () => {
+ await all({
+ 'contains([User → Name], "MULLER", "case-insensitive")': opt(
+ "contains",
+ { "case-sensitive": false },
+ fields.people.NAME,
+ "MULLER",
+ ),
+ 'doesNotContain([Product → Title], "Wallet", "case-insensitive")': opt(
+ "does-not-contain",
+ { "case-sensitive": false },
+ fields.products.TITLE,
+ "Wallet",
+ ),
+ });
+ });
+
+ it("should format comparisons between two columns", async () => {
+ await all({
+ "[Total] < [Subtotal]": op(
+ "<",
+ fields.orders.TOTAL,
+ fields.orders.SUBTOTAL,
+ ),
+ "[Total] < [Product → Price]": op(
+ "<",
+ fields.orders.TOTAL,
+ fields.products.PRICE,
+ ),
+ });
+ });
+
+ it("should format the include-current option of interval", async () => {
+ await all({
+ 'interval([Created At], -30, "day", "include-current")': opt(
+ "time-interval",
+ { "include-current": true },
+ fields.orders.CREATED_AT,
+ -30,
+ "day",
+ ),
+ });
+ });
+
it("should format aggregation functions", async () => {
await all({
"Count()": op("count"),
diff --git a/frontend/src/metabase/querying/expressions/suggestions/fields.unit.spec.ts b/frontend/src/metabase/querying/expressions/suggestions/fields.unit.spec.ts
index a24c9915d12..c9b0e5ef9fb 100644
--- a/frontend/src/metabase/querying/expressions/suggestions/fields.unit.spec.ts
+++ b/frontend/src/metabase/querying/expressions/suggestions/fields.unit.spec.ts
@@ -445,6 +445,44 @@ describe("suggestFields", () => {
});
});
+ it("should suggest aggregated columns of the previous stage in filter mode (metabase#14776)", async () => {
+ const summarizedQuery = Lib.createTestQuery(SAMPLE_PROVIDER, {
+ stages: [
+ {
+ source: { type: "table", id: ORDERS_ID },
+ aggregations: [
+ {
+ type: "operator",
+ operator: "sum",
+ args: [{ type: "column", name: "TOTAL" }],
+ },
+ ],
+ breakouts: [{ type: "column", name: "CREATED_AT" }],
+ },
+ ],
+ });
+ const query = Lib.appendStage(summarizedQuery);
+ const stageIndex = 1;
+
+ const source = suggestFields({
+ query,
+ stageIndex,
+ availableColumns: columnsForExpressionMode({
+ query,
+ stageIndex,
+ expressionMode: "filter",
+ }),
+ });
+
+ const labelsFor = async (doc: string) =>
+ (await complete(source, doc))?.options.map(
+ (option) => option.displayLabel,
+ );
+
+ expect(await labelsFor("[su|")).toContain("Sum of Total");
+ expect(await labelsFor("[sum|")).toContain("Sum of Total");
+ });
+
it.each(["expression", "filter"] as const)(
"should not suggest aggregations when expressionMode = %s",
async (expressionMode) => {
diff --git a/frontend/src/metabase/querying/expressions/suggestions/functions.unit.spec.ts b/frontend/src/metabase/querying/expressions/suggestions/functions.unit.spec.ts
index 9ab03dfc994..77884364fd8 100644
--- a/frontend/src/metabase/querying/expressions/suggestions/functions.unit.spec.ts
+++ b/frontend/src/metabase/querying/expressions/suggestions/functions.unit.spec.ts
@@ -234,6 +234,20 @@ describe("suggestFunctions", () => {
const results = completer("con|c()");
expect(results).toEqual(RESULTS_NO_TEMPLATE);
});
+
+ it("should suggest case for a single letter (metabase#16210)", async () => {
+ const completer = setup({ expressionMode });
+ const results = await completer("c|");
+ const labels = results?.options.map((option) => option.label);
+ expect(labels?.[0]).toBe("case");
+ });
+
+ it("should keep suggesting case after more letters are typed (metabase#16210)", async () => {
+ const completer = setup({ expressionMode });
+ const results = await completer("ca|");
+ const labels = results?.options.map((option) => option.label);
+ expect(labels).toContain("case");
+ });
});
it("should complete functions whose name starts with the an operator name as a prefix (metabase#55686)", async () => {
diff --git a/frontend/src/metabase/querying/filters/components/FilterPicker/FilterColumnPicker/FilterColumnPicker.unit.spec.tsx b/frontend/src/metabase/querying/filters/components/FilterPicker/FilterColumnPicker/FilterColumnPicker.unit.spec.tsx
index c6c4e22c2b6..8e9cc8594de 100644
--- a/frontend/src/metabase/querying/filters/components/FilterPicker/FilterColumnPicker/FilterColumnPicker.unit.spec.tsx
+++ b/frontend/src/metabase/querying/filters/components/FilterPicker/FilterColumnPicker/FilterColumnPicker.unit.spec.tsx
@@ -22,6 +22,7 @@ interface SetupOpts {
function setup({ query, stageIndexes }: SetupOpts) {
const onColumnSelect = jest.fn<void, [ColumnListItem]>();
+ const onExpressionSelect = jest.fn<void, [Lib.DefinedClauseName?]>();
setupFieldsValuesEndpoints(SAMPLE_DB_FIELD_VALUES);
renderWithProviders(
<FilterColumnPicker
@@ -30,10 +31,10 @@ function setup({ query, stageIndexes }: SetupOpts) {
checkItemIsSelected={() => false}
onColumnSelect={onColumnSelect}
onSegmentSelect={jest.fn()}
- onExpressionSelect={jest.fn()}
+ onExpressionSelect={onExpressionSelect}
/>,
);
- return { onColumnSelect };
+ return { onColumnSelect, onExpressionSelect };
}
describe("FilterColumnPicker", () => {
@@ -164,4 +165,30 @@ describe("FilterColumnPicker", () => {
onColumnSelect.mock.calls.map(([item]) => getColumnRef(item.column)),
).toEqual(expectedColumnRefs);
});
+
+ it("should pick a custom expression from the search results", async () => {
+ const query = Lib.createTestQuery(SAMPLE_PROVIDER, DEFAULT_TEST_QUERY);
+ const { onExpressionSelect } = setup({ query, stageIndexes: [0] });
+
+ await userEvent.type(screen.getByPlaceholderText("Find..."), "coalesce");
+ expect(screen.getByText("Custom Expressions")).toBeInTheDocument();
+ await userEvent.click(screen.getByText("coalesce"));
+
+ expect(onExpressionSelect).toHaveBeenCalledTimes(1);
+ expect(onExpressionSelect).toHaveBeenCalledWith("coalesce");
+ });
+
+ it("should pick a custom expression when the search ends with an opening parenthesis", async () => {
+ const query = Lib.createTestQuery(SAMPLE_PROVIDER, DEFAULT_TEST_QUERY);
+ const { onExpressionSelect } = setup({ query, stageIndexes: [0] });
+ const search = screen.getByPlaceholderText("Find...");
+
+ await userEvent.type(search, "foo(");
+ expect(onExpressionSelect).not.toHaveBeenCalled();
+
+ await userEvent.clear(search);
+ await userEvent.type(search, "case(");
+ expect(onExpressionSelect).toHaveBeenCalledTimes(1);
+ expect(onExpressionSelect).toHaveBeenCalledWith("case");
+ });
});
diff --git a/frontend/src/metabase/querying/filters/components/FilterPicker/FilterPicker.unit.spec.tsx b/frontend/src/metabase/querying/filters/components/FilterPicker/FilterPicker.unit.spec.tsx
index c1f22a73625..ee45f24c702 100644
--- a/frontend/src/metabase/querying/filters/components/FilterPicker/FilterPicker.unit.spec.tsx
+++ b/frontend/src/metabase/querying/filters/components/FilterPicker/FilterPicker.unit.spec.tsx
@@ -34,6 +34,7 @@ import {
createQueryWithTimeFilter,
findBooleanColumn,
findDateColumn,
+ findDateTimeColumn,
findNumericColumn,
findStringColumn,
storeInitialState,
@@ -424,6 +425,18 @@ describe("FilterPicker", () => {
});
describe("custom expression", () => {
+ // The editor wraps long expressions over lines, so compare without whitespace.
+ async function expectEditorSource(source: string) {
+ const editor = await screen.findByTestId(
+ "custom-expression-query-editor",
+ );
+ await waitFor(() =>
+ expect(editor.textContent?.replace(/\s/g, "")).toBe(
+ source.replace(/\s/g, ""),
+ ),
+ );
+ }
+
async function editExpressionAndSubmit(
text: string,
{ delay }: { delay: number } = { delay: 0 },
@@ -456,6 +469,44 @@ describe("FilterPicker", () => {
);
});
+ it("should reach the custom expression editor after going back from a column (metabase#29094)", async () => {
+ setup();
+
+ await userEvent.click(screen.getByText("Total"));
+ expect(screen.getByTestId("number-filter-picker")).toBeInTheDocument();
+ await userEvent.click(screen.getByLabelText("Back"));
+ await userEvent.click(screen.getByText(/Custom expression/i));
+
+ expect(
+ await screen.findByTestId("custom-expression-query-editor"),
+ ).toBeInTheDocument();
+ });
+
+ it.each<[string, (search: HTMLElement) => Promise<void>]>([
+ [
+ "a function picked from the search results",
+ async (search) => {
+ await userEvent.type(search, "coalesce");
+ await userEvent.click(screen.getByText("coalesce"));
+ },
+ ],
+ [
+ "a search that ends with an opening parenthesis",
+ (search) => userEvent.type(search, "case("),
+ ],
+ ])("should open the expression editor for %s", async (_name, act) => {
+ setup();
+ expect(
+ screen.queryByTestId("custom-expression-query-editor"),
+ ).not.toBeInTheDocument();
+
+ await act(screen.getByPlaceholderText("Find..."));
+
+ expect(
+ await screen.findByTestId("custom-expression-query-editor"),
+ ).toBeInTheDocument();
+ });
+
it("should open the expression editor for unsupported expressions", async () => {
setup(createQueryWithNullStringFilter());
const editor = await screen.findByTestId(
@@ -467,6 +518,92 @@ describe("FilterPicker", () => {
await waitFor(() => expect(editor).toHaveProperty("readOnly", false));
});
+ it.each<[string, () => SetupOpts, string]>([
+ [
+ "a negated case-insensitive string filter (metabase#14880)",
+ () =>
+ createQueryWithStringFilter({
+ column: findStringColumn(createQuery(), "PRODUCTS", "TITLE"),
+ operator: "does-not-contain",
+ values: ["Wallet"],
+ options: { caseSensitive: false },
+ }),
+ 'doesNotContain([Product → Title], "Wallet", "case-insensitive")',
+ ],
+ [
+ "a case-insensitive string filter (metabase#14959)",
+ () =>
+ createQueryWithStringFilter({
+ column: findStringColumn(createQuery(), "PRODUCTS", "TITLE"),
+ operator: "contains",
+ values: ["MULLER"],
+ options: { caseSensitive: false },
+ }),
+ 'contains([Product → Title], "MULLER", "case-insensitive")',
+ ],
+ [
+ "an is-empty string filter",
+ () =>
+ createQueryWithStringFilter({
+ operator: "is-empty",
+ values: [],
+ }),
+ "isEmpty([Product → Description])",
+ ],
+ [
+ "an is-empty numeric filter",
+ () => createQueryWithNumberFilter({ operator: "is-null", values: [] }),
+ "isNull([Total])",
+ ],
+ ])(
+ "should convert %s to a custom expression",
+ async (_name, getOpts, expectedSource) => {
+ setup(getOpts());
+
+ await userEvent.click(screen.getByLabelText("Back"));
+ await userEvent.click(screen.getByText(/Custom expression/i));
+
+ await expectEditorSource(expectedSource);
+ },
+ );
+
+ it("should show a comparison between two columns as a custom expression (metabase#12492)", async () => {
+ const query = createQuery();
+ const clause = Lib.expressionClause(">", [
+ findDateTimeColumn(query),
+ findStringColumn(query, "PRODUCTS", "CREATED_AT"),
+ ]);
+ setup(createFilteredQuery(query, clause));
+
+ await expectEditorSource("[Created At] > [Product → Created At]");
+ });
+
+ it("should keep include-current after converting a relative date filter to a custom expression (metabase#12457)", async () => {
+ const { query, getNextFilter } = setup(
+ createQueryWithRelativeDateFilter({
+ value: -30,
+ unit: "day",
+ options: { includeCurrent: true },
+ }),
+ );
+
+ await userEvent.click(screen.getByLabelText("Back"));
+ await userEvent.click(screen.getByLabelText("Back"));
+ await userEvent.click(screen.getByText(/Custom expression/i));
+
+ const button = await screen.findByRole("button", { name: "Update" });
+ await waitFor(() => expect(button).toBeEnabled());
+ await userEvent.click(button);
+
+ expect(
+ Lib.relativeDateFilterParts(query, 0, getNextFilter()),
+ ).toMatchObject({
+ value: -30,
+ unit: "day",
+ options: { includeCurrent: true },
+ });
+ });
+
it("should update a filter with a numeric custom expression", async () => {
const { query, getNextFilter } = setup(
createQueryWithCustomNumberFilter(),
diff --git a/frontend/src/metabase/querying/filters/components/FilterPicker/FilterValuePicker/FilterValuePicker.unit.spec.tsx b/frontend/src/metabase/querying/filters/components/FilterPicker/FilterValuePicker/FilterValuePicker.unit.spec.tsx
index cee077d9860..bf0b5965495 100644
--- a/frontend/src/metabase/querying/filters/components/FilterPicker/FilterValuePicker/FilterValuePicker.unit.spec.tsx
+++ b/frontend/src/metabase/querying/filters/components/FilterPicker/FilterValuePicker/FilterValuePicker.unit.spec.tsx
@@ -234,6 +234,23 @@ describe("StringFilterValuePicker", () => {
expect(onChange).toHaveBeenCalledWith(["Gadget"]);
});
+ it("should search the list of values by substring (metabase#20551)", async () => {
+ await setupStringPicker({
+ query,
+ stageIndex,
+ column,
+ values: [],
+ fieldId,
+ fieldValues: PRODUCT_CATEGORY_VALUES,
+ });
+
+ await userEvent.type(screen.getByPlaceholderText("Search the list"), "i");
+ expect(screen.getByText("Doohickey")).toBeInTheDocument();
+ expect(screen.getByText("Gizmo")).toBeInTheDocument();
+ expect(screen.getByText("Widget")).toBeInTheDocument();
+ expect(screen.queryByText("Gadget")).not.toBeInTheDocument();
+ });
+
it("should allow to update selected values", async () => {
const { onChange } = await setupStringPicker({
query,
diff --git a/frontend/src/metabase/querying/filters/components/FilterPicker/NumberFilterPicker/NumberFilterPicker.unit.spec.tsx b/frontend/src/metabase/querying/filters/components/FilterPicker/NumberFilterPicker/NumberFilterPicker.unit.spec.tsx
index 8ba6f518a26..1bc79f96ecf 100644
--- a/frontend/src/metabase/querying/filters/components/FilterPicker/NumberFilterPicker/NumberFilterPicker.unit.spec.tsx
+++ b/frontend/src/metabase/querying/filters/components/FilterPicker/NumberFilterPicker/NumberFilterPicker.unit.spec.tsx
@@ -206,6 +206,22 @@ describe("NumberFilterPicker", () => {
expect(getNextFilterColumnName()).toBe("Total");
});
+ it("should keep only the first number of a comma-separated input (metabase#9339)", async () => {
+ const { getNextFilterParts } = setup();
+
+ await setOperator("Greater than");
+ const input = screen.getByPlaceholderText("Enter a number");
+ await userEvent.type(input, "9339,1234");
+ await userEvent.tab();
+
+ expect(input).toHaveValue("9339");
+ await userEvent.click(screen.getByText("Add filter"));
+ expect(getNextFilterParts()).toMatchObject({
+ operator: ">",
+ values: [9339],
+ });
+ });
+
it("should add a filter with a big integer value", async () => {
const query = createQuery();
const columns = Lib.filterableColumns(query, -1);
diff --git a/frontend/src/metabase/ui/components/inputs/MultiAutocomplete/MultiAutocomplete.unit.spec.tsx b/frontend/src/metabase/ui/components/inputs/MultiAutocomplete/MultiAutocomplete.unit.spec.tsx
index 92297a8b390..b67cee178d4 100644
--- a/frontend/src/metabase/ui/components/inputs/MultiAutocomplete/MultiAutocomplete.unit.spec.tsx
+++ b/frontend/src/metabase/ui/components/inputs/MultiAutocomplete/MultiAutocomplete.unit.spec.tsx
@@ -467,6 +467,23 @@ describe("MultiAutocomplete", () => {
expect(getOption("One")).toBeInTheDocument();
});
+ it("should not let escape reach other keydown listeners while the dropdown is open", async () => {
+ const onWindowKeyDown = jest.fn<void, [KeyboardEvent]>();
+ window.addEventListener("keydown", onWindowKeyDown);
+ const { input } = setup({ data: REMAPPED_DATA });
+
+ await userEvent.click(input);
+ expect(getOption("One")).toBeInTheDocument();
+
+ await userEvent.keyboard("{Escape}");
+ expect(queryOption("One")).not.toBeInTheDocument();
+ expect(onWindowKeyDown).not.toHaveBeenCalled();
+
+ await userEvent.keyboard("{Escape}");
+ expect(onWindowKeyDown).toHaveBeenCalledTimes(1);
+ window.removeEventListener("keydown", onWindowKeyDown);
+ });
+
it("should not submit the input value during a keyboard composition session (metabase#60630)", async () => {
const { input, onChange } = setup();
await userEvent.type(input, "foo");