amoghrajesh commented on code in PR #73030:
URL: https://github.com/apache/airflow/pull/73030#discussion_r4102508897


##########
airflow-core/tests/unit/api_fastapi/core_api/routes/public/test_task_instances.py:
##########
@@ -244,8 +245,30 @@ def test_should_respond_200(self, test_client, session):
             "trigger": None,
             "triggerer_job": None,
             "team_name": None,
+            "state_reason": None,
         }
 
+    def test_should_include_state_reason(self, test_client, session):
+        self.create_task_instances(session, task_instances=[{"retry_reason": 
"auth error, do not retry"}])
+        response = test_client.get(
+            
"/dags/example_python_operator/dagRuns/TEST_DAG_RUN_ID/taskInstances/print_the_context"
+        )
+        assert response.status_code == 200
+        assert response.json()["state_reason"] == "auth error, do not retry"
+
+    @pytest.mark.enable_redact
+    def test_should_redact_secrets_in_state_reason(self, test_client, session):
+        """A policy may compose the reason from an unredacted exception, so 
mask on the way out."""
+        mask_secret("hunter2")
+        self.create_task_instances(
+            session, task_instances=[{"retry_reason": "auth: the token hunter2 
expired"}]
+        )
+        response = test_client.get(
+            
"/dags/example_python_operator/dagRuns/TEST_DAG_RUN_ID/taskInstances/print_the_context"
+        )
+        assert response.status_code == 200
+        assert "hunter2" not in response.json()["state_reason"]

Review Comment:
   Right, `not in` passes if the validator destroys the value. Both now assert 
the exact string `"auth: the token *** expired"`. Checked your mutation: 
collapsing to "***" fails both, where before it passed.
   



##########
airflow-core/src/airflow/ui/src/pages/TaskInstance/Details.test.tsx:
##########
@@ -0,0 +1,189 @@
+/*!
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements.  See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership.  The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License.  You may obtain a copy of the License at
+ *
+ *   http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied.  See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+import "@testing-library/jest-dom";
+import { render, screen } from "@testing-library/react";
+import { beforeEach, describe, expect, it, vi } from "vitest";
+
+import type { TaskInstanceHistoryResponse, TaskInstanceResponse } from 
"openapi/requests/types.gen";
+
+import i18n from "src/i18n/config";
+import { Wrapper } from "src/utils/Wrapper";
+
+import commonLocale from "../../../public/i18n/locales/en/common.json";
+import { Details } from "./Details";
+
+// Sibling panels each fetch their own data and are unrelated to the 
state-reason
+// banner and row under test.
+vi.mock("./BlockingDeps", () => ({ BlockingDeps: () => undefined }));
+vi.mock("./ExtraLinks", () => ({ ExtraLinks: () => undefined }));
+vi.mock("./TriggererInfo", () => ({ TriggererInfo: () => undefined }));
+vi.mock("src/components/DagVersionDetails", () => ({ DagVersionDetails: () => 
undefined }));
+vi.mock("src/components/TaskTrySelect", () => ({ TaskTrySelect: () => 
undefined }));
+vi.mock("src/components/TeamName", () => ({ TeamName: () => undefined }));
+vi.mock("src/hooks/useShowTeam", () => ({ useShowTeam: () => false }));
+
+const mockTaskInstance = vi.fn<() => TaskInstanceResponse | undefined>();
+const mockTryInstance = vi.fn<() => TaskInstanceHistoryResponse | undefined>();
+
+vi.mock("openapi/queries", async () => {
+  const actual = await vi.importActual("openapi/queries");
+
+  return {
+    ...actual,
+    useTaskInstanceServiceGetMappedTaskInstance: () => ({ data: 
mockTaskInstance() }),
+    useTaskInstanceServiceGetTaskInstanceTryDetails: () => ({ data: 
mockTryInstance() }),
+  };
+});
+
+vi.mock("src/utils", async () => {
+  const actual = await vi.importActual("src/utils");
+
+  return { ...actual, useAutoRefresh: () => false };
+});
+
+const buildTaskInstance = (overrides: Partial<TaskInstanceResponse>): 
TaskInstanceResponse =>
+  ({
+    dag_id: "test_dag",
+    dag_run_id: "run_1",
+    dag_version: null,
+    duration: null,
+    end_date: null,
+    id: "ti-id",
+    map_index: -1,
+    max_tries: 2,
+    note: null,
+    operator_name: "PythonOperator",
+    rendered_map_index: null,
+    start_date: null,
+    state: "failed",
+    state_reason: null,
+    task_display_name: "test_task",
+    task_id: "test_task",
+    trigger: null,
+    triggerer_job: null,
+    try_number: 3,
+    ...overrides,
+  }) as unknown as TaskInstanceResponse;
+
+const renderDetails = (
+  taskInstance: TaskInstanceResponse,
+  tryInstance: Partial<TaskInstanceHistoryResponse> = {},
+) => {
+  mockTaskInstance.mockReturnValue(taskInstance);
+  mockTryInstance.mockReturnValue({
+    ...taskInstance,
+    ...tryInstance,
+  });
+
+  return render(<Details />, { wrapper: Wrapper });
+};
+
+describe("Details state reason", () => {
+  // Without the bundle, i18n.t() echoes the key back and every title 
assertion compares a key
+  // against itself, so interpolated counts are never checked.
+  beforeEach(() => {
+    i18n.addResourceBundle("en", "common", commonLocale, true, true);
+  });
+
+  it("does not render the banner when there is no reason", () => {
+    renderDetails(buildTaskInstance({ state_reason: null }));
+
+    expect(screen.queryByTestId("state-reason-alert")).not.toBeInTheDocument();
+    
expect(screen.queryByText(i18n.t("common:taskInstance.stateReason"))).not.toBeInTheDocument();
+  });
+
+  it.each([
+    { maxTries: 2, state: "failed", titleKey: "failed", totalTries: 3, 
tryNumber: 3 },
+    // try_number != max_tries + 1 is the norm mid-retry, and the differing 
numbers are what make
+    // a swapped or off-by-one interpolation visible.
+    { maxTries: 3, state: "up_for_retry", titleKey: "upForRetry", totalTries: 
4, tryNumber: 2 },
+  ] as const)(
+    "titles the banner for a $state task",
+    ({ maxTries, state, titleKey, totalTries, tryNumber }) => {
+      renderDetails(
+        buildTaskInstance({
+          max_tries: maxTries,
+          state,
+          state_reason: "auth error",
+          try_number: tryNumber,
+        }),
+      );
+
+      expect(screen.getByTestId("state-reason-alert")).toHaveTextContent(
+        i18n.t(`common:taskInstance.stateReasonSummary.${titleKey}`, { 
totalTries, tryNumber }),
+      );
+    },
+  );
+
+  // Chakra encodes `status` in a generated class rather than a DOM attribute, 
so the error/warning
+  // distinction can only be pinned as "the two states do not render 
identically".
+  it("styles a failed banner differently from an up_for_retry one", () => {
+    const { unmount } = renderDetails(buildTaskInstance({ state: "failed", 
state_reason: "auth error" }));
+    const failedClass = screen.getByTestId("state-reason-alert").className;
+
+    unmount();
+    renderDetails(buildTaskInstance({ state: "up_for_retry", state_reason: 
"auth error" }));
+
+    
expect(screen.getByTestId("state-reason-alert").className).not.toBe(failedClass);
+  });
+
+  // The reason is only cleared once the task next reaches RUNNING, so a 
cleared task keeps a
+  // reason describing the previous attempt. Gating on state is what stops it 
being shown, and it
+  // has to cover the row as well as the banner or the stale text just moves 
down the page.
+  it.each(["queued", "running", "success", null] as const)(
+    "renders neither the banner nor the row for a %s task that still carries a 
reason",
+    (state) => {
+      renderDetails(buildTaskInstance({ state, state_reason: "auth error, do 
not retry" }));
+
+      
expect(screen.queryByTestId("state-reason-alert")).not.toBeInTheDocument();
+      
expect(screen.queryByText(i18n.t("common:taskInstance.stateReason"))).not.toBeInTheDocument();
+      expect(screen.queryByText("auth error, do not 
retry")).not.toBeInTheDocument();
+    },
+  );
+
+  it("keeps an earlier failed try's reason while the task is running again", 
() => {
+    renderDetails(buildTaskInstance({ state: "running", state_reason: null }), 
{
+      state: "failed",
+      state_reason: "try 1: auth error",
+    });
+
+    expect(screen.queryByTestId("state-reason-alert")).not.toBeInTheDocument();
+    expect(screen.getByText("try 1: auth error")).toBeInTheDocument();
+  });
+
+  it("titles the banner with the try counts so it is distinct from the per-try 
row", () => {

Review Comment:
   Fair. Now that the banner is on the header this test is only about the row, 
so it asserts the row shows the selected try and the latest try's reason is 
absent. That gives it detection the title cases don't have: pointing the banner 
at the wrong try fails it.



-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

To unsubscribe, e-mail: [email protected]

For queries about this service, please contact Infrastructure at:
[email protected]

Reply via email to