Copilot commented on code in PR #34442:
URL: https://github.com/apache/superset/pull/34442#discussion_r2248597458


##########
superset-frontend/src/features/databases/DatabaseModal/DatabaseConnectionForm/EncryptedField.test.tsx:
##########
@@ -0,0 +1,864 @@
+/**
+ * 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 { render, fireEvent, screen } from 'spec/helpers/testing-library';
+import { t } from '@superset-ui/core';
+import { DatabaseObject, ConfigurationMethod } from '../../types';
+import { EncryptedField, encryptedCredentialsMap } from './EncryptedField';
+
+// Mock the useToasts hook
+const mockAddDangerToast = jest.fn();
+jest.mock('src/components/MessageToasts/withToasts', () => ({
+  useToasts: () => ({
+    addDangerToast: mockAddDangerToast,
+  }),
+}));
+
+// Mock FileReader with proper async simulation
+class MockFileReader implements Partial<FileReader> {
+  onload: ((this: FileReader, ev: ProgressEvent<FileReader>) => any) | null =
+    null;
+
+  onerror: ((this: FileReader, ev: ProgressEvent<FileReader>) => any) | null =
+    null;
+
+  onabort: ((this: FileReader, ev: ProgressEvent<FileReader>) => any) | null =
+    null;
+
+  onloadend: ((this: FileReader, ev: ProgressEvent<FileReader>) => any) | null 
=
+    null;
+
+  onloadstart:
+    | ((this: FileReader, ev: ProgressEvent<FileReader>) => any)
+    | null = null;
+
+  onprogress:
+    | ((this: FileReader, ev: ProgressEvent<FileReader>) => any)
+    | null = null;
+
+  result: string | null = null;
+
+  error: DOMException | null = null;
+
+  readyState: 0 | 1 | 2 = FileReader.DONE;
+
+  readAsText = jest.fn((_file: File) => {
+    // Simulate async file reading
+    setTimeout(() => {
+      if (this.result !== null && this.onload) {
+        this.onload.call(this as any, {} as ProgressEvent<FileReader>);
+      }
+    }, 0);
+  });
+
+  readAsArrayBuffer = jest.fn();
+
+  readAsBinaryString = jest.fn();
+
+  readAsDataURL = jest.fn();
+
+  abort = jest.fn();
+
+  addEventListener = jest.fn();
+
+  removeEventListener = jest.fn();
+
+  dispatchEvent = jest.fn();
+}
+
+const mockFileReader = new MockFileReader();
+
+Object.defineProperty(global, 'FileReader', {
+  writable: true,
+  value: jest.fn(() => mockFileReader),
+});
+
+describe('EncryptedField', () => {
+  // Generic test utilities
+  const createMockDb = (
+    engine: string,
+    parameters: Record<string, any> = {},
+  ): DatabaseObject => ({
+    configuration_method: ConfigurationMethod.DynamicForm,
+    database_name: 'test-db',
+    driver: 'test-driver',
+    id: 1,
+    name: 'Test Database',
+    is_managed_externally: false,
+    engine,
+    parameters,
+  });
+
+  const createMockChangeMethods = () => ({
+    onEncryptedExtraInputChange: jest.fn(),
+    onParametersChange: jest.fn(),
+    onChange: jest.fn(),
+    onQueryChange: jest.fn(),
+    onParametersUploadFileChange: jest.fn(),
+    onAddTableCatalog: jest.fn(),
+    onRemoveTableCatalog: jest.fn(),
+    onExtraInputChange: jest.fn(),
+    onSSHTunnelParametersChange: jest.fn(),
+  });
+
+  const defaultProps = {
+    required: false,
+    onParametersChange: jest.fn(),
+    onParametersUploadFileChange: jest.fn(),
+    changeMethods: createMockChangeMethods(),
+    validationErrors: null,
+    getValidation: jest.fn(),
+    clearValidationErrors: jest.fn(),
+    field: 'test',
+    isValidating: false,
+    isEditMode: false,
+    editNewDb: false,
+    db: createMockDb('test-engine'),
+  };
+
+  beforeEach(() => {
+    jest.clearAllMocks();
+    mockFileReader.readAsText.mockClear();
+    mockFileReader.result = null;
+  });
+
+  afterEach(() => {
+    jest.clearAllMocks();
+  });
+
+  describe('Core Logic Tests', () => {
+    describe('Field Name Resolution', () => {
+      it('resolves field name from credentials map and engine', () => {
+        const testEngine = 'mock-test-engine';
+        const testFieldName = 'mock_credential_field';
+
+        // Temporarily override the credentials map
+        const originalMap = { ...encryptedCredentialsMap };
+        (encryptedCredentialsMap as any)[testEngine] = testFieldName;
+
+        const mockDb = createMockDb(testEngine);
+        const props = { ...defaultProps, db: mockDb };
+
+        render(<EncryptedField {...props} />);
+
+        // Verify the component initialized with correct field name
+        expect(props.changeMethods.onParametersChange).toHaveBeenCalledWith({
+          target: {
+            name: testFieldName,
+            value: '',
+          },
+        });
+
+        // Restore original map
+        Object.assign(encryptedCredentialsMap, originalMap);
+        delete (encryptedCredentialsMap as any)[testEngine];

Review Comment:
   The pattern of temporarily modifying and then restoring the 
encryptedCredentialsMap is repeated throughout the test file. Consider creating 
a helper function or utility to encapsulate this setup/teardown pattern to 
reduce code duplication.
   ```suggestion
           // Use helper to temporarily override the credentials map
           withTemporaryEncryptedCredentialsMap(testEngine, testFieldName, () 
=> {
             const mockDb = createMockDb(testEngine);
             const props = { ...defaultProps, db: mockDb };
   
             render(<EncryptedField {...props} />);
   
             // Verify the component initialized with correct field name
             
expect(props.changeMethods.onParametersChange).toHaveBeenCalledWith({
               target: {
                 name: testFieldName,
                 value: '',
               },
             });
           });
   ```



##########
superset-frontend/src/features/databases/DatabaseModal/DatabaseConnectionForm/EncryptedField.test.tsx:
##########
@@ -0,0 +1,864 @@
+/**
+ * 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 { render, fireEvent, screen } from 'spec/helpers/testing-library';
+import { t } from '@superset-ui/core';
+import { DatabaseObject, ConfigurationMethod } from '../../types';
+import { EncryptedField, encryptedCredentialsMap } from './EncryptedField';
+
+// Mock the useToasts hook
+const mockAddDangerToast = jest.fn();
+jest.mock('src/components/MessageToasts/withToasts', () => ({
+  useToasts: () => ({
+    addDangerToast: mockAddDangerToast,
+  }),
+}));
+
+// Mock FileReader with proper async simulation
+class MockFileReader implements Partial<FileReader> {
+  onload: ((this: FileReader, ev: ProgressEvent<FileReader>) => any) | null =
+    null;
+
+  onerror: ((this: FileReader, ev: ProgressEvent<FileReader>) => any) | null =
+    null;
+
+  onabort: ((this: FileReader, ev: ProgressEvent<FileReader>) => any) | null =
+    null;
+
+  onloadend: ((this: FileReader, ev: ProgressEvent<FileReader>) => any) | null 
=
+    null;
+
+  onloadstart:
+    | ((this: FileReader, ev: ProgressEvent<FileReader>) => any)
+    | null = null;
+
+  onprogress:
+    | ((this: FileReader, ev: ProgressEvent<FileReader>) => any)
+    | null = null;
+
+  result: string | null = null;
+
+  error: DOMException | null = null;
+
+  readyState: 0 | 1 | 2 = FileReader.DONE;
+
+  readAsText = jest.fn((_file: File) => {
+    // Simulate async file reading
+    setTimeout(() => {
+      if (this.result !== null && this.onload) {
+        this.onload.call(this as any, {} as ProgressEvent<FileReader>);
+      }
+    }, 0);
+  });
+
+  readAsArrayBuffer = jest.fn();
+
+  readAsBinaryString = jest.fn();
+
+  readAsDataURL = jest.fn();
+
+  abort = jest.fn();
+
+  addEventListener = jest.fn();
+
+  removeEventListener = jest.fn();
+
+  dispatchEvent = jest.fn();
+}
+
+const mockFileReader = new MockFileReader();
+

Review Comment:
   [nitpick] The MockFileReader class has an extensive implementation spanning 
50+ lines but is only used to mock basic file reading functionality. Consider 
using jest.createMockFromModule() or a simpler mock implementation to reduce 
complexity and improve maintainability.
   ```suggestion
   // Mock FileReader with a simple Jest mock
   beforeAll(() => {
     // @ts-ignore
     global.FileReader = jest.fn().mockImplementation(() => {
       return {
         onload: null,
         result: null,
         readAsText: jest.fn(function (this: any, _file: File) {
           setTimeout(() => {
             if (this.onload) {
               this.onload({} as ProgressEvent<FileReader>);
             }
           }, 0);
         }),
       };
     });
   });
   
   afterAll(() => {
     // @ts-ignore
     delete global.FileReader;
   });
   ```



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