chihsuan commented on code in PR #11825:
URL: https://github.com/apache/ozone/pull/11825#discussion_r4421864679


##########
hadoop-ozone/recon/src/main/resources/webapps/recon/ozone-recon-web/src/__tests__/heatmap/Heatmap.test.tsx:
##########
@@ -0,0 +1,267 @@
+/*
+ * 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 React from 'react';
+import { fireEvent, render, screen, waitFor } from '@testing-library/react';
+import userEvent from '@testing-library/user-event';
+import { vi } from 'vitest';
+
+import Heatmap from '@/v2/pages/heatmap/heatmap';
+import * as commonUtils from '@/utils/common';
+import {
+  heatmapRequests,
+  heatmapServer,
+  heatmapServerErrorHandler,
+  heatmapUnavailableHandler,
+  resetHeatmapRequestTracking
+} from '@tests/mocks/heatmapMocks/heatmapServer';
+
+vi.spyOn(commonUtils, 'showDataFetchError');
+
+const { collectDrillDownTiles } = vi.hoisted(() => {
+  type MockHeatmapNode = {
+    label?: string | null;
+    path?: string;
+    color?: number;
+    children?: MockHeatmapNode[];
+  };
+
+  /** Non-leaf treemap tiles (no color, has path) call onClick — same rule as 
HeatmapPlot nodeClick. */

Review Comment:
   Could we test the real `nodeClick` in `HeatmapPlot.test.tsx` instead? This 
mock copies the click rule, so if the rule in `heatmapPlot.tsx` breaks, the 
tests still pass. Also, real key leaves have a `path`, but the fixtures don't.



##########
hadoop-ozone/recon/src/main/resources/webapps/recon/ozone-recon-web/src/__tests__/heatmap/Heatmap.test.tsx:
##########
@@ -0,0 +1,267 @@
+/*
+ * 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 React from 'react';
+import { fireEvent, render, screen, waitFor } from '@testing-library/react';
+import userEvent from '@testing-library/user-event';
+import { vi } from 'vitest';
+
+import Heatmap from '@/v2/pages/heatmap/heatmap';
+import * as commonUtils from '@/utils/common';
+import {
+  heatmapRequests,
+  heatmapServer,
+  heatmapServerErrorHandler,
+  heatmapUnavailableHandler,
+  resetHeatmapRequestTracking
+} from '@tests/mocks/heatmapMocks/heatmapServer';
+
+vi.spyOn(commonUtils, 'showDataFetchError');
+
+const { collectDrillDownTiles } = vi.hoisted(() => {
+  type MockHeatmapNode = {
+    label?: string | null;
+    path?: string;
+    color?: number;
+    children?: MockHeatmapNode[];
+  };
+
+  /** Non-leaf treemap tiles (no color, has path) call onClick — same rule as 
HeatmapPlot nodeClick. */
+  function collectDrillDownTiles(node: MockHeatmapNode, onClick: (path: 
string) => void): React.ReactNode[] {
+    const tiles: React.ReactNode[] = [];
+    node.children?.forEach((child) => {
+      if (child.path && child.color === undefined) {
+        tiles.push(
+          <div
+            key={child.path}
+            role="button"
+            tabIndex={0}
+            data-testid={`heatmap-tile-${child.label}`}
+            onClick={() => onClick(child.path!)}
+            onKeyDown={(e) => {
+              if (e.key === 'Enter' || e.key === ' ') {
+                onClick(child.path!);
+              }
+            }}
+          >
+            {child.label}
+          </div>
+        );
+      }
+      tiles.push(...collectDrillDownTiles(child, onClick));
+    });
+    return tiles;
+  }
+
+  return { collectDrillDownTiles };
+});
+
+vi.mock('@/v2/components/plots/heatmapPlot', () => ({
+  default: ({ data, onClick, entityType }: {
+    data: { label?: string | null; path?: string; color?: number; children?: 
unknown[] };
+    onClick: (path: string) => void;
+    entityType: string;
+  }) => (
+    <div data-testid="heatmap-plot" data-label={data.label ?? ''} 
data-entity-type={entityType}>
+      {collectDrillDownTiles(data, onClick)}
+    </div>
+  ),
+}));
+
+vi.mock('@/v2/hooks/useAPIData.hook', async (importOriginal) => {
+  const actual = await importOriginal<typeof 
import('@/v2/hooks/useAPIData.hook')>();
+  return {
+    ...actual,
+    useApiData: <T,>(url: string, defaultValue: T, options = {}) => {
+      // The hook's own initial GET does not handle a rejected request, so a 
404/500 on mount surfaces as an
+      // unhandled rejection in tests. Skip it and issue the initial request 
with a handled promise instead.
+      const api = actual.useApiData(url, defaultValue, {
+        ...options,
+        initialFetch: false,
+        retryAttempts: 0,
+        retryDelay: 0,
+      });
+      React.useEffect(() => {
+        if (url) {
+          api.execute().catch(() => undefined);
+        }
+      }, []); // eslint-disable-line react-hooks/exhaustive-deps
+      return api;
+    },
+  };
+});

Review Comment:
   Could we catch the rejection inside `useApiData` instead, maybe in a 
separate Jira? It likely shows up in the browser console on any failed request 
too. Since this wrapper turns off `initialFetch`, the page's own hook settings 
aren't tested. If the page sets `initialFetch` to false, every test still 
passes.



##########
hadoop-ozone/recon/src/main/resources/webapps/recon/ozone-recon-web/src/__tests__/heatmap/Heatmap.test.tsx:
##########
@@ -0,0 +1,267 @@
+/*
+ * 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 React from 'react';
+import { fireEvent, render, screen, waitFor } from '@testing-library/react';
+import userEvent from '@testing-library/user-event';
+import { vi } from 'vitest';
+
+import Heatmap from '@/v2/pages/heatmap/heatmap';
+import * as commonUtils from '@/utils/common';
+import {
+  heatmapRequests,
+  heatmapServer,
+  heatmapServerErrorHandler,
+  heatmapUnavailableHandler,
+  resetHeatmapRequestTracking
+} from '@tests/mocks/heatmapMocks/heatmapServer';
+
+vi.spyOn(commonUtils, 'showDataFetchError');
+
+const { collectDrillDownTiles } = vi.hoisted(() => {
+  type MockHeatmapNode = {
+    label?: string | null;
+    path?: string;
+    color?: number;
+    children?: MockHeatmapNode[];
+  };
+
+  /** Non-leaf treemap tiles (no color, has path) call onClick — same rule as 
HeatmapPlot nodeClick. */
+  function collectDrillDownTiles(node: MockHeatmapNode, onClick: (path: 
string) => void): React.ReactNode[] {
+    const tiles: React.ReactNode[] = [];
+    node.children?.forEach((child) => {
+      if (child.path && child.color === undefined) {
+        tiles.push(
+          <div
+            key={child.path}
+            role="button"
+            tabIndex={0}
+            data-testid={`heatmap-tile-${child.label}`}
+            onClick={() => onClick(child.path!)}
+            onKeyDown={(e) => {
+              if (e.key === 'Enter' || e.key === ' ') {
+                onClick(child.path!);
+              }
+            }}
+          >
+            {child.label}
+          </div>
+        );
+      }
+      tiles.push(...collectDrillDownTiles(child, onClick));
+    });
+    return tiles;
+  }
+
+  return { collectDrillDownTiles };
+});
+
+vi.mock('@/v2/components/plots/heatmapPlot', () => ({
+  default: ({ data, onClick, entityType }: {
+    data: { label?: string | null; path?: string; color?: number; children?: 
unknown[] };
+    onClick: (path: string) => void;
+    entityType: string;
+  }) => (
+    <div data-testid="heatmap-plot" data-label={data.label ?? ''} 
data-entity-type={entityType}>
+      {collectDrillDownTiles(data, onClick)}
+    </div>
+  ),
+}));
+
+vi.mock('@/v2/hooks/useAPIData.hook', async (importOriginal) => {
+  const actual = await importOriginal<typeof 
import('@/v2/hooks/useAPIData.hook')>();
+  return {
+    ...actual,
+    useApiData: <T,>(url: string, defaultValue: T, options = {}) => {
+      // The hook's own initial GET does not handle a rejected request, so a 
404/500 on mount surfaces as an
+      // unhandled rejection in tests. Skip it and issue the initial request 
with a handled promise instead.
+      const api = actual.useApiData(url, defaultValue, {
+        ...options,
+        initialFetch: false,
+        retryAttempts: 0,
+        retryDelay: 0,
+      });
+      React.useEffect(() => {
+        if (url) {
+          api.execute().catch(() => undefined);
+        }
+      }, []); // eslint-disable-line react-hooks/exhaustive-deps
+      return api;
+    },
+  };
+});
+
+const waitForPlot = (label: string) => waitFor(() => {
+  expect(screen.getByTestId('heatmap-plot')).toHaveAttribute('data-label', 
label);
+});
+
+const searchPath = async (path: string) => {
+  const pathInput = screen.getByPlaceholderText('/');
+  await userEvent.clear(pathInput);
+  if (path) {
+    await userEvent.type(pathInput, path);
+  }
+  fireEvent.click(screen.getByRole('button', { name: /search/i }));
+};
+
+// antd Dropdown opens its overlay on hover after a short delay.
+const selectFromDropdown = async (trigger: RegExp, item: string) => {
+  fireEvent.mouseOver(screen.getByRole('button', { name: trigger }));
+  fireEvent.click(await screen.findByText(item));
+};
+
+// Give any request fired on click a chance to reach the mock server before 
asserting none was sent.
+const flushPendingRequests = () => new Promise((resolve) => 
setTimeout(resolve, 50));
+
+describe('Heatmap page', () => {
+  beforeAll(() => heatmapServer.listen());
+
+  beforeEach(() => {
+    resetHeatmapRequestTracking();
+    vi.mocked(commonUtils.showDataFetchError).mockClear();
+  });
+
+  afterEach(() => heatmapServer.resetHandlers());
+  afterAll(() => heatmapServer.close());
+
+  test('renders header, filters, legend, and heatmap plot with data', async () 
=> {
+    render(<Heatmap />);
+
+    expect(screen.getByText('Heatmap')).toBeInTheDocument();
+    expect(screen.getByText('Path')).toBeInTheDocument();
+    expect(screen.getByPlaceholderText('/')).toHaveValue('/');
+    expect(screen.getByText(/Entity Type:\s*key/)).toBeInTheDocument();
+    expect(screen.getByText(/Last\s+24H/)).toBeInTheDocument();
+    expect(screen.getByText('Less Accessed')).toBeInTheDocument();
+    expect(screen.getByText('Moderate Accessed')).toBeInTheDocument();
+    expect(screen.getByText('Most Accessed')).toBeInTheDocument();
+
+    await waitForPlot('root');
+    
expect(screen.getByTestId('heatmap-plot')).toHaveAttribute('data-entity-type', 
'key');
+    expect(heatmapRequests).toEqual([{ path: '/', entityType: 'key', 
startDate: '24H' }]);
+  });
+
+  test('shows validation error for invalid path characters', async () => {
+    render(<Heatmap />);
+    await waitForPlot('root');
+
+    const pathInput = screen.getByPlaceholderText('/');
+    await userEvent.clear(pathInput);
+    await userEvent.type(pathInput, 'bad@path');
+
+    expect(screen.getByText('Please enter valid path')).toBeInTheDocument();
+  });

Review Comment:
   I think I found a small bug here. The error message shows up, but clicking 
Search still sends the invalid path to the API. Might be worth a follow-up Jira?



-- 
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]


---------------------------------------------------------------------
To unsubscribe, e-mail: [email protected]
For additional commands, e-mail: [email protected]

Reply via email to