sadpandajoe commented on code in PR #44851:
URL: https://github.com/apache/superset/pull/44851#discussion_r4209791045


##########
superset-frontend/src/explore/actions/metadataSync.test.ts:
##########
@@ -0,0 +1,370 @@
+/**
+ * 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 { AnyAction, applyMiddleware, createStore } from 'redux';
+import {
+  ControlPanelState,
+  ControlStateMapping,
+  Dataset,
+  dndAdhocFilterControl,
+  datePickerInAdhocFilterMixin,
+} from '@superset-ui/chart-controls';
+import {
+  DatasourceType,
+  FeatureFlag,
+  getChartControlPanelRegistry,
+  QueryFormData,
+  TimeGranularity,
+  SupersetClient,
+} from '@superset-ui/core';
+import exploreReducer, {
+  ExploreState,
+} from 'src/explore/reducers/exploreReducer';
+import { ExplorePageState } from 'src/explore/types';
+import { getControlsState } from 'src/explore/store';
+import {
+  getControlConfig,
+  getControlStateFromControlConfig,
+  getFormDataFromControls,
+} from 'src/explore/controlUtils';
+import tableControlPanel from 
'../../../plugins/plugin-chart-table/src/controlPanel';
+import { buildQuery } from 
'../../../plugins/plugin-chart-table/src/buildQuery';
+import { TableChartFormData } from 
'../../../plugins/plugin-chart-table/src/types';
+import versionHistoryReducer, {
+  CLEAR_VERSION_SESSION_LOG,
+} from 'src/features/versionHistory/reducer';
+import { VersionHistoryState } from 'src/features/versionHistory/types';
+import { versionSessionLogMiddleware } from 
'src/features/versionHistory/sessionLogMiddleware';
+import {
+  refreshSemanticMetadata,
+  setExploreControls,
+  syncSemanticMetadata,
+} from './exploreActions';
+
+const vizType = 'metadata-sync-regression';
+
+beforeEach(() => {
+  getChartControlPanelRegistry().registerValue(vizType, {
+    controlPanelSections: [
+      {
+        controlSetRows: [
+          ['metrics'],
+          [
+            {
+              name: 'adhoc_filters',
+              config: {
+                ...dndAdhocFilterControl,
+                ...datePickerInAdhocFilterMixin,
+              },
+            },
+          ],
+          [
+            {
+              name: 'groupby',
+              config: {
+                type: 'SelectControl',
+                multi: true,
+                mapStateToProps: (state: ControlPanelState) => ({
+                  choices: (state.datasource as Dataset).columns.map(column => 
[
+                    column.column_name,
+                    column.column_name,
+                  ]),
+                }),
+              },
+            },
+          ],
+        ],
+      },
+    ],
+  });
+});
+
+afterEach(() => {
+  getChartControlPanelRegistry().remove(vizType);
+  jest.restoreAllMocks();
+});
+
+test.each([false, true])(
+  'metadata sync preserves a cleared time filter and logs only removed choices 
(removed choice: %s)',
+  async removed => {
+    const previousFlags = window.featureFlags;
+    window.featureFlags = {
+      ...previousFlags,
+      [FeatureFlag.VersionHistory]: true,
+    };
+    const datasource: Dataset = {
+      id: 7,
+      type: DatasourceType.SemanticView,
+      columns: [
+        { column_name: 'country', type: 'STRING', groupby: true },
+        { column_name: 'created_at', type: 'TIMESTAMP', is_dttm: true },
+      ],
+      metrics: [
+        { uuid: 'orders-metric', metric_name: 'orders', expression: 'orders' },
+      ],
+      column_formats: {},
+      verbose_map: {},
+      main_dttm_col: 'created_at',
+      datasource_name: 'orders',
+      description: null,
+    };
+    const formData: QueryFormData = {
+      datasource: '7__semantic_view',
+      viz_type: vizType,
+      metrics: ['orders'],
+      groupby: ['country'],
+      adhoc_filters: [],
+    };
+    const common = {
+      conf: { DEFAULT_VIZ_TYPE: vizType, DEFAULT_TIME_FILTER: 'Last year' },
+    };
+    const initialExplore: ExploreState = {
+      datasource,
+      common,
+      form_data: formData,
+      controls: {
+        datasource: { type: 'SelectControl', value: formData.datasource },
+        viz_type: { type: 'SelectControl', value: vizType },
+        metrics: { type: 'SelectControl', value: ['orders'] },
+        groupby: { type: 'SelectControl', value: ['country'] },
+      },
+    };
+    initialExplore.controls = getControlsState(
+      initialExplore as Parameters<typeof getControlsState>[0],
+      formData,
+    ) as ControlStateMapping;
+    expect(initialExplore.controls.adhoc_filters.value).toEqual([
+      expect.objectContaining({
+        operator: 'TEMPORAL_RANGE',
+        comparator: 'Last year',
+      }),
+    ]);
+    // The user removed the initialized time filter before syncing metadata.
+    initialExplore.controls.adhoc_filters = {
+      ...initialExplore.controls.adhoc_filters,
+      value: [],
+    };
+    Object.freeze(initialExplore.controls.metrics);
+    Object.freeze(initialExplore.controls.groupby);
+    Object.freeze(initialExplore.controls);
+    Object.freeze(initialExplore);
+    const initialState = {
+      explore: initialExplore,
+      versionHistory: versionHistoryReducer(undefined, {
+        type: CLEAR_VERSION_SESSION_LOG,
+      }),
+    };
+    const store = createStore(
+      (
+        state: {
+          explore: ExploreState;
+          versionHistory: VersionHistoryState;
+        } = initialState,
+        action: AnyAction,
+      ) => ({
+        explore: exploreReducer(
+          state.explore,
+          action as Parameters<typeof exploreReducer>[1],
+        ),
+        versionHistory: versionHistoryReducer(
+          state.versionHistory,
+          action as Parameters<typeof versionHistoryReducer>[1],
+        ),
+      }),
+      applyMiddleware(versionSessionLogMiddleware),
+    );
+    const fresh: Dataset = {
+      ...datasource,
+      columns: removed ? [] : datasource.columns,
+      metrics: [
+        ...datasource.metrics,
+        {
+          uuid: 'revenue-metric',
+          metric_name: 'revenue',
+          expression: 'revenue',
+        },
+      ],
+    };
+    const getSpy = jest
+      .spyOn(SupersetClient, 'get')
+      .mockResolvedValueOnce({ json: fresh } as never);
+    const postSpy = jest.spyOn(SupersetClient, 'post').mockResolvedValueOnce({
+      json: {
+        result: {
+          compatible_metrics: ['orders', 'revenue'],
+          compatible_dimensions: ['country'],
+        },
+      },
+    } as never);
+    try {
+      await refreshSemanticMetadata(7, () => true)(
+        store.dispatch,
+        () => store.getState() as Pick<ExplorePageState, 'explore'>,
+      );
+      expect(getSpy).toHaveBeenCalledTimes(1);
+      expect(postSpy).toHaveBeenCalledTimes(1);
+      expect(store.getState().explore.datasource).toEqual(fresh);

Review Comment:
   This test adds a `revenue` metric to the refreshed datasource, but it only 
asserts the datasource swap and that the selected `orders` value is preserved. 
If the reducer stopped refreshing each control's `savedMetrics`, every 
assertion here would still pass while the new metric stayed unselectable in 
Explore, which is the headline behavior of the sync. Could you assert that the 
metric control's `savedMetrics` includes `revenue` after the sync (ideally a 
Big Number singleton `metric` control selecting it, so `controls.metric.value 
=== 'revenue'`)?



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