You are viewing a plain text version of this content. The canonical link for it is here.
Posted to notifications@superset.apache.org by "sadpandajoe (via GitHub)" <gi...@apache.org> on 2025/11/18 23:16:54 UTC
[PR] refactor(datasets): add comprehensive unit tests for dataset API hooks and fix api guards [superset]
sadpandajoe opened a new pull request, #36175:
URL: https://github.com/apache/superset/pull/36175
<!---
Please write the PR title following the conventions at https://www.conventionalcommits.org/en/v1.0.0/
Example:
fix(dashboard): load charts correctly
-->
### SUMMARY
This PR adds comprehensive unit test coverage for the dataset API hooks used in the filter configuration flow, plus fixes two critical bugs discovered during testing.
**New Test Coverage (35 tests)**
src/hooks/apiResources/datasets.test.ts (21 tests)
- getDatasetId utility function - ID extraction from string/numeric formats
- createVerboseMap utility function - verbose name mapping from columns/metrics
- useDatasetDrillInfo hook - REST API path, caching behavior, error handling
- Extension path coverage - drill-by extension integration, error handling, malformed payloads
- Edge cases - NaN IDs, empty strings, malformed datasource IDs
src/features/datasets/hooks/useDatasetLists.test.ts (14 tests)
- Pagination - single page, multi-page fetching
- Error handling - API errors, network timeouts, persistent failures
- Guard conditions - schema null/undefined, database undefined
- Schema encoding - special characters in schema names
**Bug Fixes**
1. Pagination infinite loop (useDatasetLists.ts:68)
- Problem: Error handler in pagination loop didn't break, causing infinite retries on persistent API errors
- Fix: Added break statement in catch block
- Risk: CRITICAL - could cause browser hangs/crashes
2. Missing database guard (useDatasetLists.ts:82)
- Problem: API calls fired with database: undefined when db not selected
- Fix: Added db?.id !== undefined check to guard condition
- Risk: MEDIUM - API spam with malformed filters
### BEFORE/AFTER SCREENSHOTS OR ANIMATED GIF
<!--- Skip this if not applicable -->
### TESTING INSTRUCTIONS
<!--- Required! What steps can be taken to manually verify the changes? -->
### ADDITIONAL INFORMATION
<!--- Check any relevant boxes with "x" -->
<!--- HINT: Include "Fixes #nnn" if you are fixing an existing issue -->
- [ ] Has associated issue:
- [ ] Required feature flags:
- [ ] Changes UI
- [ ] Includes DB Migration (follow approval process in [SIP-59](https://github.com/apache/superset/issues/13351))
- [ ] Migration is atomic, supports rollback & is backwards-compatible
- [ ] Confirm DB migration upgrade and downgrade tested
- [ ] Runtime estimates and downtime expectations provided
- [ ] Introduces new feature or API
- [ ] Removes existing feature or API
--
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: notifications-unsubscribe@superset.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
---------------------------------------------------------------------
To unsubscribe, e-mail: notifications-unsubscribe@superset.apache.org
For additional commands, e-mail: notifications-help@superset.apache.org
Re: [PR] refactor(datasets): add comprehensive unit tests for dataset API hooks and fix api guards [superset]
Posted by "sadpandajoe (via GitHub)" <gi...@apache.org>.
sadpandajoe merged PR #36175:
URL: https://github.com/apache/superset/pull/36175
--
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: notifications-unsubscribe@superset.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
---------------------------------------------------------------------
To unsubscribe, e-mail: notifications-unsubscribe@superset.apache.org
For additional commands, e-mail: notifications-help@superset.apache.org
Re: [PR] refactor(datasets): add comprehensive unit tests for dataset API hooks and fix api guards [superset]
Posted by "bito-code-review[bot] (via GitHub)" <gi...@apache.org>.
bito-code-review[bot] commented on PR #36175:
URL: https://github.com/apache/superset/pull/36175#issuecomment-3549833723
AI Code Review is in progress (usually takes 3 to 15 minutes unless it's a very large PR).
--
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: notifications-unsubscribe@superset.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
---------------------------------------------------------------------
To unsubscribe, e-mail: notifications-unsubscribe@superset.apache.org
For additional commands, e-mail: notifications-help@superset.apache.org
Re: [PR] refactor(datasets): add comprehensive unit tests for dataset API hooks and fix api guards [superset]
Posted by "Copilot (via GitHub)" <gi...@apache.org>.
Copilot commented on code in PR #36175:
URL: https://github.com/apache/superset/pull/36175#discussion_r2539927695
##########
superset-frontend/src/hooks/apiResources/datasets.test.ts:
##########
@@ -0,0 +1,453 @@
+/**
+ * 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 { renderHook } from '@testing-library/react-hooks';
+import { Dataset } from 'src/components/Chart/types';
+import {
+ cachedSupersetGet,
+ supersetGetCache,
+} from 'src/utils/cachedSupersetGet';
+import {
+ getDatasetId,
+ createVerboseMap,
+ useDatasetDrillInfo,
+} from './datasets';
+
+jest.mock('src/utils/cachedSupersetGet', () => ({
+ cachedSupersetGet: jest.fn(),
+ supersetGetCache: {
+ delete: jest.fn(),
+ },
+}));
+
+// Mock getExtensionsRegistry at module level - returns undefined by default
+const mockGetExtensionsRegistry = jest.fn(() => ({ get: () => undefined }));
+jest.mock('@superset-ui/core', () => ({
+ ...jest.requireActual('@superset-ui/core'),
+ getExtensionsRegistry: () => mockGetExtensionsRegistry(),
+}));
+
+const mockedCachedSupersetGet = jest.mocked(cachedSupersetGet);
+const mockedSupersetGetCacheDelete = jest.mocked(supersetGetCache.delete);
+
+test('getDatasetId extracts numeric ID from string datasource ID', () => {
+ expect(getDatasetId('123__table')).toBe(123);
+ expect(getDatasetId('456__another_table')).toBe(456);
+});
+
+test('getDatasetId handles numeric datasource ID', () => {
+ expect(getDatasetId(789)).toBe(789);
+ expect(getDatasetId(0)).toBe(0);
+});
+
+test('createVerboseMap creates verbose_map from columns', () => {
+ const dataset = {
+ columns: [
+ { column_name: 'col1', verbose_name: 'Column 1' },
+ { column_name: 'col2', verbose_name: 'Column 2' },
+ { column_name: 'col3' }, // no verbose_name
+ ],
+ metrics: [],
+ } as Dataset;
+
+ const verboseMap = createVerboseMap(dataset);
+
+ expect(verboseMap).toEqual({
+ col1: 'Column 1',
+ col2: 'Column 2',
+ col3: 'col3', // falls back to column_name
+ });
+});
+
+test('createVerboseMap creates verbose_map from metrics', () => {
+ const dataset = {
+ columns: [],
+ metrics: [
+ { metric_name: 'metric1', verbose_name: 'Metric 1' },
+ { metric_name: 'metric2', verbose_name: 'Metric 2' },
+ { metric_name: 'metric3' }, // no verbose_name
+ ],
+ } as any;
+
+ const verboseMap = createVerboseMap(dataset);
+
+ expect(verboseMap).toEqual({
+ metric1: 'Metric 1',
+ metric2: 'Metric 2',
+ metric3: 'metric3', // falls back to metric_name
+ });
+});
+
+test('createVerboseMap creates verbose_map from both columns and metrics', () => {
+ const dataset = {
+ columns: [{ column_name: 'col1', verbose_name: 'Column 1' }],
+ metrics: [{ metric_name: 'metric1', verbose_name: 'Metric 1' }],
+ } as Dataset;
+
+ const verboseMap = createVerboseMap(dataset);
+
+ expect(verboseMap).toEqual({
+ col1: 'Column 1',
+ metric1: 'Metric 1',
+ });
+});
+
+test('createVerboseMap handles undefined dataset', () => {
+ const verboseMap = createVerboseMap(undefined);
+ expect(verboseMap).toEqual({});
+});
+
+// eslint-disable-next-line no-restricted-globals -- TODO: Migrate from describe blocks
+describe('useDatasetDrillInfo', () => {
+ beforeEach(() => {
+ jest.clearAllMocks();
+ });
+
+ test('fetches dataset drill info successfully', async () => {
+ const mockDataset = {
+ id: 123,
+ columns: [{ column_name: 'col1', verbose_name: 'Column 1' }],
+ metrics: [{ metric_name: 'metric1', verbose_name: 'Metric 1' }],
+ };
+
+ mockedCachedSupersetGet.mockResolvedValue({
+ json: {
+ result: mockDataset,
+ },
+ } as any);
+
+ const { result, waitForNextUpdate } = renderHook(() =>
+ useDatasetDrillInfo(123, 456),
+ );
+
+ expect(result.current.status).toBe('loading');
+
+ await waitForNextUpdate();
+
+ expect(result.current.status).toBe('complete');
+ expect(result.current.result).toEqual({
+ ...mockDataset,
+ verbose_map: {
+ col1: 'Column 1',
+ metric1: 'Metric 1',
+ },
+ });
+ expect(result.current.error).toBeNull();
+ });
+
+ test('handles network errors', async () => {
+ mockedCachedSupersetGet.mockRejectedValue(new Error('Network error'));
+
+ const { result, waitForNextUpdate } = renderHook(() =>
+ useDatasetDrillInfo(123, 456),
+ );
+
+ await waitForNextUpdate();
+
+ expect(result.current.status).toBe('error');
+ expect(result.current.result).toBeNull();
+ expect(result.current.error).toBeInstanceOf(Error);
+ expect(result.current.error?.message).toBe('Network error');
+ expect(mockedSupersetGetCacheDelete).toHaveBeenCalled();
+ });
+
+ test('skips fetch when skip is true', async () => {
+ const { result } = renderHook(() =>
+ useDatasetDrillInfo(123, 456, undefined, true),
+ );
+
+ // Should immediately return complete status without fetching
+ expect(result.current.status).toBe('complete');
+ expect(result.current.result).toEqual({});
+ expect(result.current.error).toBeNull();
+
+ // Verify no API call was made
+ expect(mockedCachedSupersetGet).not.toHaveBeenCalled();
+ });
+
+ test('extracts dataset ID from string format', async () => {
+ const mockDataset = {
+ id: 123,
+ columns: [],
+ metrics: [],
+ };
+
+ mockedCachedSupersetGet.mockResolvedValue({
+ json: {
+ result: mockDataset,
+ },
+ } as any);
+
+ const { result, waitForNextUpdate } = renderHook(() =>
+ useDatasetDrillInfo('123__table', 456),
+ );
+
+ await waitForNextUpdate();
+
+ expect(result.current.status).toBe('complete');
+ expect(mockedCachedSupersetGet).toHaveBeenCalledWith({
+ endpoint: '/api/v1/dataset/123/drill_info/?q=(dashboard_id:456)',
+ });
+ });
+
+ test('does not clear cache on successful fetch', async () => {
+ const mockDataset = {
+ id: 123,
+ columns: [],
+ metrics: [],
+ };
+
+ mockedCachedSupersetGet.mockResolvedValue({
+ json: {
+ result: mockDataset,
+ },
+ } as any);
+
+ const { waitForNextUpdate } = renderHook(() =>
+ useDatasetDrillInfo(123, 456),
+ );
+
+ await waitForNextUpdate();
+
+ // Cache should NOT be deleted on success
+ expect(mockedSupersetGetCacheDelete).not.toHaveBeenCalled();
+ });
+
+ test('creates new verbose_map from columns and metrics', async () => {
+ const mockDataset = {
+ id: 123,
+ verbose_map: { old_key: 'Old Value' }, // Existing verbose_map will be replaced
+ columns: [{ column_name: 'col1', verbose_name: 'Column 1' }],
+ metrics: [{ metric_name: 'metric1', verbose_name: 'Metric 1' }],
+ };
+
+ mockedCachedSupersetGet.mockResolvedValue({
+ json: {
+ result: mockDataset,
+ },
+ } as any);
+
+ const { result, waitForNextUpdate } = renderHook(() =>
+ useDatasetDrillInfo(123, 456),
+ );
+
+ await waitForNextUpdate();
+
+ expect(result.current.status).toBe('complete');
+ // Verify verbose_map is created from columns/metrics (existing verbose_map replaced)
+ expect(result.current.result?.verbose_map).toEqual({
+ col1: 'Column 1',
+ metric1: 'Metric 1',
+ });
+ // Old key should not be present
+ expect(result.current.result?.verbose_map).not.toHaveProperty('old_key');
+ });
+
+ test('handles NaN datasource ID from malformed string', async () => {
+ mockedCachedSupersetGet.mockResolvedValue({
+ json: {
+ result: { id: NaN, columns: [], metrics: [] },
+ },
+ } as any);
+
+ const { result, waitForNextUpdate } = renderHook(() =>
+ useDatasetDrillInfo('abc', 456),
+ );
+
+ await waitForNextUpdate();
+
+ // Verify hook calls endpoint with NaN (API will handle validation)
+ expect(mockedCachedSupersetGet).toHaveBeenCalledWith({
+ endpoint: '/api/v1/dataset/NaN/drill_info/?q=(dashboard_id:456)',
+ });
+ expect(result.current.status).toBe('complete');
+ });
+});
+
+// eslint-disable-next-line no-restricted-globals -- TODO: Migrate from describe blocks
+describe('getDatasetId - malformed IDs', () => {
+ test('handles non-numeric string ID', () => {
+ const result = getDatasetId('abc');
+ expect(result).toBeNaN();
Review Comment:
The `toBeNaN()` matcher doesn't exist in Jest. Use `.toBe(NaN)` or `expect(Number.isNaN(result)).toBe(true)` instead. This test will fail at runtime.
```suggestion
expect(Number.isNaN(result)).toBe(true);
```
--
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: notifications-unsubscribe@superset.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
---------------------------------------------------------------------
To unsubscribe, e-mail: notifications-unsubscribe@superset.apache.org
For additional commands, e-mail: notifications-help@superset.apache.org
Re: [PR] refactor(datasets): add comprehensive unit tests for dataset API hooks and fix api guards [superset]
Posted by "bito-code-review[bot] (via GitHub)" <gi...@apache.org>.
bito-code-review[bot] commented on code in PR #36175:
URL: https://github.com/apache/superset/pull/36175#discussion_r2539935332
##########
superset-frontend/src/features/datasets/hooks/useDatasetLists.test.ts:
##########
@@ -0,0 +1,392 @@
+/**
+ * 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 { renderHook } from '@testing-library/react-hooks';
+import { SupersetClient } from '@superset-ui/core';
+import rison from 'rison';
+import useDatasetsList from './useDatasetLists';
+
+const mockAddDangerToast = jest.fn();
+jest.mock('src/components/MessageToasts/actions', () => ({
+ addDangerToast: (msg: string) => mockAddDangerToast(msg),
+}));
+
+// Shared test fixtures
+const mockDb = {
+ id: 1,
+ database_name: 'test_db',
+ owners: [1] as [number],
+};
+
+const mockDatasets = [
+ { id: 1, table_name: 'table1', schema: 'public' },
+ { id: 2, table_name: 'table2', schema: 'public' },
+];
+
+beforeEach(() => {
+ jest.clearAllMocks();
+});
+
+afterEach(() => {
+ jest.restoreAllMocks();
+});
+
+test('useDatasetsList fetches first page of datasets successfully', async () => {
+ const getSpy = jest.spyOn(SupersetClient, 'get').mockResolvedValue({
+ json: {
+ count: 2,
+ result: mockDatasets,
+ },
+ } as any);
+
+ const { result, waitForNextUpdate } = renderHook(() =>
+ useDatasetsList(mockDb, 'public'),
+ );
+
+ await waitForNextUpdate();
+
+ expect(result.current.datasets).toEqual(mockDatasets);
+ expect(result.current.datasetNames).toEqual(['table1', 'table2']);
+ expect(getSpy).toHaveBeenCalledTimes(1);
+});
+
+test('useDatasetsList fetches multiple pages (pagination) until count reached', async () => {
+ const page1Data = [
+ { id: 1, table_name: 'table1', schema: 'public' },
+ { id: 2, table_name: 'table2', schema: 'public' },
+ ];
+ const page2Data = [{ id: 3, table_name: 'table3', schema: 'public' }];
+
+ const getSpy = jest
+ .spyOn(SupersetClient, 'get')
+ .mockResolvedValueOnce({
+ json: {
+ count: 3,
+ result: page1Data,
+ },
+ } as any)
+ .mockResolvedValueOnce({
+ json: {
+ count: 3,
+ result: page2Data,
+ },
+ } as any);
+
+ const { result, waitForNextUpdate } = renderHook(() =>
+ useDatasetsList(mockDb, 'public'),
+ );
+
+ await waitForNextUpdate();
+
+ expect(result.current.datasets).toEqual([...page1Data, ...page2Data]);
+ expect(result.current.datasetNames).toEqual(['table1', 'table2', 'table3']);
+ expect(getSpy).toHaveBeenCalledTimes(2);
+});
+
+test('useDatasetsList extracts dataset names correctly', async () => {
+ const getSpy = jest.spyOn(SupersetClient, 'get').mockResolvedValue({
+ json: {
+ count: 3,
+ result: [
+ { id: 1, table_name: 'users' },
+ { id: 2, table_name: 'orders' },
+ { id: 3, table_name: 'products' },
+ ],
+ },
+ } as any);
+
+ const { result, waitForNextUpdate } = renderHook(() =>
+ useDatasetsList(mockDb, 'public'),
+ );
+
+ await waitForNextUpdate();
+
+ expect(result.current.datasetNames).toEqual(['users', 'orders', 'products']);
+ expect(getSpy).toHaveBeenCalledTimes(1);
+});
+
+test('useDatasetsList handles API 500 error gracefully', async () => {
+ // Mock error - loop should break immediately
+ const getSpy = jest
+ .spyOn(SupersetClient, 'get')
+ .mockRejectedValue(new Error('Internal Server Error'));
+
+ const { result, waitForNextUpdate } = renderHook(() =>
+ useDatasetsList(mockDb, 'public'),
+ );
+
+ await waitForNextUpdate();
+
+ expect(result.current.datasets).toEqual([]);
+ expect(result.current.datasetNames).toEqual([]);
+ expect(mockAddDangerToast).toHaveBeenCalledWith(
+ 'There was an error fetching dataset',
+ );
+ // Should only be called once - error causes break
+ expect(getSpy).toHaveBeenCalledTimes(1);
+});
+
+test('useDatasetsList handles empty dataset response', async () => {
+ const getSpy = jest.spyOn(SupersetClient, 'get').mockResolvedValue({
+ json: {
+ count: 0,
+ result: [],
+ },
+ } as any);
+
+ const { result, waitForNextUpdate } = renderHook(() =>
+ useDatasetsList(mockDb, 'public'),
+ );
+
+ await waitForNextUpdate();
+
+ expect(result.current.datasets).toEqual([]);
+ expect(result.current.datasetNames).toEqual([]);
+ expect(getSpy).toHaveBeenCalledTimes(1);
+});
+
+test('useDatasetsList stops pagination when results reach count', async () => {
+ // First page returns 2 items, second page returns empty (no more results)
+ const getSpy = jest
+ .spyOn(SupersetClient, 'get')
+ .mockResolvedValueOnce({
+ json: {
+ count: 2,
+ result: [
+ { id: 1, table_name: 'table1' },
+ { id: 2, table_name: 'table2' },
+ ],
+ },
+ } as any)
+ .mockResolvedValueOnce({
+ json: {
+ count: 2,
+ result: [], // No more results
+ },
+ } as any);
+
+ const { result, waitForNextUpdate } = renderHook(() =>
+ useDatasetsList(mockDb, 'public'),
+ );
+
+ await waitForNextUpdate();
+
+ expect(result.current.datasets).toHaveLength(2);
+ expect(result.current.datasetNames).toEqual(['table1', 'table2']);
+ // Should stop after results.length >= count
+ expect(getSpy).toHaveBeenCalledTimes(1);
+});
+
+test('useDatasetsList resets datasets when schema changes', async () => {
+ const getSpy = jest
+ .spyOn(SupersetClient, 'get')
+ .mockResolvedValueOnce({
+ json: {
+ count: 2,
+ result: [
+ { id: 1, table_name: 'public_table1' },
+ { id: 2, table_name: 'public_table2' },
+ ],
+ },
+ } as any)
+ .mockResolvedValueOnce({
+ json: {
+ count: 1,
+ result: [{ id: 3, table_name: 'private_table1' }],
+ },
+ } as any);
+
+ const { result, waitForNextUpdate, rerender } = renderHook(
+ ({ db, schema }) => useDatasetsList(db, schema),
+ {
+ initialProps: { db: mockDb, schema: 'public' },
+ },
+ );
+
+ await waitForNextUpdate();
+
+ expect(result.current.datasetNames).toEqual([
+ 'public_table1',
+ 'public_table2',
+ ]);
+
+ // Change schema
+ rerender({ db: mockDb, schema: 'private' });
+
+ await waitForNextUpdate();
+
+ // Should have new datasets from private schema
+ expect(result.current.datasetNames).toEqual(['private_table1']);
+ expect(getSpy).toHaveBeenCalledTimes(2);
+});
+
+test('useDatasetsList handles network timeout gracefully', async () => {
+ // Mock timeout/abort error (status: 0)
+ const timeoutError = new Error('Network timeout');
+ (timeoutError as any).status = 0;
+
+ const getSpy = jest
+ .spyOn(SupersetClient, 'get')
+ .mockRejectedValue(timeoutError);
+
+ const { result, waitForNextUpdate } = renderHook(() =>
+ useDatasetsList(mockDb, 'public'),
+ );
+
+ await waitForNextUpdate();
+
+ expect(result.current.datasets).toEqual([]);
+ expect(result.current.datasetNames).toEqual([]);
+ expect(mockAddDangerToast).toHaveBeenCalledWith(
+ 'There was an error fetching dataset',
+ );
+ // Should only be called once - error causes break
+ expect(getSpy).toHaveBeenCalledTimes(1);
+});
+
+test('useDatasetsList breaks pagination loop on persistent API errors', async () => {
+ // Mock API that always fails (persistent error)
+ const getSpy = jest
+ .spyOn(SupersetClient, 'get')
+ .mockRejectedValue(new Error('Persistent server error'));
+
+ const { result, waitForNextUpdate } = renderHook(() =>
+ useDatasetsList(mockDb, 'public'),
+ );
+
+ await waitForNextUpdate();
+
+ // Should only attempt once, then break (not infinite loop)
+ expect(getSpy).toHaveBeenCalledTimes(1);
+ expect(result.current.datasets).toEqual([]);
+ expect(result.current.datasetNames).toEqual([]);
+ expect(mockAddDangerToast).toHaveBeenCalledWith(
+ 'There was an error fetching dataset',
+ );
+ expect(mockAddDangerToast).toHaveBeenCalledTimes(1);
+});
+
+test('useDatasetsList handles error on second page gracefully', async () => {
+ // First page succeeds, second page fails
+ const getSpy = jest
+ .spyOn(SupersetClient, 'get')
+ .mockResolvedValueOnce({
+ json: {
+ count: 3, // Indicates more data exists
+ result: [{ id: 1, table_name: 'table1' }],
+ },
+ } as any)
+ .mockRejectedValue(new Error('Second page error'));
+
+ const { result, waitForNextUpdate } = renderHook(() =>
+ useDatasetsList(mockDb, 'public'),
+ );
+
+ await waitForNextUpdate();
+
+ // Should have first page data, then stop on error
+ expect(getSpy).toHaveBeenCalledTimes(2);
+ expect(result.current.datasets).toHaveLength(1);
+ expect(result.current.datasets[0].table_name).toBe('table1');
+ expect(result.current.datasetNames).toEqual(['table1']);
+ expect(mockAddDangerToast).toHaveBeenCalledWith(
+ 'There was an error fetching dataset',
+ );
+ expect(mockAddDangerToast).toHaveBeenCalledTimes(1);
+});
+
+test('useDatasetsList skips fetching when schema is null or undefined', () => {
+ const getSpy = jest.spyOn(SupersetClient, 'get');
+
+ // Test with null schema
+ const { result: resultNull, rerender } = renderHook(
+ ({ db, schema }) => useDatasetsList(db, schema),
+ { initialProps: { db: mockDb, schema: null as any } },
+ );
+
+ // Schema is null - should NOT call API
+ expect(getSpy).not.toHaveBeenCalled();
+ expect(resultNull.current.datasets).toEqual([]);
+ expect(resultNull.current.datasetNames).toEqual([]);
+
+ // Change to undefined - still should NOT call API
+ rerender({ db: mockDb, schema: undefined as any });
+ expect(getSpy).not.toHaveBeenCalled();
+ expect(resultNull.current.datasets).toEqual([]);
+ expect(resultNull.current.datasetNames).toEqual([]);
+});
+
+test('useDatasetsList skips fetching when db is undefined', () => {
+ const getSpy = jest.spyOn(SupersetClient, 'get');
+
+ const { result } = renderHook(() => useDatasetsList(undefined, 'public'));
+
+ // db is undefined - should NOT call API
+ expect(getSpy).not.toHaveBeenCalled();
+ expect(result.current.datasets).toEqual([]);
+ expect(result.current.datasetNames).toEqual([]);
+});
+
+test('useDatasetsList skips fetching when db.id is undefined', () => {
+ const getSpy = jest.spyOn(SupersetClient, 'get');
+
+ // Create db object without id property
+ const dbWithoutId = {
+ database_name: 'test_db',
+ owners: [1] as [number],
+ } as any;
+
+ const { result } = renderHook(() => useDatasetsList(dbWithoutId, 'public'));
+
+ // db.id is undefined - should NOT call API
+ expect(getSpy).not.toHaveBeenCalled();
+ expect(result.current.datasets).toEqual([]);
+ expect(result.current.datasetNames).toEqual([]);
+});
+
+test('useDatasetsList encodes schemas with spaces and special characters in endpoint URL', async () => {
+ const getSpy = jest.spyOn(SupersetClient, 'get').mockResolvedValue({
+ json: { count: 0, result: [] },
+ } as any);
+
+ const { waitForNextUpdate } = renderHook(() =>
+ useDatasetsList(mockDb, 'sales analytics'),
+ );
+
+ await waitForNextUpdate();
+
+ // Verify API was called with encoded schema
+ expect(getSpy).toHaveBeenCalledTimes(1);
+ const callArg = getSpy.mock.calls[0]?.[0]?.endpoint;
+ expect(callArg).toBeDefined();
+
+ // Verify the encoded schema is present in the URL (double-encoded by rison)
+ // Schema 'sales analytics' -> encodeURIComponent -> 'sales%20analytics' -> rison.encode_uri -> 'sales%2520analytics'
+ expect(callArg).toContain('sales%2520analytics');
Review Comment:
<div>
<div id="suggestion">
<div id="issue"><b>Incorrect URL encoding expectation in test</b></div>
<div id="fix">
The test expects double-encoded schema in the URL, but rison does not encode percent signs, leading to incorrect validation. Update to expect 'sales%20analytics' instead of 'sales%2520analytics' to match actual rison behavior. This affects the `useDatasetsList` hook's API endpoint construction, where schema encoding is critical for proper URL formation and API calls.
</div>
<details>
<summary>
<b>Code suggestion</b>
</summary>
<blockquote>Check the AI-generated fix before applying</blockquote>
<div id="code">
````suggestion
// Verify the encoded schema is present in the URL (encoded by rison)
// Schema 'sales analytics' -> encodeURIComponent -> 'sales%20analytics' -> rison.encode_uri -> 'sales%20analytics'
expect(callArg).toContain('sales%20analytics');
````
</div>
</details>
</div>
<small><i>Code Review Run <a href=https://github.com/apache/superset/pull/36175#issuecomment-3549833723>#7e8d58</a></i></small>
</div>
---
Should Bito avoid suggestions like this for future reviews? (<a href=https://alpha.bito.ai/home/ai-agents/review-rules>Manage Rules</a>)
- [ ] Yes, avoid them
--
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: notifications-unsubscribe@superset.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
---------------------------------------------------------------------
To unsubscribe, e-mail: notifications-unsubscribe@superset.apache.org
For additional commands, e-mail: notifications-help@superset.apache.org