level_0
int64 0
10k
| index
int64 0
0
| repo_id
stringlengths 22
152
| file_path
stringlengths 41
203
| content
stringlengths 11
11.5M
|
---|---|---|---|---|
7,743 | 0 | petrpan-code/apache/superset/superset-frontend/src/explore | petrpan-code/apache/superset/superset-frontend/src/explore/exploreUtils/getHostName.test.ts | /**
* 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 { getHostName } from '.';
jest.mock('src/utils/hostNamesConfig', () => ({
availableDomains: [
'domain-a',
'domain-b',
'domain-c',
'domain-d',
'domain-e',
'domain-f',
'domain-g',
],
}));
test('Should get next different domain on a loop, never the first on the list', () => {
for (let loop = 3; loop > 0; loop -= 1) {
expect(getHostName(true)).toBe('domain-b');
expect(getHostName(true)).toBe('domain-c');
expect(getHostName(true)).toBe('domain-d');
expect(getHostName(true)).toBe('domain-e');
expect(getHostName(true)).toBe('domain-f');
expect(getHostName(true)).toBe('domain-g');
}
});
test('Should always return the same domain, the first on the list', () => {
expect(getHostName(false)).toBe('domain-a');
expect(getHostName(false)).toBe('domain-a');
});
test('Should always return the same domain, the first on the list - no args', () => {
expect(getHostName()).toBe('domain-a');
expect(getHostName()).toBe('domain-a');
});
|
7,744 | 0 | petrpan-code/apache/superset/superset-frontend/src/explore | petrpan-code/apache/superset/superset-frontend/src/explore/exploreUtils/getLegacyEndpointType.test.ts | /**
* 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 { getLegacyEndpointType } from '.';
const createParams = () => ({
resultType: 'resultType',
resultFormat: 'resultFormat',
});
test('Should return resultType when resultFormat!=csv', () => {
expect(getLegacyEndpointType(createParams())).toBe('resultType');
});
test('Should return resultFormat when resultFormat:csv', () => {
expect(
getLegacyEndpointType({ ...createParams(), resultFormat: 'csv' }),
).toBe('csv');
});
|
7,745 | 0 | petrpan-code/apache/superset/superset-frontend/src/explore | petrpan-code/apache/superset/superset-frontend/src/explore/exploreUtils/getParsedExploreURLParams.test.ts | /**
* 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 { getParsedExploreURLParams } from './getParsedExploreURLParams';
const EXPLORE_BASE_URL = 'http://localhost:9000/explore/';
const setupLocation = (newUrl: string) => {
delete (window as any).location;
// @ts-ignore
window.location = new URL(newUrl);
};
test('get form_data_key and slice_id from search params - url when moving from dashboard to explore', () => {
setupLocation(
`${EXPLORE_BASE_URL}?form_data_key=yrLXmyE9fmhQ11lM1KgaD1PoPSBpuLZIJfqdyIdw9GoBwhPFRZHeIgeFiNZljbpd&slice_id=56`,
);
expect(getParsedExploreURLParams().toString()).toEqual(
'form_data_key=yrLXmyE9fmhQ11lM1KgaD1PoPSBpuLZIJfqdyIdw9GoBwhPFRZHeIgeFiNZljbpd&slice_id=56',
);
});
test('get slice_id from form_data search param - url on Chart List', () => {
setupLocation(`${EXPLORE_BASE_URL}?form_data=%7B%22slice_id%22%3A%2056%7D`);
expect(getParsedExploreURLParams().toString()).toEqual('slice_id=56');
});
test('get datasource and viz type from form_data search param - url when creating new chart', () => {
setupLocation(
`${EXPLORE_BASE_URL}?form_data=%7B%22viz_type%22%3A%22big_number%22%2C%22datasource%22%3A%222__table%22%7D`,
);
expect(getParsedExploreURLParams().toString()).toEqual(
'viz_type=big_number&datasource_id=2&datasource_type=table',
);
});
test('get permalink key from path params', () => {
setupLocation(`${EXPLORE_BASE_URL}p/kpOqweaMY9R/`);
expect(getParsedExploreURLParams().toString()).toEqual(
'permalink_key=kpOqweaMY9R',
);
});
test('get dataset id from path params', () => {
setupLocation(`${EXPLORE_BASE_URL}table/42/`);
expect(getParsedExploreURLParams().toString()).toEqual('datasource_id=42');
});
|
7,747 | 0 | petrpan-code/apache/superset/superset-frontend/src/explore | petrpan-code/apache/superset/superset-frontend/src/explore/exploreUtils/getSimpleSQLExpression.test.ts | /**
* 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 { EMPTY_STRING, NULL_STRING } from 'src/utils/common';
import { getSimpleSQLExpression } from '.';
import { Operators } from '../constants';
const params = {
subject: 'subject',
operator: 'operator',
comparator: 'comparator',
};
test('Should return "" if subject is falsy', () => {
expect(getSimpleSQLExpression('', params.operator, params.comparator)).toBe(
'',
);
expect(getSimpleSQLExpression(null, params.operator, params.comparator)).toBe(
'',
);
expect(
getSimpleSQLExpression(undefined, params.operator, params.comparator),
).toBe('');
});
test('Should return null string and empty string', () => {
expect(getSimpleSQLExpression(params.subject, Operators.IN, [null, ''])).toBe(
`subject ${Operators.IN} (${NULL_STRING}, ${EMPTY_STRING})`,
);
});
test('Should return subject if operator is falsy', () => {
expect(getSimpleSQLExpression(params.subject, '', params.comparator)).toBe(
params.subject,
);
expect(getSimpleSQLExpression(params.subject, null, params.comparator)).toBe(
params.subject,
);
expect(
getSimpleSQLExpression(params.subject, undefined, params.comparator),
).toBe(params.subject);
});
test('Should return correct string when subject and operator are valid values', () => {
expect(
getSimpleSQLExpression(params.subject, params.operator, params.comparator),
).toBe("subject operator 'comparator'");
expect(
getSimpleSQLExpression(params.subject, params.operator, [
params.comparator,
'comparator-2',
]),
).toBe("subject operator 'comparator', 'comparator-2'");
});
|
7,748 | 0 | petrpan-code/apache/superset/superset-frontend/src/explore | petrpan-code/apache/superset/superset-frontend/src/explore/exploreUtils/getURIDirectory.test.ts | /**
* 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 { getURIDirectory } from '.';
test('Cases in which the "explore_json" will be returned', () => {
['full', 'json', 'csv', 'query', 'results', 'samples'].forEach(name => {
expect(getURIDirectory(name)).toBe('/superset/explore_json/');
});
});
test('Cases in which the "explore" will be returned', () => {
expect(getURIDirectory('any-string')).toBe('/explore/');
expect(getURIDirectory()).toBe('/explore/');
});
|
7,750 | 0 | petrpan-code/apache/superset/superset-frontend/src/explore | petrpan-code/apache/superset/superset-frontend/src/explore/exploreUtils/shouldUseLegacyApi.test.ts | /**
* 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 * as Core from '@superset-ui/core';
import { getQuerySettings } from '.';
test('Should return false', () => {
const spy = jest.spyOn(Core, 'getChartMetadataRegistry');
const get = jest.fn();
spy.mockReturnValue({ get } as any);
expect(get).toBeCalledTimes(0);
const [useLegacyApi] = getQuerySettings({ viz_type: 'name_test' });
expect(useLegacyApi).toBe(false);
expect(get).toBeCalledTimes(1);
expect(get).toBeCalledWith('name_test');
});
test('Should return true', () => {
const spy = jest.spyOn(Core, 'getChartMetadataRegistry');
const get = jest.fn();
get.mockReturnValue({ useLegacyApi: true });
spy.mockReturnValue({ get } as any);
expect(get).toBeCalledTimes(0);
const [useLegacyApi] = getQuerySettings({ viz_type: 'name_test' });
expect(useLegacyApi).toBe(true);
expect(get).toBeCalledTimes(1);
expect(get).toBeCalledWith('name_test');
});
test('Should return false when useLegacyApi:false', () => {
const spy = jest.spyOn(Core, 'getChartMetadataRegistry');
const get = jest.fn();
get.mockReturnValue({ useLegacyApi: false });
spy.mockReturnValue({ get } as any);
expect(get).toBeCalledTimes(0);
const [useLegacyApi] = getQuerySettings({ viz_type: 'name_test' });
expect(useLegacyApi).toBe(false);
expect(get).toBeCalledTimes(1);
expect(get).toBeCalledWith('name_test');
});
|
7,755 | 0 | petrpan-code/apache/superset/superset-frontend/src/features | petrpan-code/apache/superset/superset-frontend/src/features/alerts/AlertReportModal.test.tsx | /**
* 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 { render, screen, waitFor } from 'spec/helpers/testing-library';
import userEvent from '@testing-library/user-event';
import AlertReportModal from './AlertReportModal';
jest.mock('src/components/AsyncAceEditor', () => ({
...jest.requireActual('src/components/AsyncAceEditor'),
TextAreaEditor: () => <div data-test="react-ace" />,
}));
const onHide = jest.fn();
test('allows change to None in log retention', async () => {
render(<AlertReportModal show onHide={onHide} />, { useRedux: true });
// open the log retention select
userEvent.click(screen.getByText('90 days'));
// change it to 30 days
userEvent.click(await screen.findByText('30 days'));
// open again
userEvent.click(screen.getAllByText('30 days')[0]);
// change it to None
userEvent.click(await screen.findByText('None'));
// get the selected item
const selectedItem = await waitFor(() =>
screen
.getAllByLabelText('Log retention')[0]
.querySelector('.ant-select-selection-item'),
);
// check if None is selected
expect(selectedItem).toHaveTextContent('None');
});
test('renders the appropriate dropdown in Message Content section', async () => {
render(<AlertReportModal show onHide={onHide} />, { useRedux: true });
const chartRadio = screen.getByRole('radio', { name: /chart/i });
// Dashboard is initially checked by default
expect(
await screen.findByRole('radio', {
name: /dashboard/i,
}),
).toBeChecked();
expect(chartRadio).not.toBeChecked();
// Only the dashboard dropdown should show
expect(screen.getByRole('combobox', { name: /dashboard/i })).toBeVisible();
expect(
screen.queryByRole('combobox', { name: /chart/i }),
).not.toBeInTheDocument();
// Click the chart radio option
userEvent.click(chartRadio);
await waitFor(() => expect(chartRadio).toBeChecked());
expect(
await screen.findByRole('radio', {
name: /dashboard/i,
}),
).not.toBeChecked();
// Now that chart is checked, only the chart dropdown should show
expect(screen.getByRole('combobox', { name: /chart/i })).toBeVisible();
expect(
screen.queryByRole('combobox', { name: /dashboard/i }),
).not.toBeInTheDocument();
});
|
7,758 | 0 | petrpan-code/apache/superset/superset-frontend/src/features/alerts | petrpan-code/apache/superset/superset-frontend/src/features/alerts/components/AlertReportCronScheduler.test.tsx | /**
* 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 { render, screen, waitFor, within } from 'spec/helpers/testing-library';
import userEvent from '@testing-library/user-event';
import { act } from 'react-dom/test-utils';
import {
AlertReportCronScheduler,
AlertReportCronSchedulerProps,
} from './AlertReportCronScheduler';
const createProps = (props: Partial<AlertReportCronSchedulerProps> = {}) => ({
onChange: jest.fn(),
value: '* * * * *',
...props,
});
test('should render', () => {
const props = createProps();
render(<AlertReportCronScheduler {...props} />);
// Text found in the first radio option
expect(screen.getByText('Every')).toBeInTheDocument();
// Text found in the second radio option
expect(screen.getByText('CRON Schedule')).toBeInTheDocument();
});
test('only one radio option should be enabled at a time', () => {
const props = createProps();
const { container } = render(<AlertReportCronScheduler {...props} />);
expect(screen.getByTestId('picker')).toBeChecked();
expect(screen.getByTestId('input')).not.toBeChecked();
const pickerContainer = container.querySelector(
'.react-js-cron-select',
) as HTMLElement;
const inputContainer = screen.getByTestId('input-content');
expect(within(pickerContainer).getAllByRole('combobox')[0]).toBeEnabled();
expect(inputContainer.querySelector('input[name="crontab"]')).toBeDisabled();
userEvent.click(screen.getByTestId('input'));
expect(within(pickerContainer).getAllByRole('combobox')[0]).toBeDisabled();
expect(inputContainer.querySelector('input[name="crontab"]')).toBeEnabled();
userEvent.click(screen.getByTestId('picker'));
expect(within(pickerContainer).getAllByRole('combobox')[0]).toBeEnabled();
expect(inputContainer.querySelector('input[name="crontab"]')).toBeDisabled();
});
test('picker mode updates correctly', async () => {
const onChangeCallback = jest.fn();
const props = createProps({
onChange: onChangeCallback,
});
const { container } = render(<AlertReportCronScheduler {...props} />);
expect(screen.getByTestId('picker')).toBeChecked();
const pickerContainer = container.querySelector(
'.react-js-cron-select',
) as HTMLElement;
const firstSelect = within(pickerContainer).getAllByRole('combobox')[0];
act(() => {
userEvent.click(firstSelect);
});
expect(await within(pickerContainer).findByText('day')).toBeInTheDocument();
act(() => {
userEvent.click(within(pickerContainer).getByText('day'));
});
expect(onChangeCallback).toHaveBeenLastCalledWith('* * * * *');
const secondSelect = container.querySelector(
'.react-js-cron-hours .ant-select-selector',
) as HTMLElement;
await waitFor(() => {
expect(secondSelect).toBeInTheDocument();
});
act(() => {
userEvent.click(secondSelect);
});
expect(await screen.findByText('9')).toBeInTheDocument();
act(() => {
userEvent.click(screen.getByText('9'));
});
await waitFor(() => {
expect(onChangeCallback).toHaveBeenLastCalledWith('* 9 * * *');
});
});
test('input mode updates correctly', async () => {
const onChangeCallback = jest.fn();
const props = createProps({
onChange: onChangeCallback,
});
render(<AlertReportCronScheduler {...props} />);
const inputContainer = screen.getByTestId('input-content');
userEvent.click(screen.getByTestId('input'));
const input = inputContainer.querySelector(
'input[name="crontab"]',
) as HTMLElement;
await waitFor(() => {
expect(input).toBeEnabled();
});
userEvent.clear(input);
expect(input).toHaveValue('');
const value = '* 10 2 * *';
await act(async () => {
await userEvent.type(input, value, { delay: 1 });
});
await waitFor(() => {
expect(input).toHaveValue(value);
});
act(() => {
userEvent.click(inputContainer);
});
expect(onChangeCallback).toHaveBeenLastCalledWith(value);
});
|
7,783 | 0 | petrpan-code/apache/superset/superset-frontend/src/features/databases | petrpan-code/apache/superset/superset-frontend/src/features/databases/DatabaseModal/index.test.tsx | /**
* 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 fetchMock from 'fetch-mock';
import userEvent from '@testing-library/user-event';
import {
render,
screen,
within,
cleanup,
act,
waitFor,
} from 'spec/helpers/testing-library';
import { getExtensionsRegistry } from '@superset-ui/core';
import setupExtensions from 'src/setup/setupExtensions';
import * as hooks from 'src/views/CRUD/hooks';
import { DatabaseObject, CONFIGURATION_METHOD } from '../types';
import DatabaseModal, {
dbReducer,
DBReducerActionType,
ActionType,
} from './index';
jest.mock('@superset-ui/core', () => ({
...jest.requireActual('@superset-ui/core'),
isFeatureEnabled: () => true,
}));
const mockHistoryPush = jest.fn();
jest.mock('react-router-dom', () => ({
...jest.requireActual('react-router-dom'),
useHistory: () => ({
push: mockHistoryPush,
}),
}));
const dbProps = {
show: true,
database_name: 'my database',
sqlalchemy_uri: 'postgres://superset:superset@something:1234/superset',
onHide: () => {},
};
const DATABASE_FETCH_ENDPOINT = 'glob:*/api/v1/database/10';
const AVAILABLE_DB_ENDPOINT = 'glob:*/api/v1/database/available*';
const VALIDATE_PARAMS_ENDPOINT = 'glob:*/api/v1/database/validate_parameters*';
const DATABASE_CONNECT_ENDPOINT = 'glob:*/api/v1/database/';
fetchMock.post(DATABASE_CONNECT_ENDPOINT, {
id: 10,
result: {
configuration_method: 'sqlalchemy_form',
database_name: 'Other2',
driver: 'apsw',
expose_in_sqllab: true,
extra: '{"allows_virtual_table_explore":true}',
sqlalchemy_uri: 'gsheets://',
},
json: 'foo',
});
fetchMock.config.overwriteRoutes = true;
fetchMock.get(DATABASE_FETCH_ENDPOINT, {
result: {
id: 10,
database_name: 'my database',
expose_in_sqllab: false,
allow_ctas: false,
allow_cvas: false,
configuration_method: 'sqlalchemy_form',
},
});
fetchMock.mock(AVAILABLE_DB_ENDPOINT, {
databases: [
{
available_drivers: ['psycopg2'],
default_driver: 'psycopg2',
engine: 'postgresql',
name: 'PostgreSQL',
parameters: {
properties: {
database: {
description: 'Database name',
type: 'string',
},
encryption: {
description: 'Use an encrypted connection to the database',
type: 'boolean',
},
host: {
description: 'Hostname or IP address',
type: 'string',
},
password: {
description: 'Password',
nullable: true,
type: 'string',
},
port: {
description: 'Database port',
format: 'int32',
maximum: 65536,
minimum: 0,
type: 'integer',
},
query: {
additionalProperties: {},
description: 'Additional parameters',
type: 'object',
},
ssh: {
description: 'Create SSH Tunnel',
type: 'boolean',
},
username: {
description: 'Username',
nullable: true,
type: 'string',
},
},
required: ['database', 'host', 'port', 'username'],
type: 'object',
},
preferred: true,
sqlalchemy_uri_placeholder:
'postgresql://user:password@host:port/dbname[?key=value&key=value...]',
engine_information: {
supports_file_upload: true,
disable_ssh_tunneling: false,
},
},
{
available_drivers: ['rest'],
engine: 'presto',
name: 'Presto',
preferred: true,
engine_information: {
supports_file_upload: true,
disable_ssh_tunneling: false,
},
},
{
available_drivers: ['mysqldb'],
default_driver: 'mysqldb',
engine: 'mysql',
name: 'MySQL',
parameters: {
properties: {
database: {
description: 'Database name',
type: 'string',
},
encryption: {
description: 'Use an encrypted connection to the database',
type: 'boolean',
},
host: {
description: 'Hostname or IP address',
type: 'string',
},
password: {
description: 'Password',
nullable: true,
type: 'string',
},
port: {
description: 'Database port',
format: 'int32',
maximum: 65536,
minimum: 0,
type: 'integer',
},
query: {
additionalProperties: {},
description: 'Additional parameters',
type: 'object',
},
username: {
description: 'Username',
nullable: true,
type: 'string',
},
},
required: ['database', 'host', 'port', 'username'],
type: 'object',
},
preferred: true,
sqlalchemy_uri_placeholder:
'mysql://user:password@host:port/dbname[?key=value&key=value...]',
engine_information: {
supports_file_upload: true,
disable_ssh_tunneling: false,
},
},
{
available_drivers: ['pysqlite'],
engine: 'sqlite',
name: 'SQLite',
preferred: true,
engine_information: {
supports_file_upload: true,
disable_ssh_tunneling: false,
},
},
{
available_drivers: ['rest'],
engine: 'druid',
name: 'Apache Druid',
preferred: false,
engine_information: {
supports_file_upload: true,
disable_ssh_tunneling: false,
},
},
{
available_drivers: ['bigquery'],
default_driver: 'bigquery',
engine: 'bigquery',
name: 'Google BigQuery',
parameters: {
properties: {
credentials_info: {
description: 'Contents of BigQuery JSON credentials.',
type: 'string',
'x-encrypted-extra': true,
},
query: {
type: 'object',
},
},
type: 'object',
},
preferred: false,
sqlalchemy_uri_placeholder: 'bigquery://{project_id}',
engine_information: {
supports_file_upload: true,
disable_ssh_tunneling: true,
},
},
{
available_drivers: ['rest'],
default_driver: 'apsw',
engine: 'gsheets',
name: 'Google Sheets',
preferred: false,
engine_information: {
supports_file_upload: false,
disable_ssh_tunneling: true,
},
},
{
available_drivers: ['connector'],
default_driver: 'connector',
engine: 'databricks',
name: 'Databricks',
parameters: {
properties: {
access_token: {
type: 'string',
},
database: {
type: 'string',
},
host: {
type: 'string',
},
http_path: {
type: 'string',
},
port: {
format: 'int32',
type: 'integer',
},
},
required: ['access_token', 'database', 'host', 'http_path', 'port'],
type: 'object',
},
preferred: true,
sqlalchemy_uri_placeholder:
'databricks+connector://token:{access_token}@{host}:{port}/{database_name}',
},
],
});
fetchMock.post(VALIDATE_PARAMS_ENDPOINT, {
message: 'OK',
});
const databaseFixture: DatabaseObject = {
id: 123,
backend: 'postgres',
configuration_method: CONFIGURATION_METHOD.DYNAMIC_FORM,
database_name: 'Postgres',
name: 'PostgresDB',
is_managed_externally: false,
driver: 'psycopg2',
};
describe('DatabaseModal', () => {
const renderAndWait = async () => {
const mounted = act(async () => {
render(<DatabaseModal {...dbProps} />, {
useRedux: true,
});
});
return mounted;
};
beforeEach(async () => {
await renderAndWait();
});
afterEach(cleanup);
describe('Visual: New database connection', () => {
test('renders the initial load of Step 1 correctly', () => {
// ---------- Components ----------
// <TabHeader> - AntD header
const closeButton = screen.getByLabelText('Close');
const step1Header = screen.getByRole('heading', {
name: /connect a database/i,
});
// <ModalHeader> - Connection header
const step1Helper = screen.getByText(/step 1 of 3/i);
const selectDbHeader = screen.getByRole('heading', {
name: /select a database to connect/i,
});
// <IconButton> - Preferred database buttons
const preferredDbButtonPostgreSQL = screen.getByRole('button', {
name: /postgresql/i,
});
const preferredDbTextPostgreSQL = within(
preferredDbButtonPostgreSQL,
).getByText(/postgresql/i);
const preferredDbButtonPresto = screen.getByRole('button', {
name: /presto/i,
});
const preferredDbTextPresto = within(preferredDbButtonPresto).getByText(
/presto/i,
);
const preferredDbButtonMySQL = screen.getByRole('button', {
name: /mysql/i,
});
const preferredDbTextMySQL = within(preferredDbButtonMySQL).getByText(
/mysql/i,
);
const preferredDbButtonSQLite = screen.getByRole('button', {
name: /sqlite/i,
});
const preferredDbTextSQLite = within(preferredDbButtonSQLite).getByText(
/sqlite/i,
);
// renderAvailableSelector() => <Select> - Supported databases selector
const supportedDbsHeader = screen.getByRole('heading', {
name: /or choose from a list of other databases we support:/i,
});
const selectorLabel = screen.getByText(/supported databases/i);
const selectorPlaceholder = screen.getByText(/choose a database\.\.\./i);
const selectorArrow = screen.getByRole('img', {
name: /down/i,
hidden: true,
});
const footer = document.getElementsByClassName('ant-modal-footer');
// ---------- TODO (lyndsiWilliams): Selector options, can't seem to get these to render properly.
// renderAvailableSelector() => <Alert> - Supported databases alert
const alertIcon = screen.getByRole('img', { name: /info icon/i });
const alertMessage = screen.getByText(/want to add a new database\?/i);
const alertDescription = screen.getByText(
/any databases that allow connections via sql alchemy uris can be added\. learn about how to connect a database driver \./i,
);
const alertLink = screen.getByRole('link', { name: /here/i });
// ---------- Assertions ----------
const visibleComponents = [
closeButton,
step1Header,
step1Helper,
selectDbHeader,
supportedDbsHeader,
selectorLabel,
selectorPlaceholder,
selectorArrow,
alertIcon,
alertMessage,
alertDescription,
alertLink,
preferredDbButtonPostgreSQL,
preferredDbButtonPresto,
preferredDbButtonMySQL,
preferredDbButtonSQLite,
preferredDbTextPostgreSQL,
preferredDbTextPresto,
preferredDbTextMySQL,
preferredDbTextSQLite,
];
visibleComponents.forEach(component => {
expect(component).toBeVisible();
});
// there should be a footer but it should not have any buttons in it
expect(footer[0]).toBeEmptyDOMElement();
});
test('renders the "Basic" tab of SQL Alchemy form (step 2 of 2) correctly', async () => {
// On step 1, click dbButton to access SQL Alchemy form
userEvent.click(
screen.getByRole('button', {
name: /sqlite/i,
}),
);
expect(await screen.findByText(/step 2 of 2/i)).toBeInTheDocument();
// ---------- Components ----------
// <TabHeader> - AntD header
const closeButton = screen.getByRole('button', { name: /close/i });
const basicHeader = screen.getByRole('heading', {
name: /connect a database/i,
});
// <ModalHeader> - Connection header
const basicHelper = screen.getByText(/step 2 of 2/i);
const basicHeaderTitle = screen.getByText(/enter primary credentials/i);
const basicHeaderSubtitle = screen.getByText(
/need help\? learn how to connect your database \./i,
);
const basicHeaderLink = within(basicHeaderSubtitle).getByRole('link', {
name: /here/i,
});
// <Tabs> - Basic/Advanced tabs
const basicTab = screen.getByRole('tab', { name: /basic/i });
const advancedTab = screen.getByRole('tab', { name: /advanced/i });
// <StyledBasicTab> - Basic tab's content
const displayNameLabel = screen.getByText(/display name*/i);
const displayNameInput = screen.getByTestId('database-name-input');
const displayNameHelper = screen.getByText(
/pick a name to help you identify this database\./i,
);
const SQLURILabel = screen.getByText(/sqlalchemy uri*/i);
const SQLURIInput = screen.getByTestId('sqlalchemy-uri-input');
const SQLURIHelper = screen.getByText(
/refer to the for more information on how to structure your uri\./i,
);
// <SSHTunnelForm> - Basic tab's SSH Tunnel Form
const SSHTunnelingToggle = screen.getByTestId('ssh-tunnel-switch');
userEvent.click(SSHTunnelingToggle);
const SSHTunnelServerAddressInput = screen.getByTestId(
'ssh-tunnel-server_address-input',
);
const SSHTunnelServerPortInput = screen.getByTestId(
'ssh-tunnel-server_port-input',
);
const SSHTunnelUsernameInput = screen.getByTestId(
'ssh-tunnel-username-input',
);
const SSHTunnelPasswordInput = screen.getByTestId(
'ssh-tunnel-password-input',
);
const testConnectionButton = screen.getByRole('button', {
name: /test connection/i,
});
// <Alert> - Basic tab's alert
const alertIcon = screen.getByRole('img', { name: /info icon/i });
const alertMessage = screen.getByText(
/additional fields may be required/i,
);
const alertDescription = screen.getByText(
/select databases require additional fields to be completed in the advanced tab to successfully connect the database\. learn what requirements your databases has \./i,
);
const alertLink = within(alertDescription).getByRole('link', {
name: /here/i,
});
// renderModalFooter() - Basic tab's footer
const backButton = screen.getByRole('button', { name: /back/i });
const connectButton = screen.getByRole('button', { name: 'Connect' });
// ---------- Assertions ----------
const visibleComponents = [
closeButton,
basicHeader,
basicHelper,
basicHeaderTitle,
basicHeaderSubtitle,
basicHeaderLink,
basicTab,
advancedTab,
displayNameLabel,
displayNameInput,
displayNameHelper,
SQLURILabel,
SQLURIInput,
SQLURIHelper,
SSHTunnelingToggle,
SSHTunnelServerAddressInput,
SSHTunnelServerPortInput,
SSHTunnelUsernameInput,
SSHTunnelPasswordInput,
testConnectionButton,
alertIcon,
alertMessage,
alertDescription,
alertLink,
backButton,
connectButton,
];
visibleComponents.forEach(component => {
expect(component).toBeVisible();
});
});
test('renders the unexpanded "Advanced" tab correctly', async () => {
// On step 1, click dbButton to access step 2
userEvent.click(
screen.getByRole('button', {
name: /sqlite/i,
}),
);
expect(await screen.findByText(/step 2 of 2/i)).toBeInTheDocument();
// Click the "Advanced" tab
userEvent.click(screen.getByRole('tab', { name: /advanced/i }));
// ---------- Components ----------
// <TabHeader> - AntD header
const closeButton = screen.getByRole('button', { name: /close/i });
const advancedHeader = screen.getByRole('heading', {
name: /connect a database/i,
});
// <ModalHeader> - Connection header
const basicHelper = screen.getByText(/step 2 of 2/i);
const basicHeaderTitle = screen.getByText(/enter primary credentials/i);
const basicHeaderSubtitle = screen.getByText(
/need help\? learn how to connect your database \./i,
);
const basicHeaderLink = within(basicHeaderSubtitle).getByRole('link', {
name: /here/i,
});
// <Tabs> - Basic/Advanced tabs
const basicTab = screen.getByRole('tab', { name: /basic/i });
const advancedTab = screen.getByRole('tab', { name: /advanced/i });
// <ExtraOptions> - Advanced tabs
const sqlLabTab = screen.getByRole('tab', {
name: /right sql lab adjust how this database will interact with sql lab\./i,
});
const sqlLabTabArrow = within(sqlLabTab).getByRole('img', {
name: /right/i,
});
const sqlLabTabHeading = screen.getByRole('heading', {
name: /sql lab/i,
});
const performanceTab = screen.getByRole('tab', {
name: /right performance adjust performance settings of this database\./i,
});
const performanceTabArrow = within(performanceTab).getByRole('img', {
name: /right/i,
});
const performanceTabHeading = screen.getByRole('heading', {
name: /performance/i,
});
const securityTab = screen.getByRole('tab', {
name: /right security add extra connection information\./i,
});
const securityTabArrow = within(securityTab).getByRole('img', {
name: /right/i,
});
const securityTabHeading = screen.getByRole('heading', {
name: /security/i,
});
const otherTab = screen.getByRole('tab', {
name: /right other additional settings\./i,
});
const otherTabArrow = within(otherTab).getByRole('img', {
name: /right/i,
});
const otherTabHeading = screen.getByRole('heading', { name: /other/i });
// renderModalFooter() - Advanced tab's footer
const backButton = screen.getByRole('button', { name: /back/i });
const connectButton = screen.getByRole('button', { name: 'Connect' });
// ---------- Assertions ----------
const visibleComponents = [
closeButton,
advancedHeader,
basicHelper,
basicHeaderTitle,
basicHeaderSubtitle,
basicHeaderLink,
basicTab,
advancedTab,
sqlLabTab,
sqlLabTabArrow,
sqlLabTabHeading,
performanceTab,
performanceTabArrow,
performanceTabHeading,
securityTab,
securityTabArrow,
securityTabHeading,
otherTab,
otherTabArrow,
otherTabHeading,
backButton,
connectButton,
];
visibleComponents.forEach(component => {
expect(component).toBeVisible();
});
});
test('renders the "Advanced" - SQL LAB tab correctly (unexpanded)', async () => {
// ---------- Components ----------
// On step 1, click dbButton to access step 2
userEvent.click(
screen.getByRole('button', {
name: /sqlite/i,
}),
);
// Click the "Advanced" tab
userEvent.click(screen.getByRole('tab', { name: /advanced/i }));
// Click the "SQL Lab" tab
userEvent.click(
screen.getByRole('tab', {
name: /right sql lab adjust how this database will interact with sql lab\./i,
}),
);
expect(await screen.findByText(/step 2 of 2/i)).toBeInTheDocument();
// ----- BEGIN STEP 2 (ADVANCED - SQL LAB)
// <TabHeader> - AntD header
const closeButton = screen.getByRole('button', { name: /close/i });
const advancedHeader = screen.getByRole('heading', {
name: /connect a database/i,
});
// <ModalHeader> - Connection header
const basicHelper = screen.getByText(/step 2 of 2/i);
const basicHeaderTitle = screen.getByText(/enter primary credentials/i);
const basicHeaderSubtitle = screen.getByText(
/need help\? learn how to connect your database \./i,
);
const basicHeaderLink = within(basicHeaderSubtitle).getByRole('link', {
name: /here/i,
});
// <Tabs> - Basic/Advanced tabs
const basicTab = screen.getByRole('tab', { name: /basic/i });
const advancedTab = screen.getByRole('tab', { name: /advanced/i });
// <ExtraOptions> - Advanced tabs
const sqlLabTab = screen.getByRole('tab', {
name: /right sql lab adjust how this database will interact with sql lab\./i,
});
// These are the checkbox SVGs that cover the actual checkboxes
const checkboxOffSVGs = screen.getAllByRole('img', {
name: /checkbox-off/i,
});
const tooltipIcons = screen.getAllByRole('img', {
name: /info-solid_small/i,
});
const exposeInSQLLabCheckbox = screen.getByRole('checkbox', {
name: /expose database in sql lab/i,
});
// This is both the checkbox and its respective SVG
// const exposeInSQLLabCheckboxSVG = checkboxOffSVGs[0].parentElement;
const exposeInSQLLabText = screen.getByText(
/expose database in sql lab/i,
);
const allowCTASCheckbox = screen.getByRole('checkbox', {
name: /allow create table as/i,
});
const allowCTASText = screen.getByText(/allow create table as/i);
const allowCVASCheckbox = screen.getByRole('checkbox', {
name: /allow create table as/i,
});
const allowCVASText = screen.getByText(/allow create table as/i);
const CTASCVASLabelText = screen.getByText(/ctas & cvas schema/i);
// This grabs the whole input by placeholder text
const CTASCVASInput = screen.getByPlaceholderText(
/create or select schema\.\.\./i,
);
const CTASCVASHelperText = screen.getByText(
/force all tables and views to be created in this schema when clicking ctas or cvas in sql lab\./i,
);
const allowDMLCheckbox = screen.getByRole('checkbox', {
name: /allow dml/i,
});
const allowDMLText = screen.getByText(/allow dml/i);
const enableQueryCostEstimationCheckbox = screen.getByRole('checkbox', {
name: /enable query cost estimation/i,
});
const enableQueryCostEstimationText = screen.getByText(
/enable query cost estimation/i,
);
const allowDbExplorationCheckbox = screen.getByRole('checkbox', {
name: /allow this database to be explored/i,
});
const allowDbExplorationText = screen.getByText(
/allow this database to be explored/i,
);
const disableSQLLabDataPreviewQueriesCheckbox = screen.getByRole(
'checkbox',
{
name: /Disable SQL Lab data preview queries/i,
},
);
const disableSQLLabDataPreviewQueriesText = screen.getByText(
/Disable SQL Lab data preview queries/i,
);
const enableRowExpansionCheckbox = screen.getByRole('checkbox', {
name: /enable row expansion in schemas/i,
});
const enableRowExpansionText = screen.getByText(
/enable row expansion in schemas/i,
);
// ---------- Assertions ----------
const visibleComponents = [
closeButton,
advancedHeader,
basicHelper,
basicHeaderTitle,
basicHeaderSubtitle,
basicHeaderLink,
basicTab,
advancedTab,
sqlLabTab,
checkboxOffSVGs[0],
checkboxOffSVGs[1],
checkboxOffSVGs[2],
checkboxOffSVGs[3],
checkboxOffSVGs[4],
checkboxOffSVGs[5],
tooltipIcons[0],
tooltipIcons[1],
tooltipIcons[2],
tooltipIcons[3],
tooltipIcons[4],
tooltipIcons[5],
tooltipIcons[6],
tooltipIcons[7],
exposeInSQLLabText,
allowCTASText,
allowCVASText,
CTASCVASLabelText,
CTASCVASInput,
CTASCVASHelperText,
allowDMLText,
enableQueryCostEstimationText,
allowDbExplorationText,
disableSQLLabDataPreviewQueriesText,
enableRowExpansionText,
];
// These components exist in the DOM but are not visible
const invisibleComponents = [
exposeInSQLLabCheckbox,
allowCTASCheckbox,
allowCVASCheckbox,
allowDMLCheckbox,
enableQueryCostEstimationCheckbox,
allowDbExplorationCheckbox,
disableSQLLabDataPreviewQueriesCheckbox,
enableRowExpansionCheckbox,
];
visibleComponents.forEach(component => {
expect(component).toBeVisible();
});
invisibleComponents.forEach(component => {
expect(component).not.toBeVisible();
});
expect(checkboxOffSVGs).toHaveLength(6);
expect(tooltipIcons).toHaveLength(8);
});
test('renders the "Advanced" - PERFORMANCE tab correctly', async () => {
// ---------- Components ----------
// On step 1, click dbButton to access step 2
userEvent.click(
screen.getByRole('button', {
name: /sqlite/i,
}),
);
// Click the "Advanced" tab
userEvent.click(screen.getByRole('tab', { name: /advanced/i }));
// Click the "Performance" tab
userEvent.click(
screen.getByRole('tab', {
name: /right performance adjust performance settings of this database\./i,
}),
);
expect(await screen.findByText(/step 2 of 2/i)).toBeInTheDocument();
// ----- BEGIN STEP 2 (ADVANCED - PERFORMANCE)
// <TabHeader> - AntD header
const closeButton = screen.getByRole('button', { name: /close/i });
const advancedHeader = screen.getByRole('heading', {
name: /connect a database/i,
});
// <ModalHeader> - Connection header
const basicHelper = screen.getByText(/step 2 of 2/i);
const basicHeaderTitle = screen.getByText(/enter primary credentials/i);
const basicHeaderSubtitle = screen.getByText(
/need help\? learn how to connect your database \./i,
);
const basicHeaderLink = within(basicHeaderSubtitle).getByRole('link', {
name: /here/i,
});
// <Tabs> - Basic/Advanced tabs
const basicTab = screen.getByRole('tab', { name: /basic/i });
const advancedTab = screen.getByRole('tab', { name: /advanced/i });
// <ExtraOptions> - Advanced tabs
const sqlLabTab = screen.getByRole('tab', {
name: /right sql lab adjust how this database will interact with sql lab\./i,
});
const performanceTab = screen.getByRole('tab', {
name: /right performance adjust performance settings of this database\./i,
});
// ---------- Assertions ----------
const visibleComponents = [
closeButton,
advancedHeader,
basicHelper,
basicHeaderTitle,
basicHeaderSubtitle,
basicHeaderLink,
basicTab,
advancedTab,
sqlLabTab,
performanceTab,
];
visibleComponents.forEach(component => {
expect(component).toBeVisible();
});
});
test('renders the "Advanced" - SECURITY tab correctly', async () => {
// ---------- Components ----------
// On step 1, click dbButton to access step 2
userEvent.click(
screen.getByRole('button', {
name: /sqlite/i,
}),
);
// Click the "Advanced" tab
userEvent.click(screen.getByRole('tab', { name: /advanced/i }));
// Click the "Security" tab
userEvent.click(
screen.getByRole('tab', {
name: /right security add extra connection information\./i,
}),
);
expect(await screen.findByText(/step 2 of 2/i)).toBeInTheDocument();
// ----- BEGIN STEP 2 (ADVANCED - SECURITY)
// <TabHeader> - AntD header
const closeButton = screen.getByRole('button', { name: /close/i });
const advancedHeader = screen.getByRole('heading', {
name: /connect a database/i,
});
// <ModalHeader> - Connection header
const basicHelper = screen.getByText(/step 2 of 2/i);
const basicHeaderTitle = screen.getByText(/enter primary credentials/i);
const basicHeaderSubtitle = screen.getByText(
/need help\? learn how to connect your database \./i,
);
const basicHeaderLink = within(basicHeaderSubtitle).getByRole('link', {
name: /here/i,
});
// <Tabs> - Basic/Advanced tabs
const basicTab = screen.getByRole('tab', { name: /basic/i });
const advancedTab = screen.getByRole('tab', { name: /advanced/i });
// <ExtraOptions> - Advanced tabs
const sqlLabTab = screen.getByRole('tab', {
name: /right sql lab adjust how this database will interact with sql lab\./i,
});
const performanceTab = screen.getByRole('tab', {
name: /right performance adjust performance settings of this database\./i,
});
const securityTab = screen.getByRole('tab', {
name: /right security add extra connection information\./i,
});
const allowFileUploadCheckbox = screen.getByRole('checkbox', {
name: /Allow file uploads to database/i,
});
const allowFileUploadText = screen.getByText(
/Allow file uploads to database/i,
);
const schemasForFileUploadText = screen.queryByText(
/Schemas allowed for File upload/i,
);
const visibleComponents = [
closeButton,
advancedHeader,
basicHelper,
basicHeaderTitle,
basicHeaderSubtitle,
basicHeaderLink,
basicTab,
advancedTab,
sqlLabTab,
performanceTab,
securityTab,
allowFileUploadText,
];
// These components exist in the DOM but are not visible
const invisibleComponents = [allowFileUploadCheckbox];
// ---------- Assertions ----------
visibleComponents.forEach(component => {
expect(component).toBeVisible();
});
invisibleComponents.forEach(component => {
expect(component).not.toBeVisible();
});
expect(schemasForFileUploadText).not.toBeInTheDocument();
});
it('renders the "Advanced" - SECURITY tab correctly after selecting Allow file uploads', async () => {
// ---------- Components ----------
// On step 1, click dbButton to access step 2
userEvent.click(
screen.getByRole('button', {
name: /sqlite/i,
}),
);
// Click the "Advanced" tab
userEvent.click(screen.getByRole('tab', { name: /advanced/i }));
// Click the "Security" tab
userEvent.click(
screen.getByRole('tab', {
name: /right security add extra connection information\./i,
}),
);
// Click the "Allow file uploads" tab
const allowFileUploadCheckbox = screen.getByRole('checkbox', {
name: /Allow file uploads to database/i,
});
userEvent.click(allowFileUploadCheckbox);
// ----- BEGIN STEP 2 (ADVANCED - SECURITY)
// <TabHeader> - AntD header
const closeButton = screen.getByRole('button', { name: /close/i });
const advancedHeader = screen.getByRole('heading', {
name: /connect a database/i,
});
// <ModalHeader> - Connection header
const basicHelper = screen.getByText(/step 2 of 2/i);
const basicHeaderTitle = screen.getByText(/enter primary credentials/i);
const basicHeaderSubtitle = screen.getByText(
/need help\? learn how to connect your database \./i,
);
const basicHeaderLink = within(basicHeaderSubtitle).getByRole('link', {
name: /here/i,
});
// <Tabs> - Basic/Advanced tabs
const basicTab = screen.getByRole('tab', { name: /basic/i });
const advancedTab = screen.getByRole('tab', { name: /advanced/i });
// <ExtraOptions> - Advanced tabs
const sqlLabTab = screen.getByRole('tab', {
name: /right sql lab adjust how this database will interact with sql lab\./i,
});
const performanceTab = screen.getByRole('tab', {
name: /right performance adjust performance settings of this database\./i,
});
const securityTab = screen.getByRole('tab', {
name: /right security add extra connection information\./i,
});
const allowFileUploadText = screen.getByText(
/Allow file uploads to database/i,
);
const schemasForFileUploadText = screen.queryByText(
/Schemas allowed for File upload/i,
);
const visibleComponents = [
closeButton,
advancedHeader,
basicHelper,
basicHeaderTitle,
basicHeaderSubtitle,
basicHeaderLink,
basicTab,
advancedTab,
sqlLabTab,
performanceTab,
securityTab,
allowFileUploadText,
];
// These components exist in the DOM but are not visible
const invisibleComponents = [allowFileUploadCheckbox];
// ---------- Assertions ----------
visibleComponents.forEach(component => {
expect(component).toBeVisible();
});
invisibleComponents.forEach(component => {
expect(component).not.toBeVisible();
});
expect(schemasForFileUploadText).toBeInTheDocument();
});
test('renders the "Advanced" - OTHER tab correctly', async () => {
// ---------- Components ----------
// On step 1, click dbButton to access step 2
userEvent.click(
screen.getByRole('button', {
name: /sqlite/i,
}),
);
// Click the "Advanced" tab
userEvent.click(screen.getByRole('tab', { name: /advanced/i }));
// Click the "Other" tab
userEvent.click(
screen.getByRole('tab', {
name: /right other additional settings\./i,
}),
);
expect(await screen.findByText(/step 2 of 2/i)).toBeInTheDocument();
// ----- BEGIN STEP 2 (ADVANCED - OTHER)
// <TabHeader> - AntD header
const closeButton = screen.getByRole('button', { name: /close/i });
const advancedHeader = screen.getByRole('heading', {
name: /connect a database/i,
});
// <ModalHeader> - Connection header
const basicHelper = screen.getByText(/step 2 of 2/i);
const basicHeaderTitle = screen.getByText(/enter primary credentials/i);
const basicHeaderSubtitle = screen.getByText(
/need help\? learn how to connect your database \./i,
);
const basicHeaderLink = within(basicHeaderSubtitle).getByRole('link', {
name: /here/i,
});
// <Tabs> - Basic/Advanced tabs
const basicTab = screen.getByRole('tab', { name: /basic/i });
const advancedTab = screen.getByRole('tab', { name: /advanced/i });
// <ExtraOptions> - Advanced tabs
const sqlLabTab = screen.getByRole('tab', {
name: /right sql lab adjust how this database will interact with sql lab\./i,
});
const performanceTab = screen.getByRole('tab', {
name: /right performance adjust performance settings of this database\./i,
});
const securityTab = screen.getByRole('tab', {
name: /right security add extra connection information\./i,
});
const otherTab = screen.getByRole('tab', {
name: /right other additional settings\./i,
});
// ---------- Assertions ----------
const visibleComponents = [
closeButton,
advancedHeader,
basicHelper,
basicHeaderTitle,
basicHeaderSubtitle,
basicHeaderLink,
basicTab,
advancedTab,
sqlLabTab,
performanceTab,
securityTab,
otherTab,
];
visibleComponents.forEach(component => {
expect(component).toBeVisible();
});
});
test('Dynamic form', async () => {
// ---------- Components ----------
// On step 1, click dbButton to access step 2
userEvent.click(
screen.getByRole('button', {
name: /postgresql/i,
}),
);
expect(await screen.findByText(/step 2 of 3/i)).toBeInTheDocument();
expect.anything();
});
});
describe('Functional: Create new database', () => {
test('directs databases to the appropriate form (dynamic vs. SQL Alchemy)', async () => {
// ---------- Dynamic example (3-step form)
// Click the PostgreSQL button to enter the dynamic form
const postgreSQLButton = screen.getByRole('button', {
name: /postgresql/i,
});
userEvent.click(postgreSQLButton);
// Dynamic form has 3 steps, seeing this text means the dynamic form is present
const dynamicFormStepText = screen.getByText(/step 2 of 3/i);
expect(dynamicFormStepText).toBeVisible();
// ---------- SQL Alchemy example (2-step form)
// Click the back button to go back to step 1,
// then click the SQLite button to enter the SQL Alchemy form
const backButton = screen.getByRole('button', { name: /back/i });
userEvent.click(backButton);
const sqliteButton = screen.getByRole('button', {
name: /sqlite/i,
});
userEvent.click(sqliteButton);
// SQL Alchemy form has 2 steps, seeing this text means the SQL Alchemy form is present
expect(await screen.findByText(/step 2 of 2/i)).toBeInTheDocument();
const sqlAlchemyFormStepText = screen.getByText(/step 2 of 2/i);
expect(sqlAlchemyFormStepText).toBeVisible();
});
describe('SQL Alchemy form flow', () => {
test('enters step 2 of 2 when proper database is selected', async () => {
userEvent.click(
screen.getByRole('button', {
name: /sqlite/i,
}),
);
expect(await screen.findByText(/step 2 of 2/i)).toBeInTheDocument();
});
test('runs fetchResource when "Connect" is clicked', () => {
/* ---------- 🐞 TODO (lyndsiWilliams): function mock is not currently working 🐞 ----------
// Mock useSingleViewResource
const mockUseSingleViewResource = jest.fn();
mockUseSingleViewResource.mockImplementation(useSingleViewResource);
const { fetchResource } = mockUseSingleViewResource('database');
// Invalid hook call?
userEvent.click(screen.getByRole('button', { name: 'Connect' }));
expect(fetchResource).toHaveBeenCalled();
The line below makes the linter happy */
expect.anything();
});
describe('step 2 component interaction', () => {
test('properly interacts with textboxes', async () => {
userEvent.click(
screen.getByRole('button', {
name: /sqlite/i,
}),
);
expect(await screen.findByText(/step 2 of 2/i)).toBeInTheDocument();
const dbNametextBox = screen.getByTestId('database-name-input');
expect(dbNametextBox).toHaveValue('SQLite');
userEvent.type(dbNametextBox, 'Different text');
expect(dbNametextBox).toHaveValue('SQLiteDifferent text');
const sqlAlchemyURItextBox = screen.getByTestId(
'sqlalchemy-uri-input',
);
expect(sqlAlchemyURItextBox).toHaveValue('');
userEvent.type(sqlAlchemyURItextBox, 'Different text');
expect(sqlAlchemyURItextBox).toHaveValue('Different text');
});
test('runs testDatabaseConnection when "TEST CONNECTION" is clicked', () => {
/* ---------- 🐞 TODO (lyndsiWilliams): function mock is not currently working 🐞 ----------
// Mock testDatabaseConnection
const mockTestDatabaseConnection = jest.fn();
mockTestDatabaseConnection.mockImplementation(testDatabaseConnection);
userEvent.click(
screen.getByRole('button', {
name: /test connection/i,
}),
);
expect(mockTestDatabaseConnection).toHaveBeenCalled();
The line below makes the linter happy */
expect.anything();
});
});
describe('SSH Tunnel Form interaction', () => {
test('properly interacts with SSH Tunnel form textboxes for dynamic form', async () => {
userEvent.click(
screen.getByRole('button', {
name: /postgresql/i,
}),
);
expect(await screen.findByText(/step 2 of 3/i)).toBeInTheDocument();
const SSHTunnelingToggle = screen.getByTestId('ssh-tunnel-switch');
userEvent.click(SSHTunnelingToggle);
const SSHTunnelServerAddressInput = screen.getByTestId(
'ssh-tunnel-server_address-input',
);
expect(SSHTunnelServerAddressInput).toHaveValue('');
userEvent.type(SSHTunnelServerAddressInput, 'localhost');
expect(SSHTunnelServerAddressInput).toHaveValue('localhost');
const SSHTunnelServerPortInput = screen.getByTestId(
'ssh-tunnel-server_port-input',
);
expect(SSHTunnelServerPortInput).toHaveValue('');
userEvent.type(SSHTunnelServerPortInput, '22');
expect(SSHTunnelServerPortInput).toHaveValue('22');
const SSHTunnelUsernameInput = screen.getByTestId(
'ssh-tunnel-username-input',
);
expect(SSHTunnelUsernameInput).toHaveValue('');
userEvent.type(SSHTunnelUsernameInput, 'test');
expect(SSHTunnelUsernameInput).toHaveValue('test');
const SSHTunnelPasswordInput = screen.getByTestId(
'ssh-tunnel-password-input',
);
expect(SSHTunnelPasswordInput).toHaveValue('');
userEvent.type(SSHTunnelPasswordInput, 'pass');
expect(SSHTunnelPasswordInput).toHaveValue('pass');
});
test('properly interacts with SSH Tunnel form textboxes', async () => {
userEvent.click(
screen.getByRole('button', {
name: /sqlite/i,
}),
);
expect(await screen.findByText(/step 2 of 2/i)).toBeInTheDocument();
const SSHTunnelingToggle = screen.getByTestId('ssh-tunnel-switch');
userEvent.click(SSHTunnelingToggle);
const SSHTunnelServerAddressInput = screen.getByTestId(
'ssh-tunnel-server_address-input',
);
expect(SSHTunnelServerAddressInput).toHaveValue('');
userEvent.type(SSHTunnelServerAddressInput, 'localhost');
expect(SSHTunnelServerAddressInput).toHaveValue('localhost');
const SSHTunnelServerPortInput = screen.getByTestId(
'ssh-tunnel-server_port-input',
);
expect(SSHTunnelServerPortInput).toHaveValue('');
userEvent.type(SSHTunnelServerPortInput, '22');
expect(SSHTunnelServerPortInput).toHaveValue('22');
const SSHTunnelUsernameInput = screen.getByTestId(
'ssh-tunnel-username-input',
);
expect(SSHTunnelUsernameInput).toHaveValue('');
userEvent.type(SSHTunnelUsernameInput, 'test');
expect(SSHTunnelUsernameInput).toHaveValue('test');
const SSHTunnelPasswordInput = screen.getByTestId(
'ssh-tunnel-password-input',
);
expect(SSHTunnelPasswordInput).toHaveValue('');
userEvent.type(SSHTunnelPasswordInput, 'pass');
expect(SSHTunnelPasswordInput).toHaveValue('pass');
});
test('if the SSH Tunneling toggle is not true, no inputs are displayed', async () => {
userEvent.click(
screen.getByRole('button', {
name: /sqlite/i,
}),
);
expect(await screen.findByText(/step 2 of 2/i)).toBeInTheDocument();
const SSHTunnelingToggle = screen.getByTestId('ssh-tunnel-switch');
expect(SSHTunnelingToggle).toBeVisible();
const SSHTunnelServerAddressInput = screen.queryByTestId(
'ssh-tunnel-server_address-input',
);
expect(SSHTunnelServerAddressInput).not.toBeInTheDocument();
const SSHTunnelServerPortInput = screen.queryByTestId(
'ssh-tunnel-server_port-input',
);
expect(SSHTunnelServerPortInput).not.toBeInTheDocument();
const SSHTunnelUsernameInput = screen.queryByTestId(
'ssh-tunnel-username-input',
);
expect(SSHTunnelUsernameInput).not.toBeInTheDocument();
const SSHTunnelPasswordInput = screen.queryByTestId(
'ssh-tunnel-password-input',
);
expect(SSHTunnelPasswordInput).not.toBeInTheDocument();
});
test('If user changes the login method, the inputs change', async () => {
userEvent.click(
screen.getByRole('button', {
name: /sqlite/i,
}),
);
expect(await screen.findByText(/step 2 of 2/i)).toBeInTheDocument();
const SSHTunnelingToggle = screen.getByTestId('ssh-tunnel-switch');
userEvent.click(SSHTunnelingToggle);
const SSHTunnelUsePasswordInput = screen.getByTestId(
'ssh-tunnel-use_password-radio',
);
expect(SSHTunnelUsePasswordInput).toBeVisible();
const SSHTunnelUsePrivateKeyInput = screen.getByTestId(
'ssh-tunnel-use_private_key-radio',
);
expect(SSHTunnelUsePrivateKeyInput).toBeVisible();
const SSHTunnelPasswordInput = screen.getByTestId(
'ssh-tunnel-password-input',
);
// By default, we use Password as login method
expect(SSHTunnelPasswordInput).toBeVisible();
// Change the login method to use private key
userEvent.click(SSHTunnelUsePrivateKeyInput);
const SSHTunnelPrivateKeyInput = screen.getByTestId(
'ssh-tunnel-private_key-input',
);
expect(SSHTunnelPrivateKeyInput).toBeVisible();
const SSHTunnelPrivateKeyPasswordInput = screen.getByTestId(
'ssh-tunnel-private_key_password-input',
);
expect(SSHTunnelPrivateKeyPasswordInput).toBeVisible();
});
});
});
describe('Dynamic form flow', () => {
test('enters step 2 of 3 when proper database is selected', async () => {
expect(await screen.findByText(/step 1 of 3/i)).toBeInTheDocument();
userEvent.click(
screen.getByRole('button', {
name: /postgresql/i,
}),
);
expect(await screen.findByText(/step 2 of 3/i)).toBeInTheDocument();
const step2of3text = screen.getByText(/step 2 of 3/i);
expect(step2of3text).toBeVisible();
});
test('enters form credentials and runs fetchResource when "Connect" is clicked', async () => {
userEvent.click(
screen.getByRole('button', {
name: /postgresql/i,
}),
);
const textboxes = screen.getAllByRole('textbox');
const hostField = textboxes[0];
const portField = screen.getByRole('spinbutton');
const databaseNameField = textboxes[1];
const usernameField = textboxes[2];
const passwordField = textboxes[3];
const connectButton = screen.getByRole('button', { name: 'Connect' });
expect(hostField).toHaveValue('');
expect(portField).toHaveValue(null);
expect(databaseNameField).toHaveValue('');
expect(usernameField).toHaveValue('');
expect(passwordField).toHaveValue('');
userEvent.type(hostField, 'localhost');
userEvent.type(portField, '5432');
userEvent.type(databaseNameField, 'postgres');
userEvent.type(usernameField, 'testdb');
userEvent.type(passwordField, 'demoPassword');
expect(await screen.findByDisplayValue(/5432/i)).toBeInTheDocument();
expect(hostField).toHaveValue('localhost');
expect(portField).toHaveValue(5432);
expect(databaseNameField).toHaveValue('postgres');
expect(usernameField).toHaveValue('testdb');
expect(passwordField).toHaveValue('demoPassword');
userEvent.click(connectButton);
await waitFor(() => {
expect(fetchMock.calls(VALIDATE_PARAMS_ENDPOINT).length).toEqual(6);
});
});
});
describe('Import database flow', () => {
test('imports a file', async () => {
const importDbButton = screen.getByTestId(
'import-database-btn',
) as HTMLInputElement;
expect(importDbButton).toBeVisible();
const testFile = new File([new ArrayBuffer(1)], 'model_export.zip');
userEvent.click(importDbButton);
userEvent.upload(importDbButton, testFile);
expect(importDbButton.files?.[0]).toStrictEqual(testFile);
expect(importDbButton.files?.item(0)).toStrictEqual(testFile);
expect(importDbButton.files).toHaveLength(1);
});
});
});
describe('DatabaseModal w/ Deeplinking Engine', () => {
const renderAndWait = async () => {
const mounted = act(async () => {
render(<DatabaseModal {...dbProps} dbEngine="PostgreSQL" />, {
useRedux: true,
});
});
return mounted;
};
beforeEach(async () => {
await renderAndWait();
});
test('enters step 2 of 3 when proper database is selected', () => {
const step2of3text = screen.getByText(/step 2 of 3/i);
expect(step2of3text).toBeVisible();
});
});
describe('DatabaseModal w/ GSheet Engine', () => {
const renderAndWait = async () => {
const dbProps = {
show: true,
database_name: 'my database',
sqlalchemy_uri: 'gsheets://',
};
const mounted = act(async () => {
render(<DatabaseModal {...dbProps} dbEngine="Google Sheets" />, {
useRedux: true,
});
});
return mounted;
};
beforeEach(async () => {
await renderAndWait();
});
it('enters step 2 of 2 when proper database is selected', () => {
const step2of2text = screen.getByText(/step 2 of 2/i);
expect(step2of2text).toBeVisible();
});
it('renders the "Advanced" - SECURITY tab without Allow File Upload Checkbox', async () => {
// Click the "Advanced" tab
userEvent.click(screen.getByRole('tab', { name: /advanced/i }));
// Click the "Security" tab
userEvent.click(
screen.getByRole('tab', {
name: /right security add extra connection information\./i,
}),
);
// ----- BEGIN STEP 2 (ADVANCED - SECURITY)
// <ExtraOptions> - Advanced tabs
const impersonateLoggerUserCheckbox = screen.getByRole('checkbox', {
name: /impersonate logged in/i,
});
const impersonateLoggerUserText = screen.getByText(
/impersonate logged in/i,
);
const allowFileUploadText = screen.queryByText(
/Allow file uploads to database/i,
);
const schemasForFileUploadText = screen.queryByText(
/Schemas allowed for File upload/i,
);
const visibleComponents = [impersonateLoggerUserText];
// These components exist in the DOM but are not visible
const invisibleComponents = [impersonateLoggerUserCheckbox];
// ---------- Assertions ----------
visibleComponents.forEach(component => {
expect(component).toBeVisible();
});
invisibleComponents.forEach(component => {
expect(component).not.toBeVisible();
});
expect(allowFileUploadText).not.toBeInTheDocument();
expect(schemasForFileUploadText).not.toBeInTheDocument();
});
it('if the SSH Tunneling toggle is not displayed, nothing should get displayed', async () => {
const SSHTunnelingToggle = screen.queryByTestId('ssh-tunnel-switch');
expect(SSHTunnelingToggle).not.toBeInTheDocument();
const SSHTunnelServerAddressInput = screen.queryByTestId(
'ssh-tunnel-server_address-input',
);
expect(SSHTunnelServerAddressInput).not.toBeInTheDocument();
const SSHTunnelServerPortInput = screen.queryByTestId(
'ssh-tunnel-server_port-input',
);
expect(SSHTunnelServerPortInput).not.toBeInTheDocument();
const SSHTunnelUsernameInput = screen.queryByTestId(
'ssh-tunnel-username-input',
);
expect(SSHTunnelUsernameInput).not.toBeInTheDocument();
const SSHTunnelPasswordInput = screen.queryByTestId(
'ssh-tunnel-password-input',
);
expect(SSHTunnelPasswordInput).not.toBeInTheDocument();
});
});
describe('DatabaseModal w errors as objects', () => {
jest.mock('src/views/CRUD/hooks', () => ({
...jest.requireActual('src/views/CRUD/hooks'),
useSingleViewResource: jest.fn(),
}));
const renderAndWait = async () => {
const mounted = act(async () => {
render(<DatabaseModal {...dbProps} dbEngine="PostgreSQL" />, {
useRedux: true,
});
});
return mounted;
};
beforeEach(async () => {
await renderAndWait();
});
test('Error displays when it is an object', async () => {
const step2of3text = screen.getByText(/step 2 of 3/i);
const errorSection = screen.getByText(/Database Creation Error/i);
expect(step2of3text).toBeVisible();
expect(errorSection).toBeVisible();
});
});
describe('DatabaseModal w errors as strings', () => {
jest.mock('src/views/CRUD/hooks', () => ({
...jest.requireActual('src/views/CRUD/hooks'),
useSingleViewResource: jest.fn(),
}));
const useSingleViewResourceMock = jest.spyOn(
hooks,
'useSingleViewResource',
);
useSingleViewResourceMock.mockReturnValue({
state: {
loading: false,
resource: null,
error: 'Test Error With String',
},
fetchResource: jest.fn(),
createResource: jest.fn(),
updateResource: jest.fn(),
clearError: jest.fn(),
setResource: jest.fn(),
});
const renderAndWait = async () => {
const mounted = act(async () => {
render(<DatabaseModal {...dbProps} dbEngine="PostgreSQL" />, {
useRedux: true,
});
});
return mounted;
};
beforeEach(async () => {
await renderAndWait();
});
test('Error displays when it is a string', async () => {
const step2of3text = screen.getByText(/step 2 of 3/i);
const errorTitleMessage = screen.getByText(/Database Creation Error/i);
const button = screen.getByText('See more');
userEvent.click(button);
const errorMessage = screen.getByText(/Test Error With String/i);
expect(errorMessage).toBeVisible();
const closeButton = screen.getByText('Close');
userEvent.click(closeButton);
expect(step2of3text).toBeVisible();
expect(errorTitleMessage).toBeVisible();
});
});
describe('DatabaseModal w Extensions', () => {
const renderAndWait = async () => {
const extensionsRegistry = getExtensionsRegistry();
extensionsRegistry.set('ssh_tunnel.form.switch', () => (
<>ssh_tunnel.form.switch extension component</>
));
setupExtensions();
const mounted = act(async () => {
render(<DatabaseModal {...dbProps} dbEngine="SQLite" />, {
useRedux: true,
});
});
return mounted;
};
beforeEach(async () => {
await renderAndWait();
});
test('should render an extension component if one is supplied', () => {
expect(
screen.getByText('ssh_tunnel.form.switch extension component'),
).toBeInTheDocument();
});
});
});
describe('dbReducer', () => {
test('it will reset state to null', () => {
const action: DBReducerActionType = { type: ActionType.reset };
const currentState = dbReducer(databaseFixture, action);
expect(currentState).toBeNull();
});
test('it will set state to payload from fetched', () => {
const action: DBReducerActionType = {
type: ActionType.fetched,
payload: databaseFixture,
};
const currentState = dbReducer({}, action);
expect(currentState).toEqual({
...databaseFixture,
engine: 'postgres',
masked_encrypted_extra: '',
parameters: undefined,
query_input: '',
});
});
test('it will set state to payload from extra editor', () => {
const action: DBReducerActionType = {
type: ActionType.extraEditorChange,
payload: { name: 'foo', json: JSON.stringify({ bar: 1 }) },
};
const currentState = dbReducer(databaseFixture, action);
// extra should be serialized
expect(currentState).toEqual({
...databaseFixture,
extra: '{"foo":{"bar":1}}',
});
});
test('it will set state to payload from editor', () => {
const action: DBReducerActionType = {
type: ActionType.editorChange,
payload: { name: 'foo', json: JSON.stringify({ bar: 1 }) },
};
const currentState = dbReducer(databaseFixture, action);
// extra should be serialized
expect(currentState).toEqual({
...databaseFixture,
foo: JSON.stringify({ bar: 1 }),
});
});
test('it will add extra payload to existing extra data', () => {
const action: DBReducerActionType = {
type: ActionType.extraEditorChange,
payload: { name: 'foo', json: JSON.stringify({ bar: 1 }) },
};
// extra should be a string
const currentState = dbReducer(
{
...databaseFixture,
extra: JSON.stringify({ name: 'baz', json: { fiz: 2 } }),
},
action,
);
// extra should be serialized
expect(currentState).toEqual({
...databaseFixture,
extra: '{"name":"baz","json":{"fiz":2},"foo":{"bar":1}}',
});
});
test('it will set state to payload from extra input change', () => {
const action: DBReducerActionType = {
type: ActionType.extraInputChange,
payload: { name: 'foo', value: 'bar' },
};
const currentState = dbReducer(databaseFixture, action);
// extra should be serialized
expect(currentState).toEqual({
...databaseFixture,
extra: '{"foo":"bar"}',
});
});
test('it will set state to payload from extra input change when checkbox', () => {
const action: DBReducerActionType = {
type: ActionType.extraInputChange,
payload: { name: 'foo', type: 'checkbox', checked: true },
};
const currentState = dbReducer(databaseFixture, action);
// extra should be serialized
expect(currentState).toEqual({
...databaseFixture,
extra: '{"foo":true}',
});
});
test('it will set state to payload from extra input change when schema_cache_timeout', () => {
const action: DBReducerActionType = {
type: ActionType.extraInputChange,
payload: { name: 'schema_cache_timeout', value: 'bar' },
};
const currentState = dbReducer(databaseFixture, action);
// extra should be serialized
expect(currentState).toEqual({
...databaseFixture,
extra: '{"metadata_cache_timeout":{"schema_cache_timeout":"bar"}}',
});
});
test('it will set state to payload from extra input change when table_cache_timeout', () => {
const action: DBReducerActionType = {
type: ActionType.extraInputChange,
payload: { name: 'table_cache_timeout', value: 'bar' },
};
const currentState = dbReducer(databaseFixture, action);
// extra should be serialized
expect(currentState).toEqual({
...databaseFixture,
extra: '{"metadata_cache_timeout":{"table_cache_timeout":"bar"}}',
});
});
test('it will overwrite state to payload from extra input change when table_cache_timeout', () => {
const action: DBReducerActionType = {
type: ActionType.extraInputChange,
payload: { name: 'table_cache_timeout', value: 'bar' },
};
const currentState = dbReducer(
{
...databaseFixture,
extra: '{"metadata_cache_timeout":{"table_cache_timeout":"foo"}}',
},
action,
);
// extra should be serialized
expect(currentState).toEqual({
...databaseFixture,
extra: '{"metadata_cache_timeout":{"table_cache_timeout":"bar"}}',
});
});
test(`it will set state to payload from extra
input change when schemas_allowed_for_file_upload`, () => {
const action: DBReducerActionType = {
type: ActionType.extraInputChange,
payload: { name: 'schemas_allowed_for_file_upload', value: 'bar' },
};
const currentState = dbReducer(databaseFixture, action);
// extra should be serialized
expect(currentState).toEqual({
...databaseFixture,
extra: '{"schemas_allowed_for_file_upload":["bar"]}',
});
});
test(`it will overwrite state to payload from extra
input change when schemas_allowed_for_file_upload`, () => {
const action: DBReducerActionType = {
type: ActionType.extraInputChange,
payload: { name: 'schemas_allowed_for_file_upload', value: 'bar' },
};
const currentState = dbReducer(
{
...databaseFixture,
extra: '{"schemas_allowed_for_file_upload":["foo"]}',
},
action,
);
// extra should be serialized
expect(currentState).toEqual({
...databaseFixture,
extra: '{"schemas_allowed_for_file_upload":["bar"]}',
});
});
test(`it will set state to payload from extra
input change when schemas_allowed_for_file_upload
with blank list`, () => {
const action: DBReducerActionType = {
type: ActionType.extraInputChange,
payload: { name: 'schemas_allowed_for_file_upload', value: 'bar,' },
};
const currentState = dbReducer(databaseFixture, action);
// extra should be serialized
expect(currentState).toEqual({
...databaseFixture,
extra: '{"schemas_allowed_for_file_upload":["bar"]}',
});
});
test('it will set state to payload from input change', () => {
const action: DBReducerActionType = {
type: ActionType.inputChange,
payload: { name: 'foo', value: 'bar' },
};
const currentState = dbReducer(databaseFixture, action);
expect(currentState).toEqual({
...databaseFixture,
foo: 'bar',
});
});
test('it will set state to payload from input change for checkbox', () => {
const action: DBReducerActionType = {
type: ActionType.inputChange,
payload: { name: 'foo', type: 'checkbox', checked: true },
};
const currentState = dbReducer(databaseFixture, action);
expect(currentState).toEqual({
...databaseFixture,
foo: true,
});
});
test('it will change state to payload from input change for checkbox', () => {
const action: DBReducerActionType = {
type: ActionType.inputChange,
payload: { name: 'allow_ctas', type: 'checkbox', checked: false },
};
const currentState = dbReducer(
{
...databaseFixture,
allow_ctas: true,
},
action,
);
expect(currentState).toEqual({
...databaseFixture,
allow_ctas: false,
});
});
test('it will add a parameter', () => {
const action: DBReducerActionType = {
type: ActionType.parametersChange,
payload: { name: 'host', value: '127.0.0.1' },
};
const currentState = dbReducer(databaseFixture, action);
expect(currentState).toEqual({
...databaseFixture,
parameters: {
host: '127.0.0.1',
},
});
});
test('it will add a parameter with existing parameters', () => {
const action: DBReducerActionType = {
type: ActionType.parametersChange,
payload: { name: 'port', value: '1234' },
};
const currentState = dbReducer(
{
...databaseFixture,
parameters: {
host: '127.0.0.1',
},
},
action,
);
expect(currentState).toEqual({
...databaseFixture,
parameters: {
host: '127.0.0.1',
port: '1234',
},
});
});
test('it will change a parameter with existing parameters', () => {
const action: DBReducerActionType = {
type: ActionType.parametersChange,
payload: { name: 'host', value: 'localhost' },
};
const currentState = dbReducer(
{
...databaseFixture,
parameters: {
host: '127.0.0.1',
},
},
action,
);
expect(currentState).toEqual({
...databaseFixture,
parameters: {
host: 'localhost',
},
});
});
test('it will set state to payload from parametersChange with catalog', () => {
const action: DBReducerActionType = {
type: ActionType.parametersChange,
payload: { name: 'name', type: 'catalog-0', value: 'bar' },
};
const currentState = dbReducer(
{ ...databaseFixture, catalog: [{ name: 'foo', value: 'baz' }] },
action,
);
expect(currentState).toEqual({
...databaseFixture,
catalog: [{ name: 'bar', value: 'baz' }],
parameters: {
catalog: {
bar: 'baz',
},
},
});
});
test('it will add a new catalog array when empty', () => {
const action: DBReducerActionType = {
type: ActionType.addTableCatalogSheet,
};
const currentState = dbReducer(databaseFixture, action);
expect(currentState).toEqual({
...databaseFixture,
catalog: [{ name: '', value: '' }],
});
});
test('it will add a new catalog array when one exists', () => {
const action: DBReducerActionType = {
type: ActionType.addTableCatalogSheet,
};
const currentState = dbReducer(
{ ...databaseFixture, catalog: [{ name: 'foo', value: 'baz' }] },
action,
);
expect(currentState).toEqual({
...databaseFixture,
catalog: [
{ name: 'foo', value: 'baz' },
{ name: '', value: '' },
],
});
});
test('it will remove a catalog when one exists', () => {
const action: DBReducerActionType = {
type: ActionType.removeTableCatalogSheet,
payload: { indexToDelete: 0 },
};
const currentState = dbReducer(
{ ...databaseFixture, catalog: [{ name: 'foo', value: 'baz' }] },
action,
);
expect(currentState).toEqual({
...databaseFixture,
catalog: [],
});
});
test('it will add db information when one is selected', () => {
const { backend, ...db } = databaseFixture;
const action: DBReducerActionType = {
type: ActionType.dbSelected,
payload: {
engine_information: {
supports_file_upload: true,
disable_ssh_tunneling: false,
},
...db,
driver: db.driver,
engine: backend,
},
};
const currentState = dbReducer({}, action);
expect(currentState).toEqual({
id: db.id,
database_name: db.database_name,
engine: backend,
configuration_method: db.configuration_method,
engine_information: {
supports_file_upload: true,
disable_ssh_tunneling: false,
},
driver: db.driver,
expose_in_sqllab: true,
extra: '{"allows_virtual_table_explore":true}',
is_managed_externally: false,
name: 'PostgresDB',
});
});
test('it will add a SSH Tunnel config parameter', () => {
const action: DBReducerActionType = {
type: ActionType.parametersSSHTunnelChange,
payload: { name: 'server_address', value: '127.0.0.1' },
};
const currentState = dbReducer(databaseFixture, action);
expect(currentState).toEqual({
...databaseFixture,
ssh_tunnel: {
server_address: '127.0.0.1',
},
});
});
test('it will add a SSH Tunnel config parameter with existing configs', () => {
const action: DBReducerActionType = {
type: ActionType.parametersSSHTunnelChange,
payload: { name: 'server_port', value: '22' },
};
const currentState = dbReducer(
{
...databaseFixture,
ssh_tunnel: {
server_address: '127.0.0.1',
},
},
action,
);
expect(currentState).toEqual({
...databaseFixture,
ssh_tunnel: {
server_address: '127.0.0.1',
server_port: '22',
},
});
});
test('it will change a SSH Tunnel config parameter with existing configs', () => {
const action: DBReducerActionType = {
type: ActionType.parametersSSHTunnelChange,
payload: { name: 'server_address', value: 'localhost' },
};
const currentState = dbReducer(
{
...databaseFixture,
ssh_tunnel: {
server_address: '127.0.0.1',
},
},
action,
);
expect(currentState).toEqual({
...databaseFixture,
ssh_tunnel: {
server_address: 'localhost',
},
});
});
test('it will remove the SSH Tunnel config parameters', () => {
const action: DBReducerActionType = {
type: ActionType.removeSSHTunnelConfig,
};
const currentState = dbReducer(databaseFixture, action);
expect(currentState).toEqual({
...databaseFixture,
ssh_tunnel: undefined,
});
});
});
|
7,797 | 0 | petrpan-code/apache/superset/superset-frontend/src/features/datasets/AddDataset | petrpan-code/apache/superset/superset-frontend/src/features/datasets/AddDataset/DatasetPanel/DatasetPanel.test.tsx | /**
* 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 { render, screen } from 'spec/helpers/testing-library';
import DatasetPanel, {
REFRESHING,
ALT_LOADING,
tableColumnDefinition,
COLUMN_TITLE,
} from 'src/features/datasets/AddDataset/DatasetPanel/DatasetPanel';
import { exampleColumns, exampleDataset } from './fixtures';
import {
SELECT_MESSAGE,
CREATE_MESSAGE,
VIEW_DATASET_MESSAGE,
SELECT_TABLE_TITLE,
NO_COLUMNS_TITLE,
NO_COLUMNS_DESCRIPTION,
ERROR_TITLE,
ERROR_DESCRIPTION,
} from './MessageContent';
jest.mock(
'src/components/Icons/Icon',
() =>
({ fileName }: { fileName: string }) =>
<span role="img" aria-label={fileName.replace('_', '-')} />,
);
describe('DatasetPanel', () => {
test('renders a blank state DatasetPanel', () => {
render(<DatasetPanel hasError={false} columnList={[]} loading={false} />, {
useRouter: true,
});
const blankDatasetImg = screen.getByRole('img', { name: /empty/i });
expect(blankDatasetImg).toBeVisible();
const blankDatasetTitle = screen.getByText(SELECT_TABLE_TITLE);
expect(blankDatasetTitle).toBeVisible();
const blankDatasetDescription1 = screen.getByText(SELECT_MESSAGE, {
exact: false,
});
expect(blankDatasetDescription1).toBeVisible();
const blankDatasetDescription2 = screen.getByText(VIEW_DATASET_MESSAGE, {
exact: false,
});
expect(blankDatasetDescription2).toBeVisible();
const sqlLabLink = screen.getByRole('button', {
name: CREATE_MESSAGE,
});
expect(sqlLabLink).toBeVisible();
});
test('renders a no columns screen', () => {
render(
<DatasetPanel
tableName="Name"
hasError={false}
columnList={[]}
loading={false}
/>,
{
useRouter: true,
},
);
const blankDatasetImg = screen.getByRole('img', { name: /empty/i });
expect(blankDatasetImg).toBeVisible();
const noColumnsTitle = screen.getByText(NO_COLUMNS_TITLE);
expect(noColumnsTitle).toBeVisible();
const noColumnsDescription = screen.getByText(NO_COLUMNS_DESCRIPTION);
expect(noColumnsDescription).toBeVisible();
});
test('renders a loading screen', () => {
render(
<DatasetPanel
tableName="Name"
hasError={false}
columnList={[]}
loading
/>,
{
useRouter: true,
},
);
const blankDatasetImg = screen.getByAltText(ALT_LOADING);
expect(blankDatasetImg).toBeVisible();
const blankDatasetTitle = screen.getByText(REFRESHING);
expect(blankDatasetTitle).toBeVisible();
});
test('renders an error screen', () => {
render(
<DatasetPanel
tableName="Name"
hasError
columnList={[]}
loading={false}
/>,
{
useRouter: true,
},
);
const errorTitle = screen.getByText(ERROR_TITLE);
expect(errorTitle).toBeVisible();
const errorDescription = screen.getByText(ERROR_DESCRIPTION);
expect(errorDescription).toBeVisible();
});
test('renders a table with columns displayed', async () => {
const tableName = 'example_name';
render(
<DatasetPanel
tableName={tableName}
hasError={false}
columnList={exampleColumns}
loading={false}
/>,
{
useRouter: true,
},
);
expect(await screen.findByText(tableName)).toBeVisible();
expect(screen.getByText(COLUMN_TITLE)).toBeVisible();
expect(
screen.getByText(tableColumnDefinition[0].title as string),
).toBeInTheDocument();
expect(
screen.getByText(tableColumnDefinition[1].title as string),
).toBeInTheDocument();
exampleColumns.forEach(row => {
expect(screen.getByText(row.name)).toBeInTheDocument();
expect(screen.getByText(row.type)).toBeInTheDocument();
});
});
test('renders an info banner if table already has a dataset', async () => {
render(
<DatasetPanel
tableName="example_table"
hasError={false}
columnList={exampleColumns}
loading={false}
datasets={exampleDataset}
/>,
{
useRouter: true,
},
);
// This is text in the info banner
expect(
await screen.findByText(
/this table already has a dataset associated with it. you can only associate one dataset with a table./i,
),
).toBeVisible();
});
});
|
7,803 | 0 | petrpan-code/apache/superset/superset-frontend/src/features/datasets/AddDataset | petrpan-code/apache/superset/superset-frontend/src/features/datasets/AddDataset/EditDataset/EditDataset.test.tsx | /**
* 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 fetchMock from 'fetch-mock';
import { render, screen } from 'spec/helpers/testing-library';
import EditDataset from './index';
const DATASET_ENDPOINT = 'glob:*api/v1/dataset/1/related_objects';
const mockedProps = {
id: '1',
};
fetchMock.get(DATASET_ENDPOINT, { charts: { results: [], count: 2 } });
test('should render edit dataset view with tabs', async () => {
render(<EditDataset {...mockedProps} />);
const columnTab = await screen.findByRole('tab', { name: /columns/i });
const metricsTab = screen.getByRole('tab', { name: /metrics/i });
const usageTab = screen.getByRole('tab', { name: /usage/i });
expect(fetchMock.calls(DATASET_ENDPOINT)).toBeTruthy();
expect(columnTab).toBeInTheDocument();
expect(metricsTab).toBeInTheDocument();
expect(usageTab).toBeInTheDocument();
});
|
7,805 | 0 | petrpan-code/apache/superset/superset-frontend/src/features/datasets/AddDataset/EditDataset | petrpan-code/apache/superset/superset-frontend/src/features/datasets/AddDataset/EditDataset/UsageTab/UsageTab.test.tsx | /**
* 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 fetchMock from 'fetch-mock';
import userEvent from '@testing-library/user-event';
import { render, screen, waitFor } from 'spec/helpers/testing-library';
import { ChartListChart, getMockChart } from 'spec/fixtures/mockCharts';
import ToastContainer from 'src/components/MessageToasts/ToastContainer';
import DatasetUsage from '.';
const DEFAULT_DATASET_ID = '1';
const DEFAULT_ORDER_COLUMN = 'last_saved_at';
const DEFAULT_ORDER_DIRECTION = 'desc';
const DEFAULT_PAGE = 0;
const DEFAULT_PAGE_SIZE = 25;
const getChartResponse = (result: ChartListChart[]) => ({
count: result.length,
result,
});
const CHARTS_ENDPOINT = 'glob:*/api/v1/chart/?*';
const mockChartsFetch = (response: fetchMock.MockResponse) => {
fetchMock.reset();
fetchMock.get('glob:*/api/v1/chart/_info?*', {
permissions: ['can_export', 'can_read', 'can_write'],
});
fetchMock.get(CHARTS_ENDPOINT, response);
};
const renderDatasetUsage = () =>
render(
<>
<DatasetUsage datasetId={DEFAULT_DATASET_ID} />
<ToastContainer />
</>,
{ useRedux: true, useRouter: true },
);
const expectLastChartRequest = (params?: {
datasetId?: string;
orderColumn?: string;
orderDirection?: 'desc' | 'asc';
page?: number;
pageSize?: number;
}) => {
const { datasetId, orderColumn, orderDirection, page, pageSize } = {
datasetId: DEFAULT_DATASET_ID,
orderColumn: DEFAULT_ORDER_COLUMN,
orderDirection: DEFAULT_ORDER_DIRECTION,
page: DEFAULT_PAGE,
pageSize: DEFAULT_PAGE_SIZE,
...(params || {}),
};
const calls = fetchMock.calls(CHARTS_ENDPOINT);
expect(calls.length).toBeGreaterThan(0);
const lastChartRequestUrl = calls[calls.length - 1][0];
expect(lastChartRequestUrl).toMatch(
new RegExp(`col:datasource_id,opr:eq,value:%27${datasetId}%27`),
);
expect(lastChartRequestUrl).toMatch(
new RegExp(`order_column:${orderColumn}`),
);
expect(lastChartRequestUrl).toMatch(
new RegExp(`order_direction:${orderDirection}`),
);
expect(lastChartRequestUrl).toMatch(new RegExp(`page:${page}`));
expect(lastChartRequestUrl).toMatch(new RegExp(`page_size:${pageSize}`));
};
test('shows loading state', async () => {
mockChartsFetch(
new Promise(resolve =>
setTimeout(() => resolve(getChartResponse([])), 250),
),
);
renderDatasetUsage();
const loadingIndicator = await screen.findByRole('status', {
name: /loading/i,
});
expect(loadingIndicator).toBeVisible();
});
test('shows error state', async () => {
mockChartsFetch(500);
renderDatasetUsage();
const errorMessage = await screen.findByText(
/an error occurred while fetching charts/i,
);
expect(errorMessage).toBeInTheDocument();
});
test('shows empty state', async () => {
mockChartsFetch(getChartResponse([]));
renderDatasetUsage();
const noChartsTitle = await screen.findByText(/no charts/i);
const noChartsDescription = screen.getByText(
/this dataset is not used to power any charts\./i,
);
expect(noChartsTitle).toBeVisible();
expect(noChartsDescription).toBeVisible();
expect(fetchMock.calls(CHARTS_ENDPOINT)).toHaveLength(1);
expectLastChartRequest();
});
test('show and sort by chart title', async () => {
mockChartsFetch(
getChartResponse([
getMockChart({ id: 1, slice_name: 'Sample A' }),
getMockChart({ id: 2, slice_name: 'Sample C' }),
getMockChart({ id: 3, slice_name: 'Sample B' }),
]),
);
renderDatasetUsage();
const chartNameColumnHeader = screen.getByText('Chart');
const chartNameLinks = await screen.findAllByRole('link', {
name: /sample/i,
});
// Default sort
expect(chartNameLinks).toHaveLength(3);
expect(chartNameLinks[0]).toHaveTextContent('Sample A');
expect(chartNameLinks[0]).toHaveAttribute('href', '/explore/?slice_id=1');
expect(chartNameLinks[1]).toHaveTextContent('Sample C');
expect(chartNameLinks[1]).toHaveAttribute('href', '/explore/?slice_id=2');
expect(chartNameLinks[2]).toHaveTextContent('Sample B');
expect(chartNameLinks[2]).toHaveAttribute('href', '/explore/?slice_id=3');
expectLastChartRequest();
// Sort by name ascending
userEvent.click(chartNameColumnHeader);
waitFor(() => {
expectLastChartRequest({
orderColumn: 'slice_name',
orderDirection: 'asc',
});
});
// Sort by name descending
userEvent.click(chartNameColumnHeader);
waitFor(() => {
expectLastChartRequest({
orderColumn: 'slice_name',
orderDirection: 'desc',
});
});
});
test('show chart owners', async () => {
mockChartsFetch(
getChartResponse([
getMockChart({
id: 1,
owners: [
{ id: 1, first_name: 'John', last_name: 'Doe', username: 'j1' },
{ id: 2, first_name: 'Jane', last_name: 'Doe', username: 'j2' },
],
}),
getMockChart({ id: 2 }),
getMockChart({
id: 3,
owners: [
{ id: 3, first_name: 'John', last_name: 'Doe', username: 'j1' },
],
}),
]),
);
renderDatasetUsage();
const chartOwners = await screen.findAllByText(/doe/i);
expect(chartOwners).toHaveLength(3);
expect(chartOwners[0]).toHaveTextContent('John Doe');
expect(chartOwners[1]).toHaveTextContent('Jane Doe');
expect(chartOwners[0].parentNode).toBe(chartOwners[1].parentNode);
expect(chartOwners[2]).toHaveTextContent('John Doe');
expect(chartOwners[2].parentNode).not.toBe(chartOwners[0].parentNode);
expect(chartOwners[2].parentNode).not.toBe(chartOwners[1].parentNode);
expectLastChartRequest();
});
const getDate = (msAgo: number) => {
const date = new Date();
date.setMilliseconds(date.getMilliseconds() - msAgo);
return date;
};
test('show and sort by chart last modified', async () => {
mockChartsFetch(
getChartResponse([
getMockChart({ id: 2, last_saved_at: getDate(10000).toISOString() }),
getMockChart({ id: 1, last_saved_at: getDate(1000000).toISOString() }),
getMockChart({ id: 3, last_saved_at: getDate(100000000).toISOString() }),
]),
);
renderDatasetUsage();
const chartLastModifiedColumnHeader = screen.getByText('Chart last modified');
const chartLastModifiedValues = await screen.findAllByText(
/a few seconds ago|17 minutes ago|a day ago/i,
);
// Default sort
expect(chartLastModifiedValues).toHaveLength(3);
expect(chartLastModifiedValues[0]).toHaveTextContent('a few seconds ago');
expect(chartLastModifiedValues[1]).toHaveTextContent('17 minutes ago');
expect(chartLastModifiedValues[2]).toHaveTextContent('a day ago');
expectLastChartRequest();
// Sort by last modified ascending
userEvent.click(chartLastModifiedColumnHeader);
waitFor(() => {
expectLastChartRequest({ orderDirection: 'asc' });
});
// Sort by last modified descending
userEvent.click(chartLastModifiedColumnHeader);
waitFor(() => {
expectLastChartRequest({ orderDirection: 'desc' });
});
});
test('show and sort by chart last modified by', async () => {
mockChartsFetch(
getChartResponse([
getMockChart({
id: 2,
last_saved_by: { id: 1, first_name: 'John', last_name: 'Doe' },
}),
getMockChart({
id: 1,
last_saved_by: null,
}),
getMockChart({
id: 3,
last_saved_by: { id: 2, first_name: 'Jane', last_name: 'Doe' },
}),
]),
);
renderDatasetUsage();
const chartLastModifiedByColumnHeader = screen.getByText(
'Chart last modified by',
);
const chartLastModifiedByValues = await screen.findAllByText(/doe/i);
// Default sort
expect(chartLastModifiedByValues).toHaveLength(2);
expect(chartLastModifiedByValues[0]).toHaveTextContent('John Doe');
expect(chartLastModifiedByValues[1]).toHaveTextContent('Jane Doe');
expectLastChartRequest();
// Sort by last modified ascending
userEvent.click(chartLastModifiedByColumnHeader);
waitFor(() => {
expectLastChartRequest({ orderDirection: 'asc' });
});
// Sort by last modified descending
userEvent.click(chartLastModifiedByColumnHeader);
waitFor(() => {
expectLastChartRequest({ orderDirection: 'desc' });
});
});
test('show chart dashboards', async () => {
mockChartsFetch(
getChartResponse([
getMockChart({
id: 1,
dashboards: [
{ id: 1, dashboard_title: 'Sample dashboard A' },
{ id: 2, dashboard_title: 'Sample dashboard B' },
],
}),
getMockChart({ id: 2 }),
getMockChart({
id: 3,
dashboards: [{ id: 3, dashboard_title: 'Sample dashboard C' }],
}),
]),
);
renderDatasetUsage();
const chartDashboards = await screen.findAllByRole('link', {
name: /sample dashboard/i,
});
expect(chartDashboards).toHaveLength(3);
expect(chartDashboards[0]).toHaveTextContent('Sample dashboard A');
expect(chartDashboards[0]).toHaveAttribute('href', '/superset/dashboard/1');
expect(chartDashboards[1]).toHaveTextContent('Sample dashboard B');
expect(chartDashboards[1]).toHaveAttribute('href', '/superset/dashboard/2');
expect(chartDashboards[0].closest('.ant-table-cell')).toBe(
chartDashboards[1].closest('.ant-table-cell'),
);
expect(chartDashboards[2]).toHaveTextContent('Sample dashboard C');
expect(chartDashboards[2]).toHaveAttribute('href', '/superset/dashboard/3');
expect(chartDashboards[2].closest('.ant-table-cell')).not.toBe(
chartDashboards[0].closest('.ant-table-cell'),
);
expect(chartDashboards[2].closest('.ant-table-cell')).not.toBe(
chartDashboards[1].closest('.ant-table-cell'),
);
expectLastChartRequest();
expect(
screen.queryByRole('button', {
name: /right/i,
}),
).not.toBeInTheDocument();
});
test('paginates', async () => {
const charts = [];
for (let i = 0; i < 65; i += 1) {
charts.push(
getMockChart({
id: i + 1,
slice_name: `Sample chart ${i + 1}`,
}),
);
}
mockChartsFetch(getChartResponse(charts));
renderDatasetUsage();
// First page
let chartNameValues = await screen.findAllByRole('cell', {
name: /sample chart/i,
});
expect(chartNameValues).toHaveLength(25);
expect(chartNameValues[0]).toHaveTextContent('Sample chart 1');
expect(chartNameValues[24]).toHaveTextContent('Sample chart 25');
// Second page
userEvent.click(
screen.getByRole('button', {
name: /right/i,
}),
);
chartNameValues = await screen.findAllByRole('cell', {
name: /sample chart/i,
});
expect(chartNameValues).toHaveLength(25);
expect(chartNameValues[0]).toHaveTextContent('Sample chart 26');
expect(chartNameValues[24]).toHaveTextContent('Sample chart 50');
// Third page
userEvent.click(
screen.getByRole('button', {
name: /right/i,
}),
);
chartNameValues = await screen.findAllByRole('cell', {
name: /sample chart/i,
});
expect(chartNameValues).toHaveLength(15);
expect(chartNameValues[0]).toHaveTextContent('Sample chart 51');
expect(chartNameValues[14]).toHaveTextContent('Sample chart 65');
});
|
7,807 | 0 | petrpan-code/apache/superset/superset-frontend/src/features/datasets/AddDataset | petrpan-code/apache/superset/superset-frontend/src/features/datasets/AddDataset/Footer/Footer.test.tsx | /**
* 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 { render, screen } from 'spec/helpers/testing-library';
import Footer from 'src/features/datasets/AddDataset/Footer';
const mockHistoryPush = jest.fn();
jest.mock('react-router-dom', () => ({
...jest.requireActual('react-router-dom'),
useHistory: () => ({
push: mockHistoryPush,
}),
}));
const mockedProps = {
url: 'realwebsite.com',
};
const mockPropsWithDataset = {
url: 'realwebsite.com',
datasetObject: {
database: {
id: '1',
database_name: 'examples',
},
owners: [1, 2, 3],
schema: 'public',
dataset_name: 'Untitled',
table_name: 'real_info',
},
hasColumns: true,
};
describe('Footer', () => {
test('renders a Footer with a cancel button and a disabled create button', () => {
render(<Footer {...mockedProps} />, { useRedux: true });
const saveButton = screen.getByRole('button', {
name: /Cancel/i,
});
const createButton = screen.getByRole('button', {
name: /Create/i,
});
expect(saveButton).toBeVisible();
expect(createButton).toBeDisabled();
});
test('renders a Create Dataset button when a table is selected', () => {
render(<Footer {...mockPropsWithDataset} />, { useRedux: true });
const createButton = screen.getByRole('button', {
name: /Create/i,
});
expect(createButton).toBeEnabled();
});
test('create button becomes disabled when table already has a dataset', () => {
render(<Footer datasets={['real_info']} {...mockPropsWithDataset} />, {
useRedux: true,
});
const createButton = screen.getByRole('button', {
name: /Create/i,
});
expect(createButton).toBeDisabled();
});
});
|
7,809 | 0 | petrpan-code/apache/superset/superset-frontend/src/features/datasets/AddDataset | petrpan-code/apache/superset/superset-frontend/src/features/datasets/AddDataset/Header/Header.test.tsx | /**
* 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 { render, screen, waitFor } from 'spec/helpers/testing-library';
import Header, { DEFAULT_TITLE } from 'src/features/datasets/AddDataset/Header';
describe('Header', () => {
const mockSetDataset = jest.fn();
const waitForRender = (props?: any) =>
waitFor(() => render(<Header setDataset={mockSetDataset} {...props} />));
test('renders a blank state Header', async () => {
await waitForRender();
const datasetName = screen.getByText(/new dataset/i);
expect(datasetName).toBeVisible();
});
test('displays "New dataset" when a table is not selected', async () => {
await waitForRender();
const datasetName = screen.getByText(/new dataset/i);
expect(datasetName.innerHTML).toBe(DEFAULT_TITLE);
});
test('displays table name when a table is selected', async () => {
// The schema and table name are passed in through props once selected
await waitForRender({ schema: 'testSchema', title: 'testTable' });
const datasetName = screen.getByText(/testtable/i);
expect(datasetName.innerHTML).toBe('testTable');
});
});
|
7,811 | 0 | petrpan-code/apache/superset/superset-frontend/src/features/datasets/AddDataset | petrpan-code/apache/superset/superset-frontend/src/features/datasets/AddDataset/LeftPanel/LeftPanel.test.tsx | /**
* 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 fetchMock from 'fetch-mock';
import userEvent from '@testing-library/user-event';
import { render, screen, waitFor } from 'spec/helpers/testing-library';
import LeftPanel from 'src/features/datasets/AddDataset/LeftPanel';
import { exampleDataset } from 'src/features/datasets/AddDataset/DatasetPanel/fixtures';
const databasesEndpoint = 'glob:*/api/v1/database/?q*';
const schemasEndpoint = 'glob:*/api/v1/database/*/schemas*';
const tablesEndpoint = 'glob:*/api/v1/database/*/tables/?q*';
beforeEach(() => {
fetchMock.get(databasesEndpoint, {
count: 2,
description_columns: {},
ids: [1, 2],
label_columns: {
allow_file_upload: 'Allow Csv Upload',
allow_ctas: 'Allow Ctas',
allow_cvas: 'Allow Cvas',
allow_dml: 'Allow Dml',
allow_multi_schema_metadata_fetch: 'Allow Multi Schema Metadata Fetch',
allow_run_async: 'Allow Run Async',
allows_cost_estimate: 'Allows Cost Estimate',
allows_subquery: 'Allows Subquery',
allows_virtual_table_explore: 'Allows Virtual Table Explore',
disable_data_preview: 'Disables SQL Lab Data Preview',
backend: 'Backend',
changed_on: 'Changed On',
changed_on_delta_humanized: 'Changed On Delta Humanized',
'created_by.first_name': 'Created By First Name',
'created_by.last_name': 'Created By Last Name',
database_name: 'Database Name',
explore_database_id: 'Explore Database Id',
expose_in_sqllab: 'Expose In Sqllab',
force_ctas_schema: 'Force Ctas Schema',
id: 'Id',
},
list_columns: [
'allow_file_upload',
'allow_ctas',
'allow_cvas',
'allow_dml',
'allow_multi_schema_metadata_fetch',
'allow_run_async',
'allows_cost_estimate',
'allows_subquery',
'allows_virtual_table_explore',
'disable_data_preview',
'backend',
'changed_on',
'changed_on_delta_humanized',
'created_by.first_name',
'created_by.last_name',
'database_name',
'explore_database_id',
'expose_in_sqllab',
'force_ctas_schema',
'id',
],
list_title: 'List Database',
order_columns: [
'allow_file_upload',
'allow_dml',
'allow_run_async',
'changed_on',
'changed_on_delta_humanized',
'created_by.first_name',
'database_name',
'expose_in_sqllab',
],
result: [
{
allow_file_upload: false,
allow_ctas: false,
allow_cvas: false,
allow_dml: false,
allow_multi_schema_metadata_fetch: false,
allow_run_async: false,
allows_cost_estimate: null,
allows_subquery: true,
allows_virtual_table_explore: true,
disable_data_preview: false,
backend: 'postgresql',
changed_on: '2021-03-09T19:02:07.141095',
changed_on_delta_humanized: 'a day ago',
created_by: null,
database_name: 'test-postgres',
explore_database_id: 1,
expose_in_sqllab: true,
force_ctas_schema: null,
id: 1,
},
{
allow_csv_upload: false,
allow_ctas: false,
allow_cvas: false,
allow_dml: false,
allow_multi_schema_metadata_fetch: false,
allow_run_async: false,
allows_cost_estimate: null,
allows_subquery: true,
allows_virtual_table_explore: true,
disable_data_preview: false,
backend: 'mysql',
changed_on: '2021-03-09T19:02:07.141095',
changed_on_delta_humanized: 'a day ago',
created_by: null,
database_name: 'test-mysql',
explore_database_id: 1,
expose_in_sqllab: true,
force_ctas_schema: null,
id: 2,
},
],
});
fetchMock.get(schemasEndpoint, {
result: ['information_schema', 'public'],
});
fetchMock.get(tablesEndpoint, {
count: 3,
result: [
{ value: 'Sheet1', type: 'table', extra: null },
{ value: 'Sheet2', type: 'table', extra: null },
{ value: 'Sheet3', type: 'table', extra: null },
],
});
});
afterEach(() => {
fetchMock.reset();
});
const mockFun = jest.fn();
test('should render', async () => {
render(<LeftPanel setDataset={mockFun} />, {
useRedux: true,
});
expect(
await screen.findByText(/Select database or type to search databases/i),
).toBeInTheDocument();
});
test('should render schema selector, database selector container, and selects', async () => {
render(<LeftPanel setDataset={mockFun} />, { useRedux: true });
expect(
await screen.findByText(/Select database or type to search databases/i),
).toBeVisible();
const databaseSelect = screen.getByRole('combobox', {
name: 'Select database or type to search databases',
});
const schemaSelect = screen.getByRole('combobox', {
name: 'Select schema or type to search schemas',
});
expect(databaseSelect).toBeInTheDocument();
expect(schemaSelect).toBeInTheDocument();
});
test('does not render blank state if there is nothing selected', async () => {
render(<LeftPanel setDataset={mockFun} />, { useRedux: true });
expect(
await screen.findByText(/Select database or type to search databases/i),
).toBeInTheDocument();
const emptyState = screen.queryByRole('img', { name: /empty/i });
expect(emptyState).not.toBeInTheDocument();
});
test('renders list of options when user clicks on schema', async () => {
render(<LeftPanel setDataset={mockFun} dataset={exampleDataset[0]} />, {
useRedux: true,
});
// Click 'test-postgres' database to access schemas
const databaseSelect = screen.getByRole('combobox', {
name: 'Select database or type to search databases',
});
userEvent.click(databaseSelect);
expect(await screen.findByText('test-postgres')).toBeInTheDocument();
userEvent.click(screen.getByText('test-postgres'));
// Schema select will be automatically populated if there is only one schema
const schemaSelect = screen.getByRole('combobox', {
name: /select schema or type to search schemas/i,
});
await waitFor(() => {
expect(schemaSelect).toBeEnabled();
});
});
test('searches for a table name', async () => {
render(<LeftPanel setDataset={mockFun} dataset={exampleDataset[0]} />, {
useRedux: true,
});
// Click 'test-postgres' database to access schemas
const databaseSelect = screen.getByRole('combobox', {
name: /select database or type to search databases/i,
});
userEvent.click(databaseSelect);
userEvent.click(await screen.findByText('test-postgres'));
const schemaSelect = screen.getByRole('combobox', {
name: /select schema or type to search schemas/i,
});
const tableSelect = screen.getByRole('combobox', {
name: /select table or type to search tables/i,
});
await waitFor(() => expect(schemaSelect).toBeEnabled());
// Click 'public' schema to access tables
userEvent.click(schemaSelect);
userEvent.click(screen.getAllByText('public')[1]);
await waitFor(() => expect(fetchMock.calls(tablesEndpoint).length).toBe(1));
userEvent.click(tableSelect);
await waitFor(() => {
expect(
screen.queryByRole('option', {
name: /Sheet1/i,
}),
).toBeInTheDocument();
expect(
screen.queryByRole('option', {
name: /Sheet2/i,
}),
).toBeInTheDocument();
});
userEvent.type(tableSelect, 'Sheet3');
await waitFor(() => {
expect(
screen.queryByRole('option', { name: /Sheet1/i }),
).not.toBeInTheDocument();
expect(
screen.queryByRole('option', { name: /Sheet2/i }),
).not.toBeInTheDocument();
expect(
screen.queryByRole('option', {
name: /Sheet3/i,
}),
).toBeInTheDocument();
});
});
test('renders a warning icon when a table name has a pre-existing dataset', async () => {
render(
<LeftPanel
setDataset={mockFun}
dataset={exampleDataset[0]}
datasetNames={['Sheet2']}
/>,
{
useRedux: true,
},
);
// Click 'test-postgres' database to access schemas
const databaseSelect = screen.getByRole('combobox', {
name: /select database or type to search databases/i,
});
userEvent.click(databaseSelect);
userEvent.click(await screen.findByText('test-postgres'));
const schemaSelect = screen.getByRole('combobox', {
name: /select schema or type to search schemas/i,
});
const tableSelect = screen.getByRole('combobox', {
name: /select table or type to search tables/i,
});
await waitFor(() => expect(schemaSelect).toBeEnabled());
// Warning icon should not show yet
expect(
screen.queryByRole('img', { name: 'warning' }),
).not.toBeInTheDocument();
// Click 'public' schema to access tables
userEvent.click(schemaSelect);
userEvent.click(screen.getAllByText('public')[1]);
userEvent.click(tableSelect);
await waitFor(() => {
expect(
screen.queryByRole('option', {
name: /Sheet2/i,
}),
).toBeInTheDocument();
});
userEvent.type(tableSelect, 'Sheet2');
// Sheet2 should now show the warning icon
expect(screen.getByRole('img', { name: 'alert-solid' })).toBeInTheDocument();
});
|
7,813 | 0 | petrpan-code/apache/superset/superset-frontend/src/features/datasets/AddDataset | petrpan-code/apache/superset/superset-frontend/src/features/datasets/AddDataset/RightPanel/RightPanel.test.tsx | /**
* 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 { render, screen } from 'spec/helpers/testing-library';
import RightPanel from 'src/features/datasets/AddDataset/RightPanel';
describe('RightPanel', () => {
it('renders a blank state RightPanel', () => {
render(<RightPanel />);
expect(screen.getByText(/right panel/i)).toBeVisible();
});
});
|
7,815 | 0 | petrpan-code/apache/superset/superset-frontend/src/features/datasets | petrpan-code/apache/superset/superset-frontend/src/features/datasets/DatasetLayout/DatasetLayout.test.tsx | /**
* 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 { render, screen, waitFor } from 'spec/helpers/testing-library';
import DatasetLayout from 'src/features/datasets/DatasetLayout';
import Header from 'src/features/datasets/AddDataset/Header';
import LeftPanel from 'src/features/datasets/AddDataset/LeftPanel';
import DatasetPanel from 'src/features/datasets/AddDataset/DatasetPanel';
import RightPanel from 'src/features/datasets/AddDataset/RightPanel';
import Footer from 'src/features/datasets/AddDataset/Footer';
const mockHistoryPush = jest.fn();
jest.mock('react-router-dom', () => ({
...jest.requireActual('react-router-dom'),
useHistory: () => ({
push: mockHistoryPush,
}),
}));
describe('DatasetLayout', () => {
it('renders nothing when no components are passed in', () => {
render(<DatasetLayout />, { useRouter: true });
const layoutWrapper = screen.getByTestId('dataset-layout-wrapper');
expect(layoutWrapper).toHaveTextContent('');
});
const mockSetDataset = jest.fn();
const waitForRender = () =>
waitFor(() => render(<Header setDataset={mockSetDataset} />));
it('renders a Header when passed in', async () => {
await waitForRender();
expect(screen.getByText(/new dataset/i)).toBeVisible();
});
it('renders a LeftPanel when passed in', async () => {
render(
<DatasetLayout leftPanel={<LeftPanel setDataset={() => null} />} />,
{ useRedux: true, useRouter: true },
);
expect(
await screen.findByText(/Select database or type to search databases/i),
).toBeInTheDocument();
expect(LeftPanel).toBeTruthy();
});
it('renders a DatasetPanel when passed in', () => {
render(<DatasetLayout datasetPanel={<DatasetPanel />} />, {
useRouter: true,
});
const blankDatasetImg = screen.getByRole('img', { name: /empty/i });
const blankDatasetTitle = screen.getByText(/select dataset source/i);
expect(blankDatasetImg).toBeVisible();
expect(blankDatasetTitle).toBeVisible();
});
it('renders a RightPanel when passed in', () => {
render(<DatasetLayout rightPanel={RightPanel()} />, { useRouter: true });
expect(screen.getByText(/right panel/i)).toBeVisible();
});
it('renders a Footer when passed in', () => {
render(<DatasetLayout footer={<Footer url="" />} />, {
useRedux: true,
useRouter: true,
});
expect(screen.getByText(/Cancel/i)).toBeVisible();
});
});
|
7,821 | 0 | petrpan-code/apache/superset/superset-frontend/src/features/datasets | petrpan-code/apache/superset/superset-frontend/src/features/datasets/metadataBar/useDatasetMetadataBar.test.tsx | /**
* 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 fetchMock from 'fetch-mock';
import { renderHook } from '@testing-library/react-hooks';
import { createWrapper, render } from 'spec/helpers/testing-library';
import { supersetGetCache } from 'src/utils/cachedSupersetGet';
import { useDatasetMetadataBar } from './useDatasetMetadataBar';
const MOCK_DATASET = {
changed_on: '2023-01-26T12:06:58.733316',
changed_on_humanized: 'a month ago',
changed_by: { first_name: 'Han', last_name: 'Solo' },
created_by: { first_name: 'Luke', last_name: 'Skywalker' },
created_on: '2023-01-26T12:06:54.965034',
created_on_humanized: 'a month ago',
table_name: `This is dataset's name`,
owners: [
{ first_name: 'John', last_name: 'Doe' },
{ first_name: 'Luke', last_name: 'Skywalker' },
],
description: 'This is a dataset description',
};
afterEach(() => {
fetchMock.restore();
supersetGetCache.clear();
});
test('renders dataset metadata bar from request', async () => {
fetchMock.get('glob:*/api/v1/dataset/1', {
result: MOCK_DATASET,
});
const { result, waitForValueToChange } = renderHook(
() => useDatasetMetadataBar({ datasetId: 1 }),
{
wrapper: createWrapper(),
},
);
expect(result.current.status).toEqual('loading');
await waitForValueToChange(() => result.current.status);
expect(result.current.status).toEqual('complete');
expect(fetchMock.called()).toBeTruthy();
const { findByText, findAllByRole } = render(result.current.metadataBar);
expect(await findByText(`This is dataset's name`)).toBeVisible();
expect(await findByText('This is a dataset description')).toBeVisible();
expect(await findByText('Luke Skywalker')).toBeVisible();
expect(await findByText('a month ago')).toBeVisible();
expect(await findAllByRole('img')).toHaveLength(4);
});
test('renders dataset metadata bar without request', async () => {
fetchMock.get('glob:*/api/v1/dataset/1', {
result: {},
});
const { result } = renderHook(
() => useDatasetMetadataBar({ dataset: MOCK_DATASET }),
{
wrapper: createWrapper(),
},
);
expect(result.current.status).toEqual('complete');
expect(fetchMock.called()).toBeFalsy();
const { findByText, findAllByRole } = render(result.current.metadataBar);
expect(await findByText(`This is dataset's name`)).toBeVisible();
expect(await findByText('This is a dataset description')).toBeVisible();
expect(await findByText('Luke Skywalker')).toBeVisible();
expect(await findByText('a month ago')).toBeVisible();
expect(await findAllByRole('img')).toHaveLength(4);
});
test('renders dataset metadata bar without description and owners', async () => {
fetchMock.get('glob:*/api/v1/dataset/1', {
result: {
changed_on: '2023-01-26T12:06:58.733316',
changed_on_humanized: 'a month ago',
created_on: '2023-01-26T12:06:54.965034',
created_on_humanized: 'a month ago',
table_name: `This is dataset's name`,
},
});
const { result, waitForValueToChange } = renderHook(
() => useDatasetMetadataBar({ datasetId: 1 }),
{
wrapper: createWrapper(),
},
);
expect(result.current.status).toEqual('loading');
await waitForValueToChange(() => result.current.status);
expect(result.current.status).toEqual('complete');
expect(fetchMock.called()).toBeTruthy();
const { findByText, queryByText, findAllByRole } = render(
result.current.metadataBar,
);
expect(await findByText(`This is dataset's name`)).toBeVisible();
expect(queryByText('This is a dataset description')).not.toBeInTheDocument();
expect(await findByText('Not available')).toBeVisible();
expect(await findByText('a month ago')).toBeVisible();
expect(await findAllByRole('img')).toHaveLength(3);
});
|
7,823 | 0 | petrpan-code/apache/superset/superset-frontend/src/features | petrpan-code/apache/superset/superset-frontend/src/features/home/ActivityTable.test.tsx | /**
* 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 { styledMount as mount } from 'spec/helpers/theming';
import { act } from 'react-dom/test-utils';
import { ReactWrapper } from 'enzyme';
import { Provider } from 'react-redux';
import fetchMock from 'fetch-mock';
import thunk from 'redux-thunk';
import configureStore from 'redux-mock-store';
import { TableTab } from 'src/views/CRUD/types';
import ActivityTable from './ActivityTable';
const mockStore = configureStore([thunk]);
const store = mockStore({});
const chartsEndpoint = 'glob:*/api/v1/chart/?*';
const dashboardsEndpoint = 'glob:*/api/v1/dashboard/?*';
const mockData = {
[TableTab.Viewed]: [
{
slice_name: 'ChartyChart',
changed_on_utc: '24 Feb 2014 10:13:14',
url: '/fakeUrl/explore',
id: '4',
table: {},
},
],
[TableTab.Created]: [
{
dashboard_title: 'Dashboard_Test',
changed_on_utc: '24 Feb 2014 10:13:14',
url: '/fakeUrl/dashboard',
id: '3',
},
],
};
fetchMock.get(chartsEndpoint, {
result: [
{
slice_name: 'ChartyChart',
changed_on_utc: '24 Feb 2014 10:13:14',
url: '/fakeUrl/explore',
id: '4',
table: {},
},
],
});
fetchMock.get(dashboardsEndpoint, {
result: [
{
dashboard_title: 'Dashboard_Test',
changed_on_utc: '24 Feb 2014 10:13:14',
url: '/fakeUrl/dashboard',
id: '3',
},
],
});
describe('ActivityTable', () => {
const activityProps = {
activeChild: TableTab.Created,
activityData: mockData,
setActiveChild: jest.fn(),
user: { userId: '1' },
isFetchingActivityData: false,
};
let wrapper: ReactWrapper;
beforeAll(async () => {
await act(async () => {
wrapper = mount(
<Provider store={store}>
<ActivityTable {...activityProps} />
</Provider>,
);
});
});
it('the component renders', () => {
expect(wrapper.find(ActivityTable)).toExist();
});
it('renders tabs with three buttons', () => {
expect(wrapper.find('[role="tab"]')).toHaveLength(3);
});
it('renders ActivityCards', async () => {
expect(wrapper.find('ListViewCard')).toExist();
});
it('calls the getEdited batch call when edited tab is clicked', async () => {
act(() => {
const handler = wrapper.find('[role="tab"] a').at(1).prop('onClick');
if (handler) {
handler({} as any);
}
});
const dashboardCall = fetchMock.calls(/dashboard\/\?q/);
const chartCall = fetchMock.calls(/chart\/\?q/);
// waitforcomponenttopaint does not work here in this instance...
setTimeout(() => {
expect(chartCall).toHaveLength(1);
expect(dashboardCall).toHaveLength(1);
});
});
it('show empty state if there is no data', () => {
const activityProps = {
activeChild: TableTab.Created,
activityData: {},
setActiveChild: jest.fn(),
user: { userId: '1' },
isFetchingActivityData: false,
};
const wrapper = mount(
<Provider store={store}>
<ActivityTable {...activityProps} />
</Provider>,
);
expect(wrapper.find('EmptyState')).toExist();
});
});
|
7,825 | 0 | petrpan-code/apache/superset/superset-frontend/src/features | petrpan-code/apache/superset/superset-frontend/src/features/home/ChartTable.test.tsx | /**
* 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 { styledMount as mount } from 'spec/helpers/theming';
import thunk from 'redux-thunk';
import fetchMock from 'fetch-mock';
import configureStore from 'redux-mock-store';
import { act } from 'react-dom/test-utils';
import { ReactWrapper } from 'enzyme';
import waitForComponentToPaint from 'spec/helpers/waitForComponentToPaint';
import ChartTable from './ChartTable';
const mockStore = configureStore([thunk]);
const store = mockStore({});
const chartsEndpoint = 'glob:*/api/v1/chart/?*';
const chartsInfoEndpoint = 'glob:*/api/v1/chart/_info*';
const chartFavoriteStatusEndpoint = 'glob:*/api/v1/chart/favorite_status*';
const mockCharts = [...new Array(3)].map((_, i) => ({
changed_on_utc: new Date().toISOString(),
created_by: 'super user',
id: i,
slice_name: `cool chart ${i}`,
url: 'url',
viz_type: 'bar',
datasource_title: `ds${i}`,
thumbnail_url: '',
}));
fetchMock.get(chartsEndpoint, {
result: mockCharts,
});
fetchMock.get(chartsInfoEndpoint, {
permissions: ['can_add', 'can_edit', 'can_delete'],
});
fetchMock.get(chartFavoriteStatusEndpoint, {
result: [],
});
describe('ChartTable', () => {
const mockedProps = {
user: {
userId: '2',
},
mine: [],
otherTabData: [],
otherTabFilters: [],
otherTabTitle: 'Other',
showThumbnails: false,
};
let wrapper: ReactWrapper;
beforeEach(async () => {
act(() => {
wrapper = mount(<ChartTable store={store} {...mockedProps} />);
});
await waitForComponentToPaint(wrapper);
});
it('renders', () => {
expect(wrapper.find(ChartTable)).toExist();
});
it('fetches chart favorites and renders chart cards', async () => {
act(() => {
const handler = wrapper.find('[role="tab"] a').at(0).prop('onClick');
if (handler) {
handler({} as any);
}
});
await waitForComponentToPaint(wrapper);
expect(fetchMock.calls(chartsEndpoint)).toHaveLength(1);
expect(wrapper.find('ChartCard')).toExist();
});
it('renders other tab by default', async () => {
await act(async () => {
wrapper = mount(
<ChartTable
user={{ userId: '2' }}
mine={[]}
otherTabData={mockCharts}
otherTabFilters={[]}
otherTabTitle="Other"
showThumbnails={false}
store={store}
/>,
);
});
await waitForComponentToPaint(wrapper);
expect(wrapper.find('EmptyState')).not.toExist();
expect(wrapper.find('ChartCard')).toExist();
});
it('display EmptyState if there is no data', async () => {
await act(async () => {
wrapper = mount(
<ChartTable
user={{ userId: '2' }}
mine={[]}
otherTabData={[]}
otherTabFilters={[]}
otherTabTitle="Other"
showThumbnails={false}
store={store}
/>,
);
});
expect(wrapper.find('EmptyState')).toExist();
});
});
|
7,827 | 0 | petrpan-code/apache/superset/superset-frontend/src/features | petrpan-code/apache/superset/superset-frontend/src/features/home/DashboardTable.test.tsx | /**
* 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 { styledMount as mount } from 'spec/helpers/theming';
import thunk from 'redux-thunk';
import configureStore from 'redux-mock-store';
import fetchMock from 'fetch-mock';
import { act } from 'react-dom/test-utils';
import waitForComponentToPaint from 'spec/helpers/waitForComponentToPaint';
import DashboardCard from 'src/features/dashboards/DashboardCard';
import DashboardTable from './DashboardTable';
// store needed for withToasts(DashboardTable)
const mockStore = configureStore([thunk]);
const store = mockStore({});
const dashboardsEndpoint = 'glob:*/api/v1/dashboard/?*';
const dashboardInfoEndpoint = 'glob:*/api/v1/dashboard/_info*';
const dashboardFavEndpoint = 'glob:*/api/v1/dashboard/favorite_status?*';
const mockDashboards = [
{
id: 1,
url: 'url',
dashboard_title: 'title',
changed_on_utc: '24 Feb 2014 10:13:14',
},
];
fetchMock.get(dashboardsEndpoint, { result: mockDashboards });
fetchMock.get(dashboardInfoEndpoint, {
permissions: ['can_list', 'can_edit', 'can_delete'],
});
fetchMock.get(dashboardFavEndpoint, {
result: [],
});
describe('DashboardTable', () => {
const dashboardProps = {
dashboardFilter: 'Favorite',
user: {
userId: '2',
},
mine: mockDashboards,
};
let wrapper = mount(<DashboardTable store={store} {...dashboardProps} />);
beforeAll(async () => {
await waitForComponentToPaint(wrapper);
});
it('renders', () => {
expect(wrapper.find(DashboardTable)).toExist();
});
it('render a submenu with clickable tabs and buttons', async () => {
expect(wrapper.find('SubMenu')).toExist();
expect(wrapper.find('[role="tab"]')).toHaveLength(2);
expect(wrapper.find('Button')).toHaveLength(6);
act(() => {
const handler = wrapper.find('[role="tab"] a').at(0).prop('onClick');
if (handler) {
handler({} as any);
}
});
await waitForComponentToPaint(wrapper);
expect(fetchMock.calls(/dashboard\/\?q/)).toHaveLength(1);
});
it('render DashboardCard', () => {
expect(wrapper.find(DashboardCard)).toExist();
});
it('display EmptyState if there is no data', async () => {
await act(async () => {
wrapper = mount(
<DashboardTable
dashboardFilter="Mine"
user={{ userId: '2' }}
mine={[]}
store={store}
/>,
);
});
expect(wrapper.find('EmptyState')).toExist();
});
});
|
7,829 | 0 | petrpan-code/apache/superset/superset-frontend/src/features | petrpan-code/apache/superset/superset-frontend/src/features/home/EmptyState.test.tsx | /**
* 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 { styledMount as mount } from 'spec/helpers/theming';
import { TableTab } from 'src/views/CRUD/types';
import EmptyState, { EmptyStateProps } from './EmptyState';
import { WelcomeTable } from './types';
describe('EmptyState', () => {
const variants: EmptyStateProps[] = [
{
tab: TableTab.Favorite,
tableName: WelcomeTable.Dashboards,
},
{
tab: TableTab.Mine,
tableName: WelcomeTable.Dashboards,
},
{
tab: TableTab.Favorite,
tableName: WelcomeTable.Charts,
},
{
tab: TableTab.Mine,
tableName: WelcomeTable.Charts,
},
{
tab: TableTab.Favorite,
tableName: WelcomeTable.SavedQueries,
},
{
tab: TableTab.Mine,
tableName: WelcomeTable.SavedQueries,
},
];
const recents: EmptyStateProps[] = [
{
tab: TableTab.Viewed,
tableName: WelcomeTable.Recents,
},
{
tab: TableTab.Edited,
tableName: WelcomeTable.Recents,
},
{
tab: TableTab.Created,
tableName: WelcomeTable.Recents,
},
];
variants.forEach(variant => {
it(`it renders an ${variant.tab} ${variant.tableName} empty state`, () => {
const wrapper = mount(<EmptyState {...variant} />);
expect(wrapper).toExist();
const textContainer = wrapper.find('.ant-empty-description');
expect(textContainer.text()).toEqual(
variant.tab === TableTab.Favorite
? "You don't have any favorites yet!"
: `No ${
variant.tableName === WelcomeTable.SavedQueries
? 'saved queries'
: variant.tableName.toLowerCase()
} yet`,
);
expect(wrapper.find('button')).toHaveLength(1);
});
});
recents.forEach(recent => {
it(`it renders a ${recent.tab} ${recent.tableName} empty state`, () => {
const wrapper = mount(<EmptyState {...recent} />);
expect(wrapper).toExist();
const textContainer = wrapper.find('.ant-empty-description');
expect(wrapper.find('.ant-empty-image').children()).toHaveLength(1);
expect(textContainer.text()).toContain(
`Recently ${recent.tab?.toLowerCase()} charts, dashboards, and saved queries will appear here`,
);
});
});
});
|
7,831 | 0 | petrpan-code/apache/superset/superset-frontend/src/features | petrpan-code/apache/superset/superset-frontend/src/features/home/LanguagePicker.test.tsx | /**
* 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 { render, screen } from 'spec/helpers/testing-library';
import userEvent from '@testing-library/user-event';
import { MainNav as Menu } from 'src/components/Menu';
import LanguagePicker from './LanguagePicker';
const mockedProps = {
locale: 'en',
languages: {
en: {
flag: 'us',
name: 'English',
url: '/lang/en',
},
it: {
flag: 'it',
name: 'Italian',
url: '/lang/it',
},
},
};
test('should render', async () => {
const { container } = render(
<Menu>
<LanguagePicker {...mockedProps} />
</Menu>,
);
expect(await screen.findByRole('button')).toBeInTheDocument();
expect(container).toBeInTheDocument();
});
test('should render the language picker', async () => {
render(
<Menu>
<LanguagePicker {...mockedProps} />
</Menu>,
);
expect(await screen.findByLabelText('Languages')).toBeInTheDocument();
});
test('should render the items', async () => {
render(
<Menu>
<LanguagePicker {...mockedProps} />
</Menu>,
);
userEvent.hover(screen.getByRole('button'));
expect(await screen.findByText('English')).toBeInTheDocument();
expect(await screen.findByText('Italian')).toBeInTheDocument();
});
|
7,833 | 0 | petrpan-code/apache/superset/superset-frontend/src/features | petrpan-code/apache/superset/superset-frontend/src/features/home/Menu.test.tsx | /**
* 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 * as reactRedux from 'react-redux';
import fetchMock from 'fetch-mock';
import { render, screen } from 'spec/helpers/testing-library';
import setupExtensions from 'src/setup/setupExtensions';
import userEvent from '@testing-library/user-event';
import { getExtensionsRegistry } from '@superset-ui/core';
import { Menu } from './Menu';
const dropdownItems = [
{
label: 'Data',
icon: 'fa-database',
childs: [
{
label: 'Connect Database',
name: 'dbconnect',
perm: true,
},
{
label: 'Connect Google Sheet',
name: 'gsheets',
perm: true,
},
{
label: 'Upload a CSV',
name: 'Upload a CSV',
url: '/csvtodatabaseview/form',
perm: true,
},
{
label: 'Upload a Columnar File',
name: 'Upload a Columnar file',
url: '/columnartodatabaseview/form',
perm: true,
},
{
label: 'Upload Excel',
name: 'Upload Excel',
url: '/exceltodatabaseview/form',
perm: true,
},
],
},
{
label: 'SQL query',
url: '/sqllab?new=true',
icon: 'fa-fw fa-search',
perm: 'can_sqllab',
view: 'Superset',
},
{
label: 'Chart',
url: '/chart/add',
icon: 'fa-fw fa-bar-chart',
perm: 'can_write',
view: 'Chart',
},
{
label: 'Dashboard',
url: '/dashboard/new',
icon: 'fa-fw fa-dashboard',
perm: 'can_write',
view: 'Dashboard',
},
];
const user = {
createdOn: '2021-04-27T18:12:38.952304',
email: 'admin',
firstName: 'admin',
isActive: true,
lastName: 'admin',
permissions: {},
roles: {
Admin: [
['can_sqllab', 'Superset'],
['can_write', 'Dashboard'],
['can_write', 'Chart'],
],
},
userId: 1,
username: 'admin',
};
const mockedProps = {
user,
data: {
menu: [
{
name: 'Home',
icon: '',
label: 'Home',
url: '/superset/welcome',
index: 1,
},
{
name: 'Sources',
icon: 'fa-table',
label: 'Sources',
index: 2,
childs: [
{
name: 'Datasets',
icon: 'fa-table',
label: 'Datasets',
url: '/tablemodelview/list/',
index: 1,
},
'-',
{
name: 'Databases',
icon: 'fa-database',
label: 'Databases',
url: '/databaseview/list/',
index: 2,
},
],
},
{
name: 'Charts',
icon: 'fa-bar-chart',
label: 'Charts',
url: '/chart/list/',
index: 3,
},
{
name: 'Dashboards',
icon: 'fa-dashboard',
label: 'Dashboards',
url: '/dashboard/list/',
index: 4,
},
{
name: 'Data',
icon: 'fa-database',
label: 'Data',
childs: [
{
name: 'Databases',
icon: 'fa-database',
label: 'Databases',
url: '/databaseview/list/',
},
{
name: 'Datasets',
icon: 'fa-table',
label: 'Datasets',
url: '/tablemodelview/list/',
},
'-',
],
},
],
brand: {
path: '/superset/profile/admin/',
icon: '/static/assets/images/superset-logo-horiz.png',
alt: 'Superset',
width: '126',
tooltip: '',
text: '',
},
environment_tag: {
text: 'Production',
color: '#000',
},
navbar_right: {
show_watermark: false,
bug_report_url: '/report/',
documentation_url: '/docs/',
languages: {
en: {
flag: 'us',
name: 'English',
url: '/lang/en',
},
it: {
flag: 'it',
name: 'Italian',
url: '/lang/it',
},
},
show_language_picker: true,
user_is_anonymous: true,
user_info_url: '/users/userinfo/',
user_logout_url: '/logout/',
user_login_url: '/login/',
user_profile_url: '/profile/',
locale: 'en',
version_string: '1.0.0',
version_sha: 'randomSHA',
build_number: 'randomBuildNumber',
},
settings: [
{
name: 'Security',
icon: 'fa-cogs',
label: 'Security',
index: 1,
childs: [
{
name: 'List Users',
icon: 'fa-user',
label: 'List Users',
url: '/users/list/',
index: 1,
},
],
},
],
},
};
const notanonProps = {
...mockedProps,
data: {
...mockedProps.data,
navbar_right: {
...mockedProps.data.navbar_right,
user_is_anonymous: false,
},
},
};
const useSelectorMock = jest.spyOn(reactRedux, 'useSelector');
fetchMock.get(
'glob:*api/v1/database/?q=(filters:!((col:allow_file_upload,opr:upload_is_enabled,value:!t)))',
{},
);
beforeEach(() => {
// setup a DOM element as a render target
useSelectorMock.mockClear();
});
test('should render', async () => {
useSelectorMock.mockReturnValue({ roles: user.roles });
const { container } = render(<Menu {...mockedProps} />, {
useRedux: true,
useQueryParams: true,
useRouter: true,
});
expect(await screen.findByText(/sources/i)).toBeInTheDocument();
expect(container).toBeInTheDocument();
});
test('should render the navigation', async () => {
useSelectorMock.mockReturnValue({ roles: user.roles });
render(<Menu {...mockedProps} />, {
useRedux: true,
useQueryParams: true,
useRouter: true,
});
expect(await screen.findByRole('navigation')).toBeInTheDocument();
});
test('should render the brand', async () => {
useSelectorMock.mockReturnValue({ roles: user.roles });
const {
data: {
brand: { alt, icon },
},
} = mockedProps;
render(<Menu {...mockedProps} />, {
useRedux: true,
useQueryParams: true,
useRouter: true,
});
expect(await screen.findByAltText(alt)).toBeInTheDocument();
const image = screen.getByAltText(alt);
expect(image).toHaveAttribute('src', icon);
});
test('should render the environment tag', async () => {
useSelectorMock.mockReturnValue({ roles: user.roles });
const {
data: { environment_tag },
} = mockedProps;
render(<Menu {...mockedProps} />, {
useRedux: true,
useQueryParams: true,
useRouter: true,
});
expect(await screen.findByText(environment_tag.text)).toBeInTheDocument();
});
test('should render all the top navbar menu items', async () => {
useSelectorMock.mockReturnValue({ roles: user.roles });
const {
data: { menu },
} = mockedProps;
render(<Menu {...mockedProps} />, {
useRedux: true,
useQueryParams: true,
useRouter: true,
});
expect(await screen.findByText(menu[0].label)).toBeInTheDocument();
menu.forEach(item => {
expect(screen.getByText(item.label)).toBeInTheDocument();
});
});
test('should render the top navbar child menu items', async () => {
useSelectorMock.mockReturnValue({ roles: user.roles });
const {
data: { menu },
} = mockedProps;
render(<Menu {...mockedProps} />, {
useRedux: true,
useQueryParams: true,
useRouter: true,
});
const sources = screen.getByText('Sources');
userEvent.hover(sources);
const datasets = await screen.findByText('Datasets');
const databases = await screen.findByText('Databases');
const dataset = menu[1].childs![0] as { url: string };
const database = menu[1].childs![2] as { url: string };
expect(datasets).toHaveAttribute('href', dataset.url);
expect(databases).toHaveAttribute('href', database.url);
});
test('should render the dropdown items', async () => {
useSelectorMock.mockReturnValue({ roles: user.roles });
render(<Menu {...notanonProps} />, {
useRedux: true,
useQueryParams: true,
useRouter: true,
});
const dropdown = screen.getByTestId('new-dropdown-icon');
userEvent.hover(dropdown);
// todo (philip): test data submenu
expect(await screen.findByText(dropdownItems[1].label)).toHaveAttribute(
'href',
dropdownItems[1].url,
);
expect(await screen.findByText(dropdownItems[1].label)).toHaveAttribute(
'href',
dropdownItems[1].url,
);
expect(
screen.getByTestId(`menu-item-${dropdownItems[1].label}`),
).toBeInTheDocument();
expect(await screen.findByText(dropdownItems[2].label)).toHaveAttribute(
'href',
dropdownItems[2].url,
);
expect(
screen.getByTestId(`menu-item-${dropdownItems[2].label}`),
).toBeInTheDocument();
});
test('should render the Settings', async () => {
useSelectorMock.mockReturnValue({ roles: user.roles });
render(<Menu {...mockedProps} />, {
useRedux: true,
useQueryParams: true,
useRouter: true,
});
const settings = await screen.findByText('Settings');
expect(settings).toBeInTheDocument();
});
test('should render the Settings menu item', async () => {
useSelectorMock.mockReturnValue({ roles: user.roles });
render(<Menu {...mockedProps} />, {
useRedux: true,
useQueryParams: true,
useRouter: true,
});
userEvent.hover(screen.getByText('Settings'));
const label = await screen.findByText('Security');
expect(label).toBeInTheDocument();
});
test('should render the Settings dropdown child menu items', async () => {
useSelectorMock.mockReturnValue({ roles: user.roles });
const {
data: { settings },
} = mockedProps;
render(<Menu {...mockedProps} />, {
useRedux: true,
useQueryParams: true,
useRouter: true,
});
userEvent.hover(screen.getByText('Settings'));
const listUsers = await screen.findByText('List Users');
expect(listUsers).toHaveAttribute('href', settings[0].childs[0].url);
});
test('should render the plus menu (+) when user is not anonymous', async () => {
useSelectorMock.mockReturnValue({ roles: user.roles });
render(<Menu {...notanonProps} />, {
useRedux: true,
useQueryParams: true,
useRouter: true,
});
expect(await screen.findByTestId('new-dropdown')).toBeInTheDocument();
});
test('should NOT render the plus menu (+) when user is anonymous', async () => {
useSelectorMock.mockReturnValue({ roles: user.roles });
render(<Menu {...mockedProps} />, {
useRedux: true,
useQueryParams: true,
useRouter: true,
});
expect(await screen.findByText(/sources/i)).toBeInTheDocument();
expect(screen.queryByTestId('new-dropdown')).not.toBeInTheDocument();
});
test('should render the user actions when user is not anonymous', async () => {
useSelectorMock.mockReturnValue({ roles: mockedProps.user.roles });
const {
data: {
navbar_right: { user_info_url, user_logout_url },
},
} = mockedProps;
render(<Menu {...notanonProps} />, {
useRedux: true,
useQueryParams: true,
useRouter: true,
});
userEvent.hover(screen.getByText('Settings'));
const user = await screen.findByText('User');
expect(user).toBeInTheDocument();
const info = await screen.findByText('Info');
const logout = await screen.findByText('Logout');
expect(info).toHaveAttribute('href', user_info_url);
expect(logout).toHaveAttribute('href', user_logout_url);
});
test('should NOT render the user actions when user is anonymous', async () => {
useSelectorMock.mockReturnValue({ roles: user.roles });
render(<Menu {...mockedProps} />, {
useRedux: true,
useQueryParams: true,
useRouter: true,
});
expect(await screen.findByText(/sources/i)).toBeInTheDocument();
expect(screen.queryByText('User')).not.toBeInTheDocument();
});
test('should render the Profile link when available', async () => {
useSelectorMock.mockReturnValue({ roles: user.roles });
const {
data: {
navbar_right: { user_profile_url },
},
} = mockedProps;
render(<Menu {...notanonProps} />, {
useRedux: true,
useQueryParams: true,
useRouter: true,
});
userEvent.hover(screen.getByText('Settings'));
const profile = await screen.findByText('Profile');
expect(profile).toHaveAttribute('href', user_profile_url);
});
test('should render the About section and version_string, sha or build_number when available', async () => {
useSelectorMock.mockReturnValue({ roles: user.roles });
const {
data: {
navbar_right: { version_sha, version_string, build_number },
},
} = mockedProps;
render(<Menu {...mockedProps} />, {
useRedux: true,
useQueryParams: true,
useRouter: true,
});
userEvent.hover(screen.getByText('Settings'));
const about = await screen.findByText('About');
const version = await screen.findByText(`Version: ${version_string}`);
const sha = await screen.findByText(`SHA: ${version_sha}`);
const build = await screen.findByText(`Build: ${build_number}`);
expect(about).toBeInTheDocument();
expect(version).toBeInTheDocument();
expect(sha).toBeInTheDocument();
expect(build).toBeInTheDocument();
});
test('should render the Documentation link when available', async () => {
useSelectorMock.mockReturnValue({ roles: user.roles });
const {
data: {
navbar_right: { documentation_url },
},
} = mockedProps;
render(<Menu {...mockedProps} />, {
useRedux: true,
useQueryParams: true,
useRouter: true,
});
userEvent.hover(screen.getByText('Settings'));
const doc = await screen.findByTitle('Documentation');
expect(doc).toHaveAttribute('href', documentation_url);
});
test('should render the Bug Report link when available', async () => {
useSelectorMock.mockReturnValue({ roles: user.roles });
const {
data: {
navbar_right: { bug_report_url },
},
} = mockedProps;
render(<Menu {...mockedProps} />, {
useRedux: true,
useQueryParams: true,
useRouter: true,
});
const bugReport = await screen.findByTitle('Report a bug');
expect(bugReport).toHaveAttribute('href', bug_report_url);
});
test('should render the Login link when user is anonymous', async () => {
useSelectorMock.mockReturnValue({ roles: user.roles });
const {
data: {
navbar_right: { user_login_url },
},
} = mockedProps;
render(<Menu {...mockedProps} />, {
useRedux: true,
useQueryParams: true,
useRouter: true,
});
const login = await screen.findByText('Login');
expect(login).toHaveAttribute('href', user_login_url);
});
test('should render the Language Picker', async () => {
useSelectorMock.mockReturnValue({ roles: user.roles });
render(<Menu {...mockedProps} />, {
useRedux: true,
useQueryParams: true,
useRouter: true,
});
expect(await screen.findByLabelText('Languages')).toBeInTheDocument();
});
test('should hide create button without proper roles', async () => {
useSelectorMock.mockReturnValue({ roles: [] });
render(<Menu {...mockedProps} />, {
useRedux: true,
useQueryParams: true,
useRouter: true,
});
expect(await screen.findByText(/sources/i)).toBeInTheDocument();
expect(screen.queryByTestId('new-dropdown')).not.toBeInTheDocument();
});
test('should render without QueryParamProvider', async () => {
useSelectorMock.mockReturnValue({ roles: [] });
render(<Menu {...mockedProps} />, {
useRedux: true,
useRouter: true,
useQueryParams: true,
});
expect(await screen.findByText(/sources/i)).toBeInTheDocument();
expect(screen.queryByTestId('new-dropdown')).not.toBeInTheDocument();
});
test('should render an extension component if one is supplied', async () => {
const extensionsRegistry = getExtensionsRegistry();
extensionsRegistry.set('navbar.right', () => (
<>navbar.right extension component</>
));
setupExtensions();
render(<Menu {...mockedProps} />, { useRouter: true, useQueryParams: true });
expect(
await screen.findByText('navbar.right extension component'),
).toBeInTheDocument();
});
|
7,835 | 0 | petrpan-code/apache/superset/superset-frontend/src/features | petrpan-code/apache/superset/superset-frontend/src/features/home/RightMenu.test.tsx | /**
* 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 * as reactRedux from 'react-redux';
import fetchMock from 'fetch-mock';
import { render, screen, waitFor } from 'spec/helpers/testing-library';
import userEvent from '@testing-library/user-event';
import RightMenu from './RightMenu';
import { GlobalMenuDataOptions, RightMenuProps } from './types';
jest.mock('react-redux', () => ({
...jest.requireActual('react-redux'),
useSelector: jest.fn(),
}));
jest.mock('src/features/databases/DatabaseModal', () => () => <span />);
const dropdownItems = [
{
label: 'Data',
icon: 'fa-database',
childs: [
{
label: 'Connect database',
name: GlobalMenuDataOptions.DB_CONNECTION,
perm: true,
},
{
label: 'Create dataset',
name: GlobalMenuDataOptions.DATASET_CREATION,
perm: true,
},
{
label: 'Connect Google Sheet',
name: GlobalMenuDataOptions.GOOGLE_SHEETS,
perm: true,
},
{
label: 'Upload CSV to database',
name: 'Upload a CSV',
url: '/csvtodatabaseview/form',
perm: true,
},
{
label: 'Upload columnar file to database',
name: 'Upload a Columnar file',
url: '/columnartodatabaseview/form',
perm: true,
},
{
label: 'Upload Excel file to database',
name: 'Upload Excel',
url: '/exceltodatabaseview/form',
perm: true,
},
],
},
{
label: 'SQL query',
url: '/sqllab?new=true',
icon: 'fa-fw fa-search',
perm: 'can_sqllab',
view: 'Superset',
},
{
label: 'Chart',
url: '/chart/add',
icon: 'fa-fw fa-bar-chart',
perm: 'can_write',
view: 'Chart',
},
{
label: 'Dashboard',
url: '/dashboard/new',
icon: 'fa-fw fa-dashboard',
perm: 'can_write',
view: 'Dashboard',
},
];
const createProps = (): RightMenuProps => ({
align: 'flex-end',
navbarRight: {
show_watermark: false,
bug_report_url: undefined,
documentation_url: undefined,
languages: {
en: {
flag: 'us',
name: 'English',
url: '/lang/en',
},
it: {
flag: 'it',
name: 'Italian',
url: '/lang/it',
},
},
show_language_picker: false,
user_is_anonymous: false,
user_info_url: '/users/userinfo/',
user_logout_url: '/logout/',
user_login_url: '/login/',
user_profile_url: '/profile/',
locale: 'en',
version_string: '1.0.0',
version_sha: 'randomSHA',
build_number: 'randomBuildNumber',
},
settings: [],
isFrontendRoute: () => true,
environmentTag: {
color: 'error.base',
text: 'Development2',
},
});
const mockNonExamplesDB = [...new Array(2)].map((_, i) => ({
changed_by: {
first_name: `user`,
last_name: `${i}`,
},
database_name: `db ${i}`,
backend: 'postgresql',
allow_run_async: true,
allow_dml: false,
allow_file_upload: true,
expose_in_sqllab: false,
changed_on_delta_humanized: `${i} day(s) ago`,
changed_on: new Date().toISOString,
id: i,
engine_information: {
supports_file_upload: true,
},
}));
const useSelectorMock = jest.spyOn(reactRedux, 'useSelector');
beforeEach(async () => {
useSelectorMock.mockReset();
fetchMock.get(
'glob:*api/v1/database/?q=(filters:!((col:allow_file_upload,opr:upload_is_enabled,value:!t)))',
{ result: [], count: 0 },
);
fetchMock.get(
'glob:*api/v1/database/?q=(filters:!((col:database_name,opr:neq,value:examples)))',
{ result: [], count: 0 },
);
});
afterEach(fetchMock.restore);
const resetUseSelectorMock = () => {
useSelectorMock.mockReturnValueOnce({
createdOn: '2021-04-27T18:12:38.952304',
email: 'admin',
firstName: 'admin',
isActive: true,
lastName: 'admin',
permissions: {},
roles: {
Admin: [
['can_this_form_get', 'CsvToDatabaseView'], // So we can upload CSV
['can_write', 'Database'], // So we can write DBs
['can_write', 'Dataset'], // So we can write Datasets
['can_write', 'Chart'], // So we can write Datasets
],
},
userId: 1,
username: 'admin',
});
// By default we get file extensions to be uploaded
useSelectorMock.mockReturnValueOnce('1');
// By default we get file extensions to be uploaded
useSelectorMock.mockReturnValueOnce({
CSV_EXTENSIONS: ['csv'],
EXCEL_EXTENSIONS: ['xls', 'xlsx'],
COLUMNAR_EXTENSIONS: ['parquet', 'zip'],
ALLOWED_EXTENSIONS: ['parquet', 'zip', 'xls', 'xlsx', 'csv'],
});
};
test('renders', async () => {
const mockedProps = createProps();
// Initial Load
resetUseSelectorMock();
const { container } = render(<RightMenu {...mockedProps} />, {
useRedux: true,
useQueryParams: true,
});
// expect(await screen.findByText(/Settings/i)).toBeInTheDocument();
await waitFor(() => expect(container).toBeInTheDocument());
});
test('If user has permission to upload files AND connect DBs we query existing DBs that has allow_file_upload as True and DBs that are not examples', async () => {
const mockedProps = createProps();
// Initial Load
resetUseSelectorMock();
const { container } = render(<RightMenu {...mockedProps} />, {
useRedux: true,
useQueryParams: true,
});
await waitFor(() => expect(container).toBeVisible());
const callsD = fetchMock.calls(/database\/\?q/);
expect(callsD).toHaveLength(2);
expect(callsD[0][0]).toMatchInlineSnapshot(
`"http://localhost/api/v1/database/?q=(filters:!((col:allow_file_upload,opr:upload_is_enabled,value:!t)))"`,
);
expect(callsD[1][0]).toMatchInlineSnapshot(
`"http://localhost/api/v1/database/?q=(filters:!((col:database_name,opr:neq,value:examples)))"`,
);
});
test('If only examples DB exist we must show the Connect Database option', async () => {
const mockedProps = createProps();
fetchMock.get(
'glob:*api/v1/database/?q=(filters:!((col:allow_file_upload,opr:upload_is_enabled,value:!t)))',
{ result: [...mockNonExamplesDB], count: 2 },
{ overwriteRoutes: true },
);
fetchMock.get(
'glob:*api/v1/database/?q=(filters:!((col:database_name,opr:neq,value:examples)))',
{ result: [], count: 0 },
{ overwriteRoutes: true },
);
// Initial Load
resetUseSelectorMock();
// setAllowUploads called
resetUseSelectorMock();
render(<RightMenu {...mockedProps} />, {
useRedux: true,
useQueryParams: true,
useRouter: true,
});
const dropdown = screen.getByTestId('new-dropdown-icon');
userEvent.hover(dropdown);
const dataMenu = await screen.findByText(dropdownItems[0].label);
userEvent.hover(dataMenu);
expect(await screen.findByText('Connect database')).toBeInTheDocument();
expect(screen.queryByText('Create dataset')).not.toBeInTheDocument();
});
test('If more than just examples DB exist we must show the Create dataset option', async () => {
const mockedProps = createProps();
fetchMock.get(
'glob:*api/v1/database/?q=(filters:!((col:allow_file_upload,opr:upload_is_enabled,value:!t)))',
{ result: [...mockNonExamplesDB], count: 2 },
{ overwriteRoutes: true },
);
fetchMock.get(
'glob:*api/v1/database/?q=(filters:!((col:database_name,opr:neq,value:examples)))',
{ result: [...mockNonExamplesDB], count: 2 },
{ overwriteRoutes: true },
);
// Initial Load
resetUseSelectorMock();
// setAllowUploads called
resetUseSelectorMock();
// setNonExamplesDBConnected called
resetUseSelectorMock();
render(<RightMenu {...mockedProps} />, {
useRedux: true,
useQueryParams: true,
useRouter: true,
});
const dropdown = screen.getByTestId('new-dropdown-icon');
userEvent.hover(dropdown);
const dataMenu = await screen.findByText(dropdownItems[0].label);
userEvent.hover(dataMenu);
expect(await screen.findByText('Create dataset')).toBeInTheDocument();
expect(screen.queryByText('Connect database')).not.toBeInTheDocument();
});
test('If there is a DB with allow_file_upload set as True the option should be enabled', async () => {
const mockedProps = createProps();
fetchMock.get(
'glob:*api/v1/database/?q=(filters:!((col:allow_file_upload,opr:upload_is_enabled,value:!t)))',
{ result: [...mockNonExamplesDB], count: 2 },
{ overwriteRoutes: true },
);
fetchMock.get(
'glob:*api/v1/database/?q=(filters:!((col:database_name,opr:neq,value:examples)))',
{ result: [...mockNonExamplesDB], count: 2 },
{ overwriteRoutes: true },
);
// Initial load
resetUseSelectorMock();
// setAllowUploads called
resetUseSelectorMock();
// setNonExamplesDBConnected called
resetUseSelectorMock();
render(<RightMenu {...mockedProps} />, {
useRedux: true,
useQueryParams: true,
useRouter: true,
});
const dropdown = screen.getByTestId('new-dropdown-icon');
userEvent.hover(dropdown);
const dataMenu = await screen.findByText(dropdownItems[0].label);
userEvent.hover(dataMenu);
expect(
(await screen.findByText('Upload CSV to database')).closest('a'),
).toHaveAttribute('href', '/csvtodatabaseview/form');
});
test('If there is NOT a DB with allow_file_upload set as True the option should be disabled', async () => {
const mockedProps = createProps();
fetchMock.get(
'glob:*api/v1/database/?q=(filters:!((col:allow_file_upload,opr:upload_is_enabled,value:!t)))',
{ result: [], count: 0 },
{ overwriteRoutes: true },
);
fetchMock.get(
'glob:*api/v1/database/?q=(filters:!((col:database_name,opr:neq,value:examples)))',
{ result: [...mockNonExamplesDB], count: 2 },
{ overwriteRoutes: true },
);
// Initial load
resetUseSelectorMock();
// setAllowUploads called
resetUseSelectorMock();
// setNonExamplesDBConnected called
resetUseSelectorMock();
render(<RightMenu {...mockedProps} />, {
useRedux: true,
useQueryParams: true,
useRouter: true,
});
const dropdown = screen.getByTestId('new-dropdown-icon');
userEvent.hover(dropdown);
const dataMenu = await screen.findByText(dropdownItems[0].label);
userEvent.hover(dataMenu);
expect(await screen.findByText('Upload CSV to database')).toBeInTheDocument();
expect(
(await screen.findByText('Upload CSV to database')).closest('a'),
).not.toBeInTheDocument();
});
|
7,837 | 0 | petrpan-code/apache/superset/superset-frontend/src/features | petrpan-code/apache/superset/superset-frontend/src/features/home/SavedQueries.test.tsx | /**
* 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 thunk from 'redux-thunk';
import { styledMount as mount } from 'spec/helpers/theming';
import fetchMock from 'fetch-mock';
import configureStore from 'redux-mock-store';
import { act } from 'react-dom/test-utils';
import waitForComponentToPaint from 'spec/helpers/waitForComponentToPaint';
import SubMenu from './SubMenu';
import SavedQueries from './SavedQueries';
// store needed for withToasts(DashboardTable)
const mockStore = configureStore([thunk]);
const store = mockStore({});
const queriesEndpoint = 'glob:*/api/v1/saved_query/?*';
const savedQueriesInfo = 'glob:*/api/v1/saved_query/_info*';
const mockqueries = [...new Array(3)].map((_, i) => ({
created_by: {
id: i,
first_name: `user`,
last_name: `${i}`,
},
created_on: `${i}-2020`,
database: {
database_name: `db ${i}`,
id: i,
},
changed_on_delta_humanized: '1 day ago',
db_id: i,
description: `SQL for ${i}`,
id: i,
label: `query ${i}`,
schema: 'public',
sql: `SELECT ${i} FROM table`,
sql_tables: [
{
catalog: null,
schema: null,
table: `${i}`,
},
],
}));
fetchMock.get(queriesEndpoint, {
result: mockqueries,
});
fetchMock.get(savedQueriesInfo, {
permissions: ['can_list', 'can_edit', 'can_delete'],
});
describe('SavedQueries', () => {
const savedQueryProps = {
user: {
userId: '1',
},
mine: mockqueries,
};
const wrapper = mount(<SavedQueries store={store} {...savedQueryProps} />);
const clickTab = (idx: number) => {
act(() => {
const handler = wrapper.find('[role="tab"] a').at(idx).prop('onClick');
if (handler) {
handler({} as any);
}
});
};
beforeAll(async () => {
await waitForComponentToPaint(wrapper);
});
it('is valid', () => {
expect(wrapper.find(SavedQueries)).toExist();
});
it('fetches queries mine and renders listviewcard cards', async () => {
clickTab(0);
await waitForComponentToPaint(wrapper);
expect(fetchMock.calls(/saved_query\/\?q/)).toHaveLength(1);
expect(wrapper.find('ListViewCard')).toExist();
});
it('renders a submenu with clickable tables and buttons', async () => {
expect(wrapper.find(SubMenu)).toExist();
expect(wrapper.find('[role="tab"]')).toHaveLength(1);
expect(wrapper.find('button')).toHaveLength(2);
clickTab(0);
await waitForComponentToPaint(wrapper);
expect(fetchMock.calls(/saved_query\/\?q/)).toHaveLength(2);
});
});
|
7,839 | 0 | petrpan-code/apache/superset/superset-frontend/src/features | petrpan-code/apache/superset/superset-frontend/src/features/home/SubMenu.test.tsx | /**
* 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 userEvent from '@testing-library/user-event';
import React from 'react';
import { BrowserRouter } from 'react-router-dom';
import { render, screen } from 'spec/helpers/testing-library';
import SubMenu, { ButtonProps } from './SubMenu';
const mockedProps = {
name: 'Title',
tabs: [
{
name: 'Page1',
label: 'Page1',
url: '/page1',
usesRouter: true,
},
{
name: 'Page2',
label: 'Page2',
url: '/page2',
usesRouter: true,
},
{
name: 'Page3',
label: 'Page3',
url: '/page3',
usesRouter: false,
},
],
dropDownLinks: [
{
label: 'test an upload',
childs: [
{
label: 'Upload Test',
name: 'Upload Test',
url: '/test/form',
perm: true,
},
],
},
],
};
const setup = (overrides: Record<string, any> = {}) => {
const props = {
...mockedProps,
...overrides,
};
return render(
<BrowserRouter>
<SubMenu {...props} />
</BrowserRouter>,
);
};
test('should render', async () => {
const { container } = setup();
expect(await screen.findByText(/title/i)).toBeInTheDocument();
expect(container).toBeInTheDocument();
});
test('should render the navigation', async () => {
setup();
expect(await screen.findByRole('navigation')).toBeInTheDocument();
});
test('should render the brand', async () => {
setup();
expect(await screen.findByText('Title')).toBeInTheDocument();
});
test('should render the right number of tabs', async () => {
setup();
expect(await screen.findAllByRole('tab')).toHaveLength(3);
});
test('should render all the tabs links', async () => {
const { tabs } = mockedProps;
setup();
expect(await screen.findAllByRole('tab')).toHaveLength(3);
tabs.forEach(tab => {
const tabItem = screen.getByText(tab.label);
expect(tabItem).toHaveAttribute('href', tab.url);
});
});
test('should render dropdownlinks', async () => {
setup();
userEvent.hover(screen.getByText('test an upload'));
const label = await screen.findByText('test an upload');
expect(label).toBeInTheDocument();
});
test('should render the buttons', async () => {
const mockFunc = jest.fn();
const buttons = [
{
name: 'test_button',
onClick: mockFunc,
buttonStyle: 'primary' as ButtonProps['buttonStyle'],
},
{
name: 'danger_button',
onClick: mockFunc,
buttonStyle: 'danger' as ButtonProps['buttonStyle'],
},
];
setup({ buttons });
const testButton = screen.getByText(buttons[0].name);
expect(await screen.findAllByRole('button')).toHaveLength(3);
userEvent.click(testButton);
expect(mockFunc).toHaveBeenCalled();
});
|
7,843 | 0 | petrpan-code/apache/superset/superset-frontend/src/features | petrpan-code/apache/superset/superset-frontend/src/features/profile/CreatedContent.test.tsx | /**
* 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 { shallow } from 'enzyme';
import thunk from 'redux-thunk';
import configureStore from 'redux-mock-store';
import TableLoader from 'src/components/TableLoader';
import CreatedContent from './CreatedContent';
import { user } from './fixtures';
// store needed for withToasts(TableLoader)
const mockStore = configureStore([thunk]);
const store = mockStore({});
describe('CreatedContent', () => {
const mockedProps = {
user,
};
it('renders 2 TableLoader', () => {
const wrapper = shallow(<CreatedContent {...mockedProps} />, {
context: { store },
});
expect(wrapper.find(TableLoader)).toHaveLength(2);
});
it('renders 2 titles', () => {
const wrapper = shallow(<CreatedContent {...mockedProps} />, {
context: { store },
});
expect(wrapper.find('h3')).toHaveLength(2);
});
});
|
7,845 | 0 | petrpan-code/apache/superset/superset-frontend/src/features | petrpan-code/apache/superset/superset-frontend/src/features/profile/Favorites.test.tsx | /**
* 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 { shallow } from 'enzyme';
import thunk from 'redux-thunk';
import configureStore from 'redux-mock-store';
import TableLoader from 'src/components/TableLoader';
import Favorites from './Favorites';
import { user } from './fixtures';
// store needed for withToasts(TableLoader)
const mockStore = configureStore([thunk]);
const store = mockStore({});
describe('Favorites', () => {
const mockedProps = {
user,
};
it('renders 2 TableLoader', () => {
const wrapper = shallow(<Favorites {...mockedProps} />, {
context: { store },
});
expect(wrapper.find(TableLoader)).toHaveLength(2);
});
it('renders 2 titles', () => {
const wrapper = shallow(<Favorites {...mockedProps} />, {
context: { store },
});
expect(wrapper.find('h3')).toHaveLength(2);
});
});
|
7,847 | 0 | petrpan-code/apache/superset/superset-frontend/src/features | petrpan-code/apache/superset/superset-frontend/src/features/profile/RecentActivity.test.tsx | /**
* 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 { shallow } from 'enzyme';
import TableLoader from 'src/components/TableLoader';
import RecentActivity from './RecentActivity';
import { user } from './fixtures';
describe('RecentActivity', () => {
const mockedProps = {
user,
};
it('is valid', () => {
expect(React.isValidElement(<RecentActivity {...mockedProps} />)).toBe(
true,
);
});
it('renders a TableLoader', () => {
const wrapper = shallow(<RecentActivity {...mockedProps} />);
expect(wrapper.find(TableLoader)).toExist();
});
});
|
7,849 | 0 | petrpan-code/apache/superset/superset-frontend/src/features | petrpan-code/apache/superset/superset-frontend/src/features/profile/Security.test.tsx | /**
* 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 { styledMount as mount } from 'spec/helpers/theming';
import Label from 'src/components/Label';
import { user, userNoPerms } from './fixtures';
import Security from './Security';
describe('Security', () => {
const mockedProps = {
user,
};
it('is valid', () => {
expect(React.isValidElement(<Security {...mockedProps} />)).toBe(true);
});
it('renders 2 role labels', () => {
const wrapper = mount(<Security {...mockedProps} />);
expect(wrapper.find('.roles').find(Label)).toHaveLength(2);
});
it('renders 2 datasource labels', () => {
const wrapper = mount(<Security {...mockedProps} />);
expect(wrapper.find('.datasources').find(Label)).toHaveLength(2);
});
it('renders 3 database labels', () => {
const wrapper = mount(<Security {...mockedProps} />);
expect(wrapper.find('.databases').find(Label)).toHaveLength(3);
});
it('renders no permission label when empty', () => {
const wrapper = mount(<Security user={userNoPerms} />);
expect(wrapper.find('.datasources').find(Label)).not.toExist();
expect(wrapper.find('.databases').find(Label)).not.toExist();
});
});
|
7,851 | 0 | petrpan-code/apache/superset/superset-frontend/src/features | petrpan-code/apache/superset/superset-frontend/src/features/profile/UserInfo.test.tsx | /**
* 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 Gravatar from 'react-gravatar';
import { mount } from 'enzyme';
import UserInfo from './UserInfo';
import { user } from './fixtures';
describe('UserInfo', () => {
const mockedProps = {
user,
};
it('is valid', () => {
expect(React.isValidElement(<UserInfo {...mockedProps} />)).toBe(true);
});
it('renders a Gravatar', () => {
const wrapper = mount(<UserInfo {...mockedProps} />);
expect(wrapper.find(Gravatar)).toExist();
});
it('renders a Panel', () => {
const wrapper = mount(<UserInfo {...mockedProps} />);
expect(wrapper.find('.panel')).toExist();
});
it('renders 5 icons', () => {
const wrapper = mount(<UserInfo {...mockedProps} />);
expect(wrapper.find('i')).toHaveLength(5);
});
it('renders roles information', () => {
const wrapper = mount(<UserInfo {...mockedProps} />);
expect(wrapper.find('.roles').text()).toBe(' Alpha, sql_lab');
});
it('shows the right user-id', () => {
const wrapper = mount(<UserInfo {...mockedProps} />);
expect(wrapper.find('.user-id').text()).toBe('5');
});
});
|
7,855 | 0 | petrpan-code/apache/superset/superset-frontend/src/features | petrpan-code/apache/superset/superset-frontend/src/features/queries/QueryPreviewModal.test.tsx | /**
* 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 thunk from 'redux-thunk';
import configureStore from 'redux-mock-store';
import waitForComponentToPaint from 'spec/helpers/waitForComponentToPaint';
import { styledMount as mount } from 'spec/helpers/theming';
import { QueryObject } from 'src/views/CRUD/types';
import SyntaxHighlighter from 'react-syntax-highlighter/dist/cjs/light';
import { act } from 'react-dom/test-utils';
import { QueryState } from '@superset-ui/core';
import QueryPreviewModal from './QueryPreviewModal';
// store needed for withToasts
const mockStore = configureStore([thunk]);
const store = mockStore({});
const mockQueries: QueryObject[] = [...new Array(3)].map((_, i) => ({
changed_on: new Date().toISOString(),
id: i,
slice_name: `cool chart ${i}`,
database: {
database_name: 'main db',
},
schema: 'public',
sql: `SELECT ${i} FROM table`,
executed_sql: `SELECT ${i} FROM table LIMIT 1000`,
sql_tables: [
{ schema: 'foo', table: 'table' },
{ schema: 'bar', table: 'table_2' },
],
status: QueryState.SUCCESS,
tab_name: 'Main Tab',
user: {
first_name: 'cool',
last_name: 'dude',
id: 2,
username: 'cooldude',
},
start_time: new Date().valueOf(),
end_time: new Date().valueOf(),
rows: 200,
tmp_table_name: '',
tracking_url: '',
}));
describe('QueryPreviewModal', () => {
let currentIndex = 0;
let currentQuery = mockQueries[currentIndex];
const mockedProps = {
onHide: jest.fn(),
openInSqlLab: jest.fn(),
queries: mockQueries,
query: currentQuery,
fetchData: jest.fn(() => {
currentIndex += 1;
currentQuery = mockQueries[currentIndex];
}),
show: true,
};
const wrapper = mount(<QueryPreviewModal store={store} {...mockedProps} />);
beforeAll(async () => {
await waitForComponentToPaint(wrapper);
});
it('renders a SynxHighlighter', () => {
expect(wrapper.find(SyntaxHighlighter)).toExist();
});
it('toggles between user sql and executed sql', () => {
expect(
wrapper.find(SyntaxHighlighter).props().children,
).toMatchInlineSnapshot(`"SELECT 0 FROM table"`);
act(() => {
const props = wrapper
.find('[data-test="toggle-executed-sql"]')
.first()
.props();
if (typeof props.onClick === 'function') {
props.onClick({} as React.MouseEvent);
}
});
wrapper.update();
expect(
wrapper.find(SyntaxHighlighter).props().children,
).toMatchInlineSnapshot(`"SELECT 0 FROM table LIMIT 1000"`);
});
describe('Previous button', () => {
it('disabled when query is the first in list', () => {
expect(
wrapper.find('[data-test="previous-query"]').first().props().disabled,
).toBe(true);
});
it('falls fetchData with previous index', () => {
const mockedProps2 = {
...mockedProps,
query: mockQueries[1],
};
const wrapper2 = mount(
<QueryPreviewModal store={store} {...mockedProps2} />,
);
act(() => {
const props = wrapper2
.find('[data-test="previous-query"]')
.first()
.props();
if (typeof props.onClick === 'function') {
props.onClick({} as React.MouseEvent);
}
});
expect(mockedProps2.fetchData).toHaveBeenCalledWith(0);
});
});
describe('Next button', () => {
it('calls fetchData with next index', () => {
act(() => {
const props = wrapper.find('[data-test="next-query"]').first().props();
if (typeof props.onClick === 'function') {
props.onClick({} as React.MouseEvent);
}
});
expect(mockedProps.fetchData).toHaveBeenCalledWith(1);
});
it('disabled when query is last in list', () => {
const mockedProps2 = {
...mockedProps,
query: mockQueries[2],
};
const wrapper2 = mount(
<QueryPreviewModal store={store} {...mockedProps2} />,
);
expect(
wrapper2.find('[data-test="next-query"]').first().props().disabled,
).toBe(true);
});
});
describe('Open in SQL Lab button', () => {
it('calls openInSqlLab prop', () => {
const props = wrapper
.find('[data-test="open-in-sql-lab"]')
.first()
.props();
if (typeof props.onClick === 'function') {
props.onClick({} as React.MouseEvent);
}
expect(mockedProps.openInSqlLab).toHaveBeenCalled();
});
});
});
|
7,862 | 0 | petrpan-code/apache/superset/superset-frontend/src/features/reports | petrpan-code/apache/superset/superset-frontend/src/features/reports/ReportModal/ReportModal.test.tsx | /**
* 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 * as React from 'react';
import userEvent from '@testing-library/user-event';
import sinon from 'sinon';
import fetchMock from 'fetch-mock';
import { render, screen, waitFor } from 'spec/helpers/testing-library';
import * as uiCore from '@superset-ui/core';
import * as actions from 'src/features/reports/ReportModal/actions';
import { FeatureFlag } from '@superset-ui/core';
import ReportModal from '.';
let isFeatureEnabledMock: jest.MockInstance<boolean, [string]>;
const REPORT_ENDPOINT = 'glob:*/api/v1/report*';
fetchMock.get(REPORT_ENDPOINT, {});
const NOOP = () => {};
const defaultProps = {
addDangerToast: NOOP,
addSuccessToast: NOOP,
addReport: NOOP,
onHide: NOOP,
onReportAdd: NOOP,
show: true,
userId: 1,
userEmail: '[email protected]',
dashboardId: 1,
creationMethod: 'dashboards',
chart: {
sliceFormData: {
viz_type: 'table',
},
},
};
describe('Email Report Modal', () => {
beforeAll(() => {
isFeatureEnabledMock = jest
.spyOn(uiCore, 'isFeatureEnabled')
.mockImplementation(
(featureFlag: FeatureFlag) => featureFlag === FeatureFlag.ALERT_REPORTS,
);
});
beforeEach(() => {
render(<ReportModal {...defaultProps} />, { useRedux: true });
});
afterAll(() => {
// @ts-ignore
isFeatureEnabledMock.restore();
});
it('inputs respond correctly', () => {
// ----- Report name textbox
// Initial value
const reportNameTextbox = screen.getByTestId('report-name-test');
expect(reportNameTextbox).toHaveDisplayValue('Weekly Report');
// Type in the textbox and assert that it worked
userEvent.type(reportNameTextbox, 'Report name text test');
expect(reportNameTextbox).toHaveDisplayValue('Report name text test');
// ----- Report description textbox
// Initial value
const reportDescriptionTextbox = screen.getByTestId(
'report-description-test',
);
expect(reportDescriptionTextbox).toHaveDisplayValue('');
// Type in the textbox and assert that it worked
userEvent.type(reportDescriptionTextbox, 'Report description text test');
expect(reportDescriptionTextbox).toHaveDisplayValue(
'Report description text test',
);
// ----- Crontab
const crontabInputs = screen.getAllByRole('combobox');
expect(crontabInputs).toHaveLength(5);
});
it('does not allow user to create a report without a name', () => {
// Grab name textbox and add button
const reportNameTextbox = screen.getByTestId('report-name-test');
const addButton = screen.getByRole('button', { name: /add/i });
// Add button should be enabled while name textbox has text
expect(reportNameTextbox).toHaveDisplayValue('Weekly Report');
expect(addButton).toBeEnabled();
// Clear the text from the name textbox
userEvent.clear(reportNameTextbox);
// Add button should now be disabled, blocking user from creation
expect(reportNameTextbox).toHaveDisplayValue('');
expect(addButton).toBeDisabled();
});
describe('Email Report Modal', () => {
let isFeatureEnabledMock: any;
let dispatch: any;
beforeEach(async () => {
isFeatureEnabledMock = jest
.spyOn(uiCore, 'isFeatureEnabled')
.mockImplementation(() => true);
dispatch = sinon.spy();
});
afterAll(() => {
isFeatureEnabledMock.mockRestore();
});
it('creates a new email report', async () => {
// ---------- Render/value setup ----------
const reportValues = {
id: 1,
result: {
active: true,
creation_method: 'dashboards',
crontab: '0 12 * * 1',
dashboard: 1,
name: 'Weekly Report',
owners: [1],
recipients: [
{
recipient_config_json: {
target: '[email protected]',
},
type: 'Email',
},
],
type: 'Report',
},
};
// This is needed to structure the reportValues to match the fetchMock return
const stringyReportValues = `{"id":1,"result":{"active":true,"creation_method":"dashboards","crontab":"0 12 * * 1","dashboard":${1},"name":"Weekly Report","owners":[${1}],"recipients":[{"recipient_config_json":{"target":"[email protected]"},"type":"Email"}],"type":"Report"}}`;
// Watch for report POST
fetchMock.post(REPORT_ENDPOINT, reportValues);
// Click "Add" button to create a new email report
const addButton = screen.getByRole('button', { name: /add/i });
await waitFor(() => userEvent.click(addButton));
// Mock addReport from Redux
const makeRequest = () => {
const request = actions.addReport(reportValues);
return request(dispatch);
};
await makeRequest();
// 🐞 ----- There are 2 POST calls at this point ----- 🐞
// addReport's mocked POST return should match the mocked values
expect(fetchMock.lastOptions()?.body).toEqual(stringyReportValues);
expect(dispatch.callCount).toBe(2);
const reportCalls = fetchMock.calls(REPORT_ENDPOINT);
expect(reportCalls).toHaveLength(2);
});
});
});
|
7,867 | 0 | petrpan-code/apache/superset/superset-frontend/src/features/reports/ReportModal | petrpan-code/apache/superset/superset-frontend/src/features/reports/ReportModal/HeaderReportDropdown/index.test.tsx | /**
* 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 * as React from 'react';
import userEvent from '@testing-library/user-event';
import { render, screen, act } from 'spec/helpers/testing-library';
import * as featureFlags from '@superset-ui/core';
import HeaderReportDropdown, { HeaderReportProps } from '.';
let isFeatureEnabledMock: jest.MockInstance<boolean, [string]>;
const createProps = () => ({
dashboardId: 1,
useTextMenu: false,
isDropdownVisible: false,
setIsDropdownVisible: jest.fn,
setShowReportSubMenu: jest.fn,
});
const stateWithOnlyUser = {
user: {
email: '[email protected]',
firstName: 'admin',
isActive: true,
lastName: 'admin',
permissions: {},
createdOn: '2022-01-12T10:17:37.801361',
roles: { Admin: [['menu_access', 'Manage']] },
userId: 1,
username: 'admin',
},
reports: {},
};
const stateWithNonAdminUser = {
user: {
email: '[email protected]',
firstName: 'nonadmin',
isActive: true,
lastName: 'nonadmin',
permissions: {},
createdOn: '2022-01-12T10:17:37.801361',
roles: {
Gamme: [['no_menu_access', 'Manage']],
OtherRole: [['menu_access', 'Manage']],
},
userId: 1,
username: 'nonadmin',
},
reports: {},
};
const stateWithNonMenuAccessOnManage = {
user: {
email: '[email protected]',
firstName: 'nonaccess',
isActive: true,
lastName: 'nonaccess',
permissions: {},
createdOn: '2022-01-12T10:17:37.801361',
roles: { Gamma: [['no_menu_access', 'Manage']] },
userId: 1,
username: 'nonaccess',
},
reports: {},
};
const stateWithUserAndReport = {
user: {
email: '[email protected]',
firstName: 'admin',
isActive: true,
lastName: 'admin',
permissions: {},
createdOn: '2022-01-12T10:17:37.801361',
roles: { Admin: [['menu_access', 'Manage']] },
userId: 1,
username: 'admin',
},
reports: {
dashboards: {
1: {
id: 1,
result: {
active: true,
creation_method: 'dashboards',
crontab: '0 12 * * 1',
dashboard: 1,
name: 'Weekly Report',
owners: [1],
recipients: [
{
recipient_config_json: {
target: '[email protected]',
},
type: 'Email',
},
],
type: 'Report',
},
},
},
},
};
function setup(props: HeaderReportProps, initialState = {}) {
render(
<div>
<HeaderReportDropdown {...props} />
</div>,
{ useRedux: true, initialState },
);
}
describe('Header Report Dropdown', () => {
beforeAll(() => {
isFeatureEnabledMock = jest
.spyOn(featureFlags, 'isFeatureEnabled')
.mockImplementation(
(featureFlag: featureFlags.FeatureFlag) =>
featureFlag === featureFlags.FeatureFlag.ALERT_REPORTS,
);
});
afterAll(() => {
// @ts-ignore
isFeatureEnabledMock.restore();
});
it('renders correctly', () => {
const mockedProps = createProps();
act(() => {
setup(mockedProps, stateWithUserAndReport);
});
expect(screen.getByRole('button')).toBeInTheDocument();
});
it('renders the dropdown correctly', () => {
const mockedProps = createProps();
act(() => {
setup(mockedProps, stateWithUserAndReport);
});
const emailReportModalButton = screen.getByRole('button');
userEvent.click(emailReportModalButton);
expect(screen.getByText('Email reports active')).toBeInTheDocument();
expect(screen.getByText('Edit email report')).toBeInTheDocument();
expect(screen.getByText('Delete email report')).toBeInTheDocument();
});
it('opens an edit modal', async () => {
const mockedProps = createProps();
act(() => {
setup(mockedProps, stateWithUserAndReport);
});
const emailReportModalButton = screen.getByRole('button');
userEvent.click(emailReportModalButton);
const editModal = screen.getByText('Edit email report');
userEvent.click(editModal);
const textBoxes = await screen.findAllByText('Edit email report');
expect(textBoxes).toHaveLength(2);
});
it('opens a delete modal', () => {
const mockedProps = createProps();
act(() => {
setup(mockedProps, stateWithUserAndReport);
});
const emailReportModalButton = screen.getByRole('button');
userEvent.click(emailReportModalButton);
const deleteModal = screen.getByText('Delete email report');
userEvent.click(deleteModal);
expect(screen.getByText('Delete Report?')).toBeInTheDocument();
});
it('renders a new report modal if there is no report', () => {
const mockedProps = createProps();
act(() => {
setup(mockedProps, stateWithOnlyUser);
});
const emailReportModalButton = screen.getByRole('button');
userEvent.click(emailReportModalButton);
expect(screen.getByText('Schedule a new email report')).toBeInTheDocument();
});
it('renders Manage Email Reports Menu if textMenu is set to true and there is a report', () => {
let mockedProps = createProps();
mockedProps = {
...mockedProps,
useTextMenu: true,
isDropdownVisible: true,
};
act(() => {
setup(mockedProps, stateWithUserAndReport);
});
expect(screen.getByText('Email reports active')).toBeInTheDocument();
expect(screen.getByText('Edit email report')).toBeInTheDocument();
expect(screen.getByText('Delete email report')).toBeInTheDocument();
});
it('renders Schedule Email Reports if textMenu is set to true and there is a report', () => {
let mockedProps = createProps();
mockedProps = {
...mockedProps,
useTextMenu: true,
isDropdownVisible: true,
};
act(() => {
setup(mockedProps, stateWithOnlyUser);
});
expect(screen.getByText('Set up an email report')).toBeInTheDocument();
});
it('renders Schedule Email Reports as long as user has permission through any role', () => {
let mockedProps = createProps();
mockedProps = {
...mockedProps,
useTextMenu: true,
isDropdownVisible: true,
};
act(() => {
setup(mockedProps, stateWithNonAdminUser);
});
expect(screen.getByText('Set up an email report')).toBeInTheDocument();
});
it('do not render Schedule Email Reports if user no permission', () => {
let mockedProps = createProps();
mockedProps = {
...mockedProps,
useTextMenu: true,
isDropdownVisible: true,
};
act(() => {
setup(mockedProps, stateWithNonMenuAccessOnManage);
});
expect(
screen.queryByText('Set up an email report'),
).not.toBeInTheDocument();
});
});
|
7,869 | 0 | petrpan-code/apache/superset/superset-frontend/src/features | petrpan-code/apache/superset/superset-frontend/src/features/rls/RowLevelSecurityModal.test.tsx | /**
* 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 fetchMock from 'fetch-mock';
import { render, screen, waitFor, within } from 'spec/helpers/testing-library';
import { act } from 'react-dom/test-utils';
import userEvent from '@testing-library/user-event';
import RowLevelSecurityModal, {
RowLevelSecurityModalProps,
} from './RowLevelSecurityModal';
import { FilterType } from './types';
const getRuleEndpoint = 'glob:*/api/v1/rowlevelsecurity/1';
const getRelatedRolesEndpoint =
'glob:*/api/v1/rowlevelsecurity/related/roles?q*';
const getRelatedTablesEndpoint =
'glob:*/api/v1/rowlevelsecurity/related/tables?q*';
const postRuleEndpoint = 'glob:*/api/v1/rowlevelsecurity/*';
const putRuleEndpoint = 'glob:*/api/v1/rowlevelsecurity/1';
const mockGetRuleResult = {
description_columns: {},
id: 1,
label_columns: {
clause: 'Clause',
description: 'Description',
filter_type: 'Filter Type',
group_key: 'Group Key',
name: 'Name',
'roles.id': 'Roles Id',
'roles.name': 'Roles Name',
'tables.id': 'Tables Id',
'tables.table_name': 'Tables Table Name',
},
result: {
clause: 'gender="girl"',
description: 'test rls rule with RTL',
filter_type: 'Base',
group_key: 'g1',
id: 1,
name: 'rls 1',
roles: [
{
id: 1,
name: 'Admin',
},
],
tables: [
{
id: 2,
table_name: 'birth_names',
},
],
},
show_columns: [
'name',
'description',
'filter_type',
'tables.id',
'tables.table_name',
'roles.id',
'roles.name',
'group_key',
'clause',
],
show_title: 'Show Row Level Security Filter',
};
const mockGetRolesResult = {
count: 3,
result: [
{
extra: {},
text: 'Admin',
value: 1,
},
{
extra: {},
text: 'Public',
value: 2,
},
{
extra: {},
text: 'Alpha',
value: 3,
},
],
};
const mockGetTablesResult = {
count: 3,
result: [
{
extra: {},
text: 'wb_health_population',
value: 1,
},
{
extra: {},
text: 'birth_names',
value: 2,
},
{
extra: {},
text: 'long_lat',
value: 3,
},
],
};
fetchMock.get(getRuleEndpoint, mockGetRuleResult);
fetchMock.get(getRelatedRolesEndpoint, mockGetRolesResult);
fetchMock.get(getRelatedTablesEndpoint, mockGetTablesResult);
fetchMock.post(postRuleEndpoint, {});
fetchMock.put(putRuleEndpoint, {});
global.URL.createObjectURL = jest.fn();
const NOOP = () => {};
const addNewRuleDefaultProps: RowLevelSecurityModalProps = {
addDangerToast: NOOP,
addSuccessToast: NOOP,
show: true,
rule: null,
onHide: NOOP,
};
describe('Rule modal', () => {
async function renderAndWait(props: RowLevelSecurityModalProps) {
const mounted = act(async () => {
render(<RowLevelSecurityModal {...props} />, { useRedux: true });
});
return mounted;
}
it('Sets correct title for adding new rule', async () => {
await renderAndWait(addNewRuleDefaultProps);
const title = screen.getByText('Add Rule');
expect(title).toBeInTheDocument();
expect(fetchMock.calls(getRuleEndpoint)).toHaveLength(0);
expect(fetchMock.calls(getRelatedTablesEndpoint)).toHaveLength(0);
expect(fetchMock.calls(getRelatedRolesEndpoint)).toHaveLength(0);
});
it('Sets correct title for editing existing rule', async () => {
await renderAndWait({
...addNewRuleDefaultProps,
rule: {
id: 1,
name: 'test rule',
filter_type: FilterType.BASE,
tables: [{ key: 1, id: 1, value: 'birth_names' }],
roles: [],
},
});
const title = screen.getByText('Edit Rule');
expect(title).toBeInTheDocument();
expect(fetchMock.calls(getRuleEndpoint)).toHaveLength(1);
expect(fetchMock.calls(getRelatedTablesEndpoint)).toHaveLength(0);
expect(fetchMock.calls(getRelatedRolesEndpoint)).toHaveLength(0);
});
it('Fills correct values when editing rule', async () => {
await renderAndWait({
...addNewRuleDefaultProps,
rule: {
id: 1,
name: 'rls 1',
filter_type: FilterType.BASE,
},
});
const name = await screen.findByTestId('rule-name-test');
expect(name).toHaveDisplayValue('rls 1');
userEvent.type(name, 'rls 2');
expect(name).toHaveDisplayValue('rls 2');
const filterType = await screen.findByText('Base');
expect(filterType).toBeInTheDocument();
const roles = await screen.findByText('Admin');
expect(roles).toBeInTheDocument();
const tables = await screen.findByText('birth_names');
expect(tables).toBeInTheDocument();
const groupKey = await screen.findByTestId('group-key-test');
expect(groupKey).toHaveValue('g1');
userEvent.clear(groupKey);
userEvent.type(groupKey, 'g2');
expect(groupKey).toHaveValue('g2');
const clause = await screen.findByTestId('clause-test');
expect(clause).toHaveValue('gender="girl"');
userEvent.clear(clause);
userEvent.type(clause, 'gender="boy"');
expect(clause).toHaveValue('gender="boy"');
const description = await screen.findByTestId('description-test');
expect(description).toHaveValue('test rls rule with RTL');
userEvent.clear(description);
userEvent.type(description, 'test description');
expect(description).toHaveValue('test description');
});
it('Does not allow to create rule without name, tables and clause', async () => {
await renderAndWait(addNewRuleDefaultProps);
const addButton = screen.getByRole('button', { name: /add/i });
expect(addButton).toBeDisabled();
const nameTextBox = screen.getByTestId('rule-name-test');
userEvent.type(nameTextBox, 'name');
expect(addButton).toBeDisabled();
const getSelect = () => screen.getByRole('combobox', { name: 'Tables' });
const getElementByClassName = (className: string) =>
document.querySelector(className)! as HTMLElement;
const findSelectOption = (text: string) =>
waitFor(() =>
within(getElementByClassName('.rc-virtual-list')).getByText(text),
);
const open = () => waitFor(() => userEvent.click(getSelect()));
await open();
userEvent.click(await findSelectOption('birth_names'));
expect(addButton).toBeDisabled();
const clause = await screen.findByTestId('clause-test');
userEvent.type(clause, 'gender="girl"');
expect(addButton).toBeEnabled();
});
it('Creates a new rule', async () => {
await renderAndWait(addNewRuleDefaultProps);
const addButton = screen.getByRole('button', { name: /add/i });
const nameTextBox = screen.getByTestId('rule-name-test');
userEvent.type(nameTextBox, 'name');
const getSelect = () => screen.getByRole('combobox', { name: 'Tables' });
const getElementByClassName = (className: string) =>
document.querySelector(className)! as HTMLElement;
const findSelectOption = (text: string) =>
waitFor(() =>
within(getElementByClassName('.rc-virtual-list')).getByText(text),
);
const open = () => waitFor(() => userEvent.click(getSelect()));
await open();
userEvent.click(await findSelectOption('birth_names'));
const clause = await screen.findByTestId('clause-test');
userEvent.type(clause, 'gender="girl"');
await waitFor(() => userEvent.click(addButton));
expect(fetchMock.calls(postRuleEndpoint)).toHaveLength(1);
});
it('Updates existing rule', async () => {
await renderAndWait({
...addNewRuleDefaultProps,
rule: {
id: 1,
name: 'rls 1',
filter_type: FilterType.BASE,
},
});
const addButton = screen.getByRole('button', { name: /save/i });
await waitFor(() => userEvent.click(addButton));
expect(fetchMock.calls(putRuleEndpoint)).toHaveLength(4);
});
});
|
7,875 | 0 | petrpan-code/apache/superset/superset-frontend/src/features | petrpan-code/apache/superset/superset-frontend/src/features/tags/TagModal.test.tsx | /**
* 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 { render, screen } from 'spec/helpers/testing-library';
import TagModal from 'src/features/tags/TagModal';
import fetchMock from 'fetch-mock';
import { Tag } from 'src/views/CRUD/types';
const mockedProps = {
onHide: () => {},
refreshData: () => {},
addSuccessToast: () => {},
addDangerToast: () => {},
show: true,
};
const fetchEditFetchObjects = `glob:*/api/v1/tag/get_objects/?tags=*`;
test('should render', () => {
const { container } = render(<TagModal {...mockedProps} />);
expect(container).toBeInTheDocument();
});
test('renders correctly in create mode', () => {
const { getByPlaceholderText, getByText } = render(
<TagModal {...mockedProps} />,
);
expect(getByPlaceholderText('Name of your tag')).toBeInTheDocument();
expect(getByText('Create Tag')).toBeInTheDocument();
});
test('renders correctly in edit mode', () => {
fetchMock.get(fetchEditFetchObjects, [[]]);
const editTag: Tag = {
id: 1,
name: 'Test Tag',
description: 'A test tag',
type: 'dashboard',
changed_on_delta_humanized: '',
created_on_delta_humanized: '',
created_by: {
first_name: 'joe',
last_name: 'smith',
},
changed_by: {
first_name: 'tom',
last_name: 'brown',
},
};
render(<TagModal {...mockedProps} editTag={editTag} />);
expect(screen.getByPlaceholderText(/name of your tag/i)).toHaveValue(
editTag.name,
);
});
|
7,878 | 0 | petrpan-code/apache/superset/superset-frontend/src | petrpan-code/apache/superset/superset-frontend/src/filters/utils.test.ts | /**
* 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 {
GenericDataType,
getNumberFormatter,
getTimeFormatter,
NumberFormats,
TimeFormats,
} from '@superset-ui/core';
import {
getDataRecordFormatter,
getRangeExtraFormData,
getSelectExtraFormData,
} from 'src/filters/utils';
import { FALSE_STRING, NULL_STRING, TRUE_STRING } from 'src/utils/common';
describe('Filter utils', () => {
describe('getRangeExtraFormData', () => {
it('getRangeExtraFormData - col: "testCol", lower: 1, upper: 2', () => {
expect(getRangeExtraFormData('testCol', 1, 2)).toEqual({
filters: [
{
col: 'testCol',
op: '>=',
val: 1,
},
{
col: 'testCol',
op: '<=',
val: 2,
},
],
});
});
it('getRangeExtraFormData - col: "testCol", lower: 0, upper: 0', () => {
expect(getRangeExtraFormData('testCol', 0, 0)).toEqual({
filters: [
{
col: 'testCol',
op: '==',
val: 0,
},
],
});
});
it('getRangeExtraFormData - col: "testCol", lower: null, upper: 2', () => {
expect(getRangeExtraFormData('testCol', null, 2)).toEqual({
filters: [
{
col: 'testCol',
op: '<=',
val: 2,
},
],
});
});
it('getRangeExtraFormData - col: "testCol", lower: 1, upper: undefined', () => {
expect(getRangeExtraFormData('testCol', 1, undefined)).toEqual({
filters: [
{
col: 'testCol',
op: '>=',
val: 1,
},
],
});
});
});
describe('getSelectExtraFormData', () => {
it('getSelectExtraFormData - col: "testCol", value: ["value"], emptyFilter: false, inverseSelection: false', () => {
expect(
getSelectExtraFormData('testCol', ['value'], false, false),
).toEqual({
filters: [
{
col: 'testCol',
op: 'IN',
val: ['value'],
},
],
});
});
it('getSelectExtraFormData - col: "testCol", value: ["value"], emptyFilter: true, inverseSelection: false', () => {
expect(getSelectExtraFormData('testCol', ['value'], true, false)).toEqual(
{
adhoc_filters: [
{
clause: 'WHERE',
expressionType: 'SQL',
sqlExpression: '1 = 0',
},
],
},
);
});
it('getSelectExtraFormData - col: "testCol", value: ["value"], emptyFilter: false, inverseSelection: true', () => {
expect(getSelectExtraFormData('testCol', ['value'], false, true)).toEqual(
{
filters: [
{
col: 'testCol',
op: 'NOT IN',
val: ['value'],
},
],
},
);
});
it('getSelectExtraFormData - col: "testCol", value: [], emptyFilter: false, inverseSelection: false', () => {
expect(getSelectExtraFormData('testCol', [], false, false)).toEqual({});
});
it('getSelectExtraFormData - col: "testCol", value: undefined, emptyFilter: false, inverseSelection: false', () => {
expect(
getSelectExtraFormData('testCol', undefined, false, false),
).toEqual({});
});
it('getSelectExtraFormData - col: "testCol", value: null, emptyFilter: false, inverseSelection: false', () => {
expect(getSelectExtraFormData('testCol', null, false, false)).toEqual({});
});
});
describe('getDataRecordFormatter', () => {
it('default formatter returns expected values', () => {
const formatter = getDataRecordFormatter();
expect(formatter(null, GenericDataType.STRING)).toEqual(NULL_STRING);
expect(formatter(null, GenericDataType.NUMERIC)).toEqual(NULL_STRING);
expect(formatter(null, GenericDataType.TEMPORAL)).toEqual(NULL_STRING);
expect(formatter(null, GenericDataType.BOOLEAN)).toEqual(NULL_STRING);
expect(formatter('foo', GenericDataType.STRING)).toEqual('foo');
expect(formatter('foo', GenericDataType.NUMERIC)).toEqual('foo');
expect(formatter('foo', GenericDataType.TEMPORAL)).toEqual('foo');
expect(formatter('foo', GenericDataType.BOOLEAN)).toEqual(FALSE_STRING);
expect(formatter(true, GenericDataType.BOOLEAN)).toEqual(TRUE_STRING);
expect(formatter(false, GenericDataType.BOOLEAN)).toEqual(FALSE_STRING);
expect(formatter('true', GenericDataType.BOOLEAN)).toEqual(TRUE_STRING);
expect(formatter('false', GenericDataType.BOOLEAN)).toEqual(FALSE_STRING);
expect(formatter('TRUE', GenericDataType.BOOLEAN)).toEqual(TRUE_STRING);
expect(formatter('FALSE', GenericDataType.BOOLEAN)).toEqual(FALSE_STRING);
expect(formatter(0, GenericDataType.BOOLEAN)).toEqual(FALSE_STRING);
expect(formatter(1, GenericDataType.BOOLEAN)).toEqual(TRUE_STRING);
expect(formatter(2, GenericDataType.BOOLEAN)).toEqual(TRUE_STRING);
expect(formatter(0, GenericDataType.STRING)).toEqual('0');
expect(formatter(0, GenericDataType.NUMERIC)).toEqual('0');
expect(formatter(0, GenericDataType.TEMPORAL)).toEqual('0');
expect(formatter(1234567.89, GenericDataType.STRING)).toEqual(
'1234567.89',
);
expect(formatter(1234567.89, GenericDataType.NUMERIC)).toEqual(
'1234567.89',
);
expect(formatter(1234567.89, GenericDataType.TEMPORAL)).toEqual(
'1234567.89',
);
expect(formatter(1234567.89, GenericDataType.BOOLEAN)).toEqual(
TRUE_STRING,
);
});
it('formatter with defined formatters returns expected values', () => {
const formatter = getDataRecordFormatter({
timeFormatter: getTimeFormatter(TimeFormats.DATABASE_DATETIME),
numberFormatter: getNumberFormatter(NumberFormats.SMART_NUMBER),
});
expect(formatter(null, GenericDataType.STRING)).toEqual(NULL_STRING);
expect(formatter(null, GenericDataType.NUMERIC)).toEqual(NULL_STRING);
expect(formatter(null, GenericDataType.TEMPORAL)).toEqual(NULL_STRING);
expect(formatter(null, GenericDataType.BOOLEAN)).toEqual(NULL_STRING);
expect(formatter('foo', GenericDataType.STRING)).toEqual('foo');
expect(formatter('foo', GenericDataType.NUMERIC)).toEqual('foo');
expect(formatter('foo', GenericDataType.TEMPORAL)).toEqual('foo');
expect(formatter('foo', GenericDataType.BOOLEAN)).toEqual(FALSE_STRING);
expect(formatter(0, GenericDataType.STRING)).toEqual('0');
expect(formatter(0, GenericDataType.NUMERIC)).toEqual('0');
expect(formatter(0, GenericDataType.TEMPORAL)).toEqual(
'1970-01-01 00:00:00',
);
expect(formatter(0, GenericDataType.BOOLEAN)).toEqual(FALSE_STRING);
expect(formatter(1234567.89, GenericDataType.STRING)).toEqual(
'1234567.89',
);
expect(formatter(1234567.89, GenericDataType.NUMERIC)).toEqual('1.23M');
expect(formatter(1234567.89, GenericDataType.TEMPORAL)).toEqual(
'1970-01-01 00:20:34',
);
expect(formatter(1234567.89, GenericDataType.BOOLEAN)).toEqual(
TRUE_STRING,
);
expect(formatter('1970-01-01 00:00:00', GenericDataType.STRING)).toEqual(
'1970-01-01 00:00:00',
);
expect(formatter('1970-01-01 00:00:00', GenericDataType.NUMERIC)).toEqual(
'1970-01-01 00:00:00',
);
expect(formatter('1970-01-01 00:00:00', GenericDataType.BOOLEAN)).toEqual(
FALSE_STRING,
);
expect(
formatter('1970-01-01 00:00:00', GenericDataType.TEMPORAL),
).toEqual('1970-01-01 00:00:00');
});
});
});
|
7,890 | 0 | petrpan-code/apache/superset/superset-frontend/src/filters/components | petrpan-code/apache/superset/superset-frontend/src/filters/components/Range/RangeFilterPlugin.test.tsx | /**
* 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 { AppSection, GenericDataType } from '@superset-ui/core';
import React from 'react';
import { render, screen } from 'spec/helpers/testing-library';
import RangeFilterPlugin from './RangeFilterPlugin';
import { SingleValueType } from './SingleValueType';
import transformProps from './transformProps';
const rangeProps = {
formData: {
datasource: '3__table',
groupby: ['SP_POP_TOTL'],
adhocFilters: [],
extraFilters: [],
extraFormData: {},
granularitySqla: 'ds',
metrics: [
{
aggregate: 'MIN',
column: {
column_name: 'SP_POP_TOTL',
id: 1,
type_generic: GenericDataType.NUMERIC,
},
expressionType: 'SIMPLE',
hasCustomLabel: true,
label: 'min',
},
{
aggregate: 'MAX',
column: {
column_name: 'SP_POP_TOTL',
id: 2,
type_generic: GenericDataType.NUMERIC,
},
expressionType: 'SIMPLE',
hasCustomLabel: true,
label: 'max',
},
],
rowLimit: 1000,
showSearch: true,
defaultValue: [10, 70],
timeRangeEndpoints: ['inclusive', 'exclusive'],
urlParams: {},
vizType: 'filter_range',
inputRef: { current: null },
},
height: 20,
hooks: {},
filterState: { value: [10, 70] },
queriesData: [
{
rowcount: 1,
colnames: ['min', 'max'],
coltypes: [GenericDataType.NUMERIC, GenericDataType.NUMERIC],
data: [{ min: 10, max: 100 }],
applied_filters: [],
rejected_filters: [],
},
],
width: 220,
behaviors: ['NATIVE_FILTER'],
isRefreshing: false,
appSection: AppSection.DASHBOARD,
};
describe('RangeFilterPlugin', () => {
const setDataMask = jest.fn();
const getWrapper = (props = {}) =>
render(
// @ts-ignore
<RangeFilterPlugin
// @ts-ignore
{...transformProps({
...rangeProps,
formData: { ...rangeProps.formData, ...props },
})}
setDataMask={setDataMask}
/>,
);
beforeEach(() => {
jest.clearAllMocks();
});
it('should call setDataMask with correct filter', () => {
getWrapper();
expect(setDataMask).toHaveBeenCalledWith({
extraFormData: {
filters: [
{
col: 'SP_POP_TOTL',
op: '<=',
val: 70,
},
],
},
filterState: {
label: 'x ≤ 70',
value: [10, 70],
},
});
});
it('should call setDataMask with correct greater than filter', () => {
getWrapper({
enableSingleValue: SingleValueType.Minimum,
defaultValue: [20, 60],
});
expect(setDataMask).toHaveBeenCalledWith({
extraFormData: {
filters: [
{
col: 'SP_POP_TOTL',
op: '>=',
val: 20,
},
],
},
filterState: {
label: 'x ≥ 20',
value: [20, 100],
},
});
expect(screen.getByRole('slider')).toHaveAttribute('aria-valuenow', '20');
});
it('should call setDataMask with correct less than filter', () => {
getWrapper({
enableSingleValue: SingleValueType.Maximum,
defaultValue: [20, 60],
});
expect(setDataMask).toHaveBeenCalledWith({
extraFormData: {
filters: [
{
col: 'SP_POP_TOTL',
op: '<=',
val: 60,
},
],
},
filterState: {
label: 'x ≤ 60',
value: [10, 60],
},
});
expect(screen.getByRole('slider')).toHaveAttribute('aria-valuenow', '60');
});
it('should call setDataMask with correct exact filter', () => {
getWrapper({ enableSingleValue: SingleValueType.Exact });
expect(setDataMask).toHaveBeenCalledWith({
extraFormData: {
filters: [
{
col: 'SP_POP_TOTL',
op: '==',
val: 10,
},
],
},
filterState: {
label: 'x = 10',
value: [10, 10],
},
});
});
});
|
7,899 | 0 | petrpan-code/apache/superset/superset-frontend/src/filters/components | petrpan-code/apache/superset/superset-frontend/src/filters/components/Select/SelectFilterPlugin.test.tsx | /**
* 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 userEvent from '@testing-library/user-event';
import { AppSection } from '@superset-ui/core';
import React from 'react';
import { render, screen } from 'spec/helpers/testing-library';
import { NULL_STRING } from 'src/utils/common';
import SelectFilterPlugin from './SelectFilterPlugin';
import transformProps from './transformProps';
jest.useFakeTimers();
const selectMultipleProps = {
formData: {
sortAscending: true,
multiSelect: true,
enableEmptyFilter: true,
defaultToFirstItem: false,
inverseSelection: false,
searchAllOptions: false,
datasource: '3__table',
groupby: ['gender'],
adhocFilters: [],
extraFilters: [],
extraFormData: {},
granularitySqla: 'ds',
metrics: ['count'],
rowLimit: 1000,
showSearch: true,
defaultValue: ['boy'],
timeRangeEndpoints: ['inclusive', 'exclusive'],
urlParams: {},
vizType: 'filter_select',
inputRef: { current: null },
},
height: 20,
hooks: {},
ownState: {},
filterState: { value: ['boy'] },
queriesData: [
{
rowcount: 2,
colnames: ['gender'],
coltypes: [1],
data: [{ gender: 'boy' }, { gender: 'girl' }, { gender: null }],
applied_filters: [{ column: 'gender' }],
rejected_filters: [],
},
],
width: 220,
behaviors: ['NATIVE_FILTER'],
isRefreshing: false,
appSection: AppSection.DASHBOARD,
};
describe('SelectFilterPlugin', () => {
const setDataMask = jest.fn();
const getWrapper = (props = {}) =>
render(
// @ts-ignore
<SelectFilterPlugin
// @ts-ignore
{...transformProps({
...selectMultipleProps,
formData: { ...selectMultipleProps.formData, ...props },
})}
setDataMask={setDataMask}
/>,
);
beforeEach(() => {
jest.clearAllMocks();
});
test('Add multiple values with first render', async () => {
getWrapper();
expect(setDataMask).toHaveBeenCalledWith({
extraFormData: {
filters: [
{
col: 'gender',
op: 'IN',
val: ['boy'],
},
],
},
filterState: {
label: 'boy',
value: ['boy'],
},
});
userEvent.click(screen.getByRole('combobox'));
userEvent.click(screen.getByTitle('girl'));
expect(await screen.findByTitle(/girl/i)).toBeInTheDocument();
expect(setDataMask).toHaveBeenCalledWith({
extraFormData: {
filters: [
{
col: 'gender',
op: 'IN',
val: ['boy', 'girl'],
},
],
},
filterState: {
label: 'boy, girl',
value: ['boy', 'girl'],
},
});
});
test('Remove multiple values when required', () => {
getWrapper();
userEvent.click(
screen.getByRole('img', {
name: /close-circle/i,
hidden: true,
}),
);
expect(setDataMask).toHaveBeenCalledWith({
extraFormData: {
adhoc_filters: [
{
clause: 'WHERE',
expressionType: 'SQL',
sqlExpression: '1 = 0',
},
],
},
filterState: {
label: undefined,
value: null,
},
});
});
test('Remove multiple values when not required', () => {
getWrapper({ enableEmptyFilter: false });
userEvent.click(
screen.getByRole('img', {
name: /close-circle/i,
hidden: true,
}),
);
expect(setDataMask).toHaveBeenCalledWith({
extraFormData: {},
filterState: {
label: undefined,
value: null,
},
});
});
test('Select single values with inverse', async () => {
getWrapper({ multiSelect: false, inverseSelection: true });
userEvent.click(screen.getByRole('combobox'));
expect(await screen.findByTitle('girl')).toBeInTheDocument();
userEvent.click(screen.getByTitle('girl'));
expect(setDataMask).toHaveBeenCalledWith({
extraFormData: {
filters: [
{
col: 'gender',
op: 'NOT IN',
val: ['girl'],
},
],
},
filterState: {
label: 'girl (excluded)',
value: ['girl'],
},
});
});
test('Select single null (empty) value', async () => {
getWrapper();
userEvent.click(screen.getByRole('combobox'));
expect(await screen.findByRole('combobox')).toBeInTheDocument();
userEvent.click(screen.getByTitle(NULL_STRING));
expect(setDataMask).toHaveBeenLastCalledWith({
extraFormData: {
filters: [
{
col: 'gender',
op: 'IN',
val: ['boy', null],
},
],
},
filterState: {
label: `boy, ${NULL_STRING}`,
value: ['boy', null],
},
});
});
test('receives the correct filter when search all options', async () => {
getWrapper({ searchAllOptions: true, multiSelect: false });
userEvent.click(screen.getByRole('combobox'));
expect(await screen.findByRole('combobox')).toBeInTheDocument();
userEvent.click(screen.getByTitle('girl'));
expect(setDataMask).toHaveBeenLastCalledWith(
expect.objectContaining({
extraFormData: {
filters: [
{
col: 'gender',
op: 'IN',
val: ['girl'],
},
],
},
}),
);
});
test('number of fired queries when searching', async () => {
getWrapper({ searchAllOptions: true });
userEvent.click(screen.getByRole('combobox'));
expect(await screen.findByRole('combobox')).toBeInTheDocument();
await userEvent.type(screen.getByRole('combobox'), 'a');
// Closes the select
userEvent.tab();
// One call for the search term and other for the empty search
expect(setDataMask).toHaveBeenCalledTimes(2);
});
});
|
7,901 | 0 | petrpan-code/apache/superset/superset-frontend/src/filters/components | petrpan-code/apache/superset/superset-frontend/src/filters/components/Select/buildQuery.test.ts | /**
* 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 { GenericDataType } from '@superset-ui/core';
import buildQuery from './buildQuery';
import { PluginFilterSelectQueryFormData } from './types';
describe('Select buildQuery', () => {
const formData: PluginFilterSelectQueryFormData = {
datasource: '5__table',
groupby: ['my_col'],
viz_type: 'filter_select',
sortAscending: undefined,
sortMetric: undefined,
filters: undefined,
enableEmptyFilter: false,
inverseSelection: false,
multiSelect: false,
defaultToFirstItem: false,
searchAllOptions: false,
height: 100,
width: 100,
};
it('should build a default query', () => {
const queryContext = buildQuery(formData);
expect(queryContext.queries.length).toEqual(1);
const [query] = queryContext.queries;
expect(query.columns).toEqual(['my_col']);
expect(query.filters).toEqual([]);
expect(query.metrics).toEqual([]);
expect(query.orderby).toEqual([]);
});
it('should sort descending by metric', () => {
const queryContext = buildQuery({
...formData,
sortMetric: 'my_metric',
sortAscending: false,
});
expect(queryContext.queries.length).toEqual(1);
const [query] = queryContext.queries;
expect(query.columns).toEqual(['my_col']);
expect(query.metrics).toEqual(['my_metric']);
expect(query.orderby).toEqual([['my_metric', false]]);
});
it('should sort ascending by metric', () => {
const queryContext = buildQuery({
...formData,
sortMetric: 'my_metric',
sortAscending: true,
});
expect(queryContext.queries.length).toEqual(1);
const [query] = queryContext.queries;
expect(query.columns).toEqual(['my_col']);
expect(query.metrics).toEqual(['my_metric']);
expect(query.orderby).toEqual([['my_metric', true]]);
});
it('should sort ascending by column', () => {
const queryContext = buildQuery({
...formData,
sortAscending: true,
});
expect(queryContext.queries.length).toEqual(1);
const [query] = queryContext.queries;
expect(query.columns).toEqual(['my_col']);
expect(query.metrics).toEqual([]);
expect(query.orderby).toEqual([['my_col', true]]);
});
it('should sort descending by column', () => {
const queryContext = buildQuery({
...formData,
sortAscending: false,
});
expect(queryContext.queries.length).toEqual(1);
const [query] = queryContext.queries;
expect(query.columns).toEqual(['my_col']);
expect(query.metrics).toEqual([]);
expect(query.orderby).toEqual([['my_col', false]]);
});
it('should add text search parameter for string to query filter', () => {
const queryContext = buildQuery(formData, {
ownState: {
search: 'abc',
coltypeMap: { my_col: GenericDataType.STRING },
},
});
expect(queryContext.queries.length).toEqual(1);
const [query] = queryContext.queries;
expect(query.filters).toEqual([
{ col: 'my_col', op: 'ILIKE', val: '%abc%' },
]);
});
it('should add text search parameter for numeric to query filter', () => {
const queryContext = buildQuery(formData, {
ownState: {
search: '123',
coltypeMap: { my_col: GenericDataType.NUMERIC },
},
});
expect(queryContext.queries.length).toEqual(1);
const [query] = queryContext.queries;
expect(query.filters).toEqual([
{ col: 'my_col', op: 'ILIKE', val: '%123%' },
]);
});
});
|
7,924 | 0 | petrpan-code/apache/superset/superset-frontend/src | petrpan-code/apache/superset/superset-frontend/src/hooks/useDebounceValue.test.ts | /**
* 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 { act, renderHook } from '@testing-library/react-hooks';
import { useDebounceValue } from './useDebounceValue';
afterEach(() => {
jest.clearAllTimers();
jest.useRealTimers();
});
test('should return the initial value', () => {
const { result } = renderHook(() => useDebounceValue('hello'));
expect(result.current).toBe('hello');
});
test('should update debounced value after delay', async () => {
jest.useFakeTimers();
const { result, rerender } = renderHook(
({ value, delay }) => useDebounceValue(value, delay),
{ initialProps: { value: 'hello', delay: 1000 } },
);
expect(result.current).toBe('hello');
act(() => {
rerender({ value: 'world', delay: 1000 });
jest.advanceTimersByTime(500);
});
expect(result.current).toBe('hello');
act(() => {
jest.advanceTimersByTime(1000);
});
expect(result.current).toBe('world');
});
it('should cancel previous timeout when value changes', async () => {
jest.useFakeTimers();
const { result, rerender } = renderHook(
({ value, delay }) => useDebounceValue(value, delay),
{ initialProps: { value: 'hello', delay: 1000 } },
);
expect(result.current).toBe('hello');
rerender({ value: 'world', delay: 1000 });
jest.advanceTimersByTime(500);
rerender({ value: 'foo', delay: 1000 });
jest.advanceTimersByTime(500);
expect(result.current).toBe('hello');
});
test('should cancel the timeout when unmounting', async () => {
jest.useFakeTimers();
const { result, unmount } = renderHook(() => useDebounceValue('hello', 1000));
expect(result.current).toBe('hello');
unmount();
jest.advanceTimersByTime(1000);
expect(clearTimeout).toHaveBeenCalled();
});
|
7,930 | 0 | petrpan-code/apache/superset/superset-frontend/src/hooks | petrpan-code/apache/superset/superset-frontend/src/hooks/apiResources/apiResources.test.ts | /**
* 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 { makeApi } from '@superset-ui/core';
import { act, renderHook } from '@testing-library/react-hooks';
import {
ResourceStatus,
useApiResourceFullBody,
useApiV1Resource,
useTransformedResource,
} from './apiResources';
const fakeApiResult = {
id: 1,
name: 'fake api result',
};
const nameToAllCaps = (thing: any) => ({
...thing,
name: thing.name.toUpperCase(),
});
jest.mock('@superset-ui/core', () => ({
...jest.requireActual<any>('@superset-ui/core'),
makeApi: jest
.fn()
.mockReturnValue(jest.fn().mockResolvedValue(fakeApiResult)),
}));
describe('apiResource hooks', () => {
beforeAll(() => {
jest.useFakeTimers();
});
afterAll(() => {
jest.useRealTimers();
});
describe('useApiResourceFullBody', () => {
it('returns a loading state at the start', async () => {
const { result } = renderHook(() =>
useApiResourceFullBody('/test/endpoint'),
);
expect(result.current).toEqual({
status: ResourceStatus.LOADING,
result: null,
error: null,
});
await act(async () => {
jest.runAllTimers();
});
});
it('resolves to the value from the api', async () => {
const { result } = renderHook(() =>
useApiResourceFullBody('/test/endpoint'),
);
await act(async () => {
jest.runAllTimers();
});
expect(result.current).toEqual({
status: ResourceStatus.COMPLETE,
result: fakeApiResult,
error: null,
});
});
it('handles api errors', async () => {
const fakeError = new Error('fake api error');
(makeApi as any).mockReturnValue(jest.fn().mockRejectedValue(fakeError));
const { result } = renderHook(() =>
useApiResourceFullBody('/test/endpoint'),
);
await act(async () => {
jest.runAllTimers();
});
expect(result.current).toEqual({
status: ResourceStatus.ERROR,
result: null,
error: fakeError,
});
});
});
describe('useTransformedResource', () => {
it('applies a transformation to the resource', () => {
const { result } = renderHook(() =>
useTransformedResource(
{
status: ResourceStatus.COMPLETE,
result: fakeApiResult,
error: null,
},
nameToAllCaps,
),
);
expect(result.current).toEqual({
status: ResourceStatus.COMPLETE,
result: {
id: 1,
name: 'FAKE API RESULT',
},
error: null,
});
});
it('works while loading', () => {
const nameToAllCaps = (thing: any) => ({
...thing,
name: thing.name.toUpperCase(),
});
const { result } = renderHook(() =>
useTransformedResource(
{
status: ResourceStatus.LOADING,
result: null,
error: null,
},
nameToAllCaps,
),
);
expect(result.current).toEqual({
status: ResourceStatus.LOADING,
result: null,
error: null,
});
});
});
describe('useApiV1Endpoint', () => {
it('resolves to the value from the api', async () => {
(makeApi as any).mockReturnValue(
jest.fn().mockResolvedValue({
meta: 'data',
count: 1,
result: fakeApiResult,
}),
);
const { result } = renderHook(() => useApiV1Resource('/test/endpoint'));
await act(async () => {
jest.runAllTimers();
});
expect(result.current).toEqual({
status: ResourceStatus.COMPLETE,
result: fakeApiResult,
error: null,
});
});
});
});
|
7,934 | 0 | petrpan-code/apache/superset/superset-frontend/src/hooks | petrpan-code/apache/superset/superset-frontend/src/hooks/apiResources/databaseFunctions.test.ts | /**
* 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 fetchMock from 'fetch-mock';
import { act, renderHook } from '@testing-library/react-hooks';
import {
createWrapper,
defaultStore as store,
} from 'spec/helpers/testing-library';
import { api } from 'src/hooks/apiResources/queryApi';
import { useDatabaseFunctionsQuery } from './databaseFunctions';
const fakeApiResult = {
function_names: ['abs', 'avg', 'sum'],
};
const expectedResult = fakeApiResult.function_names;
const expectDbId = 'db1';
const dbFunctionNamesApiRoute = `glob:*/api/v1/database/${expectDbId}/function_names/`;
afterEach(() => {
fetchMock.reset();
act(() => {
store.dispatch(api.util.resetApiState());
});
});
beforeEach(() => {
fetchMock.get(dbFunctionNamesApiRoute, fakeApiResult);
});
test('returns api response mapping json result', async () => {
const { result, waitFor } = renderHook(
() =>
useDatabaseFunctionsQuery({
dbId: expectDbId,
}),
{
wrapper: createWrapper({
useRedux: true,
store,
}),
},
);
await waitFor(() =>
expect(fetchMock.calls(dbFunctionNamesApiRoute).length).toBe(1),
);
expect(result.current.data).toEqual(expectedResult);
expect(fetchMock.calls(dbFunctionNamesApiRoute).length).toBe(1);
act(() => {
result.current.refetch();
});
await waitFor(() =>
expect(fetchMock.calls(dbFunctionNamesApiRoute).length).toBe(2),
);
expect(result.current.data).toEqual(expectedResult);
});
test('returns cached data without api request', async () => {
const { result, waitFor, rerender } = renderHook(
() =>
useDatabaseFunctionsQuery({
dbId: expectDbId,
}),
{
wrapper: createWrapper({
store,
useRedux: true,
}),
},
);
await waitFor(() => expect(result.current.data).toEqual(expectedResult));
expect(fetchMock.calls(dbFunctionNamesApiRoute).length).toBe(1);
rerender();
await waitFor(() => expect(result.current.data).toEqual(expectedResult));
expect(fetchMock.calls(dbFunctionNamesApiRoute).length).toBe(1);
});
|
7,938 | 0 | petrpan-code/apache/superset/superset-frontend/src/hooks | petrpan-code/apache/superset/superset-frontend/src/hooks/apiResources/queryApi.test.ts | /**
* 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 fetchMock from 'fetch-mock';
import configureStore, { MockStore } from 'redux-mock-store';
import rison from 'rison';
import { JsonResponse } from '@superset-ui/core';
import { supersetClientQuery } from './queryApi';
const getBaseQueryApiMock = (store: MockStore) => ({
...new AbortController(),
dispatch: store.dispatch,
getState: store.getState,
extra: undefined,
endpoint: 'endpoint',
type: 'query' as const,
});
const mockStore = configureStore();
const store = mockStore();
afterEach(() => {
fetchMock.reset();
});
test('supersetClientQuery should build the endpoint with rison encoded query string and return data when successful', async () => {
const expectedData = { id: 1, name: 'Test' };
const expectedUrl = '/api/v1/get-endpoint/';
const expectedPostUrl = '/api/v1/post-endpoint/';
const urlParams = { str: 'string', num: 123, bool: true };
const getEndpoint = `glob:*${expectedUrl}?q=${rison.encode(urlParams)}`;
const postEndpoint = `glob:*${expectedPostUrl}?q=${rison.encode(urlParams)}`;
fetchMock.get(getEndpoint, { result: expectedData });
fetchMock.post(postEndpoint, { result: expectedData });
const result = await supersetClientQuery(
{
endpoint: expectedUrl,
urlParams,
},
getBaseQueryApiMock(store),
{},
);
expect(fetchMock.calls(getEndpoint)).toHaveLength(1);
expect(fetchMock.calls(postEndpoint)).toHaveLength(0);
expect((result.data as JsonResponse).json.result).toEqual(expectedData);
await supersetClientQuery(
{
method: 'post',
endpoint: expectedPostUrl,
urlParams,
},
getBaseQueryApiMock(store),
{},
);
expect(fetchMock.calls(getEndpoint)).toHaveLength(1);
expect(fetchMock.calls(postEndpoint)).toHaveLength(1);
});
test('supersetClientQuery should return error when unsuccessful', async () => {
const expectedError = 'Request failed';
const expectedUrl = '/api/v1/get-endpoint/';
const endpoint = `glob:*${expectedUrl}`;
fetchMock.get(endpoint, { throws: new Error(expectedError) });
const result = await supersetClientQuery(
{ endpoint },
getBaseQueryApiMock(store),
{},
);
expect(result.error).toEqual({ error: expectedError });
});
test('supersetClientQuery should return parsed response by parseMethod', async () => {
const expectedUrl = '/api/v1/get-endpoint/';
const endpoint = `glob:*${expectedUrl}`;
const bitIntVal = '9223372036854775807';
const expectedData = `{ "id": ${bitIntVal} }`;
fetchMock.get(endpoint, expectedData);
const result = await supersetClientQuery(
{ endpoint, parseMethod: 'json-bigint' },
getBaseQueryApiMock(store),
{},
);
expect(`${(result.data as JsonResponse).json.id}`).toEqual(bitIntVal);
});
|
7,940 | 0 | petrpan-code/apache/superset/superset-frontend/src/hooks | petrpan-code/apache/superset/superset-frontend/src/hooks/apiResources/queryValidations.test.ts | /**
* 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 fetchMock from 'fetch-mock';
import { act, renderHook } from '@testing-library/react-hooks';
import {
createWrapper,
defaultStore as store,
} from 'spec/helpers/testing-library';
import { api } from 'src/hooks/apiResources/queryApi';
import { useQueryValidationsQuery } from './queryValidations';
const fakeApiResult = {
result: [
{
end_column: null,
line_number: 3,
message: 'ERROR: syntax error at or near ";"',
start_column: null,
},
],
};
const expectedResult = fakeApiResult.result;
const expectDbId = 'db1';
const expectSchema = 'my_schema';
const expectSql = 'SELECT * from example_table';
const expectTemplateParams = '{"a": 1, "v": "str"}';
afterEach(() => {
fetchMock.reset();
act(() => {
store.dispatch(api.util.resetApiState());
});
});
test('returns api response mapping json result', async () => {
const queryValidationApiRoute = `glob:*/api/v1/database/${expectDbId}/validate_sql/`;
fetchMock.post(queryValidationApiRoute, fakeApiResult);
const { result, waitFor } = renderHook(
() =>
useQueryValidationsQuery({
dbId: expectDbId,
sql: expectSql,
schema: expectSchema,
templateParams: expectTemplateParams,
}),
{
wrapper: createWrapper({
useRedux: true,
store,
}),
},
);
await waitFor(() =>
expect(fetchMock.calls(queryValidationApiRoute).length).toBe(1),
);
expect(result.current.data).toEqual(expectedResult);
expect(fetchMock.calls(queryValidationApiRoute).length).toBe(1);
expect(
JSON.parse(`${fetchMock.calls(queryValidationApiRoute)[0][1]?.body}`),
).toEqual({
schema: expectSchema,
sql: expectSql,
template_params: JSON.parse(expectTemplateParams),
});
act(() => {
result.current.refetch();
});
await waitFor(() =>
expect(fetchMock.calls(queryValidationApiRoute).length).toBe(2),
);
expect(result.current.data).toEqual(expectedResult);
});
test('returns cached data without api request', async () => {
const queryValidationApiRoute = `glob:*/api/v1/database/${expectDbId}/validate_sql/`;
fetchMock.post(queryValidationApiRoute, fakeApiResult);
const { result, waitFor, rerender } = renderHook(
() =>
useQueryValidationsQuery({
dbId: expectDbId,
sql: expectSql,
schema: expectSchema,
templateParams: expectTemplateParams,
}),
{
wrapper: createWrapper({
useRedux: true,
store,
}),
},
);
await waitFor(() => expect(result.current.data).toEqual(expectedResult));
expect(fetchMock.calls(queryValidationApiRoute).length).toBe(1);
rerender();
await waitFor(() => expect(result.current.data).toEqual(expectedResult));
expect(fetchMock.calls(queryValidationApiRoute).length).toBe(1);
});
|
7,942 | 0 | petrpan-code/apache/superset/superset-frontend/src/hooks | petrpan-code/apache/superset/superset-frontend/src/hooks/apiResources/schemas.test.ts | /**
* 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 rison from 'rison';
import fetchMock from 'fetch-mock';
import { act, renderHook } from '@testing-library/react-hooks';
import {
createWrapper,
defaultStore as store,
} from 'spec/helpers/testing-library';
import { api } from 'src/hooks/apiResources/queryApi';
import { useSchemas } from './schemas';
const fakeApiResult = {
result: ['test schema 1', 'test schema b'],
};
const fakeApiResult2 = {
result: ['test schema 2', 'test schema a'],
};
const expectedResult = fakeApiResult.result.map((value: string) => ({
value,
label: value,
title: value,
}));
const expectedResult2 = fakeApiResult2.result.map((value: string) => ({
value,
label: value,
title: value,
}));
describe('useSchemas hook', () => {
afterEach(() => {
fetchMock.reset();
act(() => {
store.dispatch(api.util.resetApiState());
});
});
test('returns api response mapping json result', async () => {
const expectDbId = 'db1';
const forceRefresh = false;
const schemaApiRoute = `glob:*/api/v1/database/${expectDbId}/schemas/*`;
fetchMock.get(schemaApiRoute, fakeApiResult);
const onSuccess = jest.fn();
const { result, waitFor } = renderHook(
() =>
useSchemas({
dbId: expectDbId,
onSuccess,
}),
{
wrapper: createWrapper({
useRedux: true,
store,
}),
},
);
await waitFor(() => expect(fetchMock.calls(schemaApiRoute).length).toBe(1));
expect(result.current.data).toEqual(expectedResult);
expect(
fetchMock.calls(
`end:/api/v1/database/${expectDbId}/schemas/?q=${rison.encode({
force: forceRefresh,
})}`,
).length,
).toBe(1);
expect(onSuccess).toHaveBeenCalledTimes(1);
act(() => {
result.current.refetch();
});
await waitFor(() => expect(fetchMock.calls(schemaApiRoute).length).toBe(2));
expect(
fetchMock.calls(
`end:/api/v1/database/${expectDbId}/schemas/?q=${rison.encode({
force: true,
})}`,
).length,
).toBe(1);
expect(onSuccess).toHaveBeenCalledTimes(2);
expect(result.current.data).toEqual(expectedResult);
});
test('returns cached data without api request', async () => {
const expectDbId = 'db1';
const schemaApiRoute = `glob:*/api/v1/database/${expectDbId}/schemas/*`;
fetchMock.get(schemaApiRoute, fakeApiResult);
const { result, rerender, waitFor } = renderHook(
() =>
useSchemas({
dbId: expectDbId,
}),
{
wrapper: createWrapper({
useRedux: true,
store,
}),
},
);
await waitFor(() => expect(result.current.data).toEqual(expectedResult));
expect(fetchMock.calls(schemaApiRoute).length).toBe(1);
rerender();
await waitFor(() => expect(result.current.data).toEqual(expectedResult));
expect(fetchMock.calls(schemaApiRoute).length).toBe(1);
});
it('returns refreshed data after expires', async () => {
const expectDbId = 'db1';
const schemaApiRoute = `glob:*/api/v1/database/*/schemas/*`;
fetchMock.get(schemaApiRoute, url =>
url.includes(expectDbId) ? fakeApiResult : fakeApiResult2,
);
const onSuccess = jest.fn();
const { result, rerender, waitFor } = renderHook(
({ dbId }) =>
useSchemas({
dbId,
onSuccess,
}),
{
initialProps: { dbId: expectDbId },
wrapper: createWrapper({
useRedux: true,
store,
}),
},
);
await waitFor(() => expect(result.current.data).toEqual(expectedResult));
expect(fetchMock.calls(schemaApiRoute).length).toBe(1);
expect(onSuccess).toHaveBeenCalledTimes(1);
rerender({ dbId: 'db2' });
await waitFor(() => expect(result.current.data).toEqual(expectedResult2));
expect(fetchMock.calls(schemaApiRoute).length).toBe(2);
expect(onSuccess).toHaveBeenCalledTimes(2);
rerender({ dbId: expectDbId });
await waitFor(() => expect(result.current.data).toEqual(expectedResult));
expect(fetchMock.calls(schemaApiRoute).length).toBe(2);
expect(onSuccess).toHaveBeenCalledTimes(3);
// clean up cache
act(() => {
store.dispatch(api.util.invalidateTags(['Schemas']));
});
await waitFor(() => expect(fetchMock.calls(schemaApiRoute).length).toBe(3));
expect(fetchMock.calls(schemaApiRoute)[2][0]).toContain(expectDbId);
await waitFor(() => expect(result.current.data).toEqual(expectedResult));
});
});
|
7,944 | 0 | petrpan-code/apache/superset/superset-frontend/src/hooks | petrpan-code/apache/superset/superset-frontend/src/hooks/apiResources/sqlEditorTabs.test.ts | /**
* 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 fetchMock from 'fetch-mock';
import { act, renderHook } from '@testing-library/react-hooks';
import {
createWrapper,
defaultStore as store,
} from 'spec/helpers/testing-library';
import { api } from 'src/hooks/apiResources/queryApi';
import { LatestQueryEditorVersion } from 'src/SqlLab/types';
import { useUpdateSqlEditorTabMutation } from './sqlEditorTabs';
const expectedQueryEditor = {
version: LatestQueryEditorVersion,
id: '123',
dbId: 456,
name: 'tab 1',
sql: 'SELECT * from example_table',
schema: 'my_schema',
templateParams: '{"a": 1, "v": "str"}',
queryLimit: 1000,
remoteId: null,
autorun: false,
hideLeftBar: false,
updatedAt: Date.now(),
};
afterEach(() => {
fetchMock.reset();
act(() => {
store.dispatch(api.util.resetApiState());
});
});
test('puts api request with formData', async () => {
const tabStateMutationApiRoute = `glob:*/tabstateview/${expectedQueryEditor.id}`;
fetchMock.put(tabStateMutationApiRoute, 200);
const { result, waitFor } = renderHook(
() => useUpdateSqlEditorTabMutation(),
{
wrapper: createWrapper({
useRedux: true,
store,
}),
},
);
act(() => {
result.current[0]({
queryEditor: expectedQueryEditor,
});
});
await waitFor(() =>
expect(fetchMock.calls(tabStateMutationApiRoute).length).toBe(1),
);
const formData = fetchMock.calls(tabStateMutationApiRoute)[0][1]
?.body as FormData;
expect(formData.get('database_id')).toBe(`${expectedQueryEditor.dbId}`);
expect(formData.get('schema')).toBe(
JSON.stringify(`${expectedQueryEditor.schema}`),
);
expect(formData.get('sql')).toBe(
JSON.stringify(`${expectedQueryEditor.sql}`),
);
expect(formData.get('label')).toBe(
JSON.stringify(`${expectedQueryEditor.name}`),
);
expect(formData.get('query_limit')).toBe(`${expectedQueryEditor.queryLimit}`);
expect(formData.has('latest_query_id')).toBe(false);
expect(formData.get('template_params')).toBe(
JSON.stringify(`${expectedQueryEditor.templateParams}`),
);
expect(formData.get('hide_left_bar')).toBe(
`${expectedQueryEditor.hideLeftBar}`,
);
expect(formData.get('extra_json')).toBe(
JSON.stringify(
JSON.stringify({
updatedAt: expectedQueryEditor.updatedAt,
version: LatestQueryEditorVersion,
}),
),
);
});
|
7,946 | 0 | petrpan-code/apache/superset/superset-frontend/src/hooks | petrpan-code/apache/superset/superset-frontend/src/hooks/apiResources/sqlLab.test.ts | /**
* 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 fetchMock from 'fetch-mock';
import { act, renderHook } from '@testing-library/react-hooks';
import {
createWrapper,
defaultStore as store,
} from 'spec/helpers/testing-library';
import { api } from 'src/hooks/apiResources/queryApi';
import { DEFAULT_COMMON_BOOTSTRAP_DATA } from 'src/constants';
import { useSqlLabInitialState } from './sqlLab';
const fakeApiResult = {
result: {
common: DEFAULT_COMMON_BOOTSTRAP_DATA,
tab_state_ids: [],
databases: [],
queries: {},
user: {
userId: 1,
username: 'some name',
isActive: true,
isAnonymous: false,
firstName: 'first name',
lastName: 'last name',
permissions: {},
roles: {},
},
},
};
const expectedResult = fakeApiResult.result;
const sqlLabInitialStateApiRoute = `glob:*/api/v1/sqllab/`;
afterEach(() => {
fetchMock.reset();
act(() => {
store.dispatch(api.util.resetApiState());
});
});
beforeEach(() => {
fetchMock.get(sqlLabInitialStateApiRoute, fakeApiResult);
});
test('returns api response mapping json result', async () => {
const { result, waitFor } = renderHook(() => useSqlLabInitialState(), {
wrapper: createWrapper({
useRedux: true,
store,
}),
});
await waitFor(() =>
expect(fetchMock.calls(sqlLabInitialStateApiRoute).length).toBe(1),
);
expect(result.current.data).toEqual(expectedResult);
expect(fetchMock.calls(sqlLabInitialStateApiRoute).length).toBe(1);
// clean up cache
act(() => {
store.dispatch(api.util.invalidateTags(['SqlLabInitialState']));
});
await waitFor(() =>
expect(fetchMock.calls(sqlLabInitialStateApiRoute).length).toBe(2),
);
expect(result.current.data).toEqual(expectedResult);
});
test('returns cached data without api request', async () => {
const { result, waitFor, rerender } = renderHook(
() => useSqlLabInitialState(),
{
wrapper: createWrapper({
store,
useRedux: true,
}),
},
);
await waitFor(() => expect(result.current.data).toEqual(expectedResult));
expect(fetchMock.calls(sqlLabInitialStateApiRoute).length).toBe(1);
rerender();
await waitFor(() => expect(result.current.data).toEqual(expectedResult));
expect(fetchMock.calls(sqlLabInitialStateApiRoute).length).toBe(1);
});
|
7,948 | 0 | petrpan-code/apache/superset/superset-frontend/src/hooks | petrpan-code/apache/superset/superset-frontend/src/hooks/apiResources/tables.test.ts | /**
* 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 rison from 'rison';
import fetchMock from 'fetch-mock';
import { act, renderHook } from '@testing-library/react-hooks';
import {
createWrapper,
defaultStore as store,
} from 'spec/helpers/testing-library';
import { api } from 'src/hooks/apiResources/queryApi';
import { useTables } from './tables';
const fakeApiResult = {
count: 2,
result: [
{
id: 1,
name: 'fake api result1',
label: 'fake api label1',
},
{
id: 2,
name: 'fake api result2',
label: 'fake api label2',
},
],
};
const fakeHasMoreApiResult = {
count: 4,
result: [
{
id: 1,
name: 'fake api result1',
label: 'fake api label1',
},
{
id: 2,
name: 'fake api result2',
label: 'fake api label2',
},
],
};
const fakeSchemaApiResult = ['schema1', 'schema2'];
const expectedData = {
options: fakeApiResult.result,
hasMore: false,
};
const expectedHasMoreData = {
options: fakeHasMoreApiResult.result,
hasMore: true,
};
describe('useTables hook', () => {
afterEach(() => {
fetchMock.reset();
act(() => {
store.dispatch(api.util.resetApiState());
});
});
test('returns api response mapping json options', async () => {
const expectDbId = 'db1';
const expectedSchema = 'schema1';
const schemaApiRoute = `glob:*/api/v1/database/${expectDbId}/schemas/*`;
const tableApiRoute = `glob:*/api/v1/database/${expectDbId}/tables/?q=*`;
fetchMock.get(tableApiRoute, fakeApiResult);
fetchMock.get(schemaApiRoute, {
result: fakeSchemaApiResult,
});
const { result, waitFor } = renderHook(
() =>
useTables({
dbId: expectDbId,
schema: expectedSchema,
}),
{
wrapper: createWrapper({
useRedux: true,
store,
}),
},
);
await waitFor(() => expect(result.current.data).toEqual(expectedData));
expect(fetchMock.calls(schemaApiRoute).length).toBe(1);
expect(
fetchMock.calls(
`end:api/v1/database/${expectDbId}/tables/?q=${rison.encode({
force: false,
schema_name: expectedSchema,
})}`,
).length,
).toBe(1);
act(() => {
result.current.refetch();
});
await waitFor(() =>
expect(
fetchMock.calls(
`end:api/v1/database/${expectDbId}/tables/?q=${rison.encode({
force: true,
schema_name: expectedSchema,
})}`,
).length,
).toBe(1),
);
expect(fetchMock.calls(schemaApiRoute).length).toBe(1);
expect(result.current.data).toEqual(expectedData);
});
test('skips the deprecated schema option', async () => {
const expectDbId = 'db1';
const unexpectedSchema = 'invalid schema';
const schemaApiRoute = `glob:*/api/v1/database/${expectDbId}/schemas/*`;
const tableApiRoute = `glob:*/api/v1/database/${expectDbId}/tables/?q=*`;
fetchMock.get(tableApiRoute, fakeApiResult);
fetchMock.get(schemaApiRoute, {
result: fakeSchemaApiResult,
});
const { result, waitFor } = renderHook(
() =>
useTables({
dbId: expectDbId,
schema: unexpectedSchema,
}),
{
wrapper: createWrapper({
useRedux: true,
store,
}),
},
);
await waitFor(() => expect(fetchMock.calls(schemaApiRoute).length).toBe(1));
expect(result.current.data).toEqual(undefined);
expect(
fetchMock.calls(
`end:api/v1/database/${expectDbId}/tables/?q=${rison.encode({
force: false,
schema_name: unexpectedSchema,
})}`,
).length,
).toBe(0);
});
test('returns hasMore when total is larger than result size', async () => {
const expectDbId = 'db1';
const expectedSchema = 'schema2';
const tableApiRoute = `glob:*/api/v1/database/${expectDbId}/tables/?q=*`;
fetchMock.get(tableApiRoute, fakeHasMoreApiResult);
fetchMock.get(`glob:*/api/v1/database/${expectDbId}/schemas/*`, {
result: fakeSchemaApiResult,
});
const { result, waitFor } = renderHook(
() =>
useTables({
dbId: expectDbId,
schema: expectedSchema,
}),
{
wrapper: createWrapper({
useRedux: true,
store,
}),
},
);
await waitFor(() => expect(fetchMock.calls(tableApiRoute).length).toBe(1));
expect(result.current.data).toEqual(expectedHasMoreData);
});
test('returns cached data without api request', async () => {
const expectDbId = 'db1';
const expectedSchema = 'schema1';
const tableApiRoute = `glob:*/api/v1/database/${expectDbId}/tables/?q=*`;
fetchMock.get(tableApiRoute, fakeApiResult);
fetchMock.get(`glob:*/api/v1/database/${expectDbId}/schemas/*`, {
result: fakeSchemaApiResult,
});
const { result, rerender, waitFor } = renderHook(
() =>
useTables({
dbId: expectDbId,
schema: expectedSchema,
}),
{
wrapper: createWrapper({
useRedux: true,
store,
}),
},
);
await waitFor(() => expect(fetchMock.calls(tableApiRoute).length).toBe(1));
rerender();
await waitFor(() => expect(result.current.data).toEqual(expectedData));
expect(fetchMock.calls(tableApiRoute).length).toBe(1);
});
test('returns refreshed data after expires', async () => {
const expectDbId = 'db1';
const expectedSchema = 'schema1';
const tableApiRoute = `glob:*/api/v1/database/${expectDbId}/tables/?q=*`;
fetchMock.get(tableApiRoute, url =>
url.includes(expectedSchema) ? fakeApiResult : fakeHasMoreApiResult,
);
fetchMock.get(`glob:*/api/v1/database/${expectDbId}/schemas/*`, {
result: fakeSchemaApiResult,
});
const { result, rerender, waitFor } = renderHook(
({ schema }) =>
useTables({
dbId: expectDbId,
schema,
}),
{
initialProps: { schema: expectedSchema },
wrapper: createWrapper({
useRedux: true,
store,
}),
},
);
await waitFor(() => expect(result.current.data).toEqual(expectedData));
expect(fetchMock.calls(tableApiRoute).length).toBe(1);
rerender({ schema: 'schema2' });
await waitFor(() =>
expect(result.current.data).toEqual(expectedHasMoreData),
);
expect(fetchMock.calls(tableApiRoute).length).toBe(2);
rerender({ schema: expectedSchema });
await waitFor(() => expect(result.current.data).toEqual(expectedData));
expect(fetchMock.calls(tableApiRoute).length).toBe(2);
// clean up cache
act(() => {
store.dispatch(api.util.invalidateTags(['Tables']));
});
await waitFor(() => expect(fetchMock.calls(tableApiRoute).length).toBe(3));
await waitFor(() => expect(result.current.data).toEqual(expectedData));
rerender({ schema: 'schema2' });
await waitFor(() =>
expect(result.current.data).toEqual(expectedHasMoreData),
);
expect(fetchMock.calls(tableApiRoute).length).toBe(4);
rerender({ schema: expectedSchema });
await waitFor(() => expect(result.current.data).toEqual(expectedData));
expect(fetchMock.calls(tableApiRoute).length).toBe(4);
});
});
|
7,952 | 0 | petrpan-code/apache/superset/superset-frontend/src | petrpan-code/apache/superset/superset-frontend/src/middleware/asyncEvent.test.ts | /**
* 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 fetchMock from 'fetch-mock';
import WS from 'jest-websocket-mock';
import sinon from 'sinon';
import * as uiCore from '@superset-ui/core';
import { parseErrorJson } from 'src/utils/getClientErrorObject';
import * as asyncEvent from 'src/middleware/asyncEvent';
describe('asyncEvent middleware', () => {
const asyncPendingEvent = {
status: 'pending',
result_url: null,
job_id: 'foo123',
channel_id: '999',
errors: [],
};
const asyncDoneEvent = {
id: '1518951480106-0',
status: 'done',
result_url: '/api/v1/chart/data/cache-key-1',
job_id: 'foo123',
channel_id: '999',
errors: [],
};
const asyncErrorEvent = {
id: '1518951480107-0',
status: 'error',
result_url: null,
job_id: 'foo123',
channel_id: '999',
errors: [{ message: "Error: relation 'foo' does not exist" }],
};
const chartData = {
result: [
{
cache_key: '199f01f81f99c98693694821e4458111',
cached_dttm: null,
cache_timeout: 86400,
annotation_data: {},
error: null,
is_cached: false,
query:
'SELECT product_line AS product_line,\n sum(sales) AS "(Sales)"\nFROM cleaned_sales_data\nGROUP BY product_line\nLIMIT 50000',
status: 'success',
stacktrace: null,
rowcount: 7,
colnames: ['product_line', '(Sales)'],
coltypes: [1, 0],
data: [
{
product_line: 'Classic Cars',
'(Sales)': 3919615.66,
},
],
applied_filters: [
{
column: '__time_range',
},
],
rejected_filters: [],
},
],
};
const EVENTS_ENDPOINT = 'glob:*/api/v1/async_event/*';
const CACHED_DATA_ENDPOINT = 'glob:*/api/v1/chart/data/*';
let featureEnabledStub: any;
beforeEach(async () => {
featureEnabledStub = sinon.stub(uiCore, 'isFeatureEnabled');
featureEnabledStub.withArgs('GLOBAL_ASYNC_QUERIES').returns(true);
});
afterEach(() => {
fetchMock.reset();
featureEnabledStub.restore();
});
afterAll(fetchMock.reset);
describe('polling transport', () => {
const config = {
GLOBAL_ASYNC_QUERIES_TRANSPORT: 'polling',
GLOBAL_ASYNC_QUERIES_POLLING_DELAY: 50,
GLOBAL_ASYNC_QUERIES_WEBSOCKET_URL: '',
};
beforeEach(async () => {
fetchMock.get(EVENTS_ENDPOINT, {
status: 200,
body: { result: [asyncDoneEvent] },
});
fetchMock.get(CACHED_DATA_ENDPOINT, {
status: 200,
body: { result: chartData },
});
asyncEvent.init(config);
});
it('resolves with chart data on event done status', async () => {
await expect(
asyncEvent.waitForAsyncData(asyncPendingEvent),
).resolves.toEqual([chartData]);
expect(fetchMock.calls(EVENTS_ENDPOINT)).toHaveLength(1);
expect(fetchMock.calls(CACHED_DATA_ENDPOINT)).toHaveLength(1);
});
it('rejects on event error status', async () => {
fetchMock.reset();
fetchMock.get(EVENTS_ENDPOINT, {
status: 200,
body: { result: [asyncErrorEvent] },
});
const errorResponse = await parseErrorJson(asyncErrorEvent);
await expect(
asyncEvent.waitForAsyncData(asyncPendingEvent),
).rejects.toEqual(errorResponse);
expect(fetchMock.calls(EVENTS_ENDPOINT)).toHaveLength(1);
expect(fetchMock.calls(CACHED_DATA_ENDPOINT)).toHaveLength(0);
});
it('rejects on cached data fetch error', async () => {
fetchMock.reset();
fetchMock.get(EVENTS_ENDPOINT, {
status: 200,
body: { result: [asyncDoneEvent] },
});
fetchMock.get(CACHED_DATA_ENDPOINT, {
status: 400,
});
const errorResponse = [{ error: 'Bad Request' }];
await expect(
asyncEvent.waitForAsyncData(asyncPendingEvent),
).rejects.toEqual(errorResponse);
expect(fetchMock.calls(EVENTS_ENDPOINT)).toHaveLength(1);
expect(fetchMock.calls(CACHED_DATA_ENDPOINT)).toHaveLength(1);
});
});
describe('ws transport', () => {
let wsServer: WS;
const config = {
GLOBAL_ASYNC_QUERIES_TRANSPORT: 'ws',
GLOBAL_ASYNC_QUERIES_POLLING_DELAY: 50,
GLOBAL_ASYNC_QUERIES_WEBSOCKET_URL: 'ws://127.0.0.1:8080/',
};
beforeEach(async () => {
fetchMock.get(EVENTS_ENDPOINT, {
status: 200,
body: { result: [asyncDoneEvent] },
});
fetchMock.get(CACHED_DATA_ENDPOINT, {
status: 200,
body: { result: chartData },
});
wsServer = new WS(config.GLOBAL_ASYNC_QUERIES_WEBSOCKET_URL);
asyncEvent.init(config);
});
afterEach(() => {
WS.clean();
});
it('resolves with chart data on event done status', async () => {
await wsServer.connected;
const promise = asyncEvent.waitForAsyncData(asyncPendingEvent);
wsServer.send(JSON.stringify(asyncDoneEvent));
await expect(promise).resolves.toEqual([chartData]);
expect(fetchMock.calls(CACHED_DATA_ENDPOINT)).toHaveLength(1);
expect(fetchMock.calls(EVENTS_ENDPOINT)).toHaveLength(0);
});
it('rejects on event error status', async () => {
await wsServer.connected;
const promise = asyncEvent.waitForAsyncData(asyncPendingEvent);
wsServer.send(JSON.stringify(asyncErrorEvent));
const errorResponse = await parseErrorJson(asyncErrorEvent);
await expect(promise).rejects.toEqual(errorResponse);
expect(fetchMock.calls(CACHED_DATA_ENDPOINT)).toHaveLength(0);
expect(fetchMock.calls(EVENTS_ENDPOINT)).toHaveLength(0);
});
it('rejects on cached data fetch error', async () => {
fetchMock.reset();
fetchMock.get(CACHED_DATA_ENDPOINT, {
status: 400,
});
await wsServer.connected;
const promise = asyncEvent.waitForAsyncData(asyncPendingEvent);
wsServer.send(JSON.stringify(asyncDoneEvent));
const errorResponse = [{ error: 'Bad Request' }];
await expect(promise).rejects.toEqual(errorResponse);
expect(fetchMock.calls(CACHED_DATA_ENDPOINT)).toHaveLength(1);
expect(fetchMock.calls(EVENTS_ENDPOINT)).toHaveLength(0);
});
it('resolves when events are received before listener', async () => {
await wsServer.connected;
wsServer.send(JSON.stringify(asyncDoneEvent));
const promise = asyncEvent.waitForAsyncData(asyncPendingEvent);
await expect(promise).resolves.toEqual([chartData]);
expect(fetchMock.calls(CACHED_DATA_ENDPOINT)).toHaveLength(1);
expect(fetchMock.calls(EVENTS_ENDPOINT)).toHaveLength(0);
});
});
});
|
7,963 | 0 | petrpan-code/apache/superset/superset-frontend/src/pages | petrpan-code/apache/superset/superset-frontend/src/pages/Chart/Chart.test.tsx | /**
* 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 fetchMock from 'fetch-mock';
import { Link } from 'react-router-dom';
import {
render,
waitFor,
screen,
fireEvent,
} from 'spec/helpers/testing-library';
import { getExploreFormData } from 'spec/fixtures/mockExploreFormData';
import { getDashboardFormData } from 'spec/fixtures/mockDashboardFormData';
import { LocalStorageKeys } from 'src/utils/localStorageHelpers';
import getFormDataWithExtraFilters from 'src/dashboard/util/charts/getFormDataWithExtraFilters';
import { URL_PARAMS } from 'src/constants';
import { JsonObject } from '@superset-ui/core';
import ChartPage from '.';
jest.mock('re-resizable', () => ({
Resizable: () => <div data-test="mock-re-resizable" />,
}));
jest.mock(
'src/explore/components/ExploreChartPanel',
() =>
({ exploreState }: { exploreState: JsonObject }) =>
(
<div data-test="mock-explore-chart-panel">
{JSON.stringify(exploreState)}
</div>
),
);
jest.mock('src/dashboard/util/charts/getFormDataWithExtraFilters');
describe('ChartPage', () => {
afterEach(() => {
fetchMock.reset();
});
test('fetches metadata on mount', async () => {
const exploreApiRoute = 'glob:*/api/v1/explore/*';
const exploreFormData = getExploreFormData({
viz_type: 'table',
show_cell_bars: true,
});
fetchMock.get(exploreApiRoute, {
result: { dataset: { id: 1 }, form_data: exploreFormData },
});
const { getByTestId } = render(<ChartPage />, {
useRouter: true,
useRedux: true,
});
await waitFor(() =>
expect(fetchMock.calls(exploreApiRoute).length).toBe(1),
);
expect(getByTestId('mock-explore-chart-panel')).toBeInTheDocument();
expect(getByTestId('mock-explore-chart-panel')).toHaveTextContent(
JSON.stringify({ show_cell_bars: true }).slice(1, -1),
);
});
describe('with dashboardContextFormData', () => {
const dashboardPageId = 'mockPageId';
beforeEach(() => {
localStorage.setItem(
LocalStorageKeys.dashboard__explore_context,
JSON.stringify({
[dashboardPageId]: {},
}),
);
});
afterEach(() => {
localStorage.clear();
(getFormDataWithExtraFilters as jest.Mock).mockClear();
});
test('overrides the form_data with dashboardContextFormData', async () => {
const dashboardFormData = getDashboardFormData();
(getFormDataWithExtraFilters as jest.Mock).mockReturnValue(
dashboardFormData,
);
const exploreApiRoute = 'glob:*/api/v1/explore/*';
const exploreFormData = getExploreFormData();
fetchMock.get(exploreApiRoute, {
result: { dataset: { id: 1 }, form_data: exploreFormData },
});
window.history.pushState(
{},
'',
`/?${URL_PARAMS.dashboardPageId.name}=${dashboardPageId}`,
);
const { getByTestId } = render(<ChartPage />, {
useRouter: true,
useRedux: true,
});
await waitFor(() =>
expect(fetchMock.calls(exploreApiRoute).length).toBe(1),
);
expect(getByTestId('mock-explore-chart-panel')).toHaveTextContent(
JSON.stringify({ color_scheme: dashboardFormData.color_scheme }).slice(
1,
-1,
),
);
});
test('overrides the form_data with exploreFormData when location is updated', async () => {
const dashboardFormData = {
...getDashboardFormData(),
viz_type: 'table',
show_cell_bars: true,
};
(getFormDataWithExtraFilters as jest.Mock).mockReturnValue(
dashboardFormData,
);
const exploreApiRoute = 'glob:*/api/v1/explore/*';
const exploreFormData = getExploreFormData({
viz_type: 'table',
show_cell_bars: true,
});
fetchMock.get(exploreApiRoute, {
result: { dataset: { id: 1 }, form_data: exploreFormData },
});
window.history.pushState(
{},
'',
`/?${URL_PARAMS.dashboardPageId.name}=${dashboardPageId}`,
);
const { getByTestId } = render(
<>
<Link
to={`/?${URL_PARAMS.dashboardPageId.name}=${dashboardPageId}&${URL_PARAMS.saveAction.name}=overwrite`}
>
Change route
</Link>
<ChartPage />
</>,
{
useRouter: true,
useRedux: true,
},
);
await waitFor(() =>
expect(fetchMock.calls(exploreApiRoute).length).toBe(1),
);
expect(getByTestId('mock-explore-chart-panel')).toHaveTextContent(
JSON.stringify({
show_cell_bars: dashboardFormData.show_cell_bars,
}).slice(1, -1),
);
const updatedExploreFormData = {
...exploreFormData,
show_cell_bars: false,
};
fetchMock.reset();
fetchMock.get(exploreApiRoute, {
result: { dataset: { id: 1 }, form_data: updatedExploreFormData },
});
fireEvent.click(screen.getByText('Change route'));
await waitFor(() =>
expect(fetchMock.calls(exploreApiRoute).length).toBe(1),
);
expect(getByTestId('mock-explore-chart-panel')).toHaveTextContent(
JSON.stringify({
show_cell_bars: updatedExploreFormData.show_cell_bars,
}).slice(1, -1),
);
});
});
});
|
7,965 | 0 | petrpan-code/apache/superset/superset-frontend/src/pages | petrpan-code/apache/superset/superset-frontend/src/pages/ChartCreation/ChartCreation.test.tsx | /**
* 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 { ReactWrapper } from 'enzyme';
import { styledMount as mount } from 'spec/helpers/theming';
import Button from 'src/components/Button';
import { AsyncSelect } from 'src/components';
import {
ChartCreation,
ChartCreationProps,
ChartCreationState,
} from 'src/pages/ChartCreation';
import VizTypeGallery from 'src/explore/components/controls/VizTypeControl/VizTypeGallery';
import { act } from 'spec/helpers/testing-library';
import { UserWithPermissionsAndRoles } from 'src/types/bootstrapTypes';
const datasource = {
value: '1',
label: 'table',
};
const mockUser: UserWithPermissionsAndRoles = {
createdOn: '2021-04-27T18:12:38.952304',
email: 'admin',
firstName: 'admin',
isActive: true,
lastName: 'admin',
permissions: {},
roles: { Admin: Array(173) },
userId: 1,
username: 'admin',
isAnonymous: false,
};
const mockUserWithDatasetWrite: UserWithPermissionsAndRoles = {
createdOn: '2021-04-27T18:12:38.952304',
email: 'admin',
firstName: 'admin',
isActive: true,
lastName: 'admin',
permissions: {},
roles: { Admin: [['can_write', 'Dataset']] },
userId: 1,
username: 'admin',
isAnonymous: false,
};
// We don't need the actual implementation for the tests
const routeProps = {
history: {} as any,
location: {} as any,
match: {} as any,
};
async function getWrapper(user = mockUser) {
const wrapper = mount(
<ChartCreation user={user} addSuccessToast={() => null} {...routeProps} />,
) as unknown as ReactWrapper<
ChartCreationProps,
ChartCreationState,
ChartCreation
>;
await act(() => new Promise(resolve => setTimeout(resolve, 0)));
return wrapper;
}
test('renders a select and a VizTypeGallery', async () => {
const wrapper = await getWrapper();
expect(wrapper.find(AsyncSelect)).toExist();
expect(wrapper.find(VizTypeGallery)).toExist();
});
test('renders dataset help text when user lacks dataset write permissions', async () => {
const wrapper = await getWrapper();
expect(wrapper.find('[data-test="dataset-write"]')).not.toExist();
expect(wrapper.find('[data-test="no-dataset-write"]')).toExist();
});
test('renders dataset help text when user has dataset write permissions', async () => {
const wrapper = await getWrapper(mockUserWithDatasetWrite);
expect(wrapper.find('[data-test="dataset-write"]')).toExist();
expect(wrapper.find('[data-test="no-dataset-write"]')).not.toExist();
});
test('renders a button', async () => {
const wrapper = await getWrapper();
expect(wrapper.find(Button)).toExist();
});
test('renders a disabled button if no datasource is selected', async () => {
const wrapper = await getWrapper();
expect(
wrapper.find(Button).find({ disabled: true }).hostNodes(),
).toHaveLength(1);
});
test('renders an enabled button if datasource and viz type are selected', async () => {
const wrapper = await getWrapper();
wrapper.setState({
datasource,
vizType: 'table',
});
expect(
wrapper.find(Button).find({ disabled: true }).hostNodes(),
).toHaveLength(0);
});
test('double-click viz type does nothing if no datasource is selected', async () => {
const wrapper = await getWrapper();
wrapper.instance().gotoSlice = jest.fn();
wrapper.update();
wrapper.instance().onVizTypeDoubleClick();
expect(wrapper.instance().gotoSlice).not.toBeCalled();
});
test('double-click viz type submits if datasource is selected', async () => {
const wrapper = await getWrapper();
wrapper.instance().gotoSlice = jest.fn();
wrapper.update();
wrapper.setState({
datasource,
vizType: 'table',
});
wrapper.instance().onVizTypeDoubleClick();
expect(wrapper.instance().gotoSlice).toBeCalled();
});
test('formats Explore url', async () => {
const wrapper = await getWrapper();
wrapper.setState({
datasource,
vizType: 'table',
});
const formattedUrl = '/explore/?viz_type=table&datasource=1';
expect(wrapper.instance().exploreUrl()).toBe(formattedUrl);
});
|
7,976 | 0 | petrpan-code/apache/superset/superset-frontend/src/pages | petrpan-code/apache/superset/superset-frontend/src/pages/DatasetCreation/DatasetCreation.test.tsx | /**
* 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 { render, screen } from 'spec/helpers/testing-library';
import AddDataset from 'src/pages/DatasetCreation';
const mockHistoryPush = jest.fn();
jest.mock('react-router-dom', () => ({
...jest.requireActual('react-router-dom'),
useHistory: () => ({
push: mockHistoryPush,
}),
useParams: () => ({ datasetId: undefined }),
}));
describe('AddDataset', () => {
it('renders a blank state AddDataset', async () => {
render(<AddDataset />, { useRedux: true, useRouter: true });
const blankeStateImgs = screen.getAllByRole('img', { name: /empty/i });
// Header
expect(await screen.findByText(/new dataset/i)).toBeVisible();
// Left panel
expect(blankeStateImgs[0]).toBeVisible();
// Footer
expect(screen.getByText(/Cancel/i)).toBeVisible();
expect(blankeStateImgs.length).toBe(1);
});
});
|
7,978 | 0 | petrpan-code/apache/superset/superset-frontend/src/pages | petrpan-code/apache/superset/superset-frontend/src/pages/DatasetList/DatasetList.test.tsx | /**
* 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 thunk from 'redux-thunk';
import configureStore from 'redux-mock-store';
import fetchMock from 'fetch-mock';
import { Provider } from 'react-redux';
import { styledMount as mount } from 'spec/helpers/theming';
import { render, screen, cleanup } from 'spec/helpers/testing-library';
import { FeatureFlag } from '@superset-ui/core';
import userEvent from '@testing-library/user-event';
import { QueryParamProvider } from 'use-query-params';
import * as uiCore from '@superset-ui/core';
import DatasetList from 'src/pages/DatasetList';
import ListView from 'src/components/ListView';
import Button from 'src/components/Button';
import IndeterminateCheckbox from 'src/components/IndeterminateCheckbox';
import waitForComponentToPaint from 'spec/helpers/waitForComponentToPaint';
import { act } from 'react-dom/test-utils';
import SubMenu from 'src/features/home/SubMenu';
import * as reactRedux from 'react-redux';
// store needed for withToasts(DatasetList)
const mockStore = configureStore([thunk]);
const store = mockStore({});
const datasetsInfoEndpoint = 'glob:*/api/v1/dataset/_info*';
const datasetsOwnersEndpoint = 'glob:*/api/v1/dataset/related/owners*';
const datasetsSchemaEndpoint = 'glob:*/api/v1/dataset/distinct/schema*';
const datasetsDuplicateEndpoint = 'glob:*/api/v1/dataset/duplicate*';
const databaseEndpoint = 'glob:*/api/v1/dataset/related/database*';
const datasetsEndpoint = 'glob:*/api/v1/dataset/?*';
const useSelectorMock = jest.spyOn(reactRedux, 'useSelector');
const mockdatasets = [...new Array(3)].map((_, i) => ({
changed_by_name: 'user',
kind: i === 0 ? 'virtual' : 'physical', // ensure there is 1 virtual
changed_by: 'user',
changed_on: new Date().toISOString(),
database_name: `db ${i}`,
explore_url: `https://www.google.com?${i}`,
id: i,
schema: `schema ${i}`,
table_name: `coolest table ${i}`,
owners: [{ username: 'admin', userId: 1 }],
}));
const mockUser = {
userId: 1,
};
fetchMock.get(datasetsInfoEndpoint, {
permissions: ['can_read', 'can_write', 'can_duplicate'],
});
fetchMock.get(datasetsOwnersEndpoint, {
result: [],
});
fetchMock.get(datasetsSchemaEndpoint, {
result: [],
});
fetchMock.post(datasetsDuplicateEndpoint, {
result: [],
});
fetchMock.get(datasetsEndpoint, {
result: mockdatasets,
dataset_count: 3,
});
fetchMock.get(databaseEndpoint, {
result: [],
});
async function mountAndWait(props: {}) {
const mounted = mount(
<Provider store={store}>
<DatasetList {...props} user={mockUser} />
</Provider>,
);
await waitForComponentToPaint(mounted);
return mounted;
}
describe('DatasetList', () => {
const mockedProps = {};
let wrapper: any;
beforeAll(async () => {
wrapper = await mountAndWait(mockedProps);
});
it('renders', () => {
expect(wrapper.find(DatasetList)).toExist();
});
it('renders a ListView', () => {
expect(wrapper.find(ListView)).toExist();
});
it('fetches info', () => {
const callsI = fetchMock.calls(/dataset\/_info/);
expect(callsI).toHaveLength(1);
});
it('fetches data', () => {
const callsD = fetchMock.calls(/dataset\/\?q/);
expect(callsD).toHaveLength(1);
expect(callsD[0][0]).toMatchInlineSnapshot(
`"http://localhost/api/v1/dataset/?q=(order_column:changed_on_delta_humanized,order_direction:desc,page:0,page_size:25)"`,
);
});
it('does not fetch owner filter values on mount', async () => {
await waitForComponentToPaint(wrapper);
expect(fetchMock.calls(/dataset\/related\/owners/)).toHaveLength(0);
});
it('does not fetch schema filter values on mount', async () => {
await waitForComponentToPaint(wrapper);
expect(fetchMock.calls(/dataset\/distinct\/schema/)).toHaveLength(0);
});
it('shows/hides bulk actions when bulk actions is clicked', async () => {
await waitForComponentToPaint(wrapper);
const button = wrapper.find(Button).at(0);
act(() => {
button.props().onClick();
});
await waitForComponentToPaint(wrapper);
expect(wrapper.find(IndeterminateCheckbox)).toHaveLength(
mockdatasets.length + 1, // 1 for each row and 1 for select all
);
});
it('renders different bulk selected copy depending on type of row selected', async () => {
// None selected
const checkedEvent = { target: { checked: true } };
const uncheckedEvent = { target: { checked: false } };
expect(
wrapper.find('[data-test="bulk-select-copy"]').text(),
).toMatchInlineSnapshot(`"0 Selected"`);
// Virtual Selected
act(() => {
wrapper.find(IndeterminateCheckbox).at(1).props().onChange(checkedEvent);
});
await waitForComponentToPaint(wrapper);
expect(
wrapper.find('[data-test="bulk-select-copy"]').text(),
).toMatchInlineSnapshot(`"1 Selected (Virtual)"`);
// Physical Selected
act(() => {
wrapper
.find(IndeterminateCheckbox)
.at(1)
.props()
.onChange(uncheckedEvent);
wrapper.find(IndeterminateCheckbox).at(2).props().onChange(checkedEvent);
});
await waitForComponentToPaint(wrapper);
expect(
wrapper.find('[data-test="bulk-select-copy"]').text(),
).toMatchInlineSnapshot(`"1 Selected (Physical)"`);
// All Selected
act(() => {
wrapper.find(IndeterminateCheckbox).at(0).props().onChange(checkedEvent);
});
await waitForComponentToPaint(wrapper);
expect(
wrapper.find('[data-test="bulk-select-copy"]').text(),
).toMatchInlineSnapshot(`"3 Selected (2 Physical, 1 Virtual)"`);
});
it('shows duplicate modal when duplicate action is clicked', async () => {
await waitForComponentToPaint(wrapper);
expect(
wrapper.find('[data-test="duplicate-modal-input"]').exists(),
).toBeFalsy();
act(() => {
wrapper
.find('#duplicate-action-tooltop')
.at(0)
.find('.action-button')
.props()
.onClick();
});
await waitForComponentToPaint(wrapper);
expect(
wrapper.find('[data-test="duplicate-modal-input"]').exists(),
).toBeTruthy();
});
it('calls the duplicate endpoint', async () => {
await waitForComponentToPaint(wrapper);
await act(async () => {
wrapper
.find('#duplicate-action-tooltop')
.at(0)
.find('.action-button')
.props()
.onClick();
await waitForComponentToPaint(wrapper);
wrapper
.find('[data-test="duplicate-modal-input"]')
.at(0)
.props()
.onPressEnter();
});
expect(fetchMock.calls(/dataset\/duplicate/)).toHaveLength(1);
});
it('renders a SubMenu', () => {
expect(wrapper.find(SubMenu)).toExist();
});
it('renders a SubMenu with no tabs', () => {
expect(wrapper.find(SubMenu).props().tabs).toBeUndefined();
});
});
jest.mock('react-router-dom', () => ({
...jest.requireActual('react-router-dom'),
useLocation: () => ({}),
useHistory: () => ({}),
}));
describe('RTL', () => {
async function renderAndWait() {
const mounted = act(async () => {
const mockedProps = {};
render(
<QueryParamProvider>
<DatasetList {...mockedProps} user={mockUser} />
</QueryParamProvider>,
{ useRedux: true, useRouter: true },
);
});
return mounted;
}
let isFeatureEnabledMock: jest.SpyInstance<boolean, [feature: FeatureFlag]>;
beforeEach(async () => {
isFeatureEnabledMock = jest
.spyOn(uiCore, 'isFeatureEnabled')
.mockImplementation(() => true);
await renderAndWait();
});
afterEach(() => {
cleanup();
isFeatureEnabledMock.mockRestore();
});
it('renders an "Import Dataset" tooltip under import button', async () => {
const importButton = await screen.findByTestId('import-button');
userEvent.hover(importButton);
await screen.findByRole('tooltip');
const importTooltip = screen.getByRole('tooltip', {
name: 'Import datasets',
});
expect(importTooltip).toBeInTheDocument();
});
});
describe('Prevent unsafe URLs', () => {
const mockedProps = {};
let wrapper: any;
it('Check prevent unsafe is on renders relative links', async () => {
const tdColumnsNumber = 9;
useSelectorMock.mockReturnValue(true);
wrapper = await mountAndWait(mockedProps);
const tdElements = wrapper.find(ListView).find('td');
expect(
tdElements
.at(0 * tdColumnsNumber + 1)
.find('a')
.prop('href'),
).toBe('/https://www.google.com?0');
expect(
tdElements
.at(1 * tdColumnsNumber + 1)
.find('a')
.prop('href'),
).toBe('/https://www.google.com?1');
expect(
tdElements
.at(2 * tdColumnsNumber + 1)
.find('a')
.prop('href'),
).toBe('/https://www.google.com?2');
});
it('Check prevent unsafe is off renders absolute links', async () => {
const tdColumnsNumber = 9;
useSelectorMock.mockReturnValue(false);
wrapper = await mountAndWait(mockedProps);
const tdElements = wrapper.find(ListView).find('td');
expect(
tdElements
.at(0 * tdColumnsNumber + 1)
.find('a')
.prop('href'),
).toBe('https://www.google.com?0');
expect(
tdElements
.at(1 * tdColumnsNumber + 1)
.find('a')
.prop('href'),
).toBe('https://www.google.com?1');
expect(
tdElements
.at(2 * tdColumnsNumber + 1)
.find('a')
.prop('href'),
).toBe('https://www.google.com?2');
});
});
|
7,982 | 0 | petrpan-code/apache/superset/superset-frontend/src/pages | petrpan-code/apache/superset/superset-frontend/src/pages/Home/Home.test.tsx | /**
* 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 { styledMount as mount } from 'spec/helpers/theming';
import { Provider } from 'react-redux';
import thunk from 'redux-thunk';
import fetchMock from 'fetch-mock';
import { act } from 'react-dom/test-utils';
import configureStore from 'redux-mock-store';
import * as uiCore from '@superset-ui/core';
import Welcome from 'src/pages/Home';
import { ReactWrapper } from 'enzyme';
import waitForComponentToPaint from 'spec/helpers/waitForComponentToPaint';
import { render, screen } from 'spec/helpers/testing-library';
import { getExtensionsRegistry } from '@superset-ui/core';
import setupExtensions from 'src/setup/setupExtensions';
const mockStore = configureStore([thunk]);
const store = mockStore({});
const chartsEndpoint = 'glob:*/api/v1/chart/?*';
const chartInfoEndpoint = 'glob:*/api/v1/chart/_info?*';
const chartFavoriteStatusEndpoint = 'glob:*/api/v1/chart/favorite_status?*';
const dashboardsEndpoint = 'glob:*/api/v1/dashboard/?*';
const dashboardInfoEndpoint = 'glob:*/api/v1/dashboard/_info?*';
const dashboardFavoriteStatusEndpoint =
'glob:*/api/v1/dashboard/favorite_status/?*';
const savedQueryEndpoint = 'glob:*/api/v1/saved_query/?*';
const savedQueryInfoEndpoint = 'glob:*/api/v1/saved_query/_info?*';
const recentActivityEndpoint = 'glob:*/api/v1/log/recent_activity/*';
fetchMock.get(chartsEndpoint, {
result: [
{
slice_name: 'ChartyChart',
changed_on_utc: '24 Feb 2014 10:13:14',
url: '/fakeUrl/explore',
id: '4',
table: {},
},
],
});
fetchMock.get(dashboardsEndpoint, {
result: [
{
dashboard_title: 'Dashboard_Test',
changed_on_utc: '24 Feb 2014 10:13:14',
url: '/fakeUrl/dashboard',
id: '3',
},
],
});
fetchMock.get(savedQueryEndpoint, {
result: [],
});
fetchMock.get(recentActivityEndpoint, {
Created: [],
Viewed: [],
});
fetchMock.get(chartInfoEndpoint, {
permissions: [],
});
fetchMock.get(chartFavoriteStatusEndpoint, {
result: [],
});
fetchMock.get(dashboardInfoEndpoint, {
permissions: [],
});
fetchMock.get(dashboardFavoriteStatusEndpoint, {
result: [],
});
fetchMock.get(savedQueryInfoEndpoint, {
permissions: [],
});
const mockedProps = {
user: {
username: 'alpha',
firstName: 'alpha',
lastName: 'alpha',
createdOn: '2016-11-11T12:34:17',
userId: 5,
email: '[email protected]',
isActive: true,
isAnonymous: false,
permissions: {},
roles: {
sql_lab: [['can_read', 'SavedQuery']],
},
},
};
describe('Welcome with sql role', () => {
let wrapper: ReactWrapper;
beforeAll(async () => {
await act(async () => {
wrapper = mount(
<Provider store={store}>
<Welcome {...mockedProps} />
</Provider>,
);
});
});
afterAll(() => {
fetchMock.resetHistory();
});
it('renders', () => {
expect(wrapper).toExist();
});
it('renders all panels on the page on page load', () => {
expect(wrapper.find('CollapsePanel')).toHaveLength(8);
});
it('calls api methods in parallel on page load', () => {
const chartCall = fetchMock.calls(/chart\/\?q/);
const savedQueryCall = fetchMock.calls(/saved_query\/\?q/);
const recentCall = fetchMock.calls(/api\/v1\/log\/recent_activity\/*/);
const dashboardCall = fetchMock.calls(/dashboard\/\?q/);
expect(chartCall).toHaveLength(2);
expect(recentCall).toHaveLength(1);
expect(savedQueryCall).toHaveLength(1);
expect(dashboardCall).toHaveLength(2);
});
});
describe('Welcome without sql role', () => {
let wrapper: ReactWrapper;
beforeAll(async () => {
await act(async () => {
const props = {
...mockedProps,
user: {
...mockedProps.user,
roles: {},
},
};
wrapper = mount(
<Provider store={store}>
<Welcome {...props} />
</Provider>,
);
});
});
afterAll(() => {
fetchMock.resetHistory();
});
it('renders', () => {
expect(wrapper).toExist();
});
it('renders all panels on the page on page load', () => {
expect(wrapper.find('CollapsePanel')).toHaveLength(6);
});
it('calls api methods in parallel on page load', () => {
const chartCall = fetchMock.calls(/chart\/\?q/);
const savedQueryCall = fetchMock.calls(/saved_query\/\?q/);
const recentCall = fetchMock.calls(/api\/v1\/log\/recent_activity\/*/);
const dashboardCall = fetchMock.calls(/dashboard\/\?q/);
expect(chartCall).toHaveLength(2);
expect(recentCall).toHaveLength(1);
expect(savedQueryCall).toHaveLength(0);
expect(dashboardCall).toHaveLength(2);
});
});
async function mountAndWait(props = mockedProps) {
const wrapper = mount(
<Provider store={store}>
<Welcome {...props} />
</Provider>,
);
await waitForComponentToPaint(wrapper);
return wrapper;
}
describe('Welcome page with toggle switch', () => {
let wrapper: ReactWrapper;
let isFeatureEnabledMock: any;
beforeAll(async () => {
isFeatureEnabledMock = jest
.spyOn(uiCore, 'isFeatureEnabled')
.mockReturnValue(true);
await act(async () => {
wrapper = await mountAndWait();
});
});
afterAll(() => {
isFeatureEnabledMock.restore();
});
it('shows a toggle button when feature flags is turned on', async () => {
await waitForComponentToPaint(wrapper);
expect(wrapper.find('Switch')).toExist();
});
it('does not show thumbnails when switch is off', async () => {
act(() => {
// @ts-ignore
wrapper.find('button[role="switch"]').props().onClick();
});
await waitForComponentToPaint(wrapper);
expect(wrapper.find('ImageLoader')).not.toExist();
});
});
test('should render an extension component if one is supplied', () => {
const extensionsRegistry = getExtensionsRegistry();
extensionsRegistry.set('welcome.banner', () => (
<>welcome.banner extension component</>
));
setupExtensions();
render(
<Provider store={store}>
<Welcome {...mockedProps} />
</Provider>,
);
expect(
screen.getByText('welcome.banner extension component'),
).toBeInTheDocument();
});
|
7,984 | 0 | petrpan-code/apache/superset/superset-frontend/src/pages | petrpan-code/apache/superset/superset-frontend/src/pages/Profile/Profile.test.tsx | /**
* 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 { Row, Col } from 'src/components';
import { shallow } from 'enzyme';
import Profile from 'src/pages/Profile';
import { user } from 'src/features/profile/fixtures';
describe('Profile', () => {
const mockedProps = {
user,
};
it('is valid', () => {
expect(React.isValidElement(<Profile {...mockedProps} />)).toBe(true);
});
it('renders 2 Col', () => {
const wrapper = shallow(<Profile {...mockedProps} />);
expect(wrapper.find(Row)).toExist();
expect(wrapper.find(Col)).toHaveLength(2);
});
it('renders 4 Tabs', () => {
const wrapper = shallow(<Profile {...mockedProps} />);
expect(wrapper.find('[tab]')).toHaveLength(4);
});
});
|
7,986 | 0 | petrpan-code/apache/superset/superset-frontend/src/pages | petrpan-code/apache/superset/superset-frontend/src/pages/QueryHistoryList/QueryHistoryList.test.tsx | /**
* 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 thunk from 'redux-thunk';
import configureStore from 'redux-mock-store';
import { Provider } from 'react-redux';
import fetchMock from 'fetch-mock';
import { act } from 'react-dom/test-utils';
import waitForComponentToPaint from 'spec/helpers/waitForComponentToPaint';
import { styledMount as mount } from 'spec/helpers/theming';
import QueryList from 'src/pages/QueryHistoryList';
import QueryPreviewModal from 'src/features/queries/QueryPreviewModal';
import { QueryObject } from 'src/views/CRUD/types';
import ListView from 'src/components/ListView';
import Filters from 'src/components/ListView/Filters';
import SyntaxHighlighter from 'react-syntax-highlighter/dist/cjs/light';
import SubMenu from 'src/features/home/SubMenu';
import { QueryState } from '@superset-ui/core';
// store needed for withToasts
const mockStore = configureStore([thunk]);
const store = mockStore({});
const queriesEndpoint = 'glob:*/api/v1/query/?*';
const mockQueries: QueryObject[] = [...new Array(3)].map((_, i) => ({
changed_on: new Date().toISOString(),
id: i,
slice_name: `cool chart ${i}`,
database: {
database_name: 'main db',
},
schema: 'public',
sql: `SELECT ${i} FROM table`,
executed_sql: `SELECT ${i} FROM table`,
sql_tables: [
{ schema: 'foo', table: 'table' },
{ schema: 'bar', table: 'table_2' },
],
status: QueryState.SUCCESS,
tab_name: 'Main Tab',
user: {
first_name: 'cool',
last_name: 'dude',
id: 2,
username: 'cooldude',
},
start_time: new Date().valueOf(),
end_time: new Date().valueOf(),
rows: 200,
tmp_table_name: '',
tracking_url: '',
}));
fetchMock.get(queriesEndpoint, {
result: mockQueries,
chart_count: 3,
});
fetchMock.get('glob:*/api/v1/query/related/user*', {
result: [],
count: 0,
});
fetchMock.get('glob:*/api/v1/query/related/database*', {
result: [],
count: 0,
});
fetchMock.get('glob:*/api/v1/query/disting/status*', {
result: [],
count: 0,
});
describe('QueryList', () => {
const mockedProps = {};
const wrapper = mount(
<Provider store={store}>
<QueryList {...mockedProps} />
</Provider>,
{
context: { store },
},
);
beforeAll(async () => {
await waitForComponentToPaint(wrapper);
});
it('renders', () => {
expect(wrapper.find(QueryList)).toExist();
});
it('renders a ListView', () => {
expect(wrapper.find(ListView)).toExist();
});
it('fetches data', () => {
wrapper.update();
const callsD = fetchMock.calls(/query\/\?q/);
expect(callsD).toHaveLength(1);
expect(callsD[0][0]).toMatchInlineSnapshot(
`"http://localhost/api/v1/query/?q=(order_column:start_time,order_direction:desc,page:0,page_size:25)"`,
);
});
it('renders a SyntaxHighlight', () => {
expect(wrapper.find(SyntaxHighlighter)).toExist();
});
it('opens a query preview', () => {
act(() => {
const props = wrapper
.find('[data-test="open-sql-preview-0"]')
.first()
.props();
if (props.onClick) props.onClick({} as React.MouseEvent);
});
wrapper.update();
expect(wrapper.find(QueryPreviewModal)).toExist();
});
it('searches', async () => {
const filtersWrapper = wrapper.find(Filters);
act(() => {
const props = filtersWrapper.find('[name="sql"]').first().props();
// @ts-ignore
if (props.onSubmit) props.onSubmit('fooo');
});
await waitForComponentToPaint(wrapper);
expect((fetchMock.lastCall() ?? [])[0]).toMatchInlineSnapshot(
`"http://localhost/api/v1/query/?q=(filters:!((col:sql,opr:ct,value:fooo)),order_column:start_time,order_direction:desc,page:0,page_size:25)"`,
);
});
it('renders a SubMenu', () => {
expect(wrapper.find(SubMenu)).toExist();
});
it('renders a SubMenu with Saved queries and Query History links', () => {
expect(wrapper.find(SubMenu).props().tabs).toEqual(
expect.arrayContaining([
expect.objectContaining({ label: 'Saved queries' }),
expect.objectContaining({ label: 'Query history' }),
]),
);
});
it('renders a SubMenu without Databases and Datasets links', () => {
expect(wrapper.find(SubMenu).props().tabs).not.toEqual(
expect.arrayContaining([
expect.objectContaining({ label: 'Databases' }),
expect.objectContaining({ label: 'Datasets' }),
]),
);
});
});
|
7,988 | 0 | petrpan-code/apache/superset/superset-frontend/src/pages | petrpan-code/apache/superset/superset-frontend/src/pages/RowLevelSecurityList/RowLevelSecurityList.test.tsx | /**
* 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 fetchMock from 'fetch-mock';
import { render, screen, within } from 'spec/helpers/testing-library';
import { act } from 'react-dom/test-utils';
import { MemoryRouter } from 'react-router-dom';
import { QueryParamProvider } from 'use-query-params';
import { styledMount as mount } from 'spec/helpers/theming';
import { Provider } from 'react-redux';
import configureStore from 'redux-mock-store';
import thunk from 'redux-thunk';
import waitForComponentToPaint from 'spec/helpers/waitForComponentToPaint';
import ListView from 'src/components/ListView/ListView';
import userEvent from '@testing-library/user-event';
import RowLevelSecurityList from '.';
const ruleListEndpoint = 'glob:*/api/v1/rowlevelsecurity/?*';
const ruleInfoEndpoint = 'glob:*/api/v1/rowlevelsecurity/_info*';
const mockRules = [
{
changed_on_delta_humanized: '1 days ago',
clause: '1=1',
description: 'some description',
filter_type: 'Regular',
group_key: 'group-1',
id: 1,
name: 'rule 1',
roles: [
{
id: 3,
name: 'Alpha',
},
{
id: 5,
name: 'Gamma',
},
],
tables: [
{
id: 6,
table_name: 'flights',
},
{
id: 13,
table_name: 'messages',
},
],
},
{
changed_on_delta_humanized: '2 days ago',
clause: '2=2',
description: 'some description 2',
filter_type: 'Base',
group_key: 'group-1',
id: 2,
name: 'rule 2',
roles: [
{
id: 3,
name: 'Alpha',
},
{
id: 5,
name: 'Gamma',
},
],
tables: [
{
id: 6,
table_name: 'flights',
},
{
id: 13,
table_name: 'messages',
},
],
},
];
fetchMock.get(ruleListEndpoint, { result: mockRules, count: 2 });
fetchMock.get(ruleInfoEndpoint, { permissions: ['can_read', 'can_write'] });
global.URL.createObjectURL = jest.fn();
const mockUser = {
userId: 1,
};
const mockedProps = {};
const mockStore = configureStore([thunk]);
const store = mockStore({});
describe('RulesList Enzyme', () => {
let wrapper: any;
beforeAll(async () => {
fetchMock.resetHistory();
wrapper = mount(
<MemoryRouter>
<Provider store={store}>
<RowLevelSecurityList {...mockedProps} user={mockUser} />
</Provider>
</MemoryRouter>,
);
await waitForComponentToPaint(wrapper);
});
it('renders', () => {
expect(wrapper.find(RowLevelSecurityList)).toExist();
});
it('renders a ListView', () => {
expect(wrapper.find(ListView)).toExist();
});
it('fetched data', () => {
// wrapper.update();
const apiCalls = fetchMock.calls(/rowlevelsecurity\/\?q/);
expect(apiCalls).toHaveLength(1);
expect(apiCalls[0][0]).toMatchInlineSnapshot(
`"http://localhost/api/v1/rowlevelsecurity/?q=(order_column:changed_on_delta_humanized,order_direction:desc,page:0,page_size:25)"`,
);
});
});
describe('RuleList RTL', () => {
async function renderAndWait() {
const mounted = act(async () => {
const mockedProps = {};
render(
<MemoryRouter>
<QueryParamProvider>
<RowLevelSecurityList {...mockedProps} user={mockUser} />
</QueryParamProvider>
</MemoryRouter>,
{ useRedux: true },
);
});
return mounted;
}
it('renders add rule button on empty state', async () => {
fetchMock.get(
ruleListEndpoint,
{ result: [], count: 0 },
{ overwriteRoutes: true },
);
await renderAndWait();
const emptyAddRuleButton = await screen.findByTestId('add-rule-empty');
expect(emptyAddRuleButton).toBeInTheDocument();
fetchMock.get(
ruleListEndpoint,
{ result: mockRules, count: 2 },
{ overwriteRoutes: true },
);
});
it('renders a "Rule" button to add a rule in bulk action', async () => {
await renderAndWait();
const addRuleButton = await screen.findByTestId('add-rule');
const emptyAddRuleButton = screen.queryByTestId('add-rule-empty');
expect(addRuleButton).toBeInTheDocument();
expect(emptyAddRuleButton).not.toBeInTheDocument();
});
it('renders filter options', async () => {
await renderAndWait();
const searchFilters = screen.queryAllByTestId('filters-search');
expect(searchFilters).toHaveLength(2);
const typeFilter = await screen.findByTestId('filters-select');
expect(typeFilter).toBeInTheDocument();
});
it('renders correct list columns', async () => {
await renderAndWait();
const table = screen.getByRole('table');
expect(table).toBeInTheDocument();
const nameColumn = await within(table).findByText('Name');
const fitlerTypeColumn = await within(table).findByText('Filter Type');
const groupKeyColumn = await within(table).findByText('Group Key');
const clauseColumn = await within(table).findByText('Clause');
const modifiedColumn = await within(table).findByText('Modified');
const actionsColumn = await within(table).findByText('Actions');
expect(nameColumn).toBeInTheDocument();
expect(fitlerTypeColumn).toBeInTheDocument();
expect(groupKeyColumn).toBeInTheDocument();
expect(clauseColumn).toBeInTheDocument();
expect(modifiedColumn).toBeInTheDocument();
expect(actionsColumn).toBeInTheDocument();
});
it('renders correct action buttons with write permission', async () => {
await renderAndWait();
const deleteActionIcon = screen.queryAllByTestId('rls-list-trash-icon');
expect(deleteActionIcon).toHaveLength(2);
const editActionIcon = screen.queryAllByTestId('edit-alt');
expect(editActionIcon).toHaveLength(2);
});
it('should not renders correct action buttons without write permission', async () => {
fetchMock.get(
ruleInfoEndpoint,
{ permissions: ['can_read'] },
{ overwriteRoutes: true },
);
await renderAndWait();
const deleteActionIcon = screen.queryByTestId('rls-list-trash-icon');
expect(deleteActionIcon).not.toBeInTheDocument();
const editActionIcon = screen.queryByTestId('edit-alt');
expect(editActionIcon).not.toBeInTheDocument();
fetchMock.get(
ruleInfoEndpoint,
{ permissions: ['can_read', 'can_write'] },
{ overwriteRoutes: true },
);
});
it('renders popover on new clicking rule button', async () => {
await renderAndWait();
const modal = screen.queryByTestId('rls-modal-title');
expect(modal).not.toBeInTheDocument();
const addRuleButton = await screen.findByTestId('add-rule');
userEvent.click(addRuleButton);
const modalAfterClick = screen.queryByTestId('rls-modal-title');
expect(modalAfterClick).toBeInTheDocument();
});
});
|
7,993 | 0 | petrpan-code/apache/superset/superset-frontend/src/pages | petrpan-code/apache/superset/superset-frontend/src/pages/SqlLab/SqlLab.test.tsx | /**
* 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 fetchMock from 'fetch-mock';
import React from 'react';
import { omit } from 'lodash';
import {
render,
act,
waitFor,
defaultStore as store,
createStore,
} from 'spec/helpers/testing-library';
import reducers from 'spec/helpers/reducerIndex';
import { api } from 'src/hooks/apiResources/queryApi';
import { DEFAULT_COMMON_BOOTSTRAP_DATA } from 'src/constants';
import getInitialState from 'src/SqlLab/reducers/getInitialState';
import SqlLab from '.';
const fakeApiResult = {
result: {
common: DEFAULT_COMMON_BOOTSTRAP_DATA,
tab_state_ids: [],
databases: [],
queries: {},
user: {
userId: 1,
username: 'some name',
isActive: true,
isAnonymous: false,
firstName: 'first name',
lastName: 'last name',
permissions: {},
roles: {},
},
},
};
const expectedResult = fakeApiResult.result;
const sqlLabInitialStateApiRoute = `glob:*/api/v1/sqllab/`;
afterEach(() => {
fetchMock.reset();
act(() => {
store.dispatch(api.util.resetApiState());
});
});
beforeEach(() => {
fetchMock.get(sqlLabInitialStateApiRoute, fakeApiResult);
});
jest.mock('src/SqlLab/components/App', () => () => (
<div data-test="mock-sqllab-app" />
));
test('is valid', () => {
expect(React.isValidElement(<SqlLab />)).toBe(true);
});
test('fetches initial data and renders', async () => {
expect(fetchMock.calls(sqlLabInitialStateApiRoute).length).toBe(0);
const storeWithSqlLab = createStore({}, reducers);
const { getByTestId } = render(<SqlLab />, {
useRedux: true,
useRouter: true,
store: storeWithSqlLab,
});
await waitFor(() =>
expect(fetchMock.calls(sqlLabInitialStateApiRoute).length).toBe(1),
);
expect(getByTestId('mock-sqllab-app')).toBeInTheDocument();
const { sqlLab } = getInitialState(expectedResult);
expect(storeWithSqlLab.getState()).toEqual(
expect.objectContaining({
sqlLab: expect.objectContaining(
omit(sqlLab, ['queriesLastUpdate', 'editorTabLastUpdatedAt']),
),
}),
);
});
|
8,024 | 0 | petrpan-code/apache/superset/superset-frontend/src | petrpan-code/apache/superset/superset-frontend/src/utils/cacheWrapper.test.ts | /**
* 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 { cacheWrapper } from 'src/utils/cacheWrapper';
describe('cacheWrapper', () => {
const fnResult = 'fnResult';
const fn = jest.fn<string, [number, number]>().mockReturnValue(fnResult);
let wrappedFn: (a: number, b: number) => string;
beforeEach(() => {
const cache = new Map<string, any>();
wrappedFn = cacheWrapper(fn, cache);
});
afterEach(() => {
jest.clearAllMocks();
});
it('calls fn with its arguments once when the key is not found', () => {
const returnedValue = wrappedFn(1, 2);
expect(returnedValue).toEqual(fnResult);
expect(fn).toBeCalledTimes(1);
expect(fn).toBeCalledWith(1, 2);
});
describe('subsequent calls', () => {
it('returns the correct value without fn being called multiple times', () => {
const returnedValue1 = wrappedFn(1, 2);
const returnedValue2 = wrappedFn(1, 2);
expect(returnedValue1).toEqual(fnResult);
expect(returnedValue2).toEqual(fnResult);
expect(fn).toBeCalledTimes(1);
});
it('fn is called multiple times for different arguments', () => {
wrappedFn(1, 2);
wrappedFn(1, 3);
expect(fn).toBeCalledTimes(2);
});
});
describe('with custom keyFn', () => {
let cache: Map<string, any>;
beforeEach(() => {
cache = new Map<string, any>();
wrappedFn = cacheWrapper(fn, cache, (...args) => `key-${args[0]}`);
});
it('saves fn result in cache under generated key', () => {
wrappedFn(1, 2);
expect(cache.get('key-1')).toEqual(fnResult);
});
it('subsequent calls with same generated key calls fn once, even if other arguments have changed', () => {
wrappedFn(1, 1);
wrappedFn(1, 2);
wrappedFn(1, 3);
expect(fn).toBeCalledTimes(1);
});
});
});
|
8,037 | 0 | petrpan-code/apache/superset/superset-frontend/src | petrpan-code/apache/superset/superset-frontend/src/utils/findPermission.test.ts | /**
* 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 { findPermission } from './findPermission';
test('findPermission for single role', () => {
expect(findPermission('abc', 'def', { role: [['abc', 'def']] })).toEqual(
true,
);
expect(findPermission('abc', 'def', { role: [['abc', 'de']] })).toEqual(
false,
);
expect(findPermission('abc', 'def', { role: [] })).toEqual(false);
});
test('findPermission for multiple roles', () => {
expect(
findPermission('abc', 'def', {
role1: [
['ccc', 'aaa'],
['abc', 'def'],
],
role2: [['abc', 'def']],
}),
).toEqual(true);
expect(
findPermission('abc', 'def', {
role1: [['abc', 'def']],
role2: [['abc', 'dd']],
}),
).toEqual(true);
expect(
findPermission('abc', 'def', {
role1: [['ccc', 'aaa']],
role2: [['aaa', 'ddd']],
}),
).toEqual(false);
expect(findPermission('abc', 'def', { role1: [], role2: [] })).toEqual(false);
});
test('handles nonexistent roles', () => {
expect(findPermission('abc', 'def', null)).toEqual(false);
});
|
8,042 | 0 | petrpan-code/apache/superset/superset-frontend/src | petrpan-code/apache/superset/superset-frontend/src/utils/getClientErrorObject.test.ts | /**
* 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 { ErrorTypeEnum } from 'src/components/ErrorMessage/types';
import { getClientErrorObject } from 'src/utils/getClientErrorObject';
describe('getClientErrorObject()', () => {
it('Returns a Promise', () => {
const response = getClientErrorObject('error');
expect(response instanceof Promise).toBe(true);
});
it('Returns a Promise that resolves to an object with an error key', () => {
const error = 'error';
return getClientErrorObject(error).then(errorObj => {
expect(errorObj).toMatchObject({ error });
});
});
it('Handles Response that can be parsed as json', () => {
const jsonError = { something: 'something', error: 'Error message' };
const jsonErrorString = JSON.stringify(jsonError);
return getClientErrorObject(new Response(jsonErrorString)).then(
errorObj => {
expect(errorObj).toMatchObject(jsonError);
},
);
});
it('Handles backwards compatibility between old error messages and the new SIP-40 errors format', () => {
const jsonError = {
errors: [
{
error_type: ErrorTypeEnum.GENERIC_DB_ENGINE_ERROR,
extra: { engine: 'presto', link: 'https://www.google.com' },
level: 'error',
message: 'presto error: test error',
},
],
};
const jsonErrorString = JSON.stringify(jsonError);
return getClientErrorObject(new Response(jsonErrorString)).then(
errorObj => {
expect(errorObj.error).toEqual(jsonError.errors[0].message);
expect(errorObj.link).toEqual(jsonError.errors[0].extra.link);
},
);
});
it('Handles Response that can be parsed as text', () => {
const textError = 'Hello I am a text error';
return getClientErrorObject(new Response(textError)).then(errorObj => {
expect(errorObj).toMatchObject({ error: textError });
});
});
it('Handles plain text as input', () => {
const error = 'error';
return getClientErrorObject(error).then(errorObj => {
expect(errorObj).toMatchObject({ error });
});
});
});
|
8,046 | 0 | petrpan-code/apache/superset/superset-frontend/src | petrpan-code/apache/superset/superset-frontend/src/utils/getDatasourceUid.test.ts | /**
* 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 { DatasourceType } from '@superset-ui/core';
import { getDatasourceUid } from './getDatasourceUid';
const TEST_DATASOURCE = {
id: 2,
type: DatasourceType.Table,
columns: [],
metrics: [],
column_formats: {},
currency_formats: {},
verbose_map: {},
main_dttm_col: '__timestamp',
// eg. ['["ds", true]', 'ds [asc]']
datasource_name: 'test datasource',
description: null,
};
const TEST_DATASOURCE_WITH_UID = {
...TEST_DATASOURCE,
uid: 'dataset_uid',
};
test('creates uid from id and type when dataset does not have uid field', () => {
expect(getDatasourceUid(TEST_DATASOURCE)).toEqual('2__table');
});
test('returns uid when dataset has uid field', () => {
expect(getDatasourceUid(TEST_DATASOURCE_WITH_UID)).toEqual(
TEST_DATASOURCE_WITH_UID.uid,
);
});
|
8,051 | 0 | petrpan-code/apache/superset/superset-frontend/src | petrpan-code/apache/superset/superset-frontend/src/utils/localStorageHelpers.test.ts | /**
* 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 {
getItem,
setItem,
LocalStorageKeys,
} from 'src/utils/localStorageHelpers';
describe('localStorageHelpers', () => {
beforeEach(() => {
localStorage.clear();
});
afterAll(() => {
localStorage.clear();
});
it('gets a value that was set', () => {
setItem(LocalStorageKeys.is_datapanel_open, false);
expect(getItem(LocalStorageKeys.is_datapanel_open, true)).toBe(false);
});
it('returns the default value for an unset value', () => {
expect(getItem(LocalStorageKeys.is_datapanel_open, true)).toBe(true);
});
});
|
8,053 | 0 | petrpan-code/apache/superset/superset-frontend/src | petrpan-code/apache/superset/superset-frontend/src/utils/parseCookie.test.ts | /**
* 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 parseCookie from 'src/utils/parseCookie';
describe('parseCookie', () => {
let cookieVal = '';
Object.defineProperty(document, 'cookie', {
get: jest.fn().mockImplementation(() => cookieVal),
});
it('parses cookie strings', () => {
cookieVal = 'val1=foo; val2=bar';
expect(parseCookie()).toEqual({ val1: 'foo', val2: 'bar' });
});
it('parses empty cookie strings', () => {
cookieVal = '';
expect(parseCookie()).toEqual({});
});
it('accepts an arg', () => {
expect(parseCookie('val=foo')).toEqual({ val: 'foo' });
});
});
|
8,055 | 0 | petrpan-code/apache/superset/superset-frontend/src | petrpan-code/apache/superset/superset-frontend/src/utils/rankedSearchCompare.test.ts | /**
* 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 { rankedSearchCompare } from './rankedSearchCompare';
const searchSort = (search: string) => (a: string, b: string) =>
rankedSearchCompare(a, b, search);
test('Sort exact match first', async () => {
expect(['abc', 'bc', 'bcd', 'cbc'].sort(searchSort('bc'))).toEqual([
'bc',
'bcd',
'abc',
'cbc',
]);
});
test('Sort starts with first', async () => {
expect(['her', 'Cher', 'Her', 'Hermon'].sort(searchSort('Her'))).toEqual([
'Her',
'Hermon',
'her',
'Cher',
]);
expect(
['abc', 'ab', 'aaabc', 'bbabc', 'BBabc'].sort(searchSort('abc')),
).toEqual(['abc', 'aaabc', 'bbabc', 'BBabc', 'ab']);
});
test('Sort same case first', async () => {
expect(['%f %B', '%F %b'].sort(searchSort('%F'))).toEqual(['%F %b', '%f %B']);
});
|
8,058 | 0 | petrpan-code/apache/superset/superset-frontend/src | petrpan-code/apache/superset/superset-frontend/src/utils/safeStringify.test.ts | /**
* 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 { safeStringify } from 'src/utils/safeStringify';
class Noise {
public next?: Noise;
}
describe('Stringify utility testing', () => {
it('correctly parses a simple object just like JSON', () => {
const noncircular = {
b: 'foo',
c: 'bar',
d: [
{
e: 'hello',
f: ['world'],
},
{
e: 'hello',
f: ['darkness', 'my', 'old', 'friend'],
},
],
};
expect(safeStringify(noncircular)).toEqual(JSON.stringify(noncircular));
// Checking that it works with quick-deepish-copies as well.
expect(JSON.parse(safeStringify(noncircular))).toEqual(
JSON.parse(JSON.stringify(noncircular)),
);
});
it('handles simple circular json as expected', () => {
const ping = new Noise();
const pong = new Noise();
const pang = new Noise();
ping.next = pong;
pong.next = ping;
// ping.next is pong (the circular reference) now
const safeString = safeStringify(ping);
ping.next = pang;
// ping.next is pang now, which has no circular reference, so it's safe to use JSON.stringify
const ordinaryString = JSON.stringify(ping);
expect(safeString).toEqual(ordinaryString);
});
it('creates a parseable object even when the input is circular', () => {
const ping = new Noise();
const pong = new Noise();
ping.next = pong;
pong.next = ping;
const newNoise: Noise = JSON.parse(safeStringify(ping));
expect(newNoise).toBeTruthy();
expect(newNoise.next).toEqual({});
});
it('does not remove noncircular duplicates', () => {
const a = {
foo: 'bar',
};
const repeating = {
first: a,
second: a,
third: a,
};
expect(safeStringify(repeating)).toEqual(JSON.stringify(repeating));
});
it('does not remove nodes with empty objects', () => {
const emptyObjectValues = {
a: {},
b: 'foo',
c: {
d: 'good data here',
e: {},
},
};
expect(safeStringify(emptyObjectValues)).toEqual(
JSON.stringify(emptyObjectValues),
);
});
it('does not remove nested same keys', () => {
const nestedKeys = {
a: 'b',
c: {
a: 'd',
x: 'y',
},
};
expect(safeStringify(nestedKeys)).toEqual(JSON.stringify(nestedKeys));
});
});
|
8,061 | 0 | petrpan-code/apache/superset/superset-frontend/src | petrpan-code/apache/superset/superset-frontend/src/utils/sortNumericValues.test.ts | /**
* 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 sortNumericValues from './sortNumericValues';
test('should always sort null and NaNs to bottom', () => {
expect([null, 1, 2, '1', '5', NaN].sort(sortNumericValues)).toEqual([
1,
'1',
2,
'5',
NaN,
null,
]);
expect(
[null, 1, 2, '1', '5', NaN].sort((a, b) =>
sortNumericValues(a, b, { descending: true }),
),
).toEqual(['5', 2, 1, '1', NaN, null]);
});
test('should treat null and NaN as smallest numbers', () => {
expect(
[null, 1, 2, '1', '5', NaN].sort((a, b) =>
sortNumericValues(a, b, { nanTreatment: 'asSmallest' }),
),
).toEqual([null, NaN, 1, '1', 2, '5']);
expect(
[null, 1, 2, '1', '5', NaN].sort((a, b) =>
sortNumericValues(a, b, { nanTreatment: 'asSmallest', descending: true }),
),
).toEqual(['5', 2, 1, '1', NaN, null]);
});
test('should treat null and NaN as largest numbers', () => {
expect(
[null, 1, 2, '1', '5', NaN].sort((a, b) =>
sortNumericValues(a, b, { nanTreatment: 'asLargest' }),
),
).toEqual([1, '1', 2, '5', NaN, null]);
expect(
[null, 1, 2, '1', '5', NaN].sort((a, b) =>
sortNumericValues(a, b, { nanTreatment: 'asLargest', descending: true }),
),
).toEqual([null, NaN, '5', 2, 1, '1']);
});
|
8,063 | 0 | petrpan-code/apache/superset/superset-frontend/src | petrpan-code/apache/superset/superset-frontend/src/utils/testUtils.test.ts | /**
* 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 { testWithId } from './testUtils';
describe('testUtils', () => {
it('testWithId with prefix only', () => {
expect(testWithId('prefix')()).toEqual({ 'data-test': 'prefix' });
});
it('testWithId with prefix only and idOnly', () => {
expect(testWithId('prefix', true)()).toEqual('prefix');
});
it('testWithId with id only', () => {
expect(testWithId()('id')).toEqual({ 'data-test': 'id' });
});
it('testWithId with id only and idOnly', () => {
expect(testWithId(undefined, true)('id')).toEqual('id');
});
it('testWithId with prefix and id', () => {
expect(testWithId('prefix')('id')).toEqual({ 'data-test': 'prefix__id' });
});
it('testWithId with prefix and id and idOnly', () => {
expect(testWithId('prefix', true)('id')).toEqual('prefix__id');
});
it('testWithId without prefix and id', () => {
expect(testWithId()()).toEqual({ 'data-test': '' });
});
it('testWithId without prefix and id and idOnly', () => {
expect(testWithId(undefined, true)()).toEqual('');
});
});
|
8,066 | 0 | petrpan-code/apache/superset/superset-frontend/src | petrpan-code/apache/superset/superset-frontend/src/utils/urlUtils.test.ts | /**
* 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 { isUrlExternal, parseUrl } from './urlUtils';
test('isUrlExternal', () => {
expect(isUrlExternal('http://google.com')).toBeTruthy();
expect(isUrlExternal('https://google.com')).toBeTruthy();
expect(isUrlExternal('//google.com')).toBeTruthy();
expect(isUrlExternal('google.com')).toBeTruthy();
expect(isUrlExternal('www.google.com')).toBeTruthy();
expect(isUrlExternal('mailto:[email protected]')).toBeTruthy();
// treat all urls starting with protocol or hostname as external
// such urls are not handled well by react-router Link component
expect(isUrlExternal('http://localhost:8888/port')).toBeTruthy();
expect(isUrlExternal('https://localhost/secure')).toBeTruthy();
expect(isUrlExternal('http://localhost/about')).toBeTruthy();
expect(isUrlExternal('HTTP://localhost/about')).toBeTruthy();
expect(isUrlExternal('//localhost/about')).toBeTruthy();
expect(isUrlExternal('localhost/about')).toBeTruthy();
expect(isUrlExternal('/about')).toBeFalsy();
expect(isUrlExternal('#anchor')).toBeFalsy();
});
test('parseUrl', () => {
expect(parseUrl('http://google.com')).toEqual('http://google.com');
expect(parseUrl('//google.com')).toEqual('//google.com');
expect(parseUrl('mailto:[email protected]')).toEqual(
'mailto:[email protected]',
);
expect(parseUrl('google.com')).toEqual('//google.com');
expect(parseUrl('www.google.com')).toEqual('//www.google.com');
expect(parseUrl('/about')).toEqual('/about');
expect(parseUrl('#anchor')).toEqual('#anchor');
});
|
8,073 | 0 | petrpan-code/apache/superset/superset-frontend/src | petrpan-code/apache/superset/superset-frontend/src/views/routes.test.tsx | /**
* 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 { isFrontendRoute, routes } from './routes';
jest.mock('src/pages/Home', () => () => <div data-test="mock-home" />);
describe('isFrontendRoute', () => {
it('returns true if a route matches', () => {
routes.forEach(r => {
expect(isFrontendRoute(r.path)).toBe(true);
});
});
it('returns false if a route does not match', () => {
expect(isFrontendRoute('/non-existent/path/')).toBe(false);
});
});
|
8,079 | 0 | petrpan-code/apache/superset/superset-frontend/src/views | petrpan-code/apache/superset/superset-frontend/src/views/CRUD/utils.test.tsx | /**
* 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 rison from 'rison';
import {
checkUploadExtensions,
getAlreadyExists,
getFilterValues,
getPasswordsNeeded,
getSSHPasswordsNeeded,
getSSHPrivateKeysNeeded,
getSSHPrivateKeyPasswordsNeeded,
hasTerminalValidation,
isAlreadyExists,
isNeedsPassword,
isNeedsSSHPassword,
isNeedsSSHPrivateKey,
isNeedsSSHPrivateKeyPassword,
} from 'src/views/CRUD/utils';
import { User } from 'src/types/bootstrapTypes';
import { WelcomeTable } from 'src/features/home/types';
import { Filter, TableTab } from './types';
const terminalErrors = {
errors: [
{
message: 'Error importing database',
error_type: 'GENERIC_COMMAND_ERROR',
level: 'warning',
extra: {
'metadata.yaml': { type: ['Must be equal to Database.'] },
issue_codes: [
{
code: 1010,
message:
'Issue 1010 - Superset encountered an error while running a command.',
},
],
},
},
],
};
const terminalErrorsWithOnlyIssuesCode = {
errors: [
{
message: 'Error importing database',
error_type: 'GENERIC_COMMAND_ERROR',
level: 'warning',
extra: {
issue_codes: [
{
code: 1010,
message:
'Issue 1010 - Superset encountered an error while running a command.',
},
],
},
},
],
};
const overwriteNeededErrors = {
errors: [
{
message: 'Error importing database',
error_type: 'GENERIC_COMMAND_ERROR',
level: 'warning',
extra: {
'databases/imported_database.yaml':
'Database already exists and `overwrite=true` was not passed',
issue_codes: [
{
code: 1010,
message:
'Issue 1010 - Superset encountered an error while running a command.',
},
],
},
},
],
};
const passwordNeededErrors = {
errors: [
{
message: 'Error importing database',
error_type: 'GENERIC_COMMAND_ERROR',
level: 'warning',
extra: {
'databases/imported_database.yaml': {
_schema: ['Must provide a password for the database'],
},
issue_codes: [
{
code: 1010,
message:
'Issue 1010 - Superset encountered an error while running a command.',
},
],
},
},
],
};
const sshTunnelPasswordNeededErrors = {
errors: [
{
message: 'Error importing database',
error_type: 'GENERIC_COMMAND_ERROR',
level: 'warning',
extra: {
'databases/imported_database.yaml': {
_schema: ['Must provide a password for the ssh tunnel'],
},
issue_codes: [
{
code: 1010,
message:
'Issue 1010 - Superset encountered an error while running a command.',
},
],
},
},
],
};
const sshTunnelPrivateKeyNeededErrors = {
errors: [
{
message: 'Error importing database',
error_type: 'GENERIC_COMMAND_ERROR',
level: 'warning',
extra: {
'databases/imported_database.yaml': {
_schema: ['Must provide a private key for the ssh tunnel'],
},
issue_codes: [
{
code: 1010,
message:
'Issue 1010 - Superset encountered an error while running a command.',
},
],
},
},
],
};
const sshTunnelPrivateKeyPasswordNeededErrors = {
errors: [
{
message: 'Error importing database',
error_type: 'GENERIC_COMMAND_ERROR',
level: 'warning',
extra: {
'databases/imported_database.yaml': {
_schema: ['Must provide a private key password for the ssh tunnel'],
},
issue_codes: [
{
code: 1010,
message:
'Issue 1010 - Superset encountered an error while running a command.',
},
],
},
},
],
};
test('identifies error payloads indicating that password is needed', () => {
let needsPassword;
needsPassword = isNeedsPassword({
_schema: ['Must provide a password for the database'],
});
expect(needsPassword).toBe(true);
needsPassword = isNeedsPassword(
'Database already exists and `overwrite=true` was not passed',
);
expect(needsPassword).toBe(false);
needsPassword = isNeedsPassword({ type: ['Must be equal to Database.'] });
expect(needsPassword).toBe(false);
});
test('identifies error payloads indicating that ssh_tunnel password is needed', () => {
let needsSSHTunnelPassword;
needsSSHTunnelPassword = isNeedsSSHPassword({
_schema: ['Must provide a password for the ssh tunnel'],
});
expect(needsSSHTunnelPassword).toBe(true);
needsSSHTunnelPassword = isNeedsSSHPassword(
'Database already exists and `overwrite=true` was not passed',
);
expect(needsSSHTunnelPassword).toBe(false);
needsSSHTunnelPassword = isNeedsSSHPassword({
type: ['Must be equal to Database.'],
});
expect(needsSSHTunnelPassword).toBe(false);
});
test('identifies error payloads indicating that ssh_tunnel private_key is needed', () => {
let needsSSHTunnelPrivateKey;
needsSSHTunnelPrivateKey = isNeedsSSHPrivateKey({
_schema: ['Must provide a private key for the ssh tunnel'],
});
expect(needsSSHTunnelPrivateKey).toBe(true);
needsSSHTunnelPrivateKey = isNeedsSSHPrivateKey(
'Database already exists and `overwrite=true` was not passed',
);
expect(needsSSHTunnelPrivateKey).toBe(false);
needsSSHTunnelPrivateKey = isNeedsSSHPrivateKey({
type: ['Must be equal to Database.'],
});
expect(needsSSHTunnelPrivateKey).toBe(false);
});
test('identifies error payloads indicating that ssh_tunnel private_key_password is needed', () => {
let needsSSHTunnelPrivateKeyPassword;
needsSSHTunnelPrivateKeyPassword = isNeedsSSHPrivateKeyPassword({
_schema: ['Must provide a private key password for the ssh tunnel'],
});
expect(needsSSHTunnelPrivateKeyPassword).toBe(true);
needsSSHTunnelPrivateKeyPassword = isNeedsSSHPrivateKeyPassword(
'Database already exists and `overwrite=true` was not passed',
);
expect(needsSSHTunnelPrivateKeyPassword).toBe(false);
needsSSHTunnelPrivateKeyPassword = isNeedsSSHPrivateKeyPassword({
type: ['Must be equal to Database.'],
});
expect(needsSSHTunnelPrivateKeyPassword).toBe(false);
});
test('identifies error payloads indicating that overwrite confirmation is needed', () => {
let alreadyExists;
alreadyExists = isAlreadyExists(
'Database already exists and `overwrite=true` was not passed',
);
expect(alreadyExists).toBe(true);
alreadyExists = isAlreadyExists({
_schema: ['Must provide a password for the database'],
});
expect(alreadyExists).toBe(false);
alreadyExists = isAlreadyExists({ type: ['Must be equal to Database.'] });
expect(alreadyExists).toBe(false);
});
test('extracts DB configuration files that need passwords', () => {
const passwordsNeeded = getPasswordsNeeded(passwordNeededErrors.errors);
expect(passwordsNeeded).toEqual(['databases/imported_database.yaml']);
});
test('extracts DB configuration files that need ssh_tunnel passwords', () => {
const sshPasswordsNeeded = getSSHPasswordsNeeded(
sshTunnelPasswordNeededErrors.errors,
);
expect(sshPasswordsNeeded).toEqual(['databases/imported_database.yaml']);
});
test('extracts DB configuration files that need ssh_tunnel private_keys', () => {
const sshPrivateKeysNeeded = getSSHPrivateKeysNeeded(
sshTunnelPrivateKeyNeededErrors.errors,
);
expect(sshPrivateKeysNeeded).toEqual(['databases/imported_database.yaml']);
});
test('extracts DB configuration files that need ssh_tunnel private_key_passwords', () => {
const sshPrivateKeyPasswordsNeeded = getSSHPrivateKeyPasswordsNeeded(
sshTunnelPrivateKeyPasswordNeededErrors.errors,
);
expect(sshPrivateKeyPasswordsNeeded).toEqual([
'databases/imported_database.yaml',
]);
});
test('extracts files that need overwrite confirmation', () => {
const alreadyExists = getAlreadyExists(overwriteNeededErrors.errors);
expect(alreadyExists).toEqual(['databases/imported_database.yaml']);
});
test('detects if the error message is terminal or if it requires uses intervention', () => {
let isTerminal;
isTerminal = hasTerminalValidation(terminalErrors.errors);
expect(isTerminal).toBe(true);
isTerminal = hasTerminalValidation(overwriteNeededErrors.errors);
expect(isTerminal).toBe(false);
isTerminal = hasTerminalValidation(passwordNeededErrors.errors);
expect(isTerminal).toBe(false);
isTerminal = hasTerminalValidation(sshTunnelPasswordNeededErrors.errors);
expect(isTerminal).toBe(false);
isTerminal = hasTerminalValidation(sshTunnelPrivateKeyNeededErrors.errors);
expect(isTerminal).toBe(false);
isTerminal = hasTerminalValidation(
sshTunnelPrivateKeyPasswordNeededErrors.errors,
);
expect(isTerminal).toBe(false);
});
test('error message is terminal when the "extra" field contains only the "issue_codes" key', () => {
expect(hasTerminalValidation(terminalErrorsWithOnlyIssuesCode.errors)).toBe(
true,
);
});
test('does not ask for password when the import type is wrong', () => {
const error = {
errors: [
{
message: 'Error importing database',
error_type: 'GENERIC_COMMAND_ERROR',
level: 'warning',
extra: {
'metadata.yaml': {
type: ['Must be equal to Database.'],
},
'databases/examples.yaml': {
_schema: ['Must provide a password for the database'],
},
issue_codes: [
{
code: 1010,
message:
'Issue 1010 - Superset encountered an error while running a command.',
},
],
},
},
],
};
expect(hasTerminalValidation(error.errors)).toBe(true);
});
test('successfully modified rison to encode correctly', () => {
const problemCharacters = '& # ? ^ { } [ ] | " = + `';
problemCharacters.split(' ').forEach(char => {
const testObject = { test: char };
const actualEncoding = rison.encode(testObject);
const expectedEncoding = `(test:'${char}')`; // Ex: (test:'&')
expect(actualEncoding).toEqual(expectedEncoding);
expect(rison.decode(actualEncoding)).toEqual(testObject);
});
});
test('checkUploadExtensions should return valid upload extensions', () => {
const uploadExtensionTest = ['a', 'b', 'c'];
const randomExtension = ['a', 'c'];
const randomExtensionTwo = ['c'];
const randomExtensionThree: Array<any> = [];
expect(
checkUploadExtensions(randomExtension, uploadExtensionTest),
).toBeTruthy();
expect(
checkUploadExtensions(randomExtensionTwo, uploadExtensionTest),
).toBeTruthy();
expect(
checkUploadExtensions(randomExtensionThree, uploadExtensionTest),
).toBeFalsy();
});
test('getFilterValues', () => {
const userId = 1234;
const mockUser: User = {
firstName: 'foo',
lastName: 'bar',
username: 'baz',
userId,
isActive: true,
isAnonymous: false,
};
const testCases: [
TableTab,
WelcomeTable,
User | undefined,
Filter[] | undefined,
ReturnType<typeof getFilterValues>,
][] = [
[
TableTab.Mine,
WelcomeTable.SavedQueries,
mockUser,
undefined,
[
{
id: 'created_by',
operator: 'rel_o_m',
value: `${userId}`,
},
],
],
[
TableTab.Favorite,
WelcomeTable.SavedQueries,
mockUser,
undefined,
[
{
id: 'id',
operator: 'saved_query_is_fav',
value: true,
},
],
],
[
TableTab.Created,
WelcomeTable.Charts,
mockUser,
undefined,
[
{
id: 'created_by',
operator: 'rel_o_m',
value: `${userId}`,
},
],
],
[
TableTab.Created,
WelcomeTable.Dashboards,
mockUser,
undefined,
[
{
id: 'created_by',
operator: 'rel_o_m',
value: `${userId}`,
},
],
],
[
TableTab.Created,
WelcomeTable.Recents,
mockUser,
undefined,
[
{
id: 'created_by',
operator: 'rel_o_m',
value: `${userId}`,
},
],
],
[
TableTab.Mine,
WelcomeTable.Charts,
mockUser,
undefined,
[
{
id: 'owners',
operator: 'rel_m_m',
value: `${userId}`,
},
],
],
[
TableTab.Mine,
WelcomeTable.Dashboards,
mockUser,
undefined,
[
{
id: 'owners',
operator: 'rel_m_m',
value: `${userId}`,
},
],
],
[
TableTab.Favorite,
WelcomeTable.Dashboards,
mockUser,
undefined,
[
{
id: 'id',
operator: 'dashboard_is_favorite',
value: true,
},
],
],
[
TableTab.Favorite,
WelcomeTable.Charts,
mockUser,
undefined,
[
{
id: 'id',
operator: 'chart_is_favorite',
value: true,
},
],
],
[
TableTab.Other,
WelcomeTable.Charts,
mockUser,
[
{
col: 'created_by',
opr: 'rel_o_m',
value: 0,
},
],
[
{
id: 'created_by',
operator: 'rel_o_m',
value: 0,
},
],
],
];
testCases.forEach(testCase => {
const [tab, welcomeTable, user, otherTabFilters, expectedValue] = testCase;
expect(getFilterValues(tab, welcomeTable, user, otherTabFilters)).toEqual(
expectedValue,
);
});
});
|
8,119 | 0 | petrpan-code/apache/superset/superset-websocket | petrpan-code/apache/superset/superset-websocket/spec/config.test.ts | /**
* 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 { buildConfig } from '../src/config';
test('buildConfig() builds configuration and applies env var overrides', () => {
let config = buildConfig();
expect(config.jwtSecret).toEqual(
'test123-test123-test123-test123-test123-test123-test123',
);
expect(config.redis.host).toEqual('127.0.0.1');
expect(config.redis.port).toEqual(6379);
expect(config.redis.password).toEqual('some pwd');
expect(config.redis.db).toEqual(10);
expect(config.redis.ssl).toEqual(false);
expect(config.statsd.host).toEqual('127.0.0.1');
expect(config.statsd.port).toEqual(8125);
expect(config.statsd.globalTags).toEqual([]);
process.env.JWT_SECRET = 'aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa';
process.env.REDIS_HOST = '10.10.10.10';
process.env.REDIS_PORT = '6380';
process.env.REDIS_PASSWORD = 'admin';
process.env.REDIS_DB = '4';
process.env.REDIS_SSL = 'true';
process.env.STATSD_HOST = '15.15.15.15';
process.env.STATSD_PORT = '8000';
process.env.STATSD_GLOBAL_TAGS = 'tag-1,tag-2';
config = buildConfig();
expect(config.jwtSecret).toEqual('aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa');
expect(config.redis.host).toEqual('10.10.10.10');
expect(config.redis.port).toEqual(6380);
expect(config.redis.password).toEqual('admin');
expect(config.redis.db).toEqual(4);
expect(config.redis.ssl).toEqual(true);
expect(config.statsd.host).toEqual('15.15.15.15');
expect(config.statsd.port).toEqual(8000);
expect(config.statsd.globalTags).toEqual(['tag-1', 'tag-2']);
delete process.env.JWT_SECRET;
delete process.env.REDIS_HOST;
delete process.env.REDIS_PORT;
delete process.env.REDIS_PASSWORD;
delete process.env.REDIS_DB;
delete process.env.REDIS_SSL;
delete process.env.STATSD_HOST;
delete process.env.STATSD_PORT;
delete process.env.STATSD_GLOBAL_TAGS;
});
test('buildConfig() performs deep merge between configs', () => {
const config = buildConfig();
// We left the ssl setting the default
expect(config.redis.ssl).toEqual(false);
// We overrode the pwd
expect(config.redis.password).toEqual('some pwd');
});
|
8,120 | 0 | petrpan-code/apache/superset/superset-websocket | petrpan-code/apache/superset/superset-websocket/spec/index.test.ts | /**
* 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.
*/
const jwt = require('jsonwebtoken');
const config = require('../config.test.json');
import { describe, expect, test, beforeEach, afterEach } from '@jest/globals';
import * as http from 'http';
import * as net from 'net';
import { WebSocket } from 'ws';
// NOTE: these mock variables needs to start with "mock" due to
// calls to `jest.mock` being hoisted to the top of the file.
// https://jestjs.io/docs/es6-class-mocks#calling-jestmock-with-the-module-factory-parameter
const mockRedisXrange = jest.fn();
jest.mock('ws');
jest.mock('ioredis', () => {
return jest.fn().mockImplementation(() => {
return { xrange: mockRedisXrange };
});
});
const wsMock = WebSocket as jest.Mocked<typeof WebSocket>;
const channelId = 'bc9e040c-7b4a-4817-99b9-292832d97ec7';
const streamReturnValue: server.StreamResult[] = [
[
'1615426152415-0',
[
'data',
`{"channel_id": "${channelId}", "job_id": "c9b99965-8f1e-4ce5-aa43-d6fc94d6a510", "user_id": "1", "status": "done", "errors": [], "result_url": "/superset/explore_json/data/ejr-37281682b1282cdb8f25e0de0339b386"}`,
],
],
[
'1615426152516-0',
[
'data',
`{"channel_id": "${channelId}", "job_id": "f1e5bb1f-f2f1-4f21-9b2f-c9b91dcc9b59", "user_id": "1", "status": "done", "errors": [], "result_url": "/api/v1/chart/data/qc-64e8452dc9907dd77746cb75a19202de"}`,
],
],
];
import * as server from '../src/index';
import { statsd } from '../src/index';
describe('server', () => {
let statsdIncrementMock: jest.SpyInstance;
beforeEach(() => {
mockRedisXrange.mockClear();
server.resetState();
statsdIncrementMock = jest.spyOn(statsd, 'increment').mockReturnValue();
});
afterEach(() => {
statsdIncrementMock.mockRestore();
});
describe('HTTP requests', () => {
test('services health checks', () => {
const endMock = jest.fn();
const writeHeadMock = jest.fn();
const request = {
url: '/health',
method: 'GET',
headers: {
host: 'example.com',
},
};
const response = {
writeHead: writeHeadMock,
end: endMock,
};
server.httpRequest(request as any, response as any);
expect(writeHeadMock).toBeCalledTimes(1);
expect(writeHeadMock).toHaveBeenLastCalledWith(200);
expect(endMock).toBeCalledTimes(1);
expect(endMock).toHaveBeenLastCalledWith('OK');
});
test('responds with a 404 when not found', () => {
const endMock = jest.fn();
const writeHeadMock = jest.fn();
const request = {
url: '/unsupported',
method: 'GET',
headers: {
host: 'example.com',
},
};
const response = {
writeHead: writeHeadMock,
end: endMock,
};
server.httpRequest(request as any, response as any);
expect(writeHeadMock).toBeCalledTimes(1);
expect(writeHeadMock).toHaveBeenLastCalledWith(404);
expect(endMock).toBeCalledTimes(1);
expect(endMock).toHaveBeenLastCalledWith('Not Found');
});
});
describe('incrementId', () => {
test('it increments a valid Redis stream ID', () => {
expect(server.incrementId('1607477697866-0')).toEqual('1607477697866-1');
});
test('it handles an invalid Redis stream ID', () => {
expect(server.incrementId('foo')).toEqual('foo');
});
});
describe('redisUrlFromConfig', () => {
test('it builds a valid Redis URL from defaults', () => {
expect(
server.buildRedisOpts({
port: 6379,
host: '127.0.0.1',
username: 'test-user',
password: '',
db: 0,
ssl: false,
validateHostname: false,
}),
).toEqual({ db: 0, host: '127.0.0.1', port: 6379 });
});
test('it builds a valid Redis URL with a password', () => {
expect(
server.buildRedisOpts({
port: 6380,
host: 'redis.local',
username: 'cool-user',
password: 'foo',
db: 1,
ssl: false,
validateHostname: false,
}),
).toEqual({
db: 1,
host: 'redis.local',
password: 'foo',
port: 6380,
username: 'cool-user',
});
});
test('it builds a valid Redis URL with SSL', () => {
expect(
server.buildRedisOpts({
port: 6379,
host: '127.0.0.1',
password: '',
username: 'cool-user',
db: 0,
ssl: true,
validateHostname: false,
}),
).toEqual({
db: 0,
host: '127.0.0.1',
port: 6379,
tls: { checkServerIdentity: expect.anything() },
});
});
});
describe('processStreamResults', () => {
test('sends data to channel', async () => {
const ws = new wsMock('localhost');
const sendMock = jest.spyOn(ws, 'send');
const socketInstance = { ws: ws, channel: channelId, pongTs: Date.now() };
expect(statsdIncrementMock).toBeCalledTimes(0);
server.trackClient(channelId, socketInstance);
expect(statsdIncrementMock).toBeCalledTimes(1);
expect(statsdIncrementMock).toHaveBeenNthCalledWith(
1,
'ws_connected_client',
);
server.processStreamResults(streamReturnValue);
expect(statsdIncrementMock).toBeCalledTimes(1);
const message1 = `{"id":"1615426152415-0","channel_id":"${channelId}","job_id":"c9b99965-8f1e-4ce5-aa43-d6fc94d6a510","user_id":"1","status":"done","errors":[],"result_url":"/superset/explore_json/data/ejr-37281682b1282cdb8f25e0de0339b386"}`;
const message2 = `{"id":"1615426152516-0","channel_id":"${channelId}","job_id":"f1e5bb1f-f2f1-4f21-9b2f-c9b91dcc9b59","user_id":"1","status":"done","errors":[],"result_url":"/api/v1/chart/data/qc-64e8452dc9907dd77746cb75a19202de"}`;
expect(sendMock).toHaveBeenCalledWith(message1);
expect(sendMock).toHaveBeenCalledWith(message2);
});
test('channel not present', async () => {
const ws = new wsMock('localhost');
const sendMock = jest.spyOn(ws, 'send');
expect(statsdIncrementMock).toBeCalledTimes(0);
server.processStreamResults(streamReturnValue);
expect(statsdIncrementMock).toBeCalledTimes(0);
expect(sendMock).not.toHaveBeenCalled();
});
test('error sending data to client', async () => {
const ws = new wsMock('localhost');
const sendMock = jest.spyOn(ws, 'send').mockImplementation(() => {
throw new Error();
});
const cleanChannelMock = jest.spyOn(server, 'cleanChannel');
const socketInstance = { ws: ws, channel: channelId, pongTs: Date.now() };
expect(statsdIncrementMock).toBeCalledTimes(0);
server.trackClient(channelId, socketInstance);
expect(statsdIncrementMock).toBeCalledTimes(1);
expect(statsdIncrementMock).toHaveBeenNthCalledWith(
1,
'ws_connected_client',
);
server.processStreamResults(streamReturnValue);
expect(statsdIncrementMock).toBeCalledTimes(2);
expect(statsdIncrementMock).toHaveBeenNthCalledWith(
2,
'ws_client_send_error',
);
expect(sendMock).toHaveBeenCalled();
expect(cleanChannelMock).toHaveBeenCalledWith(channelId);
cleanChannelMock.mockRestore();
});
});
describe('fetchRangeFromStream', () => {
beforeEach(() => {
mockRedisXrange.mockClear();
});
test('success with results', async () => {
mockRedisXrange.mockResolvedValueOnce(streamReturnValue);
const cb = jest.fn();
await server.fetchRangeFromStream({
sessionId: '123',
startId: '-',
endId: '+',
listener: cb,
});
expect(mockRedisXrange).toHaveBeenCalledWith(
'test-async-events-123',
'-',
'+',
);
expect(cb).toHaveBeenCalledWith(streamReturnValue);
});
test('success no results', async () => {
const cb = jest.fn();
await server.fetchRangeFromStream({
sessionId: '123',
startId: '-',
endId: '+',
listener: cb,
});
expect(mockRedisXrange).toHaveBeenCalledWith(
'test-async-events-123',
'-',
'+',
);
expect(cb).not.toHaveBeenCalled();
});
test('error', async () => {
const cb = jest.fn();
mockRedisXrange.mockRejectedValueOnce(new Error());
await server.fetchRangeFromStream({
sessionId: '123',
startId: '-',
endId: '+',
listener: cb,
});
expect(mockRedisXrange).toHaveBeenCalledWith(
'test-async-events-123',
'-',
'+',
);
expect(cb).not.toHaveBeenCalled();
});
});
describe('wsConnection', () => {
let ws: WebSocket;
let wsEventMock: jest.SpyInstance;
let trackClientSpy: jest.SpyInstance;
let fetchRangeFromStreamSpy: jest.SpyInstance;
let dateNowSpy: jest.SpyInstance;
let socketInstanceExpected: server.SocketInstance;
const getRequest = (token: string, url: string): http.IncomingMessage => {
const request = new http.IncomingMessage(new net.Socket());
request.method = 'GET';
request.headers = { cookie: `${config.jwtCookieName}=${token}` };
request.url = url;
return request;
};
beforeEach(() => {
ws = new wsMock('localhost');
wsEventMock = jest.spyOn(ws, 'on');
trackClientSpy = jest.spyOn(server, 'trackClient');
fetchRangeFromStreamSpy = jest.spyOn(server, 'fetchRangeFromStream');
dateNowSpy = jest
.spyOn(global.Date, 'now')
.mockImplementation(() =>
new Date('2021-03-10T11:01:58.135Z').valueOf(),
);
socketInstanceExpected = {
ws,
channel: channelId,
pongTs: 1615374118135,
};
});
afterEach(() => {
wsEventMock.mockRestore();
trackClientSpy.mockRestore();
fetchRangeFromStreamSpy.mockRestore();
dateNowSpy.mockRestore();
});
test('invalid JWT', async () => {
const invalidToken = jwt.sign({ channel: channelId }, 'invalid secret');
const request = getRequest(invalidToken, 'http://localhost');
expect(() => {
server.wsConnection(ws, request);
}).toThrow();
});
test('valid JWT, no lastId', async () => {
const validToken = jwt.sign({ channel: channelId }, config.jwtSecret);
const request = getRequest(validToken, 'http://localhost');
server.wsConnection(ws, request);
expect(trackClientSpy).toHaveBeenCalledWith(
channelId,
socketInstanceExpected,
);
expect(fetchRangeFromStreamSpy).not.toHaveBeenCalled();
expect(wsEventMock).toHaveBeenCalledWith('pong', expect.any(Function));
});
test('valid JWT, with lastId', async () => {
const validToken = jwt.sign({ channel: channelId }, config.jwtSecret);
const lastId = '1615426152415-0';
const request = getRequest(
validToken,
`http://localhost?last_id=${lastId}`,
);
server.wsConnection(ws, request);
expect(trackClientSpy).toHaveBeenCalledWith(
channelId,
socketInstanceExpected,
);
expect(fetchRangeFromStreamSpy).toHaveBeenCalledWith({
sessionId: channelId,
startId: '1615426152415-1',
endId: '+',
listener: server.processStreamResults,
});
expect(wsEventMock).toHaveBeenCalledWith('pong', expect.any(Function));
});
test('valid JWT, with lastId and lastFirehoseId', async () => {
const validToken = jwt.sign({ channel: channelId }, config.jwtSecret);
const lastId = '1615426152415-0';
const lastFirehoseId = '1715426152415-0';
const request = getRequest(
validToken,
`http://localhost?last_id=${lastId}`,
);
server.setLastFirehoseId(lastFirehoseId);
server.wsConnection(ws, request);
expect(trackClientSpy).toHaveBeenCalledWith(
channelId,
socketInstanceExpected,
);
expect(fetchRangeFromStreamSpy).toHaveBeenCalledWith({
sessionId: channelId,
startId: '1615426152415-1',
endId: lastFirehoseId,
listener: server.processStreamResults,
});
expect(wsEventMock).toHaveBeenCalledWith('pong', expect.any(Function));
});
});
describe('httpUpgrade', () => {
let socket: net.Socket;
let socketDestroySpy: jest.SpyInstance;
let wssUpgradeSpy: jest.SpyInstance;
const getRequest = (token: string, url: string): http.IncomingMessage => {
const request = new http.IncomingMessage(new net.Socket());
request.method = 'GET';
request.headers = { cookie: `${config.jwtCookieName}=${token}` };
request.url = url;
return request;
};
beforeEach(() => {
socket = new net.Socket();
socketDestroySpy = jest.spyOn(socket, 'destroy');
wssUpgradeSpy = jest.spyOn(server.wss, 'handleUpgrade');
});
afterEach(() => {
wssUpgradeSpy.mockRestore();
});
test('invalid JWT', async () => {
const invalidToken = jwt.sign({ channel: channelId }, 'invalid secret');
const request = getRequest(invalidToken, 'http://localhost');
server.httpUpgrade(request, socket, Buffer.alloc(5));
expect(socketDestroySpy).toHaveBeenCalled();
expect(wssUpgradeSpy).not.toHaveBeenCalled();
});
test('valid JWT, no channel', async () => {
const validToken = jwt.sign({ foo: 'bar' }, config.jwtSecret);
const request = getRequest(validToken, 'http://localhost');
server.httpUpgrade(request, socket, Buffer.alloc(5));
expect(socketDestroySpy).toHaveBeenCalled();
expect(wssUpgradeSpy).not.toHaveBeenCalled();
});
test('valid upgrade', async () => {
const validToken = jwt.sign({ channel: channelId }, config.jwtSecret);
const request = getRequest(validToken, 'http://localhost');
server.httpUpgrade(request, socket, Buffer.alloc(5));
expect(socketDestroySpy).not.toHaveBeenCalled();
expect(wssUpgradeSpy).toHaveBeenCalled();
});
});
const setReadyState = (ws: WebSocket, value: typeof ws.readyState) => {
// workaround for not being able to do
// spyOn(instance,'readyState','get').and.returnValue(value);
// See for details: https://github.com/facebook/jest/issues/9675
Object.defineProperty(ws, 'readyState', {
configurable: true,
get() {
return value;
},
});
};
describe('checkSockets', () => {
let ws: WebSocket;
let pingSpy: jest.SpyInstance;
let terminateSpy: jest.SpyInstance;
let socketInstance: server.SocketInstance;
beforeEach(() => {
ws = new wsMock('localhost');
pingSpy = jest.spyOn(ws, 'ping');
terminateSpy = jest.spyOn(ws, 'terminate');
socketInstance = { ws: ws, channel: channelId, pongTs: Date.now() };
});
test('active sockets', () => {
setReadyState(ws, WebSocket.OPEN);
server.trackClient(channelId, socketInstance);
server.checkSockets();
expect(pingSpy).toHaveBeenCalled();
expect(terminateSpy).not.toHaveBeenCalled();
expect(Object.keys(server.sockets).length).toBe(1);
});
test('stale sockets', () => {
setReadyState(ws, WebSocket.OPEN);
socketInstance.pongTs = Date.now() - 60000;
server.trackClient(channelId, socketInstance);
server.checkSockets();
expect(pingSpy).not.toHaveBeenCalled();
expect(terminateSpy).toHaveBeenCalled();
expect(Object.keys(server.sockets).length).toBe(0);
});
test('closed sockets', () => {
setReadyState(ws, WebSocket.CLOSED);
server.trackClient(channelId, socketInstance);
server.checkSockets();
expect(pingSpy).not.toHaveBeenCalled();
expect(terminateSpy).not.toHaveBeenCalled();
expect(Object.keys(server.sockets).length).toBe(0);
});
test('no sockets', () => {
// don't error
server.checkSockets();
});
});
describe('cleanChannel', () => {
let ws: WebSocket;
let socketInstance: server.SocketInstance;
beforeEach(() => {
ws = new wsMock('localhost');
socketInstance = { ws: ws, channel: channelId, pongTs: Date.now() };
});
test('active sockets', () => {
setReadyState(ws, WebSocket.OPEN);
server.trackClient(channelId, socketInstance);
server.cleanChannel(channelId);
expect(server.channels[channelId].sockets.length).toBe(1);
});
test('closing sockets', () => {
setReadyState(ws, WebSocket.CLOSING);
server.trackClient(channelId, socketInstance);
server.cleanChannel(channelId);
expect(server.channels[channelId]).toBeUndefined();
});
test('multiple sockets', () => {
setReadyState(ws, WebSocket.OPEN);
server.trackClient(channelId, socketInstance);
const ws2 = new wsMock('localhost');
setReadyState(ws2, WebSocket.OPEN);
const socketInstance2 = {
ws: ws2,
channel: channelId,
pongTs: Date.now(),
};
server.trackClient(channelId, socketInstance2);
server.cleanChannel(channelId);
expect(server.channels[channelId].sockets.length).toBe(2);
setReadyState(ws2, WebSocket.CLOSED);
server.cleanChannel(channelId);
expect(server.channels[channelId].sockets.length).toBe(1);
});
test('invalid channel', () => {
// don't error
server.cleanChannel(channelId);
});
});
});
|
97 | 0 | petrpan-code/appsmithorg/appsmith/app/client/src/entities | petrpan-code/appsmithorg/appsmith/app/client/src/entities/Action/actionProperties.test.ts | import type { Action } from "entities/Action/index";
import { PluginType } from "entities/Action/index";
import { getBindingAndReactivePathsOfAction } from "entities/Action/actionProperties";
import { EvaluationSubstitutionType } from "entities/DataTree/dataTreeFactory";
const DEFAULT_ACTION: Action = {
actionConfiguration: {},
cacheResponse: "",
datasource: {
id: "randomDatasource",
},
dynamicBindingPathList: [],
executeOnLoad: false,
id: "",
invalids: [],
isValid: false,
jsonPathKeys: [],
name: "",
workspaceId: "",
pageId: "",
pluginId: "",
messages: [],
pluginType: PluginType.DB,
};
describe("getReactivePathsOfAction", () => {
it("returns default list of no config is sent", () => {
const response = getBindingAndReactivePathsOfAction(
DEFAULT_ACTION,
undefined,
).reactivePaths;
expect(response).toStrictEqual({
data: EvaluationSubstitutionType.TEMPLATE,
isLoading: EvaluationSubstitutionType.TEMPLATE,
config: EvaluationSubstitutionType.TEMPLATE,
datasourceUrl: EvaluationSubstitutionType.TEMPLATE,
});
});
it("returns correct values for basic config", () => {
const config = [
{
sectionName: "",
id: 1,
children: [
{
label: "",
configProperty: "actionConfiguration.body",
controlType: "QUERY_DYNAMIC_TEXT",
},
{
label: "",
configProperty: "actionConfiguration.body2",
controlType: "QUERY_DYNAMIC_INPUT_TEXT",
},
{
label: "",
configProperty: "actionConfiguration.field1",
controlType: "QUERY_DYNAMIC_INPUT_TEXT",
evaluationSubstitutionType: "SMART_SUBSTITUTE",
},
{
label: "",
configProperty: "actionConfiguration.field2",
controlType: "QUERY_DYNAMIC_INPUT_TEXT",
evaluationSubstitutionType: "PARAMETER",
},
],
},
];
const basicAction = {
...DEFAULT_ACTION,
actionConfiguration: {
body: "basic action",
body2: "another body",
field1: "test",
field2: "anotherTest",
},
};
const response = getBindingAndReactivePathsOfAction(
basicAction,
config,
).reactivePaths;
expect(response).toStrictEqual({
data: EvaluationSubstitutionType.TEMPLATE,
isLoading: EvaluationSubstitutionType.TEMPLATE,
datasourceUrl: EvaluationSubstitutionType.TEMPLATE,
"config.body": EvaluationSubstitutionType.TEMPLATE,
"config.body2": EvaluationSubstitutionType.TEMPLATE,
"config.field1": EvaluationSubstitutionType.SMART_SUBSTITUTE,
"config.field2": EvaluationSubstitutionType.PARAMETER,
});
});
it("returns correct values for array field config", () => {
const config = [
{
sectionName: "",
id: 1,
children: [
{
label: "Test label",
configProperty: "actionConfiguration.params",
controlType: "ARRAY_FIELD",
schema: [
{
label: "Key",
key: "key",
controlType: "QUERY_DYNAMIC_INPUT_TEXT",
placeholderText: "Key",
},
{
label: "Value",
key: "value",
controlType: "QUERY_DYNAMIC_INPUT_TEXT",
placeholderText: "Key",
},
{
label: "random",
key: "randomKey",
controlType: "INPUT_TEXT",
placeholderText: "random",
},
],
},
],
},
];
const basicAction = {
...DEFAULT_ACTION,
actionConfiguration: {
params: [
{
key: "test1",
value: "test1",
randomKey: "test1",
},
{
key: "test2",
value: "test2",
randomKey: "test2",
},
],
},
};
const response = getBindingAndReactivePathsOfAction(
// @ts-expect-error: Types are not available
basicAction,
config,
).reactivePaths;
expect(response).toStrictEqual({
data: EvaluationSubstitutionType.TEMPLATE,
isLoading: EvaluationSubstitutionType.TEMPLATE,
datasourceUrl: EvaluationSubstitutionType.TEMPLATE,
"config.params[0].key": EvaluationSubstitutionType.TEMPLATE,
"config.params[0].value": EvaluationSubstitutionType.TEMPLATE,
"config.params[1].key": EvaluationSubstitutionType.TEMPLATE,
"config.params[1].value": EvaluationSubstitutionType.TEMPLATE,
});
});
it("handles recursive sections", () => {
const config = [
{
sectionName: "",
id: 1,
children: [
{
label: "random",
configProperty: "actionConfiguration.randomKey",
controlType: "INPUT_TEXT",
placeholderText: "random",
},
{
sectionName: "",
id: 2,
children: [
{
label: "Key",
configProperty: "actionConfiguration.key",
controlType: "QUERY_DYNAMIC_INPUT_TEXT",
placeholderText: "Key",
},
{
label: "Value",
configProperty: "actionConfiguration.value",
controlType: "QUERY_DYNAMIC_INPUT_TEXT",
placeholderText: "Key",
},
],
},
],
},
];
const basicAction = {
...DEFAULT_ACTION,
actionConfiguration: {
randomKey: "randomValue",
key: "test1",
test: "test2",
},
};
const response = getBindingAndReactivePathsOfAction(
// @ts-expect-error: Types are not available
basicAction,
config,
).reactivePaths;
expect(response).toStrictEqual({
data: EvaluationSubstitutionType.TEMPLATE,
isLoading: EvaluationSubstitutionType.TEMPLATE,
datasourceUrl: EvaluationSubstitutionType.TEMPLATE,
"config.key": EvaluationSubstitutionType.TEMPLATE,
"config.value": EvaluationSubstitutionType.TEMPLATE,
});
});
it("checks for hidden field and returns reactivePaths accordingly", () => {
const config = [
{
sectionName: "",
id: 1,
children: [
{
label: "",
configProperty: "actionConfiguration.body",
controlType: "QUERY_DYNAMIC_TEXT",
},
{
label: "",
configProperty: "actionConfiguration.body2",
controlType: "QUERY_DYNAMIC_INPUT_TEXT",
hidden: {
path: "actionConfiguration.template.setting",
comparison: "EQUALS",
value: false,
},
},
{
label: "",
configProperty: "actionConfiguration.field1",
controlType: "QUERY_DYNAMIC_INPUT_TEXT",
evaluationSubstitutionType: "SMART_SUBSTITUTE",
hidden: {
path: "actionConfiguration.template.setting",
comparison: "EQUALS",
value: true,
},
},
],
},
];
const basicAction = {
...DEFAULT_ACTION,
actionConfiguration: {
body: "basic action",
body2: "another body",
field1: "alternate body",
template: {
setting: false,
},
},
};
const response = getBindingAndReactivePathsOfAction(
basicAction,
config,
).reactivePaths;
expect(response).toStrictEqual({
data: EvaluationSubstitutionType.TEMPLATE,
isLoading: EvaluationSubstitutionType.TEMPLATE,
datasourceUrl: EvaluationSubstitutionType.TEMPLATE,
"config.body": EvaluationSubstitutionType.TEMPLATE,
"config.field1": EvaluationSubstitutionType.SMART_SUBSTITUTE,
});
basicAction.actionConfiguration.template.setting = true;
const response2 = getBindingAndReactivePathsOfAction(
basicAction,
config,
).reactivePaths;
expect(response2).toStrictEqual({
data: EvaluationSubstitutionType.TEMPLATE,
isLoading: EvaluationSubstitutionType.TEMPLATE,
datasourceUrl: EvaluationSubstitutionType.TEMPLATE,
"config.body": EvaluationSubstitutionType.TEMPLATE,
"config.body2": EvaluationSubstitutionType.TEMPLATE,
});
});
it("returns default list of no config is sent", () => {
const response = getBindingAndReactivePathsOfAction(
DEFAULT_ACTION,
undefined,
).bindingPaths;
expect(response).toStrictEqual({});
});
it("returns correct values for basic config", () => {
const config = [
{
sectionName: "",
id: 1,
children: [
{
label: "",
configProperty: "actionConfiguration.body",
controlType: "QUERY_DYNAMIC_TEXT",
},
{
label: "",
configProperty: "actionConfiguration.body2",
controlType: "QUERY_DYNAMIC_INPUT_TEXT",
},
{
label: "",
configProperty: "actionConfiguration.field1",
controlType: "QUERY_DYNAMIC_INPUT_TEXT",
evaluationSubstitutionType: "SMART_SUBSTITUTE",
},
{
label: "",
configProperty: "actionConfiguration.field2",
controlType: "QUERY_DYNAMIC_INPUT_TEXT",
evaluationSubstitutionType: "PARAMETER",
},
],
},
];
const basicAction = {
...DEFAULT_ACTION,
actionConfiguration: {
body: "basic action",
body2: "another body",
field1: "test",
field2: "anotherTest",
},
};
const response = getBindingAndReactivePathsOfAction(
basicAction,
config,
).bindingPaths;
expect(response).toStrictEqual({
"config.body": EvaluationSubstitutionType.TEMPLATE,
"config.body2": EvaluationSubstitutionType.TEMPLATE,
"config.field1": EvaluationSubstitutionType.SMART_SUBSTITUTE,
"config.field2": EvaluationSubstitutionType.PARAMETER,
});
});
});
|
102 | 0 | petrpan-code/appsmithorg/appsmith/app/client/src/entities | petrpan-code/appsmithorg/appsmith/app/client/src/entities/AppTheming/utils.test.ts | import { RenderModes } from "constants/WidgetConstants";
import { getPropertiesToUpdateForReset } from "./utils";
import ButtonWidget from "widgets/ButtonWidget";
import TableWidget from "widgets/TableWidget";
import JSONFormWidget from "widgets/JSONFormWidget";
import { registerWidgets } from "WidgetProvider/factory/registrationHelper";
describe("AppThemingSaga test", () => {
beforeAll(() => {
registerWidgets([ButtonWidget, TableWidget, JSONFormWidget]);
});
it("Checks if button widget resets to correct value", () => {
const input = [
{
widget1: {
type: "BUTTON_WIDGET",
buttonColor: "red",
widgetId: "widget1",
widgetName: "widget1",
renderMode: RenderModes.CANVAS,
version: 1,
parentColumnSpace: 1,
parentRowSpace: 1,
leftColumn: 1,
rightColumn: 1,
topRow: 1,
bottomRow: 1,
isLoading: false,
},
},
{
BUTTON_WIDGET: {
buttonColor: "{{appsmith.theme.colors.primaryColor}}",
resetButtonStyles: {},
submitButtonStyles: {},
childStylesheet: {},
},
},
];
const output = [
{
widgetId: "widget1",
updates: {
modify: {
borderRadius: "{{appsmith.theme.borderRadius.appBorderRadius}}",
buttonColor: "{{appsmith.theme.colors.primaryColor}}",
},
},
},
];
//@ts-expect-error: type mismatch
const result = getPropertiesToUpdateForReset(...input);
expect(result).toEqual(output);
});
it("Checks if table widget resets to correct value", () => {
const input = [
{
widget1: {
type: "TABLE_WIDGET",
buttonColor: "red",
widgetId: "widget1",
widgetName: "widget1",
renderMode: RenderModes.CANVAS,
version: 1,
parentColumnSpace: 1,
parentRowSpace: 1,
leftColumn: 1,
rightColumn: 1,
topRow: 1,
bottomRow: 1,
isLoading: false,
childStylesheet: {
button: {
buttonColor: "{{appsmith.theme.colors.primaryColor}}",
},
},
primaryColumns: {
customColumn1: {
columnType: "button",
buttonColor: "pink",
},
},
},
},
{
TABLE_WIDGET: {
buttonColor: "{{appsmith.theme.colors.primaryColor}}",
resetButtonStyles: {},
submitButtonStyles: {},
childStylesheet: {
button: {
buttonColor: "{{appsmith.theme.colors.primaryColor}}",
},
},
},
},
];
const output = [
{
widgetId: "widget1",
updates: {
modify: {
accentColor: "{{appsmith.theme.colors.primaryColor}}",
borderRadius: "{{appsmith.theme.borderRadius.appBorderRadius}}",
boxShadow: "{{appsmith.theme.boxShadow.appBoxShadow}}",
"primaryColumns.customColumn1.buttonColor":
"{{widget1.sanitizedTableData.map((currentRow) => ( (appsmith.theme.colors.primaryColor)))}}",
},
},
},
];
//@ts-expect-error: type mismatch
const result = getPropertiesToUpdateForReset(...input);
expect(result).toEqual(output);
});
it("Checks if json form widget resets to correct value", () => {
const input = [
{
widget1: {
isVisible: true,
schema: {
__root_schema__: {
children: {
name: {
children: {},
dataType: "string",
fieldType: "Text Input",
accessor: "name",
identifier: "name",
position: 0,
accentColor: "pink",
borderRadius: "100px",
boxShadow: "none",
},
},
dataType: "object",
fieldType: "Object",
accessor: "__root_schema__",
identifier: "__root_schema__",
originalIdentifier: "__root_schema__",
borderRadius: "{{appsmith.theme.borderRadius.appBorderRadius}}",
boxShadow: "none",
cellBorderRadius:
"{{appsmith.theme.borderRadius.appBorderRadius}}",
cellBoxShadow: "none",
},
},
version: 1,
widgetName: "JSONForm1",
type: "JSON_FORM_WIDGET",
widgetId: "widget1",
renderMode: "CANVAS",
borderRadius: "100px",
boxShadow: "someboxshadowvalue",
childStylesheet: {
TEXT_INPUT: {
accentColor: "{{appsmith.theme.colors.primaryColor}}",
borderRadius: "{{appsmith.theme.borderRadius.appBorderRadius}}",
boxShadow: "none",
},
},
resetButtonStyles: {
buttonColor: "{{appsmith.theme.colors.primaryColor}}",
},
submitButtonStyles: {
buttonColor: "{{appsmith.theme.colors.primaryColor}}",
},
isLoading: false,
parentColumnSpace: 1,
parentRowSpace: 1,
leftColumn: 1,
rightColumn: 1,
topRow: 1,
bottomRow: 1,
parentId: "parentid",
},
},
{
JSON_FORM_WIDGET: {
borderRadius: "{{appsmith.theme.borderRadius.appBorderRadius}}",
boxShadow: "{{appsmith.theme.borderRadius.appBorderRadius}}",
resetButtonStyles: {},
submitButtonStyles: {},
childStylesheet: {
TEXT_INPUT: {
accentColor: "{{appsmith.theme.borderRadius.appBorderRadius}}",
borderRadius: "{{appsmith.theme.borderRadius.appBorderRadius}}",
boxShadow: "none",
},
},
},
},
];
const output = [
{
widgetId: "widget1",
updates: {
modify: {
borderRadius: "{{appsmith.theme.borderRadius.appBorderRadius}}",
"submitButtonStyles.borderRadius":
"{{appsmith.theme.borderRadius.appBorderRadius}}",
boxShadow: "{{appsmith.theme.boxShadow.appBoxShadow}}",
"resetButtonStyles.borderRadius":
"{{appsmith.theme.borderRadius.appBorderRadius}}",
"schema.__root_schema__.borderRadius":
"{{((sourceData, formData, fieldState) => ((appsmith.theme.borderRadius.appBorderRadius)))(JSONForm1.sourceData, JSONForm1.formData, JSONForm1.fieldState)}}",
"schema.__root_schema__.cellBorderRadius":
"{{((sourceData, formData, fieldState) => ((appsmith.theme.borderRadius.appBorderRadius)))(JSONForm1.sourceData, JSONForm1.formData, JSONForm1.fieldState)}}",
"schema.__root_schema__.children.name.accentColor":
"{{((sourceData, formData, fieldState) => ((appsmith.theme.colors.primaryColor)))(JSONForm1.sourceData, JSONForm1.formData, JSONForm1.fieldState)}}",
"schema.__root_schema__.children.name.borderRadius":
"{{((sourceData, formData, fieldState) => ((appsmith.theme.borderRadius.appBorderRadius)))(JSONForm1.sourceData, JSONForm1.formData, JSONForm1.fieldState)}}",
},
},
},
];
//@ts-expect-error: type mismatch
const result = getPropertiesToUpdateForReset(...input);
expect(result).toEqual(output);
});
});
|
112 | 0 | petrpan-code/appsmithorg/appsmith/app/client/src/entities | petrpan-code/appsmithorg/appsmith/app/client/src/entities/DataTree/dataTreeWidget.test.ts | import type { FlattenedWidgetProps } from "reducers/entityReducers/canvasWidgetsReducer";
import {
generateDataTreeWidget,
getSetterConfig,
} from "entities/DataTree/dataTreeWidget";
import {
ENTITY_TYPE_VALUE,
EvaluationSubstitutionType,
} from "entities/DataTree/dataTreeFactory";
import WidgetFactory from "WidgetProvider/factory";
import { ValidationTypes } from "constants/WidgetValidation";
import { RenderModes } from "constants/WidgetConstants";
// const WidgetTypes = WidgetFactory.widgetTypes;
describe("generateDataTreeWidget", () => {
beforeEach(() => {
const getMetaProps = jest.spyOn(
WidgetFactory,
"getWidgetMetaPropertiesMap",
);
getMetaProps.mockReturnValueOnce({
text: undefined,
isDirty: false,
isFocused: false,
});
const getDerivedProps = jest.spyOn(
WidgetFactory,
"getWidgetDerivedPropertiesMap",
);
getDerivedProps.mockReturnValueOnce({
isValid: "{{true}}",
value: "{{this.text}}",
});
const getDefaultProps = jest.spyOn(
WidgetFactory,
"getWidgetDefaultPropertiesMap",
);
getDefaultProps.mockReturnValueOnce({
text: "defaultText",
});
const getPropertyConfig = jest.spyOn(
WidgetFactory,
"getWidgetPropertyPaneConfig",
);
getPropertyConfig.mockReturnValueOnce([
{
sectionName: "General",
children: [
{
propertyName: "inputType",
label: "Data type",
controlType: "DROP_DOWN",
isBindProperty: false,
isTriggerProperty: false,
},
{
propertyName: "defaultText",
label: "Default Text",
controlType: "INPUT_TEXT",
isBindProperty: true,
isTriggerProperty: false,
validation: { type: ValidationTypes.TEXT },
},
{
propertyName: "placeholderText",
label: "Placeholder",
controlType: "INPUT_TEXT",
isBindProperty: true,
isTriggerProperty: false,
validation: { type: ValidationTypes.TEXT },
},
{
propertyName: "regex",
label: "Regex",
controlType: "INPUT_TEXT",
isBindProperty: true,
isTriggerProperty: false,
validation: { type: ValidationTypes.REGEX },
},
{
propertyName: "errorMessage",
label: "Error message",
controlType: "INPUT_TEXT",
isBindProperty: true,
isTriggerProperty: false,
validation: { type: ValidationTypes.TEXT },
},
{
propertyName: "isRequired",
label: "Required",
controlType: "SWITCH",
isJSConvertible: true,
isBindProperty: true,
isTriggerProperty: false,
validation: { type: ValidationTypes.BOOLEAN },
},
{
propertyName: "isVisible",
label: "Visible",
controlType: "SWITCH",
isJSConvertible: true,
isBindProperty: true,
isTriggerProperty: false,
validation: { type: ValidationTypes.BOOLEAN },
},
{
propertyName: "isDisabled",
label: "Disabled",
controlType: "SWITCH",
isJSConvertible: true,
isBindProperty: true,
isTriggerProperty: false,
validation: { type: ValidationTypes.BOOLEAN },
},
{
propertyName: "resetOnSubmit",
label: "Reset on submit",
controlType: "SWITCH",
isJSConvertible: true,
isBindProperty: true,
isTriggerProperty: false,
validation: { type: ValidationTypes.BOOLEAN },
},
],
},
{
sectionName: "Events",
children: [
{
propertyName: "onTextChanged",
label: "onTextChanged",
controlType: "ACTION_SELECTOR",
isJSConvertible: true,
isBindProperty: true,
isTriggerProperty: true,
},
{
propertyName: "onSubmit",
label: "onSubmit",
controlType: "ACTION_SELECTOR",
isJSConvertible: true,
isBindProperty: true,
isTriggerProperty: true,
},
],
},
]);
});
afterEach(() => {
jest.clearAllMocks();
});
it("generates enhanced widget with the right properties", () => {
const widget: FlattenedWidgetProps = {
bottomRow: 0,
isLoading: false,
leftColumn: 0,
parentColumnSpace: 0,
parentRowSpace: 0,
renderMode: RenderModes.CANVAS,
rightColumn: 0,
topRow: 0,
type: "INPUT_WIDGET_V2",
version: 0,
widgetId: "123",
widgetName: "Input1",
defaultText: "",
deepObj: {
level1: {
value: 10,
},
},
};
const widgetMetaProps: Record<string, unknown> = {
text: "Tester",
isDirty: true,
deepObj: {
level1: {
metaValue: 10,
},
},
};
const getMetaProps = jest.spyOn(
WidgetFactory,
"getWidgetMetaPropertiesMap",
);
getMetaProps.mockReturnValueOnce({
text: true,
isDirty: true,
});
const bindingPaths = {
defaultText: EvaluationSubstitutionType.TEMPLATE,
placeholderText: EvaluationSubstitutionType.TEMPLATE,
regex: EvaluationSubstitutionType.TEMPLATE,
resetOnSubmit: EvaluationSubstitutionType.TEMPLATE,
isVisible: EvaluationSubstitutionType.TEMPLATE,
isRequired: EvaluationSubstitutionType.TEMPLATE,
isDisabled: EvaluationSubstitutionType.TEMPLATE,
errorMessage: EvaluationSubstitutionType.TEMPLATE,
};
const expectedData = {
value: "{{Input1.text}}",
isDirty: true,
isFocused: false,
isValid: "{{true}}",
text: "Tester",
bottomRow: 0,
isLoading: false,
leftColumn: 0,
parentColumnSpace: 0,
parentRowSpace: 0,
rightColumn: 0,
renderMode: RenderModes.CANVAS,
version: 0,
topRow: 0,
widgetId: "123",
widgetName: "Input1",
ENTITY_TYPE: ENTITY_TYPE_VALUE.WIDGET,
componentWidth: 0,
componentHeight: 0,
defaultText: "",
type: "INPUT_WIDGET_V2",
deepObj: {
level1: {
metaValue: 10,
},
},
meta: {
text: "Tester",
isDirty: true,
deepObj: {
level1: {
metaValue: 10,
},
},
},
};
const expectedConfig = {
ENTITY_TYPE: ENTITY_TYPE_VALUE.WIDGET,
widgetId: "123",
bindingPaths,
reactivePaths: {
...bindingPaths,
isDirty: EvaluationSubstitutionType.TEMPLATE,
isFocused: EvaluationSubstitutionType.TEMPLATE,
isValid: EvaluationSubstitutionType.TEMPLATE,
text: EvaluationSubstitutionType.TEMPLATE,
value: EvaluationSubstitutionType.TEMPLATE,
"meta.text": EvaluationSubstitutionType.TEMPLATE,
},
triggerPaths: {
onSubmit: true,
onTextChanged: true,
},
type: "INPUT_WIDGET_V2",
validationPaths: {
defaultText: { type: ValidationTypes.TEXT },
errorMessage: { type: ValidationTypes.TEXT },
isDisabled: { type: ValidationTypes.BOOLEAN },
isRequired: { type: ValidationTypes.BOOLEAN },
isVisible: { type: ValidationTypes.BOOLEAN },
placeholderText: { type: ValidationTypes.TEXT },
regex: { type: ValidationTypes.REGEX },
resetOnSubmit: { type: ValidationTypes.BOOLEAN },
},
dynamicBindingPathList: [
{
key: "isValid",
},
{
key: "value",
},
],
logBlackList: {
isValid: true,
value: true,
},
propertyOverrideDependency: {
text: {
DEFAULT: "defaultText",
META: "meta.text",
},
},
dependencyMap: {},
defaultMetaProps: ["text", "isDirty", "isFocused"],
defaultProps: {
text: "defaultText",
},
overridingPropertyPaths: {
defaultText: ["text", "meta.text"],
"meta.text": ["text"],
},
privateWidgets: {},
isMetaPropDirty: true,
};
const result = generateDataTreeWidget(widget, widgetMetaProps, new Set());
expect(result.unEvalEntity).toStrictEqual(expectedData);
expect(result.configEntity).toStrictEqual(expectedConfig);
});
it("generates setterConfig with the dynamic data", () => {
// Input widget
const inputWidget: FlattenedWidgetProps = {
bottomRow: 0,
isLoading: false,
leftColumn: 0,
parentColumnSpace: 0,
parentRowSpace: 0,
renderMode: RenderModes.CANVAS,
rightColumn: 0,
topRow: 0,
type: "INPUT_WIDGET_V2",
version: 0,
widgetId: "123",
widgetName: "Input1",
defaultText: "",
deepObj: {
level1: {
value: 10,
},
},
};
const inputSetterConfig: Record<string, any> = {
__setters: {
setVisibility: {
path: "isVisible",
type: "boolean",
},
setDisabled: {
path: "isDisabled",
type: "boolean",
},
setRequired: {
path: "isRequired",
type: "boolean",
},
setValue: {
path: "defaultText",
type: "string",
},
},
};
const expectedInputData = {
__setters: {
setVisibility: {
path: "Input1.isVisible",
type: "boolean",
},
setDisabled: {
path: "Input1.isDisabled",
type: "boolean",
},
setRequired: {
path: "Input1.isRequired",
type: "boolean",
},
setValue: {
path: "Input1.defaultText",
type: "string",
},
},
};
const inputResult = getSetterConfig(inputSetterConfig, inputWidget);
expect(inputResult).toStrictEqual(expectedInputData);
//Json form widget
const jsonFormWidget: FlattenedWidgetProps = {
bottomRow: 0,
isLoading: false,
leftColumn: 0,
parentColumnSpace: 0,
parentRowSpace: 0,
renderMode: RenderModes.CANVAS,
rightColumn: 0,
topRow: 0,
type: "FORM_WIDGET",
version: 0,
widgetId: "123",
widgetName: "Form1",
defaultText: "",
deepObj: {
level1: {
value: 10,
},
},
};
const jsonFormSetterConfig: Record<string, any> = {
__setters: {
setVisibility: {
path: "isVisible",
type: "boolean",
},
setData: {
path: "sourceData",
type: "object",
},
},
};
const expectedJsonFormData = {
__setters: {
setVisibility: {
path: "Form1.isVisible",
type: "boolean",
},
setData: {
path: "Form1.sourceData",
type: "object",
},
},
};
const jsonFormResult = getSetterConfig(
jsonFormSetterConfig,
jsonFormWidget,
);
expect(jsonFormResult).toStrictEqual(expectedJsonFormData);
// Table widget
const tableWidget: FlattenedWidgetProps = {
bottomRow: 0,
isLoading: false,
leftColumn: 0,
parentColumnSpace: 0,
parentRowSpace: 0,
renderMode: RenderModes.CANVAS,
rightColumn: 0,
topRow: 0,
type: "TABLE_WIDGET",
version: 0,
widgetId: "123",
widgetName: "Table1",
defaultText: "",
deepObj: {
level1: {
value: 10,
},
},
primaryColumns: {
step: {
index: 0,
width: 150,
id: "step",
horizontalAlignment: "LEFT",
verticalAlignment: "CENTER",
columnType: "text",
textSize: "PARAGRAPH",
enableFilter: true,
enableSort: true,
isVisible: true,
isCellVisible: true,
isDerived: false,
label: "step",
computedValue:
"{{Table1.sanitizedTableData.map((currentRow) => ( currentRow.step))}}",
},
task: {
index: 1,
width: 150,
id: "task",
horizontalAlignment: "LEFT",
verticalAlignment: "CENTER",
columnType: "text",
textSize: "PARAGRAPH",
enableFilter: true,
enableSort: true,
isVisible: true,
isCellVisible: true,
isDerived: false,
label: "task",
computedValue:
"{{Table1.sanitizedTableData.map((currentRow) => ( currentRow.task))}}",
},
status: {
index: 2,
width: 150,
id: "status",
horizontalAlignment: "LEFT",
verticalAlignment: "CENTER",
columnType: "text",
textSize: "PARAGRAPH",
enableFilter: true,
enableSort: true,
isVisible: true,
isCellVisible: true,
isDerived: false,
label: "status",
computedValue:
"{{Table1.sanitizedTableData.map((currentRow) => ( currentRow.status))}}",
},
action: {
index: 3,
width: 150,
id: "action",
horizontalAlignment: "LEFT",
verticalAlignment: "CENTER",
columnType: "button",
textSize: "PARAGRAPH",
enableFilter: true,
enableSort: true,
isVisible: true,
isCellVisible: true,
isDisabled: false,
isDerived: false,
label: "action",
onClick:
"{{currentRow.step === '#1' ? showAlert('Done', 'success') : currentRow.step === '#2' ? navigateTo('https://docs.appsmith.com/core-concepts/connecting-to-data-sources/querying-a-database',undefined,'NEW_WINDOW') : navigateTo('https://docs.appsmith.com/core-concepts/displaying-data-read/display-data-tables',undefined,'NEW_WINDOW')}}",
computedValue:
"{{Table1.sanitizedTableData.map((currentRow) => ( currentRow.action))}}",
},
},
};
const tableSetterConfig: Record<string, any> = {
__setters: {
setVisibility: {
path: "isVisible",
type: "string",
},
setSelectedRowIndex: {
path: "defaultSelectedRowIndex",
type: "number",
disabled: "return options.entity.multiRowSelection",
},
setSelectedRowIndices: {
path: "defaultSelectedRowIndices",
type: "array",
disabled: "return !options.entity.multiRowSelection",
},
setData: {
path: "tableData",
type: "object",
},
},
text: {
__setters: {
setIsRequired: {
path: "primaryColumns.$columnId.isRequired",
type: "boolean",
},
},
},
button: {
__setters: {
setIsRequired: {
path: "primaryColumns.$columnId.isRequired",
type: "boolean",
},
},
},
pathToSetters: [
{ path: "primaryColumns.$columnId", property: "columnType" },
],
};
const expectedTableData = {
__setters: {
setVisibility: {
path: "Table1.isVisible",
type: "string",
},
setSelectedRowIndex: {
path: "Table1.defaultSelectedRowIndex",
type: "number",
disabled: "return options.entity.multiRowSelection",
},
setSelectedRowIndices: {
path: "Table1.defaultSelectedRowIndices",
type: "array",
disabled: "return !options.entity.multiRowSelection",
},
setData: {
path: "Table1.tableData",
type: "object",
},
"primaryColumns.action.setIsRequired": {
path: "Table1.primaryColumns.action.isRequired",
type: "boolean",
},
"primaryColumns.status.setIsRequired": {
path: "Table1.primaryColumns.status.isRequired",
type: "boolean",
},
"primaryColumns.step.setIsRequired": {
path: "Table1.primaryColumns.step.isRequired",
type: "boolean",
},
"primaryColumns.task.setIsRequired": {
path: "Table1.primaryColumns.task.isRequired",
type: "boolean",
},
},
};
const tableResult = getSetterConfig(tableSetterConfig, tableWidget);
expect(tableResult).toStrictEqual(expectedTableData);
});
});
|
118 | 0 | petrpan-code/appsmithorg/appsmith/app/client/src/entities/DependencyMap | petrpan-code/appsmithorg/appsmith/app/client/src/entities/DependencyMap/__tests__/index.test.ts | import DependencyMap from "..";
import { DependencyMapUtils } from "../DependencyMapUtils";
describe("Tests for DependencyMap", () => {
const dataDependencyMap = new DependencyMap();
it("should be able to add a node", () => {
dataDependencyMap.addNodes({
a: true,
b: true,
});
expect(dataDependencyMap.nodes).toEqual({
a: true,
b: true,
});
});
it("should be able to add a dependency", () => {
dataDependencyMap.addDependency("a", ["b", "c"]);
expect(dataDependencyMap.dependencies).toEqual({
a: ["b"],
});
expect(dataDependencyMap.inverseDependencies).toEqual({ b: ["a"] });
expect(dataDependencyMap.invalidDependencies).toEqual({ a: ["c"] });
expect(dataDependencyMap.inverseInvalidDependencies).toEqual({ c: ["a"] });
});
it("should not add a dependency for nodes that do not exist", () => {
dataDependencyMap.addDependency("absentNode", ["b", "c"]);
expect(dataDependencyMap.getDirectDependencies("absentNode")).toEqual([]);
});
it("Adding new node should recompute valid and invalid dependencies", () => {
dataDependencyMap.addNodes({ c: true });
expect(dataDependencyMap.dependencies).toEqual({ a: ["b", "c"] });
expect(dataDependencyMap.inverseDependencies).toEqual({
b: ["a"],
c: ["a"],
});
expect(dataDependencyMap.invalidDependencies).toEqual({ a: [] });
expect(dataDependencyMap.inverseInvalidDependencies).toEqual({});
});
it("should be able to check if nodes are connected", () => {
dataDependencyMap.addNodes({ showAlert: true });
dataDependencyMap.addDependency("c", ["showAlert"]);
expect(dataDependencyMap.isRelated("a", ["showAlert"])).toEqual(true);
});
it("should be able to remove a node", () => {
dataDependencyMap.removeNodes({
c: true,
showAlert: true,
});
expect(dataDependencyMap.dependencies).toEqual({ a: ["b"] });
expect(dataDependencyMap.inverseDependencies).toEqual({ b: ["a"] });
expect(dataDependencyMap.invalidDependencies).toEqual({ a: ["c"] });
expect(dataDependencyMap.inverseInvalidDependencies).toEqual({ c: ["a"] });
});
});
describe("Tests for DependencyMapUtils", () => {
const dependencyMap = new DependencyMap();
const testNodes: Record<string, true> = {
"appsmith.geolocation.getCurrentPosition": true,
"appsmith.geolocation.watchPosition": true,
"appsmith.geolocation.clearWatch": true,
navigateTo: true,
showAlert: true,
showModal: true,
closeModal: true,
storeValue: true,
removeValue: true,
clearStore: true,
download: true,
copyToClipboard: true,
resetWidget: true,
setInterval: true,
clearInterval: true,
postWindowMessage: true,
Api1: true,
"Api1.actionId": true,
"Api1.run": true,
"Api1.clear": true,
"Api1.data": true,
"Api1.isLoading": true,
"Api1.responseMeta": true,
"Api1.responseMeta.statusCode": true,
"Api1.responseMeta.isExecutionSuccess": true,
"Api1.responseMeta.headers": true,
"Api1.config": true,
"Api1.config.timeoutInMillisecond": true,
"Api1.config.paginationType": true,
"Api1.config.headers": true,
"Api1.config.encodeParamsToggle": true,
"Api1.config.queryParameters": true,
"Api1.config.bodyFormData": true,
"Api1.config.httpMethod": true,
"Api1.config.selfReferencingDataPaths": true,
"Api1.config.pluginSpecifiedTemplates": true,
"Api1.config.pluginSpecifiedTemplates[0]": true,
"Api1.config.pluginSpecifiedTemplates[0].value": true,
"Api1.config.formData": true,
"Api1.config.formData.apiContentType": true,
"Api1.ENTITY_TYPE": true,
"Api1.datasourceUrl": true,
Api3: true,
"Api3.actionId": true,
"Api3.run": true,
"Api3.clear": true,
"Api3.data": true,
"Api3.isLoading": true,
"Api3.responseMeta": true,
"Api3.responseMeta.statusCode": true,
"Api3.responseMeta.isExecutionSuccess": true,
"Api3.responseMeta.headers": true,
"Api3.config": true,
"Api3.config.timeoutInMillisecond": true,
"Api3.config.paginationType": true,
"Api3.config.path": true,
"Api3.config.headers": true,
"Api3.config.encodeParamsToggle": true,
"Api3.config.queryParameters": true,
"Api3.config.bodyFormData": true,
"Api3.config.httpMethod": true,
"Api3.config.selfReferencingDataPaths": true,
"Api3.config.pluginSpecifiedTemplates": true,
"Api3.config.pluginSpecifiedTemplates[0]": true,
"Api3.config.pluginSpecifiedTemplates[0].value": true,
"Api3.config.formData": true,
"Api3.config.formData.apiContentType": true,
"Api3.ENTITY_TYPE": true,
"Api3.datasourceUrl": true,
Countries: true,
"Countries.actionId": true,
"Countries.run": true,
"Countries.clear": true,
"Countries.data": true,
"Countries.isLoading": true,
"Countries.responseMeta": true,
"Countries.responseMeta.statusCode": true,
"Countries.responseMeta.isExecutionSuccess": true,
"Countries.responseMeta.headers": true,
"Countries.config": true,
"Countries.config.timeoutInMillisecond": true,
"Countries.config.paginationType": true,
"Countries.config.headers": true,
"Countries.config.encodeParamsToggle": true,
"Countries.config.queryParameters": true,
"Countries.config.bodyFormData": true,
"Countries.config.httpMethod": true,
"Countries.config.selfReferencingDataPaths": true,
"Countries.config.pluginSpecifiedTemplates": true,
"Countries.config.pluginSpecifiedTemplates[0]": true,
"Countries.config.pluginSpecifiedTemplates[0].value": true,
"Countries.config.formData": true,
"Countries.config.formData.apiContentType": true,
"Countries.ENTITY_TYPE": true,
"Countries.datasourceUrl": true,
Api2: true,
"Api2.actionId": true,
"Api2.run": true,
"Api2.clear": true,
"Api2.data": true,
"Api2.isLoading": true,
"Api2.responseMeta": true,
"Api2.responseMeta.statusCode": true,
"Api2.responseMeta.isExecutionSuccess": true,
"Api2.responseMeta.headers": true,
"Api2.config": true,
"Api2.config.timeoutInMillisecond": true,
"Api2.config.paginationType": true,
"Api2.config.path": true,
"Api2.config.headers": true,
"Api2.config.encodeParamsToggle": true,
"Api2.config.queryParameters": true,
"Api2.config.bodyFormData": true,
"Api2.config.httpMethod": true,
"Api2.config.selfReferencingDataPaths": true,
"Api2.config.pluginSpecifiedTemplates": true,
"Api2.config.pluginSpecifiedTemplates[0]": true,
"Api2.config.pluginSpecifiedTemplates[0].value": true,
"Api2.config.formData": true,
"Api2.config.formData.apiContentType": true,
"Api2.ENTITY_TYPE": true,
"Api2.datasourceUrl": true,
reallyllongname_on_this_api_qu: true,
"reallyllongname_on_this_api_qu.actionId": true,
"reallyllongname_on_this_api_qu.run": true,
"reallyllongname_on_this_api_qu.clear": true,
"reallyllongname_on_this_api_qu.data": true,
"reallyllongname_on_this_api_qu.isLoading": true,
"reallyllongname_on_this_api_qu.responseMeta": true,
"reallyllongname_on_this_api_qu.responseMeta.statusCode": true,
"reallyllongname_on_this_api_qu.responseMeta.isExecutionSuccess": true,
"reallyllongname_on_this_api_qu.responseMeta.headers": true,
"reallyllongname_on_this_api_qu.config": true,
"reallyllongname_on_this_api_qu.config.timeoutInMillisecond": true,
"reallyllongname_on_this_api_qu.config.paginationType": true,
"reallyllongname_on_this_api_qu.config.headers": true,
"reallyllongname_on_this_api_qu.config.encodeParamsToggle": true,
"reallyllongname_on_this_api_qu.config.queryParameters": true,
"reallyllongname_on_this_api_qu.config.bodyFormData": true,
"reallyllongname_on_this_api_qu.config.httpMethod": true,
"reallyllongname_on_this_api_qu.config.selfReferencingDataPaths": true,
"reallyllongname_on_this_api_qu.config.pluginSpecifiedTemplates": true,
"reallyllongname_on_this_api_qu.config.pluginSpecifiedTemplates[0]": true,
"reallyllongname_on_this_api_qu.config.pluginSpecifiedTemplates[0].value":
true,
"reallyllongname_on_this_api_qu.config.formData": true,
"reallyllongname_on_this_api_qu.config.formData.apiContentType": true,
"reallyllongname_on_this_api_qu.ENTITY_TYPE": true,
"reallyllongname_on_this_api_qu.datasourceUrl": true,
JSObject1: true,
"JSObject1.body": true,
"JSObject1.ENTITY_TYPE": true,
"JSObject1.actionId": true,
"JSObject1.data": true,
"JSObject1.data.data": true,
"JSObject1.mutate": true,
"JSObject1.mutate.data": true,
"JSObject1.mutate1": true,
"JSObject1.mutate1.data": true,
JSObject2: true,
"JSObject2.body": true,
"JSObject2.ENTITY_TYPE": true,
"JSObject2.actionId": true,
"JSObject2.arrayType": true,
"JSObject2.myFun1": true,
"JSObject2.myFun1.data": true,
"JSObject2.myFun2": true,
"JSObject2.myFun2.data": true,
"JSObject2.IntervalCheck": true,
"JSObject2.IntervalCheck.data": true,
"JSObject2.clearInsterval": true,
"JSObject2.clearInsterval.data": true,
"JSObject2.funcKey": true,
"JSObject2.funcKey.data": true,
"JSObject2.funcType2": true,
"JSObject2.funcType2.data": true,
"JSObject2.thirdFunction": true,
"JSObject2.thirdFunction.data": true,
JSObject3: true,
"JSObject3.body": true,
"JSObject3.ENTITY_TYPE": true,
"JSObject3.actionId": true,
"JSObject3.myVar1": true,
"JSObject3.myVar2": true,
"JSObject3.myFun2": true,
"JSObject3.myFun2.data": true,
"JSObject3.new": true,
"JSObject3.new.data": true,
JSObject4: true,
"JSObject4.body": true,
"JSObject4.ENTITY_TYPE": true,
"JSObject4.actionId": true,
"JSObject4.myFun2": true,
"JSObject4.myFun2.data": true,
"JSObject4.secondFunction": true,
"JSObject4.secondFunction.data": true,
MainContainer: true,
"MainContainer.ENTITY_TYPE": true,
"MainContainer.widgetName": true,
"MainContainer.backgroundColor": true,
"MainContainer.rightColumn": true,
"MainContainer.snapColumns": true,
"MainContainer.widgetId": true,
"MainContainer.topRow": true,
"MainContainer.bottomRow": true,
"MainContainer.containerStyle": true,
"MainContainer.snapRows": true,
"MainContainer.parentRowSpace": true,
"MainContainer.canExtend": true,
"MainContainer.minHeight": true,
"MainContainer.parentColumnSpace": true,
"MainContainer.leftColumn": true,
"MainContainer.meta": true,
"MainContainer.type": true,
"MainContainer.isMobile": true,
Text9: true,
"Text9.ENTITY_TYPE": true,
"Text9.widgetName": true,
"Text9.topRow": true,
"Text9.bottomRow": true,
"Text9.parentRowSpace": true,
"Text9.animateLoading": true,
"Text9.overflow": true,
"Text9.fontFamily": true,
"Text9.parentColumnSpace": true,
"Text9.leftColumn": true,
"Text9.shouldTruncate": true,
"Text9.truncateButtonColor": true,
"Text9.text": true,
"Text9.key": true,
"Text9.rightColumn": true,
"Text9.textAlign": true,
"Text9.dynamicHeight": true,
"Text9.widgetId": true,
"Text9.isVisible": true,
"Text9.fontStyle": true,
"Text9.textColor": true,
"Text9.isLoading": true,
"Text9.originalTopRow": true,
"Text9.borderRadius": true,
"Text9.maxDynamicHeight": true,
"Text9.originalBottomRow": true,
"Text9.fontSize": true,
"Text9.minDynamicHeight": true,
"Text9.value": true,
"Text9.meta": true,
"Text9.type": true,
"Text9.isMobile": true,
Button4Copy: true,
"Button4Copy.ENTITY_TYPE": true,
"Button4Copy.resetFormOnClick": true,
"Button4Copy.boxShadow": true,
"Button4Copy.widgetName": true,
"Button4Copy.onClick": true,
"Button4Copy.buttonColor": true,
"Button4Copy.topRow": true,
"Button4Copy.bottomRow": true,
"Button4Copy.parentRowSpace": true,
"Button4Copy.animateLoading": true,
"Button4Copy.parentColumnSpace": true,
"Button4Copy.leftColumn": true,
"Button4Copy.text": true,
"Button4Copy.isDisabled": true,
"Button4Copy.key": true,
"Button4Copy.rightColumn": true,
"Button4Copy.isDefaultClickDisabled": true,
"Button4Copy.widgetId": true,
"Button4Copy.isVisible": true,
"Button4Copy.recaptchaType": true,
"Button4Copy.isLoading": true,
"Button4Copy.disabledWhenInvalid": true,
"Button4Copy.borderRadius": true,
"Button4Copy.buttonVariant": true,
"Button4Copy.placement": true,
"Button4Copy.recaptchaToken": true,
"Button4Copy.meta": true,
"Button4Copy.type": true,
"Button4Copy.isMobile": true,
Button3Copy: true,
"Button3Copy.ENTITY_TYPE": true,
"Button3Copy.resetFormOnClick": true,
"Button3Copy.boxShadow": true,
"Button3Copy.widgetName": true,
"Button3Copy.onClick": true,
"Button3Copy.buttonColor": true,
"Button3Copy.topRow": true,
"Button3Copy.bottomRow": true,
"Button3Copy.parentRowSpace": true,
"Button3Copy.animateLoading": true,
"Button3Copy.parentColumnSpace": true,
"Button3Copy.leftColumn": true,
"Button3Copy.text": true,
"Button3Copy.isDisabled": true,
"Button3Copy.key": true,
"Button3Copy.rightColumn": true,
"Button3Copy.isDefaultClickDisabled": true,
"Button3Copy.widgetId": true,
"Button3Copy.isVisible": true,
"Button3Copy.recaptchaType": true,
"Button3Copy.isLoading": true,
"Button3Copy.disabledWhenInvalid": true,
"Button3Copy.borderRadius": true,
"Button3Copy.buttonVariant": true,
"Button3Copy.placement": true,
"Button3Copy.recaptchaToken": true,
"Button3Copy.meta": true,
"Button3Copy.type": true,
"Button3Copy.isMobile": true,
Button5Copy: true,
"Button5Copy.ENTITY_TYPE": true,
"Button5Copy.resetFormOnClick": true,
"Button5Copy.boxShadow": true,
"Button5Copy.widgetName": true,
"Button5Copy.onClick": true,
"Button5Copy.buttonColor": true,
"Button5Copy.topRow": true,
"Button5Copy.bottomRow": true,
"Button5Copy.parentRowSpace": true,
"Button5Copy.animateLoading": true,
"Button5Copy.parentColumnSpace": true,
"Button5Copy.leftColumn": true,
"Button5Copy.text": true,
"Button5Copy.isDisabled": true,
"Button5Copy.key": true,
"Button5Copy.rightColumn": true,
"Button5Copy.isDefaultClickDisabled": true,
"Button5Copy.widgetId": true,
"Button5Copy.isVisible": true,
"Button5Copy.recaptchaType": true,
"Button5Copy.isLoading": true,
"Button5Copy.disabledWhenInvalid": true,
"Button5Copy.borderRadius": true,
"Button5Copy.buttonVariant": true,
"Button5Copy.placement": true,
"Button5Copy.recaptchaToken": true,
"Button5Copy.meta": true,
"Button5Copy.type": true,
"Button5Copy.isMobile": true,
Table1: true,
"Table1.ENTITY_TYPE": true,
"Table1.boxShadow": true,
"Table1.isVisibleDownload": true,
"Table1.topRow": true,
"Table1.isSortable": true,
"Table1.inlineEditingSaveOption": true,
"Table1.animateLoading": true,
"Table1.leftColumn": true,
"Table1.delimiter": true,
"Table1.defaultSelectedRowIndex": true,
"Table1.showInlineEditingOptionDropdown": true,
"Table1.accentColor": true,
"Table1.isVisibleFilters": true,
"Table1.isVisible": true,
"Table1.enableClientSideSearch": true,
"Table1.totalRecordsCount": true,
"Table1.isLoading": true,
"Table1.childStylesheet": true,
"Table1.childStylesheet.button": true,
"Table1.childStylesheet.button.buttonColor": true,
"Table1.childStylesheet.button.borderRadius": true,
"Table1.childStylesheet.button.boxShadow": true,
"Table1.childStylesheet.menuButton": true,
"Table1.childStylesheet.menuButton.menuColor": true,
"Table1.childStylesheet.menuButton.borderRadius": true,
"Table1.childStylesheet.menuButton.boxShadow": true,
"Table1.childStylesheet.iconButton": true,
"Table1.childStylesheet.iconButton.buttonColor": true,
"Table1.childStylesheet.iconButton.borderRadius": true,
"Table1.childStylesheet.iconButton.boxShadow": true,
"Table1.childStylesheet.editActions": true,
"Table1.childStylesheet.editActions.saveButtonColor": true,
"Table1.childStylesheet.editActions.saveBorderRadius": true,
"Table1.childStylesheet.editActions.discardButtonColor": true,
"Table1.childStylesheet.editActions.discardBorderRadius": true,
"Table1.borderRadius": true,
"Table1.columnUpdatedAt": true,
"Table1.defaultSelectedRowIndices": true,
"Table1.defaultSelectedRowIndices[0]": true,
"Table1.widgetName": true,
"Table1.defaultPageSize": true,
"Table1.columnOrder": true,
"Table1.columnOrder[0]": true,
"Table1.columnOrder[1]": true,
"Table1.columnOrder[2]": true,
"Table1.columnOrder[3]": true,
"Table1.columnOrder[4]": true,
"Table1.columnOrder[5]": true,
"Table1.columnOrder[6]": true,
"Table1.columnOrder[7]": true,
"Table1.columnOrder[8]": true,
"Table1.columnOrder[9]": true,
"Table1.columnOrder[10]": true,
"Table1.columnOrder[11]": true,
"Table1.columnOrder[12]": true,
"Table1.columnOrder[13]": true,
"Table1.columnOrder[14]": true,
"Table1.columnOrder[15]": true,
"Table1.columnOrder[16]": true,
"Table1.columnOrder[17]": true,
"Table1.columnOrder[18]": true,
"Table1.columnOrder[19]": true,
"Table1.columnOrder[20]": true,
"Table1.columnOrder[21]": true,
"Table1.columnOrder[22]": true,
"Table1.columnOrder[23]": true,
"Table1.columnOrder[24]": true,
"Table1.columnOrder[25]": true,
"Table1.columnOrder[26]": true,
"Table1.columnOrder[27]": true,
"Table1.columnOrder[28]": true,
"Table1.columnOrder[29]": true,
"Table1.columnOrder[30]": true,
"Table1.columnOrder[31]": true,
"Table1.columnOrder[32]": true,
"Table1.columnOrder[33]": true,
"Table1.columnOrder[34]": true,
"Table1.columnOrder[35]": true,
"Table1.bottomRow": true,
"Table1.columnWidthMap": true,
"Table1.columnWidthMap.task": true,
"Table1.columnWidthMap.step": true,
"Table1.columnWidthMap.status": true,
"Table1.parentRowSpace": true,
"Table1.primaryColumns": true,
"Table1.primaryColumns.status": true,
"Table1.primaryColumns.status.index": true,
"Table1.primaryColumns.status.width": true,
"Table1.primaryColumns.status.id": true,
"Table1.primaryColumns.status.originalId": true,
"Table1.primaryColumns.status.alias": true,
"Table1.primaryColumns.status.horizontalAlignment": true,
"Table1.primaryColumns.status.verticalAlignment": true,
"Table1.primaryColumns.status.columnType": true,
"Table1.primaryColumns.status.textSize": true,
"Table1.primaryColumns.status.enableFilter": true,
"Table1.primaryColumns.status.enableSort": true,
"Table1.primaryColumns.status.isVisible": true,
"Table1.primaryColumns.status.isCellVisible": true,
"Table1.primaryColumns.status.isCellEditable": true,
"Table1.primaryColumns.status.isDerived": true,
"Table1.primaryColumns.status.label": true,
"Table1.primaryColumns.status.computedValue": true,
"Table1.primaryColumns.status.labelColor": true,
"Table1.primaryColumns.status.validation": true,
"Table1.primaryColumns.status.isEditable": true,
"Table1.primaryColumns.status.sticky": true,
"Table1.primaryColumns.name": true,
"Table1.primaryColumns.name.allowCellWrapping": true,
"Table1.primaryColumns.name.index": true,
"Table1.primaryColumns.name.width": true,
"Table1.primaryColumns.name.originalId": true,
"Table1.primaryColumns.name.id": true,
"Table1.primaryColumns.name.alias": true,
"Table1.primaryColumns.name.horizontalAlignment": true,
"Table1.primaryColumns.name.verticalAlignment": true,
"Table1.primaryColumns.name.columnType": true,
"Table1.primaryColumns.name.textColor": true,
"Table1.primaryColumns.name.textSize": true,
"Table1.primaryColumns.name.enableFilter": true,
"Table1.primaryColumns.name.enableSort": true,
"Table1.primaryColumns.name.isVisible": true,
"Table1.primaryColumns.name.isDisabled": true,
"Table1.primaryColumns.name.isCellEditable": true,
"Table1.primaryColumns.name.isEditable": true,
"Table1.primaryColumns.name.isCellVisible": true,
"Table1.primaryColumns.name.isDerived": true,
"Table1.primaryColumns.name.label": true,
"Table1.primaryColumns.name.isSaveVisible": true,
"Table1.primaryColumns.name.isDiscardVisible": true,
"Table1.primaryColumns.name.computedValue": true,
"Table1.primaryColumns.name.cellBackground": true,
"Table1.primaryColumns.name.validation": true,
"Table1.primaryColumns.name.sticky": true,
"Table1.primaryColumns.tld": true,
"Table1.primaryColumns.tld.allowCellWrapping": true,
"Table1.primaryColumns.tld.index": true,
"Table1.primaryColumns.tld.width": true,
"Table1.primaryColumns.tld.originalId": true,
"Table1.primaryColumns.tld.id": true,
"Table1.primaryColumns.tld.alias": true,
"Table1.primaryColumns.tld.horizontalAlignment": true,
"Table1.primaryColumns.tld.verticalAlignment": true,
"Table1.primaryColumns.tld.columnType": true,
"Table1.primaryColumns.tld.textColor": true,
"Table1.primaryColumns.tld.textSize": true,
"Table1.primaryColumns.tld.enableFilter": true,
"Table1.primaryColumns.tld.enableSort": true,
"Table1.primaryColumns.tld.isVisible": true,
"Table1.primaryColumns.tld.isDisabled": true,
"Table1.primaryColumns.tld.isCellEditable": true,
"Table1.primaryColumns.tld.isEditable": true,
"Table1.primaryColumns.tld.isCellVisible": true,
"Table1.primaryColumns.tld.isDerived": true,
"Table1.primaryColumns.tld.label": true,
"Table1.primaryColumns.tld.isSaveVisible": true,
"Table1.primaryColumns.tld.isDiscardVisible": true,
"Table1.primaryColumns.tld.computedValue": true,
"Table1.primaryColumns.tld.cellBackground": true,
"Table1.primaryColumns.tld.validation": true,
"Table1.primaryColumns.tld.sticky": true,
"Table1.primaryColumns.cca2": true,
"Table1.primaryColumns.cca2.allowCellWrapping": true,
"Table1.primaryColumns.cca2.index": true,
"Table1.primaryColumns.cca2.width": true,
"Table1.primaryColumns.cca2.originalId": true,
"Table1.primaryColumns.cca2.id": true,
"Table1.primaryColumns.cca2.alias": true,
"Table1.primaryColumns.cca2.horizontalAlignment": true,
"Table1.primaryColumns.cca2.verticalAlignment": true,
"Table1.primaryColumns.cca2.columnType": true,
"Table1.primaryColumns.cca2.textColor": true,
"Table1.primaryColumns.cca2.textSize": true,
"Table1.primaryColumns.cca2.enableFilter": true,
"Table1.primaryColumns.cca2.enableSort": true,
"Table1.primaryColumns.cca2.isVisible": true,
"Table1.primaryColumns.cca2.isDisabled": true,
"Table1.primaryColumns.cca2.isCellEditable": true,
"Table1.primaryColumns.cca2.isEditable": true,
"Table1.primaryColumns.cca2.isCellVisible": true,
"Table1.primaryColumns.cca2.isDerived": true,
"Table1.primaryColumns.cca2.label": true,
"Table1.primaryColumns.cca2.isSaveVisible": true,
"Table1.primaryColumns.cca2.isDiscardVisible": true,
"Table1.primaryColumns.cca2.computedValue": true,
"Table1.primaryColumns.cca2.cellBackground": true,
"Table1.primaryColumns.cca2.validation": true,
"Table1.primaryColumns.cca2.sticky": true,
"Table1.primaryColumns.ccn3": true,
"Table1.primaryColumns.ccn3.allowCellWrapping": true,
"Table1.primaryColumns.ccn3.index": true,
"Table1.primaryColumns.ccn3.width": true,
"Table1.primaryColumns.ccn3.originalId": true,
"Table1.primaryColumns.ccn3.id": true,
"Table1.primaryColumns.ccn3.alias": true,
"Table1.primaryColumns.ccn3.horizontalAlignment": true,
"Table1.primaryColumns.ccn3.verticalAlignment": true,
"Table1.primaryColumns.ccn3.columnType": true,
"Table1.primaryColumns.ccn3.textColor": true,
"Table1.primaryColumns.ccn3.textSize": true,
"Table1.primaryColumns.ccn3.enableFilter": true,
"Table1.primaryColumns.ccn3.enableSort": true,
"Table1.primaryColumns.ccn3.isVisible": true,
"Table1.primaryColumns.ccn3.isDisabled": true,
"Table1.primaryColumns.ccn3.isCellEditable": true,
"Table1.primaryColumns.ccn3.isEditable": true,
"Table1.primaryColumns.ccn3.isCellVisible": true,
"Table1.primaryColumns.ccn3.isDerived": true,
"Table1.primaryColumns.ccn3.label": true,
"Table1.primaryColumns.ccn3.isSaveVisible": true,
"Table1.primaryColumns.ccn3.isDiscardVisible": true,
"Table1.primaryColumns.ccn3.computedValue": true,
"Table1.primaryColumns.ccn3.cellBackground": true,
"Table1.primaryColumns.ccn3.validation": true,
"Table1.primaryColumns.ccn3.sticky": true,
"Table1.primaryColumns.cca3": true,
"Table1.primaryColumns.cca3.allowCellWrapping": true,
"Table1.primaryColumns.cca3.index": true,
"Table1.primaryColumns.cca3.width": true,
"Table1.primaryColumns.cca3.originalId": true,
"Table1.primaryColumns.cca3.id": true,
"Table1.primaryColumns.cca3.alias": true,
"Table1.primaryColumns.cca3.horizontalAlignment": true,
"Table1.primaryColumns.cca3.verticalAlignment": true,
"Table1.primaryColumns.cca3.columnType": true,
"Table1.primaryColumns.cca3.textColor": true,
"Table1.primaryColumns.cca3.textSize": true,
"Table1.primaryColumns.cca3.enableFilter": true,
"Table1.primaryColumns.cca3.enableSort": true,
"Table1.primaryColumns.cca3.isVisible": true,
"Table1.primaryColumns.cca3.isDisabled": true,
"Table1.primaryColumns.cca3.isCellEditable": true,
"Table1.primaryColumns.cca3.isEditable": true,
"Table1.primaryColumns.cca3.isCellVisible": true,
"Table1.primaryColumns.cca3.isDerived": true,
"Table1.primaryColumns.cca3.label": true,
"Table1.primaryColumns.cca3.isSaveVisible": true,
"Table1.primaryColumns.cca3.isDiscardVisible": true,
"Table1.primaryColumns.cca3.computedValue": true,
"Table1.primaryColumns.cca3.cellBackground": true,
"Table1.primaryColumns.cca3.validation": true,
"Table1.primaryColumns.cca3.sticky": true,
"Table1.primaryColumns.cioc": true,
"Table1.primaryColumns.cioc.allowCellWrapping": true,
"Table1.primaryColumns.cioc.index": true,
"Table1.primaryColumns.cioc.width": true,
"Table1.primaryColumns.cioc.originalId": true,
"Table1.primaryColumns.cioc.id": true,
"Table1.primaryColumns.cioc.alias": true,
"Table1.primaryColumns.cioc.horizontalAlignment": true,
"Table1.primaryColumns.cioc.verticalAlignment": true,
"Table1.primaryColumns.cioc.columnType": true,
"Table1.primaryColumns.cioc.textColor": true,
"Table1.primaryColumns.cioc.textSize": true,
"Table1.primaryColumns.cioc.enableFilter": true,
"Table1.primaryColumns.cioc.enableSort": true,
"Table1.primaryColumns.cioc.isVisible": true,
"Table1.primaryColumns.cioc.isDisabled": true,
"Table1.primaryColumns.cioc.isCellEditable": true,
"Table1.primaryColumns.cioc.isEditable": true,
"Table1.primaryColumns.cioc.isCellVisible": true,
"Table1.primaryColumns.cioc.isDerived": true,
"Table1.primaryColumns.cioc.label": true,
"Table1.primaryColumns.cioc.isSaveVisible": true,
"Table1.primaryColumns.cioc.isDiscardVisible": true,
"Table1.primaryColumns.cioc.computedValue": true,
"Table1.primaryColumns.cioc.cellBackground": true,
"Table1.primaryColumns.cioc.validation": true,
"Table1.primaryColumns.cioc.sticky": true,
"Table1.primaryColumns.independent": true,
"Table1.primaryColumns.independent.allowCellWrapping": true,
"Table1.primaryColumns.independent.index": true,
"Table1.primaryColumns.independent.width": true,
"Table1.primaryColumns.independent.originalId": true,
"Table1.primaryColumns.independent.id": true,
"Table1.primaryColumns.independent.alias": true,
"Table1.primaryColumns.independent.horizontalAlignment": true,
"Table1.primaryColumns.independent.verticalAlignment": true,
"Table1.primaryColumns.independent.columnType": true,
"Table1.primaryColumns.independent.textColor": true,
"Table1.primaryColumns.independent.textSize": true,
"Table1.primaryColumns.independent.enableFilter": true,
"Table1.primaryColumns.independent.enableSort": true,
"Table1.primaryColumns.independent.isVisible": true,
"Table1.primaryColumns.independent.isDisabled": true,
"Table1.primaryColumns.independent.isCellEditable": true,
"Table1.primaryColumns.independent.isEditable": true,
"Table1.primaryColumns.independent.isCellVisible": true,
"Table1.primaryColumns.independent.isDerived": true,
"Table1.primaryColumns.independent.label": true,
"Table1.primaryColumns.independent.isSaveVisible": true,
"Table1.primaryColumns.independent.isDiscardVisible": true,
"Table1.primaryColumns.independent.computedValue": true,
"Table1.primaryColumns.independent.cellBackground": true,
"Table1.primaryColumns.independent.validation": true,
"Table1.primaryColumns.independent.sticky": true,
"Table1.primaryColumns.unMember": true,
"Table1.primaryColumns.unMember.allowCellWrapping": true,
"Table1.primaryColumns.unMember.index": true,
"Table1.primaryColumns.unMember.width": true,
"Table1.primaryColumns.unMember.originalId": true,
"Table1.primaryColumns.unMember.id": true,
"Table1.primaryColumns.unMember.alias": true,
"Table1.primaryColumns.unMember.horizontalAlignment": true,
"Table1.primaryColumns.unMember.verticalAlignment": true,
"Table1.primaryColumns.unMember.columnType": true,
"Table1.primaryColumns.unMember.textColor": true,
"Table1.primaryColumns.unMember.textSize": true,
"Table1.primaryColumns.unMember.enableFilter": true,
"Table1.primaryColumns.unMember.enableSort": true,
"Table1.primaryColumns.unMember.isVisible": true,
"Table1.primaryColumns.unMember.isDisabled": true,
"Table1.primaryColumns.unMember.isCellEditable": true,
"Table1.primaryColumns.unMember.isEditable": true,
"Table1.primaryColumns.unMember.isCellVisible": true,
"Table1.primaryColumns.unMember.isDerived": true,
"Table1.primaryColumns.unMember.label": true,
"Table1.primaryColumns.unMember.isSaveVisible": true,
"Table1.primaryColumns.unMember.isDiscardVisible": true,
"Table1.primaryColumns.unMember.computedValue": true,
"Table1.primaryColumns.unMember.cellBackground": true,
"Table1.primaryColumns.unMember.validation": true,
"Table1.primaryColumns.unMember.sticky": true,
"Table1.primaryColumns.currencies": true,
"Table1.primaryColumns.currencies.allowCellWrapping": true,
"Table1.primaryColumns.currencies.index": true,
"Table1.primaryColumns.currencies.width": true,
"Table1.primaryColumns.currencies.originalId": true,
"Table1.primaryColumns.currencies.id": true,
"Table1.primaryColumns.currencies.alias": true,
"Table1.primaryColumns.currencies.horizontalAlignment": true,
"Table1.primaryColumns.currencies.verticalAlignment": true,
"Table1.primaryColumns.currencies.columnType": true,
"Table1.primaryColumns.currencies.textColor": true,
"Table1.primaryColumns.currencies.textSize": true,
"Table1.primaryColumns.currencies.enableFilter": true,
"Table1.primaryColumns.currencies.enableSort": true,
"Table1.primaryColumns.currencies.isVisible": true,
"Table1.primaryColumns.currencies.isDisabled": true,
"Table1.primaryColumns.currencies.isCellEditable": true,
"Table1.primaryColumns.currencies.isEditable": true,
"Table1.primaryColumns.currencies.isCellVisible": true,
"Table1.primaryColumns.currencies.isDerived": true,
"Table1.primaryColumns.currencies.label": true,
"Table1.primaryColumns.currencies.isSaveVisible": true,
"Table1.primaryColumns.currencies.isDiscardVisible": true,
"Table1.primaryColumns.currencies.computedValue": true,
"Table1.primaryColumns.currencies.cellBackground": true,
"Table1.primaryColumns.currencies.validation": true,
"Table1.primaryColumns.currencies.sticky": true,
"Table1.primaryColumns.idd": true,
"Table1.primaryColumns.idd.allowCellWrapping": true,
"Table1.primaryColumns.idd.index": true,
"Table1.primaryColumns.idd.width": true,
"Table1.primaryColumns.idd.originalId": true,
"Table1.primaryColumns.idd.id": true,
"Table1.primaryColumns.idd.alias": true,
"Table1.primaryColumns.idd.horizontalAlignment": true,
"Table1.primaryColumns.idd.verticalAlignment": true,
"Table1.primaryColumns.idd.columnType": true,
"Table1.primaryColumns.idd.textColor": true,
"Table1.primaryColumns.idd.textSize": true,
"Table1.primaryColumns.idd.enableFilter": true,
"Table1.primaryColumns.idd.enableSort": true,
"Table1.primaryColumns.idd.isVisible": true,
"Table1.primaryColumns.idd.isDisabled": true,
"Table1.primaryColumns.idd.isCellEditable": true,
"Table1.primaryColumns.idd.isEditable": true,
"Table1.primaryColumns.idd.isCellVisible": true,
"Table1.primaryColumns.idd.isDerived": true,
"Table1.primaryColumns.idd.label": true,
"Table1.primaryColumns.idd.isSaveVisible": true,
"Table1.primaryColumns.idd.isDiscardVisible": true,
"Table1.primaryColumns.idd.computedValue": true,
"Table1.primaryColumns.idd.cellBackground": true,
"Table1.primaryColumns.idd.validation": true,
"Table1.primaryColumns.idd.sticky": true,
"Table1.primaryColumns.capital": true,
"Table1.primaryColumns.capital.allowCellWrapping": true,
"Table1.primaryColumns.capital.index": true,
"Table1.primaryColumns.capital.width": true,
"Table1.primaryColumns.capital.originalId": true,
"Table1.primaryColumns.capital.id": true,
"Table1.primaryColumns.capital.alias": true,
"Table1.primaryColumns.capital.horizontalAlignment": true,
"Table1.primaryColumns.capital.verticalAlignment": true,
"Table1.primaryColumns.capital.columnType": true,
"Table1.primaryColumns.capital.textColor": true,
"Table1.primaryColumns.capital.textSize": true,
"Table1.primaryColumns.capital.enableFilter": true,
"Table1.primaryColumns.capital.enableSort": true,
"Table1.primaryColumns.capital.isVisible": true,
"Table1.primaryColumns.capital.isDisabled": true,
"Table1.primaryColumns.capital.isCellEditable": true,
"Table1.primaryColumns.capital.isEditable": true,
"Table1.primaryColumns.capital.isCellVisible": true,
"Table1.primaryColumns.capital.isDerived": true,
"Table1.primaryColumns.capital.label": true,
"Table1.primaryColumns.capital.isSaveVisible": true,
"Table1.primaryColumns.capital.isDiscardVisible": true,
"Table1.primaryColumns.capital.computedValue": true,
"Table1.primaryColumns.capital.cellBackground": true,
"Table1.primaryColumns.capital.validation": true,
"Table1.primaryColumns.capital.sticky": true,
"Table1.primaryColumns.altSpellings": true,
"Table1.primaryColumns.altSpellings.allowCellWrapping": true,
"Table1.primaryColumns.altSpellings.index": true,
"Table1.primaryColumns.altSpellings.width": true,
"Table1.primaryColumns.altSpellings.originalId": true,
"Table1.primaryColumns.altSpellings.id": true,
"Table1.primaryColumns.altSpellings.alias": true,
"Table1.primaryColumns.altSpellings.horizontalAlignment": true,
"Table1.primaryColumns.altSpellings.verticalAlignment": true,
"Table1.primaryColumns.altSpellings.columnType": true,
"Table1.primaryColumns.altSpellings.textColor": true,
"Table1.primaryColumns.altSpellings.textSize": true,
"Table1.primaryColumns.altSpellings.enableFilter": true,
"Table1.primaryColumns.altSpellings.enableSort": true,
"Table1.primaryColumns.altSpellings.isVisible": true,
"Table1.primaryColumns.altSpellings.isDisabled": true,
"Table1.primaryColumns.altSpellings.isCellEditable": true,
"Table1.primaryColumns.altSpellings.isEditable": true,
"Table1.primaryColumns.altSpellings.isCellVisible": true,
"Table1.primaryColumns.altSpellings.isDerived": true,
"Table1.primaryColumns.altSpellings.label": true,
"Table1.primaryColumns.altSpellings.isSaveVisible": true,
"Table1.primaryColumns.altSpellings.isDiscardVisible": true,
"Table1.primaryColumns.altSpellings.computedValue": true,
"Table1.primaryColumns.altSpellings.cellBackground": true,
"Table1.primaryColumns.altSpellings.validation": true,
"Table1.primaryColumns.altSpellings.sticky": true,
"Table1.primaryColumns.region": true,
"Table1.primaryColumns.region.allowCellWrapping": true,
"Table1.primaryColumns.region.index": true,
"Table1.primaryColumns.region.width": true,
"Table1.primaryColumns.region.originalId": true,
"Table1.primaryColumns.region.id": true,
"Table1.primaryColumns.region.alias": true,
"Table1.primaryColumns.region.horizontalAlignment": true,
"Table1.primaryColumns.region.verticalAlignment": true,
"Table1.primaryColumns.region.columnType": true,
"Table1.primaryColumns.region.textColor": true,
"Table1.primaryColumns.region.textSize": true,
"Table1.primaryColumns.region.enableFilter": true,
"Table1.primaryColumns.region.enableSort": true,
"Table1.primaryColumns.region.isVisible": true,
"Table1.primaryColumns.region.isDisabled": true,
"Table1.primaryColumns.region.isCellEditable": true,
"Table1.primaryColumns.region.isEditable": true,
"Table1.primaryColumns.region.isCellVisible": true,
"Table1.primaryColumns.region.isDerived": true,
"Table1.primaryColumns.region.label": true,
"Table1.primaryColumns.region.isSaveVisible": true,
"Table1.primaryColumns.region.isDiscardVisible": true,
"Table1.primaryColumns.region.computedValue": true,
"Table1.primaryColumns.region.cellBackground": true,
"Table1.primaryColumns.region.validation": true,
"Table1.primaryColumns.region.sticky": true,
"Table1.primaryColumns.subregion": true,
"Table1.primaryColumns.subregion.allowCellWrapping": true,
"Table1.primaryColumns.subregion.index": true,
"Table1.primaryColumns.subregion.width": true,
"Table1.primaryColumns.subregion.originalId": true,
"Table1.primaryColumns.subregion.id": true,
"Table1.primaryColumns.subregion.alias": true,
"Table1.primaryColumns.subregion.horizontalAlignment": true,
"Table1.primaryColumns.subregion.verticalAlignment": true,
"Table1.primaryColumns.subregion.columnType": true,
"Table1.primaryColumns.subregion.textColor": true,
"Table1.primaryColumns.subregion.textSize": true,
"Table1.primaryColumns.subregion.enableFilter": true,
"Table1.primaryColumns.subregion.enableSort": true,
"Table1.primaryColumns.subregion.isVisible": true,
"Table1.primaryColumns.subregion.isDisabled": true,
"Table1.primaryColumns.subregion.isCellEditable": true,
"Table1.primaryColumns.subregion.isEditable": true,
"Table1.primaryColumns.subregion.isCellVisible": true,
"Table1.primaryColumns.subregion.isDerived": true,
"Table1.primaryColumns.subregion.label": true,
"Table1.primaryColumns.subregion.isSaveVisible": true,
"Table1.primaryColumns.subregion.isDiscardVisible": true,
"Table1.primaryColumns.subregion.computedValue": true,
"Table1.primaryColumns.subregion.cellBackground": true,
"Table1.primaryColumns.subregion.validation": true,
"Table1.primaryColumns.subregion.sticky": true,
"Table1.primaryColumns.languages": true,
"Table1.primaryColumns.languages.allowCellWrapping": true,
"Table1.primaryColumns.languages.index": true,
"Table1.primaryColumns.languages.width": true,
"Table1.primaryColumns.languages.originalId": true,
"Table1.primaryColumns.languages.id": true,
"Table1.primaryColumns.languages.alias": true,
"Table1.primaryColumns.languages.horizontalAlignment": true,
"Table1.primaryColumns.languages.verticalAlignment": true,
"Table1.primaryColumns.languages.columnType": true,
"Table1.primaryColumns.languages.textColor": true,
"Table1.primaryColumns.languages.textSize": true,
"Table1.primaryColumns.languages.enableFilter": true,
"Table1.primaryColumns.languages.enableSort": true,
"Table1.primaryColumns.languages.isVisible": true,
"Table1.primaryColumns.languages.isDisabled": true,
"Table1.primaryColumns.languages.isCellEditable": true,
"Table1.primaryColumns.languages.isEditable": true,
"Table1.primaryColumns.languages.isCellVisible": true,
"Table1.primaryColumns.languages.isDerived": true,
"Table1.primaryColumns.languages.label": true,
"Table1.primaryColumns.languages.isSaveVisible": true,
"Table1.primaryColumns.languages.isDiscardVisible": true,
"Table1.primaryColumns.languages.computedValue": true,
"Table1.primaryColumns.languages.cellBackground": true,
"Table1.primaryColumns.languages.validation": true,
"Table1.primaryColumns.languages.sticky": true,
"Table1.primaryColumns.translations": true,
"Table1.primaryColumns.translations.allowCellWrapping": true,
"Table1.primaryColumns.translations.index": true,
"Table1.primaryColumns.translations.width": true,
"Table1.primaryColumns.translations.originalId": true,
"Table1.primaryColumns.translations.id": true,
"Table1.primaryColumns.translations.alias": true,
"Table1.primaryColumns.translations.horizontalAlignment": true,
"Table1.primaryColumns.translations.verticalAlignment": true,
"Table1.primaryColumns.translations.columnType": true,
"Table1.primaryColumns.translations.textColor": true,
"Table1.primaryColumns.translations.textSize": true,
"Table1.primaryColumns.translations.enableFilter": true,
"Table1.primaryColumns.translations.enableSort": true,
"Table1.primaryColumns.translations.isVisible": true,
"Table1.primaryColumns.translations.isDisabled": true,
"Table1.primaryColumns.translations.isCellEditable": true,
"Table1.primaryColumns.translations.isEditable": true,
"Table1.primaryColumns.translations.isCellVisible": true,
"Table1.primaryColumns.translations.isDerived": true,
"Table1.primaryColumns.translations.label": true,
"Table1.primaryColumns.translations.isSaveVisible": true,
"Table1.primaryColumns.translations.isDiscardVisible": true,
"Table1.primaryColumns.translations.computedValue": true,
"Table1.primaryColumns.translations.cellBackground": true,
"Table1.primaryColumns.translations.validation": true,
"Table1.primaryColumns.translations.sticky": true,
"Table1.primaryColumns.latlng": true,
"Table1.primaryColumns.latlng.allowCellWrapping": true,
"Table1.primaryColumns.latlng.index": true,
"Table1.primaryColumns.latlng.width": true,
"Table1.primaryColumns.latlng.originalId": true,
"Table1.primaryColumns.latlng.id": true,
"Table1.primaryColumns.latlng.alias": true,
"Table1.primaryColumns.latlng.horizontalAlignment": true,
"Table1.primaryColumns.latlng.verticalAlignment": true,
"Table1.primaryColumns.latlng.columnType": true,
"Table1.primaryColumns.latlng.textColor": true,
"Table1.primaryColumns.latlng.textSize": true,
"Table1.primaryColumns.latlng.enableFilter": true,
"Table1.primaryColumns.latlng.enableSort": true,
"Table1.primaryColumns.latlng.isVisible": true,
"Table1.primaryColumns.latlng.isDisabled": true,
"Table1.primaryColumns.latlng.isCellEditable": true,
"Table1.primaryColumns.latlng.isEditable": true,
"Table1.primaryColumns.latlng.isCellVisible": true,
"Table1.primaryColumns.latlng.isDerived": true,
"Table1.primaryColumns.latlng.label": true,
"Table1.primaryColumns.latlng.isSaveVisible": true,
"Table1.primaryColumns.latlng.isDiscardVisible": true,
"Table1.primaryColumns.latlng.computedValue": true,
"Table1.primaryColumns.latlng.cellBackground": true,
"Table1.primaryColumns.latlng.validation": true,
"Table1.primaryColumns.latlng.sticky": true,
"Table1.primaryColumns.landlocked": true,
"Table1.primaryColumns.landlocked.allowCellWrapping": true,
"Table1.primaryColumns.landlocked.index": true,
"Table1.primaryColumns.landlocked.width": true,
"Table1.primaryColumns.landlocked.originalId": true,
"Table1.primaryColumns.landlocked.id": true,
"Table1.primaryColumns.landlocked.alias": true,
"Table1.primaryColumns.landlocked.horizontalAlignment": true,
"Table1.primaryColumns.landlocked.verticalAlignment": true,
"Table1.primaryColumns.landlocked.columnType": true,
"Table1.primaryColumns.landlocked.textColor": true,
"Table1.primaryColumns.landlocked.textSize": true,
"Table1.primaryColumns.landlocked.enableFilter": true,
"Table1.primaryColumns.landlocked.enableSort": true,
"Table1.primaryColumns.landlocked.isVisible": true,
"Table1.primaryColumns.landlocked.isDisabled": true,
"Table1.primaryColumns.landlocked.isCellEditable": true,
"Table1.primaryColumns.landlocked.isEditable": true,
"Table1.primaryColumns.landlocked.isCellVisible": true,
"Table1.primaryColumns.landlocked.isDerived": true,
"Table1.primaryColumns.landlocked.label": true,
"Table1.primaryColumns.landlocked.isSaveVisible": true,
"Table1.primaryColumns.landlocked.isDiscardVisible": true,
"Table1.primaryColumns.landlocked.computedValue": true,
"Table1.primaryColumns.landlocked.cellBackground": true,
"Table1.primaryColumns.landlocked.validation": true,
"Table1.primaryColumns.landlocked.sticky": true,
"Table1.primaryColumns.borders": true,
"Table1.primaryColumns.borders.allowCellWrapping": true,
"Table1.primaryColumns.borders.index": true,
"Table1.primaryColumns.borders.width": true,
"Table1.primaryColumns.borders.originalId": true,
"Table1.primaryColumns.borders.id": true,
"Table1.primaryColumns.borders.alias": true,
"Table1.primaryColumns.borders.horizontalAlignment": true,
"Table1.primaryColumns.borders.verticalAlignment": true,
"Table1.primaryColumns.borders.columnType": true,
"Table1.primaryColumns.borders.textColor": true,
"Table1.primaryColumns.borders.textSize": true,
"Table1.primaryColumns.borders.enableFilter": true,
"Table1.primaryColumns.borders.enableSort": true,
"Table1.primaryColumns.borders.isVisible": true,
"Table1.primaryColumns.borders.isDisabled": true,
"Table1.primaryColumns.borders.isCellEditable": true,
"Table1.primaryColumns.borders.isEditable": true,
"Table1.primaryColumns.borders.isCellVisible": true,
"Table1.primaryColumns.borders.isDerived": true,
"Table1.primaryColumns.borders.label": true,
"Table1.primaryColumns.borders.isSaveVisible": true,
"Table1.primaryColumns.borders.isDiscardVisible": true,
"Table1.primaryColumns.borders.computedValue": true,
"Table1.primaryColumns.borders.cellBackground": true,
"Table1.primaryColumns.borders.validation": true,
"Table1.primaryColumns.borders.sticky": true,
"Table1.primaryColumns.area": true,
"Table1.primaryColumns.area.allowCellWrapping": true,
"Table1.primaryColumns.area.index": true,
"Table1.primaryColumns.area.width": true,
"Table1.primaryColumns.area.originalId": true,
"Table1.primaryColumns.area.id": true,
"Table1.primaryColumns.area.alias": true,
"Table1.primaryColumns.area.horizontalAlignment": true,
"Table1.primaryColumns.area.verticalAlignment": true,
"Table1.primaryColumns.area.columnType": true,
"Table1.primaryColumns.area.textColor": true,
"Table1.primaryColumns.area.textSize": true,
"Table1.primaryColumns.area.enableFilter": true,
"Table1.primaryColumns.area.enableSort": true,
"Table1.primaryColumns.area.isVisible": true,
"Table1.primaryColumns.area.isDisabled": true,
"Table1.primaryColumns.area.isCellEditable": true,
"Table1.primaryColumns.area.isEditable": true,
"Table1.primaryColumns.area.isCellVisible": true,
"Table1.primaryColumns.area.isDerived": true,
"Table1.primaryColumns.area.label": true,
"Table1.primaryColumns.area.isSaveVisible": true,
"Table1.primaryColumns.area.isDiscardVisible": true,
"Table1.primaryColumns.area.computedValue": true,
"Table1.primaryColumns.area.cellBackground": true,
"Table1.primaryColumns.area.validation": true,
"Table1.primaryColumns.area.sticky": true,
"Table1.primaryColumns.demonyms": true,
"Table1.primaryColumns.demonyms.allowCellWrapping": true,
"Table1.primaryColumns.demonyms.index": true,
"Table1.primaryColumns.demonyms.width": true,
"Table1.primaryColumns.demonyms.originalId": true,
"Table1.primaryColumns.demonyms.id": true,
"Table1.primaryColumns.demonyms.alias": true,
"Table1.primaryColumns.demonyms.horizontalAlignment": true,
"Table1.primaryColumns.demonyms.verticalAlignment": true,
"Table1.primaryColumns.demonyms.columnType": true,
"Table1.primaryColumns.demonyms.textColor": true,
"Table1.primaryColumns.demonyms.textSize": true,
"Table1.primaryColumns.demonyms.enableFilter": true,
"Table1.primaryColumns.demonyms.enableSort": true,
"Table1.primaryColumns.demonyms.isVisible": true,
"Table1.primaryColumns.demonyms.isDisabled": true,
"Table1.primaryColumns.demonyms.isCellEditable": true,
"Table1.primaryColumns.demonyms.isEditable": true,
"Table1.primaryColumns.demonyms.isCellVisible": true,
"Table1.primaryColumns.demonyms.isDerived": true,
"Table1.primaryColumns.demonyms.label": true,
"Table1.primaryColumns.demonyms.isSaveVisible": true,
"Table1.primaryColumns.demonyms.isDiscardVisible": true,
"Table1.primaryColumns.demonyms.computedValue": true,
"Table1.primaryColumns.demonyms.cellBackground": true,
"Table1.primaryColumns.demonyms.validation": true,
"Table1.primaryColumns.demonyms.sticky": true,
"Table1.primaryColumns.flag": true,
"Table1.primaryColumns.flag.allowCellWrapping": true,
"Table1.primaryColumns.flag.index": true,
"Table1.primaryColumns.flag.width": true,
"Table1.primaryColumns.flag.originalId": true,
"Table1.primaryColumns.flag.id": true,
"Table1.primaryColumns.flag.alias": true,
"Table1.primaryColumns.flag.horizontalAlignment": true,
"Table1.primaryColumns.flag.verticalAlignment": true,
"Table1.primaryColumns.flag.columnType": true,
"Table1.primaryColumns.flag.textColor": true,
"Table1.primaryColumns.flag.textSize": true,
"Table1.primaryColumns.flag.enableFilter": true,
"Table1.primaryColumns.flag.enableSort": true,
"Table1.primaryColumns.flag.isVisible": true,
"Table1.primaryColumns.flag.isDisabled": true,
"Table1.primaryColumns.flag.isCellEditable": true,
"Table1.primaryColumns.flag.isEditable": true,
"Table1.primaryColumns.flag.isCellVisible": true,
"Table1.primaryColumns.flag.isDerived": true,
"Table1.primaryColumns.flag.label": true,
"Table1.primaryColumns.flag.isSaveVisible": true,
"Table1.primaryColumns.flag.isDiscardVisible": true,
"Table1.primaryColumns.flag.computedValue": true,
"Table1.primaryColumns.flag.cellBackground": true,
"Table1.primaryColumns.flag.validation": true,
"Table1.primaryColumns.flag.sticky": true,
"Table1.primaryColumns.maps": true,
"Table1.primaryColumns.maps.allowCellWrapping": true,
"Table1.primaryColumns.maps.index": true,
"Table1.primaryColumns.maps.width": true,
"Table1.primaryColumns.maps.originalId": true,
"Table1.primaryColumns.maps.id": true,
"Table1.primaryColumns.maps.alias": true,
"Table1.primaryColumns.maps.horizontalAlignment": true,
"Table1.primaryColumns.maps.verticalAlignment": true,
"Table1.primaryColumns.maps.columnType": true,
"Table1.primaryColumns.maps.textColor": true,
"Table1.primaryColumns.maps.textSize": true,
"Table1.primaryColumns.maps.enableFilter": true,
"Table1.primaryColumns.maps.enableSort": true,
"Table1.primaryColumns.maps.isVisible": true,
"Table1.primaryColumns.maps.isDisabled": true,
"Table1.primaryColumns.maps.isCellEditable": true,
"Table1.primaryColumns.maps.isEditable": true,
"Table1.primaryColumns.maps.isCellVisible": true,
"Table1.primaryColumns.maps.isDerived": true,
"Table1.primaryColumns.maps.label": true,
"Table1.primaryColumns.maps.isSaveVisible": true,
"Table1.primaryColumns.maps.isDiscardVisible": true,
"Table1.primaryColumns.maps.computedValue": true,
"Table1.primaryColumns.maps.cellBackground": true,
"Table1.primaryColumns.maps.validation": true,
"Table1.primaryColumns.maps.sticky": true,
"Table1.primaryColumns.population": true,
"Table1.primaryColumns.population.allowCellWrapping": true,
"Table1.primaryColumns.population.index": true,
"Table1.primaryColumns.population.width": true,
"Table1.primaryColumns.population.originalId": true,
"Table1.primaryColumns.population.id": true,
"Table1.primaryColumns.population.alias": true,
"Table1.primaryColumns.population.horizontalAlignment": true,
"Table1.primaryColumns.population.verticalAlignment": true,
"Table1.primaryColumns.population.columnType": true,
"Table1.primaryColumns.population.textColor": true,
"Table1.primaryColumns.population.textSize": true,
"Table1.primaryColumns.population.enableFilter": true,
"Table1.primaryColumns.population.enableSort": true,
"Table1.primaryColumns.population.isVisible": true,
"Table1.primaryColumns.population.isDisabled": true,
"Table1.primaryColumns.population.isCellEditable": true,
"Table1.primaryColumns.population.isEditable": true,
"Table1.primaryColumns.population.isCellVisible": true,
"Table1.primaryColumns.population.isDerived": true,
"Table1.primaryColumns.population.label": true,
"Table1.primaryColumns.population.isSaveVisible": true,
"Table1.primaryColumns.population.isDiscardVisible": true,
"Table1.primaryColumns.population.computedValue": true,
"Table1.primaryColumns.population.cellBackground": true,
"Table1.primaryColumns.population.validation": true,
"Table1.primaryColumns.population.sticky": true,
"Table1.primaryColumns.fifa": true,
"Table1.primaryColumns.fifa.allowCellWrapping": true,
"Table1.primaryColumns.fifa.index": true,
"Table1.primaryColumns.fifa.width": true,
"Table1.primaryColumns.fifa.originalId": true,
"Table1.primaryColumns.fifa.id": true,
"Table1.primaryColumns.fifa.alias": true,
"Table1.primaryColumns.fifa.horizontalAlignment": true,
"Table1.primaryColumns.fifa.verticalAlignment": true,
"Table1.primaryColumns.fifa.columnType": true,
"Table1.primaryColumns.fifa.textColor": true,
"Table1.primaryColumns.fifa.textSize": true,
"Table1.primaryColumns.fifa.enableFilter": true,
"Table1.primaryColumns.fifa.enableSort": true,
"Table1.primaryColumns.fifa.isVisible": true,
"Table1.primaryColumns.fifa.isDisabled": true,
"Table1.primaryColumns.fifa.isCellEditable": true,
"Table1.primaryColumns.fifa.isEditable": true,
"Table1.primaryColumns.fifa.isCellVisible": true,
"Table1.primaryColumns.fifa.isDerived": true,
"Table1.primaryColumns.fifa.label": true,
"Table1.primaryColumns.fifa.isSaveVisible": true,
"Table1.primaryColumns.fifa.isDiscardVisible": true,
"Table1.primaryColumns.fifa.computedValue": true,
"Table1.primaryColumns.fifa.cellBackground": true,
"Table1.primaryColumns.fifa.validation": true,
"Table1.primaryColumns.fifa.sticky": true,
"Table1.primaryColumns.car": true,
"Table1.primaryColumns.car.allowCellWrapping": true,
"Table1.primaryColumns.car.index": true,
"Table1.primaryColumns.car.width": true,
"Table1.primaryColumns.car.originalId": true,
"Table1.primaryColumns.car.id": true,
"Table1.primaryColumns.car.alias": true,
"Table1.primaryColumns.car.horizontalAlignment": true,
"Table1.primaryColumns.car.verticalAlignment": true,
"Table1.primaryColumns.car.columnType": true,
"Table1.primaryColumns.car.textColor": true,
"Table1.primaryColumns.car.textSize": true,
"Table1.primaryColumns.car.enableFilter": true,
"Table1.primaryColumns.car.enableSort": true,
"Table1.primaryColumns.car.isVisible": true,
"Table1.primaryColumns.car.isDisabled": true,
"Table1.primaryColumns.car.isCellEditable": true,
"Table1.primaryColumns.car.isEditable": true,
"Table1.primaryColumns.car.isCellVisible": true,
"Table1.primaryColumns.car.isDerived": true,
"Table1.primaryColumns.car.label": true,
"Table1.primaryColumns.car.isSaveVisible": true,
"Table1.primaryColumns.car.isDiscardVisible": true,
"Table1.primaryColumns.car.computedValue": true,
"Table1.primaryColumns.car.cellBackground": true,
"Table1.primaryColumns.car.validation": true,
"Table1.primaryColumns.car.sticky": true,
"Table1.primaryColumns.timezones": true,
"Table1.primaryColumns.timezones.allowCellWrapping": true,
"Table1.primaryColumns.timezones.index": true,
"Table1.primaryColumns.timezones.width": true,
"Table1.primaryColumns.timezones.originalId": true,
"Table1.primaryColumns.timezones.id": true,
"Table1.primaryColumns.timezones.alias": true,
"Table1.primaryColumns.timezones.horizontalAlignment": true,
"Table1.primaryColumns.timezones.verticalAlignment": true,
"Table1.primaryColumns.timezones.columnType": true,
"Table1.primaryColumns.timezones.textColor": true,
"Table1.primaryColumns.timezones.textSize": true,
"Table1.primaryColumns.timezones.enableFilter": true,
"Table1.primaryColumns.timezones.enableSort": true,
"Table1.primaryColumns.timezones.isVisible": true,
"Table1.primaryColumns.timezones.isDisabled": true,
"Table1.primaryColumns.timezones.isCellEditable": true,
"Table1.primaryColumns.timezones.isEditable": true,
"Table1.primaryColumns.timezones.isCellVisible": true,
"Table1.primaryColumns.timezones.isDerived": true,
"Table1.primaryColumns.timezones.label": true,
"Table1.primaryColumns.timezones.isSaveVisible": true,
"Table1.primaryColumns.timezones.isDiscardVisible": true,
"Table1.primaryColumns.timezones.computedValue": true,
"Table1.primaryColumns.timezones.cellBackground": true,
"Table1.primaryColumns.timezones.validation": true,
"Table1.primaryColumns.timezones.sticky": true,
"Table1.primaryColumns.continents": true,
"Table1.primaryColumns.continents.allowCellWrapping": true,
"Table1.primaryColumns.continents.index": true,
"Table1.primaryColumns.continents.width": true,
"Table1.primaryColumns.continents.originalId": true,
"Table1.primaryColumns.continents.id": true,
"Table1.primaryColumns.continents.alias": true,
"Table1.primaryColumns.continents.horizontalAlignment": true,
"Table1.primaryColumns.continents.verticalAlignment": true,
"Table1.primaryColumns.continents.columnType": true,
"Table1.primaryColumns.continents.textColor": true,
"Table1.primaryColumns.continents.textSize": true,
"Table1.primaryColumns.continents.enableFilter": true,
"Table1.primaryColumns.continents.enableSort": true,
"Table1.primaryColumns.continents.isVisible": true,
"Table1.primaryColumns.continents.isDisabled": true,
"Table1.primaryColumns.continents.isCellEditable": true,
"Table1.primaryColumns.continents.isEditable": true,
"Table1.primaryColumns.continents.isCellVisible": true,
"Table1.primaryColumns.continents.isDerived": true,
"Table1.primaryColumns.continents.label": true,
"Table1.primaryColumns.continents.isSaveVisible": true,
"Table1.primaryColumns.continents.isDiscardVisible": true,
"Table1.primaryColumns.continents.computedValue": true,
"Table1.primaryColumns.continents.cellBackground": true,
"Table1.primaryColumns.continents.validation": true,
"Table1.primaryColumns.continents.sticky": true,
"Table1.primaryColumns.flags": true,
"Table1.primaryColumns.flags.allowCellWrapping": true,
"Table1.primaryColumns.flags.index": true,
"Table1.primaryColumns.flags.width": true,
"Table1.primaryColumns.flags.originalId": true,
"Table1.primaryColumns.flags.id": true,
"Table1.primaryColumns.flags.alias": true,
"Table1.primaryColumns.flags.horizontalAlignment": true,
"Table1.primaryColumns.flags.verticalAlignment": true,
"Table1.primaryColumns.flags.columnType": true,
"Table1.primaryColumns.flags.textColor": true,
"Table1.primaryColumns.flags.textSize": true,
"Table1.primaryColumns.flags.enableFilter": true,
"Table1.primaryColumns.flags.enableSort": true,
"Table1.primaryColumns.flags.isVisible": true,
"Table1.primaryColumns.flags.isDisabled": true,
"Table1.primaryColumns.flags.isCellEditable": true,
"Table1.primaryColumns.flags.isEditable": true,
"Table1.primaryColumns.flags.isCellVisible": true,
"Table1.primaryColumns.flags.isDerived": true,
"Table1.primaryColumns.flags.label": true,
"Table1.primaryColumns.flags.isSaveVisible": true,
"Table1.primaryColumns.flags.isDiscardVisible": true,
"Table1.primaryColumns.flags.computedValue": true,
"Table1.primaryColumns.flags.cellBackground": true,
"Table1.primaryColumns.flags.validation": true,
"Table1.primaryColumns.flags.sticky": true,
"Table1.primaryColumns.coatOfArms": true,
"Table1.primaryColumns.coatOfArms.allowCellWrapping": true,
"Table1.primaryColumns.coatOfArms.index": true,
"Table1.primaryColumns.coatOfArms.width": true,
"Table1.primaryColumns.coatOfArms.originalId": true,
"Table1.primaryColumns.coatOfArms.id": true,
"Table1.primaryColumns.coatOfArms.alias": true,
"Table1.primaryColumns.coatOfArms.horizontalAlignment": true,
"Table1.primaryColumns.coatOfArms.verticalAlignment": true,
"Table1.primaryColumns.coatOfArms.columnType": true,
"Table1.primaryColumns.coatOfArms.textColor": true,
"Table1.primaryColumns.coatOfArms.textSize": true,
"Table1.primaryColumns.coatOfArms.enableFilter": true,
"Table1.primaryColumns.coatOfArms.enableSort": true,
"Table1.primaryColumns.coatOfArms.isVisible": true,
"Table1.primaryColumns.coatOfArms.isDisabled": true,
"Table1.primaryColumns.coatOfArms.isCellEditable": true,
"Table1.primaryColumns.coatOfArms.isEditable": true,
"Table1.primaryColumns.coatOfArms.isCellVisible": true,
"Table1.primaryColumns.coatOfArms.isDerived": true,
"Table1.primaryColumns.coatOfArms.label": true,
"Table1.primaryColumns.coatOfArms.isSaveVisible": true,
"Table1.primaryColumns.coatOfArms.isDiscardVisible": true,
"Table1.primaryColumns.coatOfArms.computedValue": true,
"Table1.primaryColumns.coatOfArms.cellBackground": true,
"Table1.primaryColumns.coatOfArms.validation": true,
"Table1.primaryColumns.coatOfArms.sticky": true,
"Table1.primaryColumns.startOfWeek": true,
"Table1.primaryColumns.startOfWeek.allowCellWrapping": true,
"Table1.primaryColumns.startOfWeek.index": true,
"Table1.primaryColumns.startOfWeek.width": true,
"Table1.primaryColumns.startOfWeek.originalId": true,
"Table1.primaryColumns.startOfWeek.id": true,
"Table1.primaryColumns.startOfWeek.alias": true,
"Table1.primaryColumns.startOfWeek.horizontalAlignment": true,
"Table1.primaryColumns.startOfWeek.verticalAlignment": true,
"Table1.primaryColumns.startOfWeek.columnType": true,
"Table1.primaryColumns.startOfWeek.textColor": true,
"Table1.primaryColumns.startOfWeek.textSize": true,
"Table1.primaryColumns.startOfWeek.enableFilter": true,
"Table1.primaryColumns.startOfWeek.enableSort": true,
"Table1.primaryColumns.startOfWeek.isVisible": true,
"Table1.primaryColumns.startOfWeek.isDisabled": true,
"Table1.primaryColumns.startOfWeek.isCellEditable": true,
"Table1.primaryColumns.startOfWeek.isEditable": true,
"Table1.primaryColumns.startOfWeek.isCellVisible": true,
"Table1.primaryColumns.startOfWeek.isDerived": true,
"Table1.primaryColumns.startOfWeek.label": true,
"Table1.primaryColumns.startOfWeek.isSaveVisible": true,
"Table1.primaryColumns.startOfWeek.isDiscardVisible": true,
"Table1.primaryColumns.startOfWeek.computedValue": true,
"Table1.primaryColumns.startOfWeek.cellBackground": true,
"Table1.primaryColumns.startOfWeek.validation": true,
"Table1.primaryColumns.startOfWeek.sticky": true,
"Table1.primaryColumns.capitalInfo": true,
"Table1.primaryColumns.capitalInfo.allowCellWrapping": true,
"Table1.primaryColumns.capitalInfo.index": true,
"Table1.primaryColumns.capitalInfo.width": true,
"Table1.primaryColumns.capitalInfo.originalId": true,
"Table1.primaryColumns.capitalInfo.id": true,
"Table1.primaryColumns.capitalInfo.alias": true,
"Table1.primaryColumns.capitalInfo.horizontalAlignment": true,
"Table1.primaryColumns.capitalInfo.verticalAlignment": true,
"Table1.primaryColumns.capitalInfo.columnType": true,
"Table1.primaryColumns.capitalInfo.textColor": true,
"Table1.primaryColumns.capitalInfo.textSize": true,
"Table1.primaryColumns.capitalInfo.enableFilter": true,
"Table1.primaryColumns.capitalInfo.enableSort": true,
"Table1.primaryColumns.capitalInfo.isVisible": true,
"Table1.primaryColumns.capitalInfo.isDisabled": true,
"Table1.primaryColumns.capitalInfo.isCellEditable": true,
"Table1.primaryColumns.capitalInfo.isEditable": true,
"Table1.primaryColumns.capitalInfo.isCellVisible": true,
"Table1.primaryColumns.capitalInfo.isDerived": true,
"Table1.primaryColumns.capitalInfo.label": true,
"Table1.primaryColumns.capitalInfo.isSaveVisible": true,
"Table1.primaryColumns.capitalInfo.isDiscardVisible": true,
"Table1.primaryColumns.capitalInfo.computedValue": true,
"Table1.primaryColumns.capitalInfo.cellBackground": true,
"Table1.primaryColumns.capitalInfo.validation": true,
"Table1.primaryColumns.capitalInfo.sticky": true,
"Table1.primaryColumns.postalCode": true,
"Table1.primaryColumns.postalCode.allowCellWrapping": true,
"Table1.primaryColumns.postalCode.index": true,
"Table1.primaryColumns.postalCode.width": true,
"Table1.primaryColumns.postalCode.originalId": true,
"Table1.primaryColumns.postalCode.id": true,
"Table1.primaryColumns.postalCode.alias": true,
"Table1.primaryColumns.postalCode.horizontalAlignment": true,
"Table1.primaryColumns.postalCode.verticalAlignment": true,
"Table1.primaryColumns.postalCode.columnType": true,
"Table1.primaryColumns.postalCode.textColor": true,
"Table1.primaryColumns.postalCode.textSize": true,
"Table1.primaryColumns.postalCode.enableFilter": true,
"Table1.primaryColumns.postalCode.enableSort": true,
"Table1.primaryColumns.postalCode.isVisible": true,
"Table1.primaryColumns.postalCode.isDisabled": true,
"Table1.primaryColumns.postalCode.isCellEditable": true,
"Table1.primaryColumns.postalCode.isEditable": true,
"Table1.primaryColumns.postalCode.isCellVisible": true,
"Table1.primaryColumns.postalCode.isDerived": true,
"Table1.primaryColumns.postalCode.label": true,
"Table1.primaryColumns.postalCode.isSaveVisible": true,
"Table1.primaryColumns.postalCode.isDiscardVisible": true,
"Table1.primaryColumns.postalCode.computedValue": true,
"Table1.primaryColumns.postalCode.cellBackground": true,
"Table1.primaryColumns.postalCode.validation": true,
"Table1.primaryColumns.postalCode.sticky": true,
"Table1.primaryColumns.gini": true,
"Table1.primaryColumns.gini.allowCellWrapping": true,
"Table1.primaryColumns.gini.index": true,
"Table1.primaryColumns.gini.width": true,
"Table1.primaryColumns.gini.originalId": true,
"Table1.primaryColumns.gini.id": true,
"Table1.primaryColumns.gini.alias": true,
"Table1.primaryColumns.gini.horizontalAlignment": true,
"Table1.primaryColumns.gini.verticalAlignment": true,
"Table1.primaryColumns.gini.columnType": true,
"Table1.primaryColumns.gini.textColor": true,
"Table1.primaryColumns.gini.textSize": true,
"Table1.primaryColumns.gini.enableFilter": true,
"Table1.primaryColumns.gini.enableSort": true,
"Table1.primaryColumns.gini.isVisible": true,
"Table1.primaryColumns.gini.isDisabled": true,
"Table1.primaryColumns.gini.isCellEditable": true,
"Table1.primaryColumns.gini.isEditable": true,
"Table1.primaryColumns.gini.isCellVisible": true,
"Table1.primaryColumns.gini.isDerived": true,
"Table1.primaryColumns.gini.label": true,
"Table1.primaryColumns.gini.isSaveVisible": true,
"Table1.primaryColumns.gini.isDiscardVisible": true,
"Table1.primaryColumns.gini.computedValue": true,
"Table1.primaryColumns.gini.cellBackground": true,
"Table1.primaryColumns.gini.validation": true,
"Table1.primaryColumns.gini.sticky": true,
"Table1.primaryColumns.EditActions1": true,
"Table1.primaryColumns.EditActions1.allowCellWrapping": true,
"Table1.primaryColumns.EditActions1.index": true,
"Table1.primaryColumns.EditActions1.width": true,
"Table1.primaryColumns.EditActions1.originalId": true,
"Table1.primaryColumns.EditActions1.id": true,
"Table1.primaryColumns.EditActions1.alias": true,
"Table1.primaryColumns.EditActions1.horizontalAlignment": true,
"Table1.primaryColumns.EditActions1.verticalAlignment": true,
"Table1.primaryColumns.EditActions1.columnType": true,
"Table1.primaryColumns.EditActions1.textSize": true,
"Table1.primaryColumns.EditActions1.enableFilter": true,
"Table1.primaryColumns.EditActions1.enableSort": true,
"Table1.primaryColumns.EditActions1.isVisible": true,
"Table1.primaryColumns.EditActions1.isDisabled": true,
"Table1.primaryColumns.EditActions1.isCellEditable": true,
"Table1.primaryColumns.EditActions1.isEditable": true,
"Table1.primaryColumns.EditActions1.isCellVisible": true,
"Table1.primaryColumns.EditActions1.isDerived": true,
"Table1.primaryColumns.EditActions1.label": true,
"Table1.primaryColumns.EditActions1.isSaveVisible": true,
"Table1.primaryColumns.EditActions1.isDiscardVisible": true,
"Table1.primaryColumns.EditActions1.computedValue": true,
"Table1.primaryColumns.EditActions1.validation": true,
"Table1.primaryColumns.EditActions1.buttonStyle": true,
"Table1.primaryColumns.EditActions1.saveIconAlign": true,
"Table1.primaryColumns.EditActions1.discardIconAlign": true,
"Table1.primaryColumns.EditActions1.saveActionLabel": true,
"Table1.primaryColumns.EditActions1.discardActionLabel": true,
"Table1.primaryColumns.EditActions1.saveButtonColor": true,
"Table1.primaryColumns.EditActions1.discardButtonColor": true,
"Table1.primaryColumns.EditActions1.saveBorderRadius": true,
"Table1.primaryColumns.EditActions1.discardBorderRadius": true,
"Table1.primaryColumns.EditActions1.discardButtonVariant": true,
"Table1.primaryColumns.EditActions1.isSaveDisabled": true,
"Table1.primaryColumns.EditActions1.isDiscardDisabled": true,
"Table1.primaryColumns.EditActions1.sticky": true,
"Table1.key": true,
"Table1.canFreezeColumn": true,
"Table1.rightColumn": true,
"Table1.textSize": true,
"Table1.widgetId": true,
"Table1.tableData": true,
"Table1.label": true,
"Table1.searchKey": true,
"Table1.horizontalAlignment": true,
"Table1.isVisibleSearch": true,
"Table1.isVisiblePagination": true,
"Table1.verticalAlignment": true,
"Table1.defaultSearchText": true,
"Table1.selectedRow": true,
"Table1.triggeredRow": true,
"Table1.selectedRows": true,
"Table1.pageSize": true,
"Table1.triggerRowSelection": true,
"Table1.processedTableData": true,
"Table1.orderedTableColumns": true,
"Table1.filteredTableData": true,
"Table1.updatedRows": true,
"Table1.updatedRowIndices": true,
"Table1.updatedRow": true,
"Table1.pageOffset": true,
"Table1.isEditableCellsValid": true,
"Table1.tableHeaders": true,
"Table1.pageNo": true,
"Table1.selectedRowIndex": true,
"Table1.selectedRowIndices": true,
"Table1.searchText": true,
"Table1.triggeredRowIndex": true,
"Table1.filters": true,
"Table1.sortOrder": true,
"Table1.sortOrder.column": true,
"Table1.sortOrder.order": true,
"Table1.transientTableData": true,
"Table1.updatedRowIndex": true,
"Table1.editableCell": true,
"Table1.editableCell.column": true,
"Table1.editableCell.index": true,
"Table1.editableCell.inputValue": true,
"Table1.editableCell.value": true,
"Table1.editableCell.initialValue": true,
"Table1.columnEditableCellValue": true,
"Table1.selectColumnFilterText": true,
"Table1.isAddRowInProgress": true,
"Table1.newRowContent": true,
"Table1.newRow": true,
"Table1.previousPageVisited": true,
"Table1.nextPageVisited": true,
"Table1.meta": true,
"Table1.meta.selectedRowIndex": true,
"Table1.meta.selectedRowIndices": true,
"Table1.meta.searchText": true,
"Table1.type": true,
"Table1.isMobile": true,
Button3: true,
"Button3.ENTITY_TYPE": true,
"Button3.resetFormOnClick": true,
"Button3.boxShadow": true,
"Button3.widgetName": true,
"Button3.onClick": true,
"Button3.buttonColor": true,
"Button3.topRow": true,
"Button3.bottomRow": true,
"Button3.parentRowSpace": true,
"Button3.animateLoading": true,
"Button3.parentColumnSpace": true,
"Button3.leftColumn": true,
"Button3.text": true,
"Button3.isDisabled": true,
"Button3.key": true,
"Button3.rightColumn": true,
"Button3.isDefaultClickDisabled": true,
"Button3.widgetId": true,
"Button3.isVisible": true,
"Button3.recaptchaType": true,
"Button3.isLoading": true,
"Button3.disabledWhenInvalid": true,
"Button3.borderRadius": true,
"Button3.buttonVariant": true,
"Button3.placement": true,
"Button3.recaptchaToken": true,
"Button3.meta": true,
"Button3.type": true,
"Button3.isMobile": true,
Button4: true,
"Button4.ENTITY_TYPE": true,
"Button4.resetFormOnClick": true,
"Button4.boxShadow": true,
"Button4.widgetName": true,
"Button4.onClick": true,
"Button4.buttonColor": true,
"Button4.topRow": true,
"Button4.bottomRow": true,
"Button4.parentRowSpace": true,
"Button4.animateLoading": true,
"Button4.parentColumnSpace": true,
"Button4.leftColumn": true,
"Button4.text": true,
"Button4.isDisabled": true,
"Button4.key": true,
"Button4.rightColumn": true,
"Button4.isDefaultClickDisabled": true,
"Button4.widgetId": true,
"Button4.isVisible": true,
"Button4.recaptchaType": true,
"Button4.isLoading": true,
"Button4.disabledWhenInvalid": true,
"Button4.borderRadius": true,
"Button4.buttonVariant": true,
"Button4.placement": true,
"Button4.recaptchaToken": true,
"Button4.meta": true,
"Button4.type": true,
"Button4.isMobile": true,
Button5: true,
"Button5.ENTITY_TYPE": true,
"Button5.resetFormOnClick": true,
"Button5.boxShadow": true,
"Button5.widgetName": true,
"Button5.onClick": true,
"Button5.buttonColor": true,
"Button5.topRow": true,
"Button5.bottomRow": true,
"Button5.parentRowSpace": true,
"Button5.animateLoading": true,
"Button5.parentColumnSpace": true,
"Button5.leftColumn": true,
"Button5.text": true,
"Button5.isDisabled": true,
"Button5.key": true,
"Button5.rightColumn": true,
"Button5.isDefaultClickDisabled": true,
"Button5.widgetId": true,
"Button5.isVisible": true,
"Button5.recaptchaType": true,
"Button5.isLoading": true,
"Button5.disabledWhenInvalid": true,
"Button5.borderRadius": true,
"Button5.buttonVariant": true,
"Button5.placement": true,
"Button5.recaptchaToken": true,
"Button5.meta": true,
"Button5.type": true,
"Button5.isMobile": true,
Button6: true,
"Button6.ENTITY_TYPE": true,
"Button6.resetFormOnClick": true,
"Button6.boxShadow": true,
"Button6.widgetName": true,
"Button6.onClick": true,
"Button6.buttonColor": true,
"Button6.topRow": true,
"Button6.bottomRow": true,
"Button6.parentRowSpace": true,
"Button6.animateLoading": true,
"Button6.parentColumnSpace": true,
"Button6.leftColumn": true,
"Button6.text": true,
"Button6.isDisabled": true,
"Button6.key": true,
"Button6.rightColumn": true,
"Button6.isDefaultClickDisabled": true,
"Button6.widgetId": true,
"Button6.isVisible": true,
"Button6.recaptchaType": true,
"Button6.isLoading": true,
"Button6.disabledWhenInvalid": true,
"Button6.borderRadius": true,
"Button6.buttonVariant": true,
"Button6.placement": true,
"Button6.recaptchaToken": true,
"Button6.meta": true,
"Button6.type": true,
"Button6.isMobile": true,
Button7: true,
"Button7.ENTITY_TYPE": true,
"Button7.resetFormOnClick": true,
"Button7.boxShadow": true,
"Button7.widgetName": true,
"Button7.onClick": true,
"Button7.buttonColor": true,
"Button7.topRow": true,
"Button7.bottomRow": true,
"Button7.parentRowSpace": true,
"Button7.animateLoading": true,
"Button7.parentColumnSpace": true,
"Button7.leftColumn": true,
"Button7.text": true,
"Button7.isDisabled": true,
"Button7.key": true,
"Button7.rightColumn": true,
"Button7.isDefaultClickDisabled": true,
"Button7.widgetId": true,
"Button7.isVisible": true,
"Button7.recaptchaType": true,
"Button7.isLoading": true,
"Button7.disabledWhenInvalid": true,
"Button7.borderRadius": true,
"Button7.buttonVariant": true,
"Button7.placement": true,
"Button7.recaptchaToken": true,
"Button7.meta": true,
"Button7.type": true,
"Button7.isMobile": true,
Text10: true,
"Text10.ENTITY_TYPE": true,
"Text10.widgetName": true,
"Text10.topRow": true,
"Text10.bottomRow": true,
"Text10.parentRowSpace": true,
"Text10.animateLoading": true,
"Text10.overflow": true,
"Text10.fontFamily": true,
"Text10.parentColumnSpace": true,
"Text10.leftColumn": true,
"Text10.shouldTruncate": true,
"Text10.truncateButtonColor": true,
"Text10.text": true,
"Text10.key": true,
"Text10.rightColumn": true,
"Text10.textAlign": true,
"Text10.dynamicHeight": true,
"Text10.widgetId": true,
"Text10.isVisible": true,
"Text10.fontStyle": true,
"Text10.textColor": true,
"Text10.isLoading": true,
"Text10.originalTopRow": true,
"Text10.borderRadius": true,
"Text10.maxDynamicHeight": true,
"Text10.originalBottomRow": true,
"Text10.fontSize": true,
"Text10.minDynamicHeight": true,
"Text10.value": true,
"Text10.meta": true,
"Text10.type": true,
"Text10.isMobile": true,
Select1: true,
"Select1.ENTITY_TYPE": true,
"Select1.boxShadow": true,
"Select1.widgetName": true,
"Select1.isFilterable": true,
"Select1.labelText": true,
"Select1.topRow": true,
"Select1.bottomRow": true,
"Select1.parentRowSpace": true,
"Select1.labelWidth": true,
"Select1.serverSideFiltering": true,
"Select1.defaultOptionValue": true,
"Select1.animateLoading": true,
"Select1.parentColumnSpace": true,
"Select1.leftColumn": true,
"Select1.labelPosition": true,
"Select1.placeholderText": true,
"Select1.isDisabled": true,
"Select1.sourceData": true,
"Select1.sourceData[0]": true,
"Select1.sourceData[0].label": true,
"Select1.sourceData[0].value": true,
"Select1.sourceData[1]": true,
"Select1.sourceData[1].label": true,
"Select1.sourceData[1].value": true,
"Select1.sourceData[2]": true,
"Select1.sourceData[2].label": true,
"Select1.sourceData[2].value": true,
"Select1.key": true,
"Select1.labelTextSize": true,
"Select1.isRequired": true,
"Select1.rightColumn": true,
"Select1.dynamicHeight": true,
"Select1.widgetId": true,
"Select1.accentColor": true,
"Select1.optionValue": true,
"Select1.isVisible": true,
"Select1.labelAlignment": true,
"Select1.isLoading": true,
"Select1.optionLabel": true,
"Select1.originalTopRow": true,
"Select1.borderRadius": true,
"Select1.maxDynamicHeight": true,
"Select1.originalBottomRow": true,
"Select1.minDynamicHeight": true,
"Select1.": true,
"Select1.options": true,
"Select1.isValid": true,
"Select1.selectedOptionValue": true,
"Select1.selectedOptionLabel": true,
"Select1.value": true,
"Select1.label": true,
"Select1.filterText": true,
"Select1.isDirty": true,
"Select1.meta": true,
"Select1.meta.value": true,
"Select1.meta.label": true,
"Select1.meta.filterText": true,
"Select1.type": true,
"Select1.isMobile": true,
Text11: true,
"Text11.ENTITY_TYPE": true,
"Text11.widgetName": true,
"Text11.topRow": true,
"Text11.bottomRow": true,
"Text11.parentRowSpace": true,
"Text11.animateLoading": true,
"Text11.overflow": true,
"Text11.fontFamily": true,
"Text11.parentColumnSpace": true,
"Text11.leftColumn": true,
"Text11.shouldTruncate": true,
"Text11.truncateButtonColor": true,
"Text11.text": true,
"Text11.key": true,
"Text11.rightColumn": true,
"Text11.textAlign": true,
"Text11.dynamicHeight": true,
"Text11.widgetId": true,
"Text11.isVisible": true,
"Text11.fontStyle": true,
"Text11.textColor": true,
"Text11.isLoading": true,
"Text11.originalTopRow": true,
"Text11.borderRadius": true,
"Text11.maxDynamicHeight": true,
"Text11.originalBottomRow": true,
"Text11.fontSize": true,
"Text11.minDynamicHeight": true,
"Text11.value": true,
"Text11.meta": true,
"Text11.type": true,
"Text11.isMobile": true,
Button8: true,
"Button8.ENTITY_TYPE": true,
"Button8.resetFormOnClick": true,
"Button8.boxShadow": true,
"Button8.widgetName": true,
"Button8.onClick": true,
"Button8.buttonColor": true,
"Button8.topRow": true,
"Button8.bottomRow": true,
"Button8.parentRowSpace": true,
"Button8.animateLoading": true,
"Button8.parentColumnSpace": true,
"Button8.leftColumn": true,
"Button8.text": true,
"Button8.isDisabled": true,
"Button8.key": true,
"Button8.rightColumn": true,
"Button8.isDefaultClickDisabled": true,
"Button8.widgetId": true,
"Button8.isVisible": true,
"Button8.recaptchaType": true,
"Button8.isLoading": true,
"Button8.disabledWhenInvalid": true,
"Button8.borderRadius": true,
"Button8.buttonVariant": true,
"Button8.placement": true,
"Button8.recaptchaToken": true,
"Button8.meta": true,
"Button8.type": true,
"Button8.isMobile": true,
appsmith: true,
"appsmith.user": true,
"appsmith.user.email": true,
"appsmith.user.workspaceIds": true,
"appsmith.user.workspaceIds[0]": true,
"appsmith.user.workspaceIds[1]": true,
"appsmith.user.workspaceIds[2]": true,
"appsmith.user.workspaceIds[3]": true,
"appsmith.user.workspaceIds[4]": true,
"appsmith.user.workspaceIds[5]": true,
"appsmith.user.workspaceIds[6]": true,
"appsmith.user.workspaceIds[7]": true,
"appsmith.user.workspaceIds[8]": true,
"appsmith.user.workspaceIds[9]": true,
"appsmith.user.workspaceIds[10]": true,
"appsmith.user.workspaceIds[11]": true,
"appsmith.user.workspaceIds[12]": true,
"appsmith.user.workspaceIds[13]": true,
"appsmith.user.workspaceIds[14]": true,
"appsmith.user.workspaceIds[15]": true,
"appsmith.user.username": true,
"appsmith.user.name": true,
"appsmith.user.photoId": true,
"appsmith.user.enableTelemetry": true,
"appsmith.user.emptyInstance": true,
"appsmith.user.accountNonExpired": true,
"appsmith.user.accountNonLocked": true,
"appsmith.user.credentialsNonExpired": true,
"appsmith.user.isAnonymous": true,
"appsmith.user.isEnabled": true,
"appsmith.user.isSuperUser": true,
"appsmith.user.isConfigurable": true,
"appsmith.user.adminSettingsVisible": true,
"appsmith.user.isIntercomConsentGiven": true,
"appsmith.URL": true,
"appsmith.URL.fullPath": true,
"appsmith.URL.host": true,
"appsmith.URL.hostname": true,
"appsmith.URL.queryParams": true,
"appsmith.URL.queryParams.branch": true,
"appsmith.URL.protocol": true,
"appsmith.URL.pathname": true,
"appsmith.URL.port": true,
"appsmith.URL.hash": true,
"appsmith.store": true,
"appsmith.geolocation": true,
"appsmith.geolocation.canBeRequested": true,
"appsmith.geolocation.currentPosition": true,
"appsmith.mode": true,
"appsmith.theme": true,
"appsmith.theme.colors": true,
"appsmith.theme.colors.primaryColor": true,
"appsmith.theme.colors.backgroundColor": true,
"appsmith.theme.borderRadius": true,
"appsmith.theme.borderRadius.appBorderRadius": true,
"appsmith.theme.boxShadow": true,
"appsmith.theme.boxShadow.appBoxShadow": true,
"appsmith.theme.fontFamily": true,
"appsmith.theme.fontFamily.appFont": true,
"appsmith.ENTITY_TYPE": true,
};
const dependencies = {
"Api1.datasourceUrl": [],
"Api3.config.path": [],
"JSObject1.body": [
"JSObject1.mutate1",
"JSObject1.mutate",
"JSObject1.data",
],
"JSObject1.mutate1": ["Countries.data"],
"JSObject1.mutate": ["appsmith.store"],
"JSObject1.data": ["Countries.data"],
"JSObject2.body": [
"JSObject2.funcType2",
"JSObject2.clearInsterval",
"JSObject2.thirdFunction",
"JSObject2.IntervalCheck",
"JSObject2.myFun1",
"JSObject2.funcKey",
"JSObject2.myFun2",
],
"JSObject2.arrayType": [],
"JSObject2.funcType2": ["Api1.run", "Countries.run", "JSObject1.data"],
"JSObject2.clearInsterval": [],
"JSObject2.thirdFunction": [],
"JSObject2.IntervalCheck": [
"storeValue",
"appsmith.user.name",
"Api1.run",
"showAlert",
"appsmith.store",
],
"JSObject2.myFun1": ["Countries.data", "JSObject2.arrayType"],
"JSObject2.funcKey": ["JSObject2.funcType2"],
"JSObject2.myFun2": ["storeValue", "Api1.run", "Api1.data"],
"JSObject3.body": ["JSObject3.new", "JSObject3.myFun2"],
"JSObject3.myVar1": [],
"JSObject3.myVar2": [],
"JSObject3.new": ["JSObject1.data"],
"JSObject3.myFun2": ["JSObject1.data", "Api1.run", "Api1.data"],
"JSObject4.body": ["JSObject4.myFun2", "JSObject4.secondFunction"],
"JSObject4.myFun2": [],
"JSObject4.secondFunction": ["JSObject4.myFun2"],
"Text9.truncateButtonColor": ["appsmith.theme.colors.primaryColor"],
"Text9.fontFamily": ["appsmith.theme.fontFamily.appFont"],
"Text9.borderRadius": ["appsmith.theme.borderRadius.appBorderRadius"],
"Text9.value": ["Text9.text"],
"Button4Copy.onClick": [],
"Button4Copy.buttonColor": ["appsmith.theme.colors.primaryColor"],
"Button4Copy.borderRadius": ["appsmith.theme.borderRadius.appBorderRadius"],
"Button3Copy.onClick": [],
"Button3Copy.buttonColor": ["appsmith.theme.colors.primaryColor"],
"Button3Copy.borderRadius": ["appsmith.theme.borderRadius.appBorderRadius"],
"Button5Copy.onClick": [],
"Button5Copy.buttonColor": ["appsmith.theme.colors.primaryColor"],
"Button5Copy.borderRadius": ["appsmith.theme.borderRadius.appBorderRadius"],
"Table1.searchText": ["Table1.meta.searchText", "Table1.defaultSearchText"],
"Table1.selectedRowIndex": [
"Table1.meta.selectedRowIndex",
"Table1.defaultSelectedRowIndex",
],
"Table1.selectedRowIndices": [
"Table1.meta.selectedRowIndices",
"Table1.defaultSelectedRowIndices",
],
"Table1.accentColor": ["appsmith.theme.colors.primaryColor"],
"Table1.borderRadius": ["appsmith.theme.borderRadius.appBorderRadius"],
"Table1.boxShadow": ["appsmith.theme.boxShadow.appBoxShadow"],
"Table1.primaryColumns.name.computedValue": ["Table1.processedTableData"],
"Table1.primaryColumns.tld.computedValue": ["Table1.processedTableData"],
"Table1.primaryColumns.cca2.computedValue": ["Table1.processedTableData"],
"Table1.primaryColumns.ccn3.computedValue": ["Table1.processedTableData"],
"Table1.primaryColumns.cca3.computedValue": ["Table1.processedTableData"],
"Table1.primaryColumns.cioc.computedValue": ["Table1.processedTableData"],
"Table1.primaryColumns.independent.computedValue": [
"Table1.processedTableData",
],
"Table1.primaryColumns.unMember.computedValue": [
"Table1.processedTableData",
],
"Table1.primaryColumns.currencies.computedValue": [
"Table1.processedTableData",
],
"Table1.primaryColumns.idd.computedValue": ["Table1.processedTableData"],
"Table1.primaryColumns.capital.computedValue": [
"Table1.processedTableData",
],
"Table1.primaryColumns.altSpellings.computedValue": [
"Table1.processedTableData",
],
"Table1.primaryColumns.region.computedValue": ["Table1.processedTableData"],
"Table1.primaryColumns.subregion.computedValue": [
"Table1.processedTableData",
],
"Table1.primaryColumns.languages.computedValue": [
"Table1.processedTableData",
],
"Table1.primaryColumns.translations.computedValue": [
"Table1.processedTableData",
],
"Table1.primaryColumns.latlng.computedValue": ["Table1.processedTableData"],
"Table1.primaryColumns.landlocked.computedValue": [
"Table1.processedTableData",
],
"Table1.primaryColumns.borders.computedValue": [
"Table1.processedTableData",
],
"Table1.primaryColumns.area.computedValue": ["Table1.processedTableData"],
"Table1.primaryColumns.demonyms.computedValue": [
"Table1.processedTableData",
],
"Table1.primaryColumns.flag.computedValue": ["Table1.processedTableData"],
"Table1.primaryColumns.maps.computedValue": ["Table1.processedTableData"],
"Table1.primaryColumns.population.computedValue": [
"Table1.processedTableData",
],
"Table1.primaryColumns.fifa.computedValue": ["Table1.processedTableData"],
"Table1.primaryColumns.car.computedValue": ["Table1.processedTableData"],
"Table1.primaryColumns.timezones.computedValue": [
"Table1.processedTableData",
],
"Table1.primaryColumns.continents.computedValue": [
"Table1.processedTableData",
],
"Table1.primaryColumns.flags.computedValue": ["Table1.processedTableData"],
"Table1.primaryColumns.coatOfArms.computedValue": [
"Table1.processedTableData",
],
"Table1.primaryColumns.startOfWeek.computedValue": [
"Table1.processedTableData",
],
"Table1.primaryColumns.capitalInfo.computedValue": [
"Table1.processedTableData",
],
"Table1.primaryColumns.postalCode.computedValue": [
"Table1.processedTableData",
],
"Table1.primaryColumns.gini.computedValue": ["Table1.processedTableData"],
"Table1.primaryColumns.EditActions1.saveButtonColor": [
"Table1.processedTableData",
"appsmith.theme.colors.primaryColor",
],
"Table1.primaryColumns.EditActions1.saveBorderRadius": [
"Table1.processedTableData",
"appsmith.theme.borderRadius.appBorderRadius",
],
"Table1.primaryColumns.EditActions1.discardBorderRadius": [
"Table1.processedTableData",
"appsmith.theme.borderRadius.appBorderRadius",
],
"Table1.primaryColumns.EditActions1.isSaveDisabled": [
"Table1.processedTableData",
"Table1.updatedRowIndices",
],
"Table1.primaryColumns.EditActions1.isDiscardDisabled": [
"Table1.processedTableData",
"Table1.updatedRowIndices",
],
"Table1.tableData": ["JSObject1.data"],
"Table1.selectedRow": [
"Table1.selectedRowIndices",
"Table1.selectedRowIndex",
"Table1.filteredTableData",
"Table1.processedTableData",
"Table1.primaryColumns",
],
"Table1.triggeredRow": [
"Table1.triggeredRowIndex",
"Table1.filteredTableData",
"Table1.processedTableData",
"Table1.primaryColumns",
],
"Table1.selectedRows": [
"Table1.selectedRowIndices",
"Table1.filteredTableData",
"Table1.processedTableData",
"Table1.primaryColumns",
],
"Table1.pageSize": [
"Table1.isMobile",
"Table1.bottomRow",
"Table1.topRow",
"Table1.parentRowSpace",
],
"Table1.triggerRowSelection": [],
"Table1.processedTableData": [
"Table1.tableData",
"Table1.transientTableData",
],
"Table1.orderedTableColumns": [
"Table1.primaryColumns",
"Table1.columnOrder",
"Table1.sortOrder",
"Table1.sortOrder.column",
"Table1.sortOrder.order",
],
"Table1.filteredTableData": [
"Table1.primaryColumns",
"Table1.processedTableData",
"Table1.orderedTableColumns",
"Table1.sortOrder.column",
"Table1.sortOrder.order",
"Table1.searchText",
"Table1.enableClientSideSearch",
"Table1.filters",
],
"Table1.updatedRows": [
"Table1.primaryColumns",
"Table1.transientTableData",
"Table1.processedTableData",
"Table1.tableData",
],
"Table1.updatedRowIndices": ["Table1.transientTableData"],
"Table1.updatedRow": [
"Table1.updatedRowIndex",
"Table1.filteredTableData",
"Table1.processedTableData",
"Table1.primaryColumns",
],
"Table1.pageOffset": [
"Table1.tableData",
"Table1.pageSize",
"Table1.pageNo",
],
"Table1.isEditableCellsValid": [
"Table1.editableCell",
"Table1.isAddRowInProgress",
"Table1.primaryColumns",
"Table1.newRow",
],
"Table1.tableHeaders": ["Table1.primaryColumns"],
"Button3.onClick": [],
"Button3.buttonColor": ["appsmith.theme.colors.primaryColor"],
"Button3.borderRadius": ["appsmith.theme.borderRadius.appBorderRadius"],
"Button4.onClick": [],
"Button4.buttonColor": ["appsmith.theme.colors.primaryColor"],
"Button4.borderRadius": ["appsmith.theme.borderRadius.appBorderRadius"],
"Button5.onClick": [],
"Button5.buttonColor": ["appsmith.theme.colors.primaryColor"],
"Button5.borderRadius": ["appsmith.theme.borderRadius.appBorderRadius"],
"Button6.onClick": [],
"Button6.buttonColor": ["appsmith.theme.colors.primaryColor"],
"Button6.borderRadius": ["appsmith.theme.borderRadius.appBorderRadius"],
"Button7.onClick": [],
"Button7.buttonColor": ["appsmith.theme.colors.primaryColor"],
"Button7.borderRadius": ["appsmith.theme.borderRadius.appBorderRadius"],
"Text10.truncateButtonColor": ["appsmith.theme.colors.primaryColor"],
"Text10.fontFamily": ["appsmith.theme.fontFamily.appFont"],
"Text10.borderRadius": ["appsmith.theme.borderRadius.appBorderRadius"],
"Text10.text": ["appsmith.store"],
"Text10.value": ["Text10.text"],
"Select1.value": ["Select1.meta.value", "Select1.defaultOptionValue"],
"Select1.label": ["Select1.meta.label", "Select1.defaultOptionValue"],
"Select1.filterText": ["Select1.meta.filterText"],
"Select1.accentColor": ["appsmith.theme.colors.primaryColor"],
"Select1.borderRadius": ["appsmith.theme.borderRadius.appBorderRadius"],
"Select1.options": [
"Select1.sourceData",
"Select1.optionLabel",
"Select1.optionValue",
],
"Select1.isValid": ["Select1.isRequired", "Select1.selectedOptionValue"],
"Select1.selectedOptionValue": [
"Select1.serverSideFiltering",
"Select1.options",
"Select1.value",
"Select1.isDirty",
],
"Select1.selectedOptionLabel": [
"Select1.serverSideFiltering",
"Select1.options",
"Select1.label",
"Select1.selectedOptionValue",
],
"Text11.truncateButtonColor": ["appsmith.theme.colors.primaryColor"],
"Text11.fontFamily": ["appsmith.theme.fontFamily.appFont"],
"Text11.borderRadius": ["appsmith.theme.borderRadius.appBorderRadius"],
"Text11.text": ["Select1.filterText"],
"Text11.value": ["Text11.text"],
"Button8.onClick": [],
"Button8.buttonColor": ["appsmith.theme.colors.primaryColor"],
"Button8.borderRadius": ["appsmith.theme.borderRadius.appBorderRadius"],
Api1: ["Api1.datasourceUrl", "Api1.run", "Api1.data"],
"Api3.config": ["Api3.config.path"],
Api3: ["Api3.config"],
JSObject1: [
"JSObject1.body",
"JSObject1.mutate1",
"JSObject1.mutate",
"JSObject1.data",
],
Countries: ["Countries.data", "Countries.run"],
appsmith: ["appsmith.store", "appsmith.user", "appsmith.theme"],
JSObject2: [
"JSObject2.body",
"JSObject2.funcType2",
"JSObject2.clearInsterval",
"JSObject2.thirdFunction",
"JSObject2.IntervalCheck",
"JSObject2.myFun1",
"JSObject2.funcKey",
"JSObject2.myFun2",
"JSObject2.arrayType",
],
"appsmith.user": ["appsmith.user.name"],
JSObject3: [
"JSObject3.body",
"JSObject3.new",
"JSObject3.myFun2",
"JSObject3.myVar1",
"JSObject3.myVar2",
],
JSObject4: [
"JSObject4.body",
"JSObject4.myFun2",
"JSObject4.secondFunction",
],
Text9: [
"Text9.truncateButtonColor",
"Text9.fontFamily",
"Text9.borderRadius",
"Text9.value",
"Text9.text",
],
"appsmith.theme.colors": ["appsmith.theme.colors.primaryColor"],
"appsmith.theme": [
"appsmith.theme.colors",
"appsmith.theme.fontFamily",
"appsmith.theme.borderRadius",
"appsmith.theme.boxShadow",
],
"appsmith.theme.fontFamily": ["appsmith.theme.fontFamily.appFont"],
"appsmith.theme.borderRadius": [
"appsmith.theme.borderRadius.appBorderRadius",
],
Button4Copy: [
"Button4Copy.onClick",
"Button4Copy.buttonColor",
"Button4Copy.borderRadius",
],
Button3Copy: [
"Button3Copy.onClick",
"Button3Copy.buttonColor",
"Button3Copy.borderRadius",
],
Button5Copy: [
"Button5Copy.onClick",
"Button5Copy.buttonColor",
"Button5Copy.borderRadius",
],
Table1: [
"Table1.searchText",
"Table1.meta",
"Table1.defaultSearchText",
"Table1.selectedRowIndex",
"Table1.defaultSelectedRowIndex",
"Table1.selectedRowIndices",
"Table1.defaultSelectedRowIndices",
"Table1.accentColor",
"Table1.borderRadius",
"Table1.boxShadow",
"Table1.primaryColumns",
"Table1.processedTableData",
"Table1.updatedRowIndices",
"Table1.tableData",
"Table1.selectedRow",
"Table1.filteredTableData",
"Table1.triggeredRow",
"Table1.triggeredRowIndex",
"Table1.selectedRows",
"Table1.pageSize",
"Table1.isMobile",
"Table1.bottomRow",
"Table1.topRow",
"Table1.parentRowSpace",
"Table1.triggerRowSelection",
"Table1.transientTableData",
"Table1.orderedTableColumns",
"Table1.columnOrder",
"Table1.sortOrder",
"Table1.enableClientSideSearch",
"Table1.filters",
"Table1.updatedRows",
"Table1.updatedRow",
"Table1.updatedRowIndex",
"Table1.pageOffset",
"Table1.pageNo",
"Table1.isEditableCellsValid",
"Table1.editableCell",
"Table1.isAddRowInProgress",
"Table1.newRow",
"Table1.tableHeaders",
],
"Table1.meta": [
"Table1.meta.searchText",
"Table1.meta.selectedRowIndex",
"Table1.meta.selectedRowIndices",
],
"appsmith.theme.boxShadow": ["appsmith.theme.boxShadow.appBoxShadow"],
"Table1.primaryColumns.name": ["Table1.primaryColumns.name.computedValue"],
"Table1.primaryColumns": [
"Table1.primaryColumns.name",
"Table1.primaryColumns.tld",
"Table1.primaryColumns.cca2",
"Table1.primaryColumns.ccn3",
"Table1.primaryColumns.cca3",
"Table1.primaryColumns.cioc",
"Table1.primaryColumns.independent",
"Table1.primaryColumns.unMember",
"Table1.primaryColumns.currencies",
"Table1.primaryColumns.idd",
"Table1.primaryColumns.capital",
"Table1.primaryColumns.altSpellings",
"Table1.primaryColumns.region",
"Table1.primaryColumns.subregion",
"Table1.primaryColumns.languages",
"Table1.primaryColumns.translations",
"Table1.primaryColumns.latlng",
"Table1.primaryColumns.landlocked",
"Table1.primaryColumns.borders",
"Table1.primaryColumns.area",
"Table1.primaryColumns.demonyms",
"Table1.primaryColumns.flag",
"Table1.primaryColumns.maps",
"Table1.primaryColumns.population",
"Table1.primaryColumns.fifa",
"Table1.primaryColumns.car",
"Table1.primaryColumns.timezones",
"Table1.primaryColumns.continents",
"Table1.primaryColumns.flags",
"Table1.primaryColumns.coatOfArms",
"Table1.primaryColumns.startOfWeek",
"Table1.primaryColumns.capitalInfo",
"Table1.primaryColumns.postalCode",
"Table1.primaryColumns.gini",
"Table1.primaryColumns.EditActions1",
],
"Table1.primaryColumns.tld": ["Table1.primaryColumns.tld.computedValue"],
"Table1.primaryColumns.cca2": ["Table1.primaryColumns.cca2.computedValue"],
"Table1.primaryColumns.ccn3": ["Table1.primaryColumns.ccn3.computedValue"],
"Table1.primaryColumns.cca3": ["Table1.primaryColumns.cca3.computedValue"],
"Table1.primaryColumns.cioc": ["Table1.primaryColumns.cioc.computedValue"],
"Table1.primaryColumns.independent": [
"Table1.primaryColumns.independent.computedValue",
],
"Table1.primaryColumns.unMember": [
"Table1.primaryColumns.unMember.computedValue",
],
"Table1.primaryColumns.currencies": [
"Table1.primaryColumns.currencies.computedValue",
],
"Table1.primaryColumns.idd": ["Table1.primaryColumns.idd.computedValue"],
"Table1.primaryColumns.capital": [
"Table1.primaryColumns.capital.computedValue",
],
"Table1.primaryColumns.altSpellings": [
"Table1.primaryColumns.altSpellings.computedValue",
],
"Table1.primaryColumns.region": [
"Table1.primaryColumns.region.computedValue",
],
"Table1.primaryColumns.subregion": [
"Table1.primaryColumns.subregion.computedValue",
],
"Table1.primaryColumns.languages": [
"Table1.primaryColumns.languages.computedValue",
],
"Table1.primaryColumns.translations": [
"Table1.primaryColumns.translations.computedValue",
],
"Table1.primaryColumns.latlng": [
"Table1.primaryColumns.latlng.computedValue",
],
"Table1.primaryColumns.landlocked": [
"Table1.primaryColumns.landlocked.computedValue",
],
"Table1.primaryColumns.borders": [
"Table1.primaryColumns.borders.computedValue",
],
"Table1.primaryColumns.area": ["Table1.primaryColumns.area.computedValue"],
"Table1.primaryColumns.demonyms": [
"Table1.primaryColumns.demonyms.computedValue",
],
"Table1.primaryColumns.flag": ["Table1.primaryColumns.flag.computedValue"],
"Table1.primaryColumns.maps": ["Table1.primaryColumns.maps.computedValue"],
"Table1.primaryColumns.population": [
"Table1.primaryColumns.population.computedValue",
],
"Table1.primaryColumns.fifa": ["Table1.primaryColumns.fifa.computedValue"],
"Table1.primaryColumns.car": ["Table1.primaryColumns.car.computedValue"],
"Table1.primaryColumns.timezones": [
"Table1.primaryColumns.timezones.computedValue",
],
"Table1.primaryColumns.continents": [
"Table1.primaryColumns.continents.computedValue",
],
"Table1.primaryColumns.flags": [
"Table1.primaryColumns.flags.computedValue",
],
"Table1.primaryColumns.coatOfArms": [
"Table1.primaryColumns.coatOfArms.computedValue",
],
"Table1.primaryColumns.startOfWeek": [
"Table1.primaryColumns.startOfWeek.computedValue",
],
"Table1.primaryColumns.capitalInfo": [
"Table1.primaryColumns.capitalInfo.computedValue",
],
"Table1.primaryColumns.postalCode": [
"Table1.primaryColumns.postalCode.computedValue",
],
"Table1.primaryColumns.gini": ["Table1.primaryColumns.gini.computedValue"],
"Table1.primaryColumns.EditActions1": [
"Table1.primaryColumns.EditActions1.saveButtonColor",
"Table1.primaryColumns.EditActions1.saveBorderRadius",
"Table1.primaryColumns.EditActions1.discardBorderRadius",
"Table1.primaryColumns.EditActions1.isSaveDisabled",
"Table1.primaryColumns.EditActions1.isDiscardDisabled",
],
"Table1.sortOrder": ["Table1.sortOrder.column", "Table1.sortOrder.order"],
Button3: ["Button3.onClick", "Button3.buttonColor", "Button3.borderRadius"],
Button4: ["Button4.onClick", "Button4.buttonColor", "Button4.borderRadius"],
Button5: ["Button5.onClick", "Button5.buttonColor", "Button5.borderRadius"],
Button6: ["Button6.onClick", "Button6.buttonColor", "Button6.borderRadius"],
Button7: ["Button7.onClick", "Button7.buttonColor", "Button7.borderRadius"],
Text10: [
"Text10.truncateButtonColor",
"Text10.fontFamily",
"Text10.borderRadius",
"Text10.text",
"Text10.value",
],
Select1: [
"Select1.value",
"Select1.meta",
"Select1.defaultOptionValue",
"Select1.label",
"Select1.filterText",
"Select1.accentColor",
"Select1.borderRadius",
"Select1.options",
"Select1.sourceData",
"Select1.optionLabel",
"Select1.optionValue",
"Select1.isValid",
"Select1.isRequired",
"Select1.selectedOptionValue",
"Select1.serverSideFiltering",
"Select1.isDirty",
"Select1.selectedOptionLabel",
],
"Select1.meta": [
"Select1.meta.value",
"Select1.meta.label",
"Select1.meta.filterText",
],
Text11: [
"Text11.truncateButtonColor",
"Text11.fontFamily",
"Text11.borderRadius",
"Text11.text",
"Text11.value",
],
Button8: ["Button8.onClick", "Button8.buttonColor", "Button8.borderRadius"],
"Countries.data": [],
};
dependencyMap.addNodes(testNodes);
for (const [path, deps] of Object.entries(dependencies)) {
dependencyMap.addDependency(path, deps);
}
DependencyMapUtils.makeParentsDependOnChildren(dependencyMap);
const result = DependencyMapUtils.sortDependencies(dependencyMap);
expect(result.success).toBe(true);
if (result.success) {
expect(result.sortedDependencies).toStrictEqual([
"appsmith.theme.borderRadius.appBorderRadius",
"Button8.borderRadius",
"appsmith.theme.colors.primaryColor",
"Button8.buttonColor",
"Button8.onClick",
"Button8",
"Select1.meta.filterText",
"Select1.filterText",
"Text11.text",
"Text11.value",
"Text11.borderRadius",
"appsmith.theme.fontFamily.appFont",
"Text11.fontFamily",
"Text11.truncateButtonColor",
"Text11",
"Select1.meta.label",
"Select1.meta.value",
"Select1.meta",
"Select1.isDirty",
"Select1.defaultOptionValue",
"Select1.value",
"Select1.optionValue",
"Select1.optionLabel",
"Select1.sourceData",
"Select1.options",
"Select1.serverSideFiltering",
"Select1.selectedOptionValue",
"Select1.label",
"Select1.selectedOptionLabel",
"Select1.isRequired",
"Select1.isValid",
"Select1.borderRadius",
"Select1.accentColor",
"Select1",
"appsmith.store",
"Text10.text",
"Text10.value",
"Text10.borderRadius",
"Text10.fontFamily",
"Text10.truncateButtonColor",
"Text10",
"Button7.borderRadius",
"Button7.buttonColor",
"Button7.onClick",
"Button7",
"Button6.borderRadius",
"Button6.buttonColor",
"Button6.onClick",
"Button6",
"Button5.borderRadius",
"Button5.buttonColor",
"Button5.onClick",
"Button5",
"Button4.borderRadius",
"Button4.buttonColor",
"Button4.onClick",
"Button4",
"Button3.borderRadius",
"Button3.buttonColor",
"Button3.onClick",
"Button3",
"Table1.transientTableData",
"Table1.updatedRowIndices",
"Countries.data",
"JSObject1.data",
"Table1.tableData",
"Table1.processedTableData",
"Table1.primaryColumns.EditActions1.isDiscardDisabled",
"Table1.primaryColumns.EditActions1.isSaveDisabled",
"Table1.primaryColumns.EditActions1.discardBorderRadius",
"Table1.primaryColumns.EditActions1.saveBorderRadius",
"Table1.primaryColumns.EditActions1.saveButtonColor",
"Table1.primaryColumns.EditActions1",
"Table1.primaryColumns.gini.computedValue",
"Table1.primaryColumns.gini",
"Table1.primaryColumns.postalCode.computedValue",
"Table1.primaryColumns.postalCode",
"Table1.primaryColumns.capitalInfo.computedValue",
"Table1.primaryColumns.capitalInfo",
"Table1.primaryColumns.startOfWeek.computedValue",
"Table1.primaryColumns.startOfWeek",
"Table1.primaryColumns.coatOfArms.computedValue",
"Table1.primaryColumns.coatOfArms",
"Table1.primaryColumns.flags.computedValue",
"Table1.primaryColumns.flags",
"Table1.primaryColumns.continents.computedValue",
"Table1.primaryColumns.continents",
"Table1.primaryColumns.timezones.computedValue",
"Table1.primaryColumns.timezones",
"Table1.primaryColumns.car.computedValue",
"Table1.primaryColumns.car",
"Table1.primaryColumns.fifa.computedValue",
"Table1.primaryColumns.fifa",
"Table1.primaryColumns.population.computedValue",
"Table1.primaryColumns.population",
"Table1.primaryColumns.maps.computedValue",
"Table1.primaryColumns.maps",
"Table1.primaryColumns.flag.computedValue",
"Table1.primaryColumns.flag",
"Table1.primaryColumns.demonyms.computedValue",
"Table1.primaryColumns.demonyms",
"Table1.primaryColumns.area.computedValue",
"Table1.primaryColumns.area",
"Table1.primaryColumns.borders.computedValue",
"Table1.primaryColumns.borders",
"Table1.primaryColumns.landlocked.computedValue",
"Table1.primaryColumns.landlocked",
"Table1.primaryColumns.latlng.computedValue",
"Table1.primaryColumns.latlng",
"Table1.primaryColumns.translations.computedValue",
"Table1.primaryColumns.translations",
"Table1.primaryColumns.languages.computedValue",
"Table1.primaryColumns.languages",
"Table1.primaryColumns.subregion.computedValue",
"Table1.primaryColumns.subregion",
"Table1.primaryColumns.region.computedValue",
"Table1.primaryColumns.region",
"Table1.primaryColumns.altSpellings.computedValue",
"Table1.primaryColumns.altSpellings",
"Table1.primaryColumns.capital.computedValue",
"Table1.primaryColumns.capital",
"Table1.primaryColumns.idd.computedValue",
"Table1.primaryColumns.idd",
"Table1.primaryColumns.currencies.computedValue",
"Table1.primaryColumns.currencies",
"Table1.primaryColumns.unMember.computedValue",
"Table1.primaryColumns.unMember",
"Table1.primaryColumns.independent.computedValue",
"Table1.primaryColumns.independent",
"Table1.primaryColumns.cioc.computedValue",
"Table1.primaryColumns.cioc",
"Table1.primaryColumns.cca3.computedValue",
"Table1.primaryColumns.cca3",
"Table1.primaryColumns.ccn3.computedValue",
"Table1.primaryColumns.ccn3",
"Table1.primaryColumns.cca2.computedValue",
"Table1.primaryColumns.cca2",
"Table1.primaryColumns.tld.computedValue",
"Table1.primaryColumns.tld",
"Table1.primaryColumns.name.computedValue",
"Table1.primaryColumns.name",
"Table1.meta.selectedRowIndices",
"Table1.meta.selectedRowIndex",
"Table1.meta.searchText",
"Table1.meta",
"Table1.primaryColumns",
"Table1.tableHeaders",
"Table1.newRow",
"Table1.isAddRowInProgress",
"Table1.editableCell",
"Table1.isEditableCellsValid",
"Table1.pageNo",
"Table1.parentRowSpace",
"Table1.topRow",
"Table1.bottomRow",
"Table1.isMobile",
"Table1.pageSize",
"Table1.pageOffset",
"Table1.updatedRowIndex",
"Table1.filters",
"Table1.enableClientSideSearch",
"Table1.defaultSearchText",
"Table1.searchText",
"Table1.sortOrder.order",
"Table1.sortOrder.column",
"Table1.sortOrder",
"Table1.columnOrder",
"Table1.orderedTableColumns",
"Table1.filteredTableData",
"Table1.updatedRow",
"Table1.updatedRows",
"Table1.triggerRowSelection",
"Table1.defaultSelectedRowIndices",
"Table1.selectedRowIndices",
"Table1.selectedRows",
"Table1.triggeredRowIndex",
"Table1.triggeredRow",
"Table1.defaultSelectedRowIndex",
"Table1.selectedRowIndex",
"Table1.selectedRow",
"appsmith.theme.boxShadow.appBoxShadow",
"Table1.boxShadow",
"Table1.borderRadius",
"Table1.accentColor",
"Table1",
"Button5Copy.borderRadius",
"Button5Copy.buttonColor",
"Button5Copy.onClick",
"Button5Copy",
"Button3Copy.borderRadius",
"Button3Copy.buttonColor",
"Button3Copy.onClick",
"Button3Copy",
"Button4Copy.borderRadius",
"Button4Copy.buttonColor",
"Button4Copy.onClick",
"Button4Copy",
"appsmith.theme.boxShadow",
"appsmith.theme.borderRadius",
"appsmith.theme.fontFamily",
"appsmith.theme.colors",
"Text9.text",
"Text9.value",
"Text9.borderRadius",
"Text9.fontFamily",
"Text9.truncateButtonColor",
"Text9",
"JSObject4.myFun2",
"JSObject4.secondFunction",
"JSObject4.body",
"JSObject4",
"JSObject3.myVar2",
"JSObject3.myVar1",
"Api1.data",
"Api1.run",
"JSObject3.myFun2",
"JSObject3.new",
"JSObject3.body",
"JSObject3",
"JSObject2.arrayType",
"storeValue",
"JSObject2.myFun2",
"Countries.run",
"JSObject2.funcType2",
"JSObject2.funcKey",
"JSObject2.myFun1",
"showAlert",
"appsmith.user.name",
"JSObject2.IntervalCheck",
"JSObject2.thirdFunction",
"JSObject2.clearInsterval",
"JSObject2.body",
"JSObject2",
"appsmith.theme",
"appsmith.user",
"appsmith",
"Countries",
"JSObject1.mutate",
"JSObject1.mutate1",
"JSObject1.body",
"JSObject1",
"Api3.config.path",
"Api3.config",
"Api3",
"Api1.datasourceUrl",
"Api1",
]);
}
});
|
137 | 0 | petrpan-code/appsmithorg/appsmith/app/client/src/entities | petrpan-code/appsmithorg/appsmith/app/client/src/entities/Widget/utils.test.ts | import { getAllPathsFromPropertyConfig } from "./utils";
import { RenderModes } from "constants/WidgetConstants";
import tablePropertyPaneConfig from "widgets/TableWidget/widget/propertyConfig";
import {
contentConfig,
styleConfig,
} from "widgets/ChartWidget/widget/propertyConfig";
import { EvaluationSubstitutionType } from "entities/DataTree/dataTreeFactory";
import { ValidationTypes } from "constants/WidgetValidation";
describe("getAllPathsFromPropertyConfig", () => {
it("works as expected for table widget", () => {
const widget = {
renderMode: RenderModes.CANVAS,
derivedColumns: [],
widgetName: "Table1",
rightColumn: 8,
textSize: "PARAGRAPH",
columnOrder: ["name", "createdAt", "status"],
dynamicPropertyPathList: [
{
key: "primaryColumns.name.verticalAlignment",
},
],
widgetId: "19ye491zn1",
topRow: 7,
bottomRow: 14,
parentRowSpace: 40,
tableData: "{{getUsers.data}}",
isVisible: true,
isVisibleDownload: true,
label: "Data",
searchKey: "",
type: "TABLE_WIDGET",
parentId: "0",
isLoading: false,
isSortable: true,
horizontalAlignment: "LEFT",
parentColumnSpace: 74,
version: 1,
dynamicTriggerPathList: [
{
key: "primaryColumns.status.onClick",
},
],
leftColumn: 0,
dynamicBindingPathList: [
{
key: "primaryColumns.name.computedValue",
},
{
key: "primaryColumns.createdAt.computedValue",
},
{
key: "primaryColumns.status.buttonLabel",
},
{
key: "tableData",
},
],
primaryColumns: {
name: {
index: 1,
width: 150,
id: "name",
horizontalAlignment: "LEFT",
verticalAlignment: "CENTER",
columnType: "text",
textSize: "PARAGRAPH",
enableFilter: true,
enableSort: true,
isVisible: true,
isDerived: false,
label: "name",
computedValue:
"{{Table1.tableData.map((currentRow) => (currentRow.name))}}",
},
createdAt: {
index: 2,
width: 150,
id: "createdAt",
horizontalAlignment: "LEFT",
verticalAlignment: "CENTER",
columnType: "date",
textSize: "PARAGRAPH",
enableFilter: true,
enableSort: true,
isVisible: true,
isDerived: false,
label: "createdAt",
computedValue:
"{{Table1.tableData.map((currentRow) => (currentRow.createdAt))}}",
inputFormat: "YYYY-MM-DDTHH:mm:ss",
outputFormat: "DD-MM-YYYY",
},
status: {
index: 4,
width: 150,
id: "status",
horizontalAlignment: "LEFT",
verticalAlignment: "CENTER",
columnType: "button",
textSize: "PARAGRAPH",
enableFilter: true,
enableSort: true,
isVisible: true,
isDisabled: false,
isDerived: false,
label: "status",
computedValue:
"{{Table1.tableData.map((currentRow) => (currentRow.status))}}",
buttonLabel:
"{{Table1.tableData.map((currentRow) => (currentRow.status))}}",
onClick: "{{showAlert(currentRow.status)}}",
},
},
verticalAlignment: "CENTER",
};
const config = tablePropertyPaneConfig;
const result = getAllPathsFromPropertyConfig(widget, config, {
selectedRow: true,
selectedRows: true,
tableData: true,
});
const expected = {
reactivePaths: {
selectedRow: EvaluationSubstitutionType.TEMPLATE,
selectedRows: EvaluationSubstitutionType.TEMPLATE,
tableData: "SMART_SUBSTITUTE",
"primaryColumns.status.boxShadow": EvaluationSubstitutionType.TEMPLATE,
"primaryColumns.status.borderRadius":
EvaluationSubstitutionType.TEMPLATE,
"primaryColumns.status.buttonVariant":
EvaluationSubstitutionType.TEMPLATE,
"primaryColumns.status.buttonColor":
EvaluationSubstitutionType.TEMPLATE,
"primaryColumns.status.buttonLabel":
EvaluationSubstitutionType.TEMPLATE,
"primaryColumns.status.isDisabled": EvaluationSubstitutionType.TEMPLATE,
"primaryColumns.status.isCellVisible":
EvaluationSubstitutionType.TEMPLATE,
"primaryColumns.createdAt.cellBackground":
EvaluationSubstitutionType.TEMPLATE,
"primaryColumns.createdAt.textColor":
EvaluationSubstitutionType.TEMPLATE,
"primaryColumns.createdAt.verticalAlignment":
EvaluationSubstitutionType.TEMPLATE,
"primaryColumns.createdAt.fontStyle":
EvaluationSubstitutionType.TEMPLATE,
"primaryColumns.createdAt.textSize":
EvaluationSubstitutionType.TEMPLATE,
"primaryColumns.createdAt.horizontalAlignment":
EvaluationSubstitutionType.TEMPLATE,
"primaryColumns.createdAt.outputFormat":
EvaluationSubstitutionType.TEMPLATE,
"primaryColumns.createdAt.inputFormat":
EvaluationSubstitutionType.TEMPLATE,
"primaryColumns.createdAt.isCellVisible":
EvaluationSubstitutionType.TEMPLATE,
"primaryColumns.createdAt.computedValue":
EvaluationSubstitutionType.TEMPLATE,
"primaryColumns.name.cellBackground":
EvaluationSubstitutionType.TEMPLATE,
"primaryColumns.name.textColor": EvaluationSubstitutionType.TEMPLATE,
"primaryColumns.name.verticalAlignment":
EvaluationSubstitutionType.TEMPLATE,
"primaryColumns.name.fontStyle": EvaluationSubstitutionType.TEMPLATE,
"primaryColumns.name.textSize": EvaluationSubstitutionType.TEMPLATE,
"primaryColumns.name.horizontalAlignment":
EvaluationSubstitutionType.TEMPLATE,
"primaryColumns.name.isCellVisible":
EvaluationSubstitutionType.TEMPLATE,
"primaryColumns.name.computedValue":
EvaluationSubstitutionType.TEMPLATE,
primaryColumnId: EvaluationSubstitutionType.TEMPLATE,
defaultSearchText: EvaluationSubstitutionType.TEMPLATE,
defaultSelectedRow: EvaluationSubstitutionType.TEMPLATE,
compactMode: EvaluationSubstitutionType.TEMPLATE,
isVisible: EvaluationSubstitutionType.TEMPLATE,
animateLoading: EvaluationSubstitutionType.TEMPLATE,
isSortable: EvaluationSubstitutionType.TEMPLATE,
isVisibleSearch: EvaluationSubstitutionType.TEMPLATE,
isVisibleFilters: EvaluationSubstitutionType.TEMPLATE,
isVisibleDownload: EvaluationSubstitutionType.TEMPLATE,
isVisiblePagination: EvaluationSubstitutionType.TEMPLATE,
delimiter: EvaluationSubstitutionType.TEMPLATE,
cellBackground: EvaluationSubstitutionType.TEMPLATE,
accentColor: EvaluationSubstitutionType.TEMPLATE,
textColor: EvaluationSubstitutionType.TEMPLATE,
textSize: EvaluationSubstitutionType.TEMPLATE,
borderRadius: EvaluationSubstitutionType.TEMPLATE,
boxShadow: EvaluationSubstitutionType.TEMPLATE,
},
triggerPaths: {
"primaryColumns.status.onClick": true,
onRowSelected: true,
onPageChange: true,
onPageSizeChange: true,
onSearchTextChanged: true,
onSort: true,
},
validationPaths: {
tableData: { type: "OBJECT_ARRAY", params: { default: [] } },
"primaryColumns.status.boxShadow": {
type: ValidationTypes.ARRAY_OF_TYPE_OR_TYPE,
params: { type: ValidationTypes.TEXT },
},
"primaryColumns.status.borderRadius": {
type: ValidationTypes.ARRAY_OF_TYPE_OR_TYPE,
params: { type: ValidationTypes.TEXT },
},
"primaryColumns.status.buttonVariant": {
type: ValidationTypes.ARRAY_OF_TYPE_OR_TYPE,
params: {
type: ValidationTypes.TEXT,
params: {
default: "PRIMARY",
allowedValues: ["PRIMARY", "SECONDARY", "TERTIARY"],
},
},
},
"primaryColumns.status.buttonColor": {
type: ValidationTypes.ARRAY_OF_TYPE_OR_TYPE,
params: {
type: ValidationTypes.TEXT,
params: { regex: /^(?![<|{{]).+/ },
},
},
"primaryColumns.status.isDisabled": {
type: ValidationTypes.ARRAY_OF_TYPE_OR_TYPE,
params: { type: "BOOLEAN" },
},
"primaryColumns.status.isCellVisible": {
type: ValidationTypes.ARRAY_OF_TYPE_OR_TYPE,
params: { type: "BOOLEAN" },
},
"primaryColumns.createdAt.cellBackground": {
type: ValidationTypes.ARRAY_OF_TYPE_OR_TYPE,
params: {
type: ValidationTypes.TEXT,
params: { regex: /^(?![<|{{]).+/ },
},
},
"primaryColumns.createdAt.textColor": {
type: ValidationTypes.ARRAY_OF_TYPE_OR_TYPE,
params: {
type: ValidationTypes.TEXT,
params: { regex: /^(?![<|{{]).+/ },
},
},
"primaryColumns.createdAt.verticalAlignment": {
type: ValidationTypes.ARRAY_OF_TYPE_OR_TYPE,
params: {
type: ValidationTypes.TEXT,
params: { allowedValues: ["TOP", "CENTER", "BOTTOM"] },
},
},
"primaryColumns.createdAt.fontStyle": {
type: ValidationTypes.ARRAY_OF_TYPE_OR_TYPE,
params: { type: ValidationTypes.TEXT },
},
"primaryColumns.createdAt.textSize": {
type: ValidationTypes.ARRAY_OF_TYPE_OR_TYPE,
params: { type: ValidationTypes.TEXT },
},
"primaryColumns.createdAt.horizontalAlignment": {
type: ValidationTypes.ARRAY_OF_TYPE_OR_TYPE,
params: {
type: ValidationTypes.TEXT,
params: { allowedValues: ["LEFT", "CENTER", "RIGHT"] },
},
},
"primaryColumns.createdAt.outputFormat": {
type: ValidationTypes.ARRAY_OF_TYPE_OR_TYPE,
params: {
type: ValidationTypes.TEXT,
params: {
allowedValues: [
"YYYY-MM-DDTHH:mm:ss.SSSZ",
"Epoch",
"Milliseconds",
"YYYY-MM-DD",
"YYYY-MM-DD HH:mm",
"YYYY-MM-DDTHH:mm:ss.sssZ",
"YYYY-MM-DDTHH:mm:ss",
"YYYY-MM-DD hh:mm:ss",
"Do MMM YYYY",
"DD/MM/YYYY",
"DD/MM/YYYY HH:mm",
"LLL",
"LL",
"D MMMM, YYYY",
"H:mm A D MMMM, YYYY",
"MM-DD-YYYY",
"DD-MM-YYYY",
"MM/DD/YYYY",
"DD/MM/YYYY",
"DD/MM/YY",
"MM/DD/YY",
],
},
},
},
"primaryColumns.createdAt.inputFormat": {
type: ValidationTypes.ARRAY_OF_TYPE_OR_TYPE,
params: {
type: ValidationTypes.TEXT,
params: {
allowedValues: [
"YYYY-MM-DDTHH:mm:ss.SSSZ",
"Epoch",
"Milliseconds",
"YYYY-MM-DD",
"YYYY-MM-DD HH:mm",
"YYYY-MM-DDTHH:mm:ss.sssZ",
"YYYY-MM-DDTHH:mm:ss",
"YYYY-MM-DD hh:mm:ss",
"Do MMM YYYY",
"DD/MM/YYYY",
"DD/MM/YYYY HH:mm",
"LLL",
"LL",
"D MMMM, YYYY",
"H:mm A D MMMM, YYYY",
"MM-DD-YYYY",
"DD-MM-YYYY",
"MM/DD/YYYY",
"DD/MM/YYYY",
"DD/MM/YY",
"MM/DD/YY",
],
},
},
},
"primaryColumns.createdAt.isCellVisible": {
type: ValidationTypes.ARRAY_OF_TYPE_OR_TYPE,
params: { type: "BOOLEAN" },
},
"primaryColumns.name.cellBackground": {
type: ValidationTypes.ARRAY_OF_TYPE_OR_TYPE,
params: {
type: ValidationTypes.TEXT,
params: { regex: /^(?![<|{{]).+/ },
},
},
"primaryColumns.name.textColor": {
type: ValidationTypes.ARRAY_OF_TYPE_OR_TYPE,
params: {
type: ValidationTypes.TEXT,
params: { regex: /^(?![<|{{]).+/ },
},
},
"primaryColumns.name.verticalAlignment": {
type: ValidationTypes.ARRAY_OF_TYPE_OR_TYPE,
params: {
type: ValidationTypes.TEXT,
params: { allowedValues: ["TOP", "CENTER", "BOTTOM"] },
},
},
"primaryColumns.name.fontStyle": {
type: ValidationTypes.ARRAY_OF_TYPE_OR_TYPE,
params: { type: ValidationTypes.TEXT },
},
"primaryColumns.name.textSize": {
type: ValidationTypes.ARRAY_OF_TYPE_OR_TYPE,
params: { type: ValidationTypes.TEXT },
},
"primaryColumns.name.horizontalAlignment": {
type: ValidationTypes.ARRAY_OF_TYPE_OR_TYPE,
params: {
type: ValidationTypes.TEXT,
params: { allowedValues: ["LEFT", "CENTER", "RIGHT"] },
},
},
"primaryColumns.name.isCellVisible": {
type: ValidationTypes.ARRAY_OF_TYPE_OR_TYPE,
params: { type: "BOOLEAN" },
},
primaryColumnId: { type: ValidationTypes.TEXT },
defaultSearchText: { type: ValidationTypes.TEXT },
defaultSelectedRow: {
type: "FUNCTION",
params: {
expected: {
type: "Index of row(s)",
example: "0 | [0, 1]",
autocompleteDataType: "STRING",
},
},
},
isVisible: { type: "BOOLEAN" },
animateLoading: { type: "BOOLEAN" },
isSortable: { type: "BOOLEAN", params: { default: true } },
isVisibleSearch: { type: "BOOLEAN" },
isVisibleFilters: { type: "BOOLEAN" },
isVisibleDownload: { type: "BOOLEAN" },
isVisiblePagination: { type: "BOOLEAN" },
delimiter: { type: ValidationTypes.TEXT },
cellBackground: { type: ValidationTypes.TEXT },
accentColor: { type: ValidationTypes.TEXT },
textColor: { type: ValidationTypes.TEXT },
textSize: { type: ValidationTypes.TEXT },
borderRadius: { type: ValidationTypes.TEXT },
boxShadow: { type: ValidationTypes.TEXT },
},
bindingPaths: {
tableData: "SMART_SUBSTITUTE",
"primaryColumns.status.boxShadow": EvaluationSubstitutionType.TEMPLATE,
"primaryColumns.status.borderRadius":
EvaluationSubstitutionType.TEMPLATE,
"primaryColumns.status.buttonVariant":
EvaluationSubstitutionType.TEMPLATE,
"primaryColumns.status.buttonColor":
EvaluationSubstitutionType.TEMPLATE,
"primaryColumns.status.buttonLabel":
EvaluationSubstitutionType.TEMPLATE,
"primaryColumns.status.isDisabled": EvaluationSubstitutionType.TEMPLATE,
"primaryColumns.status.isCellVisible":
EvaluationSubstitutionType.TEMPLATE,
"primaryColumns.createdAt.cellBackground":
EvaluationSubstitutionType.TEMPLATE,
"primaryColumns.createdAt.textColor":
EvaluationSubstitutionType.TEMPLATE,
"primaryColumns.createdAt.verticalAlignment":
EvaluationSubstitutionType.TEMPLATE,
"primaryColumns.createdAt.fontStyle":
EvaluationSubstitutionType.TEMPLATE,
"primaryColumns.createdAt.textSize":
EvaluationSubstitutionType.TEMPLATE,
"primaryColumns.createdAt.horizontalAlignment":
EvaluationSubstitutionType.TEMPLATE,
"primaryColumns.createdAt.outputFormat":
EvaluationSubstitutionType.TEMPLATE,
"primaryColumns.createdAt.inputFormat":
EvaluationSubstitutionType.TEMPLATE,
"primaryColumns.createdAt.isCellVisible":
EvaluationSubstitutionType.TEMPLATE,
"primaryColumns.createdAt.computedValue":
EvaluationSubstitutionType.TEMPLATE,
"primaryColumns.name.cellBackground":
EvaluationSubstitutionType.TEMPLATE,
"primaryColumns.name.textColor": EvaluationSubstitutionType.TEMPLATE,
"primaryColumns.name.verticalAlignment":
EvaluationSubstitutionType.TEMPLATE,
"primaryColumns.name.fontStyle": EvaluationSubstitutionType.TEMPLATE,
"primaryColumns.name.textSize": EvaluationSubstitutionType.TEMPLATE,
"primaryColumns.name.horizontalAlignment":
EvaluationSubstitutionType.TEMPLATE,
"primaryColumns.name.isCellVisible":
EvaluationSubstitutionType.TEMPLATE,
"primaryColumns.name.computedValue":
EvaluationSubstitutionType.TEMPLATE,
primaryColumnId: EvaluationSubstitutionType.TEMPLATE,
defaultSearchText: EvaluationSubstitutionType.TEMPLATE,
defaultSelectedRow: EvaluationSubstitutionType.TEMPLATE,
compactMode: EvaluationSubstitutionType.TEMPLATE,
isVisible: EvaluationSubstitutionType.TEMPLATE,
animateLoading: EvaluationSubstitutionType.TEMPLATE,
isSortable: EvaluationSubstitutionType.TEMPLATE,
isVisibleSearch: EvaluationSubstitutionType.TEMPLATE,
isVisibleFilters: EvaluationSubstitutionType.TEMPLATE,
isVisibleDownload: EvaluationSubstitutionType.TEMPLATE,
isVisiblePagination: EvaluationSubstitutionType.TEMPLATE,
delimiter: EvaluationSubstitutionType.TEMPLATE,
cellBackground: EvaluationSubstitutionType.TEMPLATE,
accentColor: EvaluationSubstitutionType.TEMPLATE,
textColor: EvaluationSubstitutionType.TEMPLATE,
textSize: EvaluationSubstitutionType.TEMPLATE,
borderRadius: EvaluationSubstitutionType.TEMPLATE,
boxShadow: EvaluationSubstitutionType.TEMPLATE,
},
};
// Note: Removing until we figure out how functions are represented here.
delete result.validationPaths.defaultSelectedRow.params?.fn;
expect(result).toStrictEqual(expected);
});
it("works as expected for chart widget", () => {
const widget = {
renderMode: RenderModes.CANVAS,
isVisible: true,
widgetName: "Chart1",
chartType: "LINE_CHART",
chartName: "Sales on working days",
allowScroll: false,
version: 1,
chartData: {
"random-id": {
seriesName: "",
data: "{{Api1.data}}",
},
},
xAxisName: "Last Week",
yAxisName: "Total Order Revenue $",
type: "CHART_WIDGET",
isLoading: false,
parentColumnSpace: 74,
parentRowSpace: 40,
leftColumn: 4,
rightColumn: 10,
topRow: 6,
bottomRow: 14,
parentId: "0",
widgetId: "x1naz9is2b",
dynamicBindingPathList: [
{
key: "chartData.random-id.data",
},
],
setAdaptiveYMin: "0",
};
const customEChartEnabled = true;
const showFusionChartDeprecationMessage = true;
const config = [
...contentConfig(customEChartEnabled, showFusionChartDeprecationMessage),
...styleConfig,
];
const bindingPaths = {
chartType: EvaluationSubstitutionType.TEMPLATE,
chartName: EvaluationSubstitutionType.TEMPLATE,
"chartData.random-id.seriesName": EvaluationSubstitutionType.TEMPLATE,
"chartData.random-id.data": EvaluationSubstitutionType.SMART_SUBSTITUTE,
xAxisName: EvaluationSubstitutionType.TEMPLATE,
yAxisName: EvaluationSubstitutionType.TEMPLATE,
isVisible: EvaluationSubstitutionType.TEMPLATE,
animateLoading: EvaluationSubstitutionType.TEMPLATE,
setAdaptiveYMin: EvaluationSubstitutionType.TEMPLATE,
borderRadius: EvaluationSubstitutionType.TEMPLATE,
boxShadow: EvaluationSubstitutionType.TEMPLATE,
};
const expected = {
bindingPaths,
reactivePaths: { ...bindingPaths },
triggerPaths: {
onDataPointClick: true,
},
validationPaths: {
"chartData.random-id.data": {
params: {
default: [],
children: {
params: {
required: true,
allowedKeys: [
{
name: "x",
type: ValidationTypes.TEXT,
params: {
default: "",
required: true,
},
},
{
name: "y",
type: "NUMBER",
params: {
default: 10,
required: true,
},
},
],
},
type: "OBJECT",
},
},
type: "ARRAY",
},
"chartData.random-id.seriesName": {
type: ValidationTypes.TEXT,
},
chartName: {
type: ValidationTypes.TEXT,
},
chartType: {
params: {
allowedValues: [
"LINE_CHART",
"BAR_CHART",
"PIE_CHART",
"COLUMN_CHART",
"AREA_CHART",
"CUSTOM_ECHART",
"CUSTOM_FUSION_CHART",
],
},
type: ValidationTypes.TEXT,
},
isVisible: {
type: ValidationTypes.BOOLEAN,
},
animateLoading: {
type: ValidationTypes.BOOLEAN,
},
setAdaptiveYMin: {
type: ValidationTypes.BOOLEAN,
},
xAxisName: {
type: ValidationTypes.TEXT,
},
yAxisName: {
type: ValidationTypes.TEXT,
},
borderRadius: {
type: ValidationTypes.TEXT,
},
boxShadow: {
type: ValidationTypes.TEXT,
},
},
};
const result = getAllPathsFromPropertyConfig(widget, config, {
"chartData.random-id.data": true,
});
expect(result).toStrictEqual(expected);
});
});
|
153 | 0 | petrpan-code/appsmithorg/appsmith/app/client/src | petrpan-code/appsmithorg/appsmith/app/client/src/layoutSystems/CanvasFactory.test.tsx | import { RenderModes } from "constants/WidgetConstants";
import * as editorSelectors from "selectors/editorSelectors";
import { buildChildren } from "test/factories/WidgetFactoryUtils";
import { renderAppsmithCanvas } from "./CanvasFactory";
import { render } from "test/testUtils";
import React from "react";
import store from "store";
import type { WidgetProps } from "widgets/BaseWidget";
import { LayoutSystemTypes } from "./types";
import * as layoutSystemSelectors from "selectors/layoutSystemSelectors";
describe("Layout Based Canvas aka Canvas Widget Test cases", () => {
it("Render Fixed Layout Editor Canvas when layoutSystemType/appPositioningType is FIXED and render mode is CANVAS/PAGE", () => {
const children = buildChildren([
{
type: "CANVAS_WIDGET",
parentId: "xxxxxx",
children: [],
widgetId: "yyyyyy",
dynamicHeight: "FIXED",
},
]);
if (children) {
const canvasProps = children[0];
jest
.spyOn(editorSelectors, "getRenderMode")
.mockImplementation(() => RenderModes.CANVAS);
jest
.spyOn(layoutSystemSelectors, "getLayoutSystemType")
.mockImplementation(() => LayoutSystemTypes.FIXED);
const state = store.getState();
const customState = {
...state,
entities: {
...state.entities,
canvasWidgets: {
xxxxxx: {} as WidgetProps,
yyyyyy: {} as WidgetProps,
},
},
};
const editorCanvas = render(<>{renderAppsmithCanvas(canvasProps)}</>, {
initialState: customState,
});
const editorDropTarget =
editorCanvas.container.getElementsByClassName("t--drop-target")[0];
expect(editorDropTarget).toBeTruthy();
jest
.spyOn(editorSelectors, "getRenderMode")
.mockImplementation(() => RenderModes.PAGE);
const viewerCanvas = render(<>{renderAppsmithCanvas(canvasProps)}</>, {
initialState: customState,
});
const viewerDropTarget =
viewerCanvas.container.getElementsByClassName("t--drop-target")[0];
expect(viewerDropTarget).toBeFalsy();
}
});
it("Render Auto Layout Editor Canvas when layoutSystemType/appPositioningType is AUTO and render mode is CANVAS/PAGE", () => {
const children = buildChildren([
{
type: "CANVAS_WIDGET",
parentId: "xxxxxx",
children: [],
widgetId: "yyyyyy",
dynamicHeight: "FIXED",
},
]);
if (children) {
const canvasProps = children[0];
jest
.spyOn(editorSelectors, "getRenderMode")
.mockImplementation(() => RenderModes.CANVAS);
jest
.spyOn(layoutSystemSelectors, "getLayoutSystemType")
.mockImplementation(() => LayoutSystemTypes.AUTO);
const state = store.getState();
const customState = {
...state,
entities: {
...state.entities,
canvasWidgets: {
xxxxxx: {} as WidgetProps,
yyyyyy: {} as WidgetProps,
},
},
};
const editorCanvas = render(<>{renderAppsmithCanvas(canvasProps)}</>, {
initialState: customState,
});
const editorDropTarget =
editorCanvas.container.getElementsByClassName("t--drop-target")[0];
expect(editorDropTarget).toBeTruthy();
jest
.spyOn(editorSelectors, "getRenderMode")
.mockImplementation(() => RenderModes.PAGE);
const viewerCanvas = render(<>{renderAppsmithCanvas(canvasProps)}</>, {
initialState: customState,
});
const viewerDropTarget =
viewerCanvas.container.getElementsByClassName("t--drop-target")[0];
expect(viewerDropTarget).toBeFalsy();
}
});
});
|
155 | 0 | petrpan-code/appsmithorg/appsmith/app/client/src | petrpan-code/appsmithorg/appsmith/app/client/src/layoutSystems/withLayoutSystemWidgetHOC.test.tsx | import { RenderModes } from "constants/WidgetConstants";
import React from "react";
import * as editorSelectors from "selectors/editorSelectors";
import { WidgetTypeFactories } from "test/factories/Widgets/WidgetTypeFactories";
import { render } from "test/testUtils";
import InputWidget from "widgets/InputWidgetV2/widget";
import { ModalWidget } from "widgets/ModalWidget/widget";
import { withLayoutSystemWidgetHOC } from "./withLayoutSystemWidgetHOC";
import { LayoutSystemTypes } from "./types";
import * as layoutSystemSelectors from "selectors/layoutSystemSelectors";
describe("Layout System HOC's Tests", () => {
describe("Fixed Layout Layers", () => {
it("Layout system hoc should return Fixed Editor for FIXED positioning and CANVAS render mode", () => {
const widget = InputWidget;
const HOC = withLayoutSystemWidgetHOC(widget);
const widgetProps = WidgetTypeFactories[InputWidget.type].build();
jest
.spyOn(editorSelectors, "getRenderMode")
.mockImplementation(() => RenderModes.CANVAS);
jest
.spyOn(layoutSystemSelectors, "getLayoutSystemType")
.mockImplementation(() => LayoutSystemTypes.FIXED);
const component = render(<HOC {...widgetProps} />);
const positionedLayer =
component.container.getElementsByClassName("positioned-widget")[0];
const resizerLayer =
component.container.getElementsByClassName("resize-wrapper")[0];
expect(positionedLayer).toBeTruthy();
expect(resizerLayer).toBeTruthy();
});
it("Layout system hoc should return Fixed Modal Editor for FIXED positioning and CANVAS render mode", () => {
const widget = ModalWidget;
const HOC = withLayoutSystemWidgetHOC(widget);
const widgetProps = WidgetTypeFactories[ModalWidget.type].build({
isVisible: true,
});
jest
.spyOn(editorSelectors, "getRenderMode")
.mockImplementation(() => RenderModes.CANVAS);
jest
.spyOn(layoutSystemSelectors, "getLayoutSystemType")
.mockImplementation(() => LayoutSystemTypes.FIXED);
const component = render(<HOC {...widgetProps} />);
const positionedLayer =
component.container.getElementsByClassName("positioned-widget")[0];
const resizerLayer =
component.container.getElementsByClassName("resize-wrapper")[0];
const overlayLayer =
component.container.getElementsByClassName("bp3-overlay")[0];
expect(positionedLayer).toBeFalsy();
expect(overlayLayer).toBeTruthy();
expect(resizerLayer).toBeTruthy();
});
it("Layout system hoc should return Fixed Modal Viewer for FIXED positioning and PAGE render mode", () => {
const widget = ModalWidget;
const HOC = withLayoutSystemWidgetHOC(widget);
const widgetProps = WidgetTypeFactories[ModalWidget.type].build({
isVisible: true,
});
jest
.spyOn(editorSelectors, "getRenderMode")
.mockImplementation(() => RenderModes.PAGE);
jest
.spyOn(layoutSystemSelectors, "getLayoutSystemType")
.mockImplementation(() => LayoutSystemTypes.FIXED);
const component = render(<HOC {...widgetProps} />);
const positionedLayer =
component.container.getElementsByClassName("positioned-widget")[0];
const resizerLayer =
component.container.getElementsByClassName("resize-wrapper")[0];
const overlayLayer =
component.container.getElementsByClassName("bp3-overlay")[0];
expect(positionedLayer).toBeFalsy();
expect(overlayLayer).toBeTruthy();
expect(resizerLayer).toBeFalsy();
});
it("Layout system hoc should return Fixed Viewer for FIXED positioning and PAGE render mode", () => {
const widget = InputWidget;
const HOC = withLayoutSystemWidgetHOC(widget);
const widgetProps = WidgetTypeFactories[InputWidget.type].build();
jest
.spyOn(editorSelectors, "getRenderMode")
.mockImplementation(() => RenderModes.PAGE);
jest
.spyOn(layoutSystemSelectors, "getLayoutSystemType")
.mockImplementation(() => LayoutSystemTypes.FIXED);
const component = render(<HOC {...widgetProps} />);
const positionedLayer =
component.container.getElementsByClassName("positioned-widget")[0];
const resizerLayer =
component.container.getElementsByClassName("resize-wrapper")[0];
expect(positionedLayer).toBeTruthy();
expect(resizerLayer).toBeFalsy();
});
});
describe("Auto Layout Layers", () => {
it("Layout system hoc should return Auto Layout Editor for AUTO positioning and CANVAS render mode", () => {
const widget = InputWidget;
const HOC = withLayoutSystemWidgetHOC(widget);
const widgetProps = WidgetTypeFactories[InputWidget.type].build();
jest
.spyOn(editorSelectors, "getRenderMode")
.mockImplementation(() => RenderModes.CANVAS);
jest
.spyOn(layoutSystemSelectors, "getLayoutSystemType")
.mockImplementation(() => LayoutSystemTypes.AUTO);
const component = render(<HOC {...widgetProps} />);
const flexPositionedLayer = component.container.getElementsByClassName(
"auto-layout-child-" + widgetProps.widgetId,
)[0];
const resizerLayer =
component.container.getElementsByClassName("resize-wrapper")[0];
expect(flexPositionedLayer).toBeTruthy();
expect(resizerLayer).toBeTruthy();
});
it("Layout system hoc should return Auto Modal Editor for AUTO positioning and CANVAS render mode", () => {
const widget = ModalWidget;
const HOC = withLayoutSystemWidgetHOC(widget);
const widgetProps = WidgetTypeFactories[ModalWidget.type].build({
isVisible: true,
});
jest
.spyOn(editorSelectors, "getRenderMode")
.mockImplementation(() => RenderModes.CANVAS);
jest
.spyOn(layoutSystemSelectors, "getLayoutSystemType")
.mockImplementation(() => LayoutSystemTypes.AUTO);
const component = render(<HOC {...widgetProps} />);
const flexPositionedLayer = component.container.getElementsByClassName(
"auto-layout-child-" + widgetProps.widgetId,
)[0];
const resizerLayer =
component.container.getElementsByClassName("resize-wrapper")[0];
const overlayLayer =
component.container.getElementsByClassName("bp3-overlay")[0];
expect(flexPositionedLayer).toBeFalsy();
expect(overlayLayer).toBeTruthy();
expect(resizerLayer).toBeTruthy();
});
it("Layout system hoc should return Auto Modal Viewer for AUTO positioning and PAGE render mode", () => {
const widget = ModalWidget;
const HOC = withLayoutSystemWidgetHOC(widget);
const widgetProps = WidgetTypeFactories[ModalWidget.type].build({
isVisible: true,
});
jest
.spyOn(editorSelectors, "getRenderMode")
.mockImplementation(() => RenderModes.PAGE);
jest
.spyOn(layoutSystemSelectors, "getLayoutSystemType")
.mockImplementation(() => LayoutSystemTypes.AUTO);
const component = render(<HOC {...widgetProps} />);
const flexPositionedLayer = component.container.getElementsByClassName(
"auto-layout-child-" + widgetProps.widgetId,
)[0];
const resizerLayer =
component.container.getElementsByClassName("resize-wrapper")[0];
const overlayLayer =
component.container.getElementsByClassName("bp3-overlay")[0];
expect(flexPositionedLayer).toBeFalsy();
expect(overlayLayer).toBeTruthy();
expect(resizerLayer).toBeFalsy();
});
it("Layout system hoc should return Auto Viewer for Auto positioning and PAGE render mode", () => {
const widget = InputWidget;
const HOC = withLayoutSystemWidgetHOC(widget);
const widgetProps = WidgetTypeFactories[InputWidget.type].build();
jest
.spyOn(editorSelectors, "getRenderMode")
.mockImplementation(() => RenderModes.PAGE);
jest
.spyOn(layoutSystemSelectors, "getLayoutSystemType")
.mockImplementation(() => LayoutSystemTypes.AUTO);
const component = render(<HOC {...widgetProps} />);
const flexPositionedLayer = component.container.getElementsByClassName(
"auto-layout-child-" + widgetProps.widgetId,
)[0];
const resizerLayer =
component.container.getElementsByClassName("resize-wrapper")[0];
expect(flexPositionedLayer).toBeTruthy();
expect(resizerLayer).toBeFalsy();
});
});
describe("Anvil Layout Layers", () => {
it("Layout system hoc should return Anvil Editor for ANVIL positioning and CANVAS render mode", () => {
const widget = InputWidget;
const HOC = withLayoutSystemWidgetHOC(widget);
const widgetProps = WidgetTypeFactories[InputWidget.type].build();
jest
.spyOn(editorSelectors, "getRenderMode")
.mockImplementation(() => RenderModes.CANVAS);
jest
.spyOn(layoutSystemSelectors, "getLayoutSystemType")
.mockImplementation(() => LayoutSystemTypes.ANVIL);
const component = render(<HOC {...widgetProps} />);
const flexPositionedLayer = component.container.getElementsByClassName(
"anvil-layout-child-" + widgetProps.widgetId,
)[0];
expect(flexPositionedLayer).toBeTruthy();
});
it("should return Auto Modal Editor for ANVIL positioning and CANVAS render mode", () => {
const widget = ModalWidget;
const HOC = withLayoutSystemWidgetHOC(widget);
const widgetProps = WidgetTypeFactories[ModalWidget.type].build({
isVisible: true,
});
jest
.spyOn(editorSelectors, "getRenderMode")
.mockImplementation(() => RenderModes.CANVAS);
jest
.spyOn(layoutSystemSelectors, "getLayoutSystemType")
.mockImplementation(() => LayoutSystemTypes.ANVIL);
const component = render(<HOC {...widgetProps} />);
const flexPositionedLayer = component.container.getElementsByClassName(
"anvil-layout-child-" + widgetProps.widgetId,
)[0];
const overlayLayer =
component.container.getElementsByClassName("bp3-overlay")[0];
expect(flexPositionedLayer).toBeFalsy();
expect(overlayLayer).toBeTruthy();
});
it("should return Auto Modal Viewer for ANVIL positioning and PAGE render mode", () => {
const widget = ModalWidget;
const HOC = withLayoutSystemWidgetHOC(widget);
const widgetProps = WidgetTypeFactories[ModalWidget.type].build({
isVisible: true,
});
jest
.spyOn(editorSelectors, "getRenderMode")
.mockImplementation(() => RenderModes.PAGE);
jest
.spyOn(layoutSystemSelectors, "getLayoutSystemType")
.mockImplementation(() => LayoutSystemTypes.ANVIL);
const component = render(<HOC {...widgetProps} />);
const flexPositionedLayer = component.container.getElementsByClassName(
"anvil-layout-child-" + widgetProps.widgetId,
)[0];
const overlayLayer =
component.container.getElementsByClassName("bp3-overlay")[0];
expect(flexPositionedLayer).toBeFalsy();
expect(overlayLayer).toBeTruthy();
});
it("should return Anvil Viewer for ANVIL positioning and PAGE render mode", () => {
const widget = InputWidget;
const HOC = withLayoutSystemWidgetHOC(widget);
const widgetProps = WidgetTypeFactories[InputWidget.type].build();
jest
.spyOn(editorSelectors, "getRenderMode")
.mockImplementation(() => RenderModes.PAGE);
jest
.spyOn(layoutSystemSelectors, "getLayoutSystemType")
.mockImplementation(() => LayoutSystemTypes.ANVIL);
const component = render(<HOC {...widgetProps} />);
const flexPositionedLayer = component.container.getElementsByClassName(
"anvil-layout-child-" + widgetProps.widgetId,
)[0];
expect(flexPositionedLayer).toBeTruthy();
});
});
});
|
198 | 0 | petrpan-code/appsmithorg/appsmith/app/client/src/layoutSystems/anvil | petrpan-code/appsmithorg/appsmith/app/client/src/layoutSystems/anvil/utils/AnvilDSLTransformer.test.ts | import { anvilDSLTransformer } from "./AnvilDSLTransformer";
import { mainContainerProps } from "mocks/widgetProps/input";
describe("Test the DSL transformer for Anvil", () => {
it("should add a layout if it does not exist in the DSL", () => {
// Arrange
const dsl = mainContainerProps;
// Act
const result = anvilDSLTransformer(dsl);
// Assert
expect(result).toHaveProperty("layout");
expect(result.layout).toHaveLength(1);
});
it("should not add a layout if it already exists in the DSL", () => {
// Arrange
const dsl = {
...mainContainerProps,
layout: [
{
layoutId: "existingLayout",
layoutType: "CUSTOM",
layout: [],
},
],
};
// Act
const result = anvilDSLTransformer(dsl);
// Assert
expect(result).toEqual(dsl); // The result should be the same as the input since the layout exists
});
});
|
203 | 0 | petrpan-code/appsmithorg/appsmith/app/client/src/layoutSystems/anvil | petrpan-code/appsmithorg/appsmith/app/client/src/layoutSystems/anvil/utils/widgetUtils.test.ts | import { getResponsiveMinWidth } from "./widgetUtils";
describe("WidgetUtils tests", () => {
describe("getResponsiveMinWidth", () => {
it("should return the min width as is for Hug widgets", () => {
const config = { base: "100px" };
const result = getResponsiveMinWidth(config, false);
expect(result).toEqual(config);
});
it("should return undefined if the min width is undefined for a Hug widget", () => {
const result = getResponsiveMinWidth(undefined, false);
expect(result).toEqual(undefined);
});
it("should set base as 100% for Fill widgets if minWidth config is undefined", () => {
const result = getResponsiveMinWidth(undefined, true);
expect(result).toEqual({ base: "100%", "480px": "" });
});
it("should set base as 100% for Fill widgets if minWidth config is defined as assign given minWidth at 480px", () => {
const config = { base: "100px" };
const result = getResponsiveMinWidth(config, true);
expect(result).toEqual({ base: "100%", "480px": "100px" });
});
});
});
|
205 | 0 | petrpan-code/appsmithorg/appsmith/app/client/src/layoutSystems/anvil/utils | petrpan-code/appsmithorg/appsmith/app/client/src/layoutSystems/anvil/utils/layouts/layoutUtils.test.ts | import { generateLayoutComponentMock } from "mocks/layoutComponents/layoutComponentMock";
import type {
AnvilHighlightInfo,
LayoutComponentProps,
LayoutProps,
WidgetLayoutProps,
} from "../anvilTypes";
import {
addChildToLayout,
extractWidgetIdsFromLayoutProps,
removeChildFromLayout,
} from "./layoutUtils";
import type { BaseWidgetProps } from "widgets/BaseWidgetHOC/withBaseWidgetHOC";
import { mockAnvilHighlightInfo } from "mocks/mockHighlightInfo";
import { mockButtonProps } from "mocks/widgetProps/button";
import { FlexLayerAlignment } from "layoutSystems/common/utils/constants";
import { getAnvilLayoutDOMId } from "layoutSystems/common/utils/LayoutElementPositionsObserver/utils";
describe("layoutUtils tests", () => {
describe("getLayoutId", () => {
it("should generate layout identifier using canvasId and layoutId", () => {
const canvasId = "canvasId";
const layoutId = "layoutId";
const expectedLayoutId = `layout_${canvasId}_${layoutId}`;
expect(getAnvilLayoutDOMId(canvasId, layoutId)).toBe(expectedLayoutId);
});
});
describe("addChildToLayout", () => {
it("should add child to layout at provided index", () => {
const layout: LayoutComponentProps = generateLayoutComponentMock();
const buttonWidget: BaseWidgetProps = mockButtonProps();
const children: WidgetLayoutProps[] = [
{
widgetId: buttonWidget.widgetId,
alignment: FlexLayerAlignment.Start,
},
];
// Add child at rowIndex 1. layout already contains two widgets.
let highlight: AnvilHighlightInfo = mockAnvilHighlightInfo({
rowIndex: 1,
});
let updatedLayout: LayoutProps = addChildToLayout(
layout,
children,
highlight,
);
expect(
extractWidgetIdsFromLayoutProps(updatedLayout).includes(
buttonWidget.widgetId,
),
).toBeTruthy();
// Add child at rowIndex 0.
highlight = mockAnvilHighlightInfo({ rowIndex: 0 });
updatedLayout = addChildToLayout(layout, children, highlight);
expect(extractWidgetIdsFromLayoutProps(updatedLayout)[0]).toEqual(
buttonWidget.widgetId,
);
// Add child at the end of the layout.
highlight = mockAnvilHighlightInfo({
rowIndex: updatedLayout.layout.length,
});
updatedLayout = addChildToLayout(layout, children, highlight);
expect(
extractWidgetIdsFromLayoutProps(updatedLayout).includes(
buttonWidget.widgetId,
),
).toBeTruthy();
});
});
describe("removeChildFromLayout", () => {
it("should remove child from layout at provided index", () => {
const layout: LayoutComponentProps = generateLayoutComponentMock();
const originalLength: number = layout.layout.length;
const lastWidget: WidgetLayoutProps = layout.layout[
layout.layout.length - 1
] as WidgetLayoutProps;
// Remove last child in the layout.
const updatedLayout: LayoutProps | undefined = removeChildFromLayout(
layout,
lastWidget,
);
if (!updatedLayout) return;
expect(
extractWidgetIdsFromLayoutProps(updatedLayout).includes(
lastWidget.widgetId,
),
).toBeFalsy();
expect(updatedLayout?.layout.length).toEqual(originalLength - 1);
});
it("should return undefined if layout is temporary and empty after deletion", () => {
const layoutProps: LayoutComponentProps = generateLayoutComponentMock();
const lastWidget: WidgetLayoutProps = layoutProps.layout[
layoutProps.layout.length - 1
] as WidgetLayoutProps;
// Remove last child in the layout.
const updatedLayout: LayoutProps | undefined = removeChildFromLayout(
{ ...layoutProps, layout: [lastWidget] },
lastWidget,
);
expect(updatedLayout).toBeUndefined();
});
});
});
|
207 | 0 | petrpan-code/appsmithorg/appsmith/app/client/src/layoutSystems/anvil/utils | petrpan-code/appsmithorg/appsmith/app/client/src/layoutSystems/anvil/utils/layouts/renderUtils.test.tsx | import { generateLayoutComponentMock } from "mocks/layoutComponents/layoutComponentMock";
import type { LayoutComponentProps, WidgetLayoutProps } from "../anvilTypes";
import type { WidgetProps } from "widgets/BaseWidget";
import { getChildrenMap } from "./renderUtils";
describe("renderUtils tests", () => {
describe("getChildrenMap", () => {
it("should extract proper children data for each layout", () => {
/**
* This will create a Layout Component that renders two layouts, each of which renders two widgets.
* Row
* Row
* Button
* Input
* Row
* Button
* Input
*/
const layout: LayoutComponentProps = generateLayoutComponentMock(
{},
false,
);
const childLayoutOne: LayoutComponentProps = layout
.layout[0] as LayoutComponentProps;
const childLayoutTwo: LayoutComponentProps = layout
.layout[1] as LayoutComponentProps;
const childLayoutOneWidgets: WidgetLayoutProps[] =
childLayoutOne.layout as WidgetLayoutProps[];
const childLayoutTwoWidgets: WidgetLayoutProps[] =
childLayoutTwo.layout as WidgetLayoutProps[];
// Create aggregate map of children
const map: Record<string, WidgetProps> = {
...childLayoutOne.childrenMap,
...childLayoutTwo.childrenMap,
};
// Extract childrenMap for child layout one.
let res: LayoutComponentProps["childrenMap"] = getChildrenMap(
childLayoutOne,
map,
{},
);
expect(Object.keys(res || {}).length).toEqual(2);
expect(
Object.keys(res || {}).includes(childLayoutOneWidgets[0].widgetId),
).toBeTruthy();
// Extract childrenMap for child layout two.
res = getChildrenMap(childLayoutTwo, map, {});
expect(
Object.keys(res || {}).includes(childLayoutTwoWidgets[1].widgetId),
).toBeTruthy();
res = getChildrenMap(layout, map, {});
expect(Object.keys(res || {}).length).toEqual(4);
});
});
});
|
209 | 0 | petrpan-code/appsmithorg/appsmith/app/client/src/layoutSystems/anvil/utils | petrpan-code/appsmithorg/appsmith/app/client/src/layoutSystems/anvil/utils/layouts/typeUtils.test.ts | import { generateLayoutComponentMock } from "mocks/layoutComponents/layoutComponentMock";
import { doesLayoutRenderWidgets } from "./typeUtils";
import type { LayoutComponentProps } from "../anvilTypes";
describe("Layouts - typeUtils tests", () => {
describe("doesLayoutRenderWidgets", () => {
it("should return true if layout renders widgets", () => {
const layout: LayoutComponentProps = generateLayoutComponentMock();
expect(doesLayoutRenderWidgets(layout)).toBeTruthy();
});
it("should return false if layout renders widgets", () => {
const layout: LayoutComponentProps = generateLayoutComponentMock(
{},
false,
);
expect(doesLayoutRenderWidgets(layout)).toBeFalsy();
});
});
});
|
212 | 0 | petrpan-code/appsmithorg/appsmith/app/client/src/layoutSystems/anvil/utils/layouts | petrpan-code/appsmithorg/appsmith/app/client/src/layoutSystems/anvil/utils/layouts/highlights/alignedColumnHighlights.test.ts | import { generateLayoutComponentMock } from "mocks/layoutComponents/layoutComponentMock";
import {
LayoutComponentTypes,
type LayoutComponentProps,
type AnvilHighlightInfo,
type WidgetLayoutProps,
} from "../../anvilTypes";
import { deriveAlignedColumnHighlights } from "./alignedColumnHighlights";
import {
HIGHLIGHT_SIZE,
VERTICAL_DROP_ZONE_MULTIPLIER,
} from "layoutSystems/anvil/utils/constants";
import { ResponsiveBehavior } from "layoutSystems/common/utils/constants";
import type { LayoutElementPositions } from "layoutSystems/common/types";
import { registerLayoutComponents } from "../layoutUtils";
describe("AlignedColumnHighlights tests", () => {
beforeAll(() => {
registerLayoutComponents();
});
describe("deriveAlignedColumnHighlights", () => {
it("should return three highlights for an empty layout", () => {
const layout: LayoutComponentProps = generateLayoutComponentMock({
isDropTarget: true,
layoutType: LayoutComponentTypes.ALIGNED_WIDGET_COLUMN,
layout: [],
});
const positions: LayoutElementPositions = {
[layout.layoutId]: {
height: 400,
left: 0,
top: 0,
width: 300,
offsetLeft: 0,
offsetTop: 0,
},
};
const res: AnvilHighlightInfo[] = deriveAlignedColumnHighlights(
layout,
"0",
[],
layout.layoutId,
)(positions, [
{
widgetId: "random",
type: "BUTTON_WIDGET",
responsiveBehavior: ResponsiveBehavior.Hug,
},
]);
const highlightWidth: number = positions[layout.layoutId].width / 3;
expect(res.length).toEqual(3);
// Each highlight should be of equal width = 1/3 width of the layout.
expect(res[0].width).toEqual(highlightWidth);
expect(res[1].width).toEqual(highlightWidth);
expect(res[2].width).toEqual(highlightWidth);
// highlights should be placed according to the alignment.
expect(res[0].posX).toEqual(0);
expect(res[1].posX).toEqual(highlightWidth);
expect(res[2].posX).toEqual(highlightWidth * 2);
});
it("should return a single highlight for Fill widget being dragged over an empty layout", () => {
const layout: LayoutComponentProps = generateLayoutComponentMock({
isDropTarget: true,
layoutType: LayoutComponentTypes.ALIGNED_WIDGET_COLUMN,
layout: [],
});
const positions: LayoutElementPositions = {
[layout.layoutId]: {
height: 400,
left: 0,
top: 0,
width: 300,
offsetLeft: 0,
offsetTop: 0,
},
};
const res: AnvilHighlightInfo[] = deriveAlignedColumnHighlights(
layout,
"0",
[],
layout.layoutId,
)(positions, [
{
widgetId: "1",
type: "INPUT_WIDGET",
responsiveBehavior: ResponsiveBehavior.Fill,
},
]);
expect(res.length).toEqual(1);
expect(res[0].width).toEqual(positions[layout.layoutId].width);
});
it("should derive highlights using widget positions", () => {
const layout: LayoutComponentProps = generateLayoutComponentMock({
isDropTarget: true,
layoutType: LayoutComponentTypes.ALIGNED_WIDGET_COLUMN,
});
const button: string = (layout.layout[0] as WidgetLayoutProps).widgetId;
const input: string = (layout.layout[1] as WidgetLayoutProps).widgetId;
const positions: LayoutElementPositions = {
[layout.layoutId]: {
height: 400,
left: 0,
top: 0,
width: 300,
offsetLeft: 0,
offsetTop: 0,
},
[button]: {
height: 40,
left: 10,
top: 10,
width: 120,
offsetLeft: 10,
offsetTop: 10,
},
[input]: {
height: 70,
left: 10,
top: 60,
width: 290,
offsetLeft: 10,
offsetTop: 60,
},
};
const res: AnvilHighlightInfo[] = deriveAlignedColumnHighlights(
layout,
"0",
[],
layout.layoutId,
)(positions, [
{
widgetId: "1",
type: "BUTTON_WIDGET",
responsiveBehavior: ResponsiveBehavior.Hug,
},
]);
expect(res.length).toEqual(9);
// Highlights should be horizontal
expect(res[0].height).toBeLessThan(res[0].width);
expect(res[1].isVertical).toBeFalsy();
// First set of highlights should be placed before the first widget.
expect(res[0].posY).toEqual(positions[button].top - HIGHLIGHT_SIZE);
// Second set of highlights should be placed between the two widgets.
expect(res[4].posY).toEqual(positions[input].top - HIGHLIGHT_SIZE);
expect(res[4].posY).toBeGreaterThan(
positions[button].top + positions[button].height,
);
// Final set of highlights should be placed after the last widget.
expect(res[8].posY).toEqual(
positions[input].top + positions[input].height + HIGHLIGHT_SIZE / 2,
);
});
it("should calculate proper drop zones", () => {
const layout: LayoutComponentProps = generateLayoutComponentMock({
isDropTarget: true,
layoutType: LayoutComponentTypes.ALIGNED_WIDGET_COLUMN,
});
const button: string = (layout.layout[0] as WidgetLayoutProps).widgetId;
const input: string = (layout.layout[1] as WidgetLayoutProps).widgetId;
const positions: LayoutElementPositions = {
[layout.layoutId]: {
height: 400,
left: 0,
top: 0,
width: 300,
offsetLeft: 0,
offsetTop: 0,
},
[button]: {
height: 40,
left: 10,
top: 10,
width: 120,
offsetLeft: 10,
offsetTop: 10,
},
[input]: {
height: 70,
left: 10,
top: 60,
width: 290,
offsetLeft: 10,
offsetTop: 60,
},
};
const res: AnvilHighlightInfo[] = deriveAlignedColumnHighlights(
layout,
"0",
[],
layout.layoutId,
)(positions, [
{
widgetId: "1",
type: "BUTTON_WIDGET",
responsiveBehavior: ResponsiveBehavior.Hug,
},
]);
// Top of first set of highlights should span the empty space above the first widget.
expect(res[0].dropZone.top).toEqual(
positions[button].top - HIGHLIGHT_SIZE,
);
// Bottom of first set of highlights should span half of the vertical space between this highlight and the next.
expect(res[0].dropZone.bottom).toEqual(
(positions[input].top - positions[button].top) / 2,
);
// Top of second set of highlights should span half of the vertical space between this highlight and the previous.
// In other words it should be equal to the top of the previous set.
expect(res[4].dropZone.top).toEqual(res[0].dropZone.bottom);
// Bottom of second set of highlights should span half of the vertical space between this highlight and the next.
// Since this is the last widget, it should cover half the height of the widget.
expect(res[4].dropZone.bottom).toEqual(res[7].dropZone.top);
// Bottom of final set of highlights should span the empty space below the last widget.
expect(res[8].dropZone.bottom).toEqual(
positions[layout.layoutId].height - res[8].posY,
);
});
it("should calculate highlights properly if a dragged widget is Fill widget", () => {
const layout: LayoutComponentProps = generateLayoutComponentMock({
isDropTarget: true,
layoutType: LayoutComponentTypes.ALIGNED_WIDGET_COLUMN,
});
const button: string = (layout.layout[0] as WidgetLayoutProps).widgetId;
const input: string = (layout.layout[1] as WidgetLayoutProps).widgetId;
const positions: LayoutElementPositions = {
[layout.layoutId]: {
height: 400,
left: 0,
top: 0,
width: 300,
offsetLeft: 0,
offsetTop: 0,
},
[button]: {
height: 40,
left: 10,
top: 10,
width: 120,
offsetLeft: 10,
offsetTop: 10,
},
[input]: {
height: 70,
left: 10,
top: 60,
width: 290,
offsetLeft: 10,
offsetTop: 60,
},
};
const res: AnvilHighlightInfo[] = deriveAlignedColumnHighlights(
layout,
"0",
[],
layout.layoutId,
)(positions, [
{
widgetId: "1",
type: "INPUT_WIDGET",
responsiveBehavior: ResponsiveBehavior.Fill,
},
]);
expect(res.length).toEqual(3);
// First highlight before the first widget.
expect(res[0].posY).toEqual(positions[button].top - HIGHLIGHT_SIZE);
// Second highlight before second widget.
expect(res[1].posY).toEqual(positions[input].top - HIGHLIGHT_SIZE);
// Final highlight should be placed after the last widget.
expect(res[2].posY).toEqual(
positions[input].top + positions[input].height + HIGHLIGHT_SIZE / 2,
);
});
it("1. if an existing child widget is being dragged, then it should be discounted from highlight calculation", () => {
const layout: LayoutComponentProps = generateLayoutComponentMock({
isDropTarget: true,
layoutType: LayoutComponentTypes.ALIGNED_WIDGET_COLUMN,
});
const button: string = (layout.layout[0] as WidgetLayoutProps).widgetId;
const input: string = (layout.layout[1] as WidgetLayoutProps).widgetId;
const positions: LayoutElementPositions = {
[layout.layoutId]: {
height: 400,
left: 0,
top: 0,
width: 300,
offsetLeft: 0,
offsetTop: 0,
},
[button]: {
height: 40,
left: 10,
top: 10,
width: 120,
offsetLeft: 10,
offsetTop: 10,
},
[input]: {
height: 70,
left: 10,
top: 60,
width: 290,
offsetLeft: 10,
offsetTop: 60,
},
};
/**
* Second widget (input) is being dragged over it's parent layout.
*/
const res: AnvilHighlightInfo[] = deriveAlignedColumnHighlights(
layout,
"0",
[],
layout.layoutId,
)(positions, [
{
widgetId: input,
type: "INPUT_WIDGET",
responsiveBehavior: ResponsiveBehavior.Fill,
},
]);
// Highlight for the dragged widget's position should be discounted.
expect(res.length).toEqual(2);
// First highlight before the first widget.
expect(res[0].posY).toEqual(positions[button].top - HIGHLIGHT_SIZE);
expect(res[0].rowIndex).toEqual(0);
// Final highlight should be placed after the last widget.
expect(res[1].posY).toEqual(
positions[input].top + positions[input].height + HIGHLIGHT_SIZE / 2,
);
expect(res[1].rowIndex).toEqual(1);
});
it("2. if an existing child widget is being dragged, then it should be discounted from highlight calculation", () => {
const layout: LayoutComponentProps = generateLayoutComponentMock({
isDropTarget: true,
layoutType: LayoutComponentTypes.ALIGNED_WIDGET_COLUMN,
});
const button: string = (layout.layout[0] as WidgetLayoutProps).widgetId;
const input: string = (layout.layout[1] as WidgetLayoutProps).widgetId;
const positions: LayoutElementPositions = {
[layout.layoutId]: {
height: 400,
left: 0,
top: 0,
width: 300,
offsetLeft: 0,
offsetTop: 0,
},
[button]: {
height: 40,
left: 10,
top: 10,
width: 120,
offsetLeft: 10,
offsetTop: 10,
},
[input]: {
height: 70,
left: 10,
top: 60,
width: 290,
offsetLeft: 10,
offsetTop: 60,
},
};
/**
* First widget (button) is being dragged over it's parent layout.
*/
const res: AnvilHighlightInfo[] = deriveAlignedColumnHighlights(
layout,
"0",
[],
layout.layoutId,
)(positions, [
{
widgetId: button,
type: "BUTTON_WIDGET",
responsiveBehavior: ResponsiveBehavior.Hug,
},
]);
// Highlight for the dragged widget's position should be discounted.
expect(res.length).toEqual(6);
// First highlight before the first widget.
expect(res[0].posY).toEqual(positions[input].top - HIGHLIGHT_SIZE);
expect(res[0].rowIndex).toEqual(0);
// Final highlight should be placed after the last widget.
expect(res[4].posY).toEqual(
positions[input].top + positions[input].height + HIGHLIGHT_SIZE / 2,
);
expect(res[4].rowIndex).toEqual(1);
});
it("1. should combine highlights of child layouts in the final output", () => {
/**
* Create 2 rows with two widgets in each of them.
*/
const row1: LayoutComponentProps = generateLayoutComponentMock();
const button1: string = (row1.layout[0] as WidgetLayoutProps).widgetId;
const input1: string = (row1.layout[1] as WidgetLayoutProps).widgetId;
const row2: LayoutComponentProps = generateLayoutComponentMock();
const button2: string = (row2.layout[0] as WidgetLayoutProps).widgetId;
const input2: string = (row2.layout[1] as WidgetLayoutProps).widgetId;
/**
* Create a AlignedColumn layout that will parent the two rows.
*/
const column: LayoutComponentProps = generateLayoutComponentMock(
{
layout: [row1, row2],
layoutType: LayoutComponentTypes.ALIGNED_LAYOUT_COLUMN,
},
false,
);
/**
* Create dimensions data
*/
const dimensions: LayoutElementPositions = {
[row1.layoutId]: {
height: 80,
left: 10,
top: 10,
width: 300,
offsetLeft: 10,
offsetTop: 10,
},
[button1]: {
height: 40,
left: 10,
top: 10,
width: 100,
offsetLeft: 10,
offsetTop: 10,
},
[input1]: {
height: 70,
left: 120,
top: 10,
width: 170,
offsetLeft: 120,
offsetTop: 10,
},
[row2.layoutId]: {
height: 80,
left: 10,
top: 90,
width: 300,
offsetLeft: 10,
offsetTop: 90,
},
[button2]: {
height: 40,
left: 10,
top: 10,
width: 100,
offsetLeft: 10,
offsetTop: 10,
},
[input2]: {
height: 70,
left: 120,
top: 10,
width: 170,
offsetLeft: 120,
offsetTop: 10,
},
[column.layoutId]: {
height: 200,
left: 0,
top: 0,
width: 320,
offsetLeft: 0,
offsetTop: 0,
},
};
/**
* Get highlights for the AlignedColumn layout.
*/
const res: AnvilHighlightInfo[] = deriveAlignedColumnHighlights(
column,
"0",
[],
column.layoutId,
)(dimensions, [
{
widgetId: "1",
type: "INPUT_WIDGET",
responsiveBehavior: ResponsiveBehavior.Fill,
},
]);
/**
* # of highlights:
* Row 1 - 3 (before every widget and after the last one)
* Row 2 - 3 (before every widget and after the last one)
* AlignedColumn - 3 (before every layout and after the last one)
*/
expect(res.length).toEqual(9);
// First a horizontal highlight to mark the vertical position above the first child layout.
expect(res[0].isVertical).toBeFalsy();
// Then highlights from the child layout.
expect(res[1].isVertical).toBeTruthy();
expect(res[3].isVertical).toBeTruthy();
expect(res[0].posY).toEqual(
dimensions[row1.layoutId].top - HIGHLIGHT_SIZE,
);
expect(res[0].dropZone.top).toEqual(
dimensions[row1.layoutId].top - HIGHLIGHT_SIZE,
);
expect(res[4].isVertical).toBeFalsy();
expect(res[4].posY).toEqual(
dimensions[row2.layoutId].top - HIGHLIGHT_SIZE,
);
expect(res[4].dropZone.top).toEqual(
(dimensions[row2.layoutId].top - dimensions[row1.layoutId].top) *
VERTICAL_DROP_ZONE_MULTIPLIER,
);
expect(res[4].dropZone.bottom).toEqual(res[8].dropZone.top);
});
it("2. should skip highlights of non drop target child layouts in the final output", () => {
/**
* Create 2 rows with two widgets in each of them.
*/
const row1: LayoutComponentProps = generateLayoutComponentMock();
const button1: string = (row1.layout[0] as WidgetLayoutProps).widgetId;
const input1: string = (row1.layout[1] as WidgetLayoutProps).widgetId;
const row2: LayoutComponentProps = generateLayoutComponentMock({
isDropTarget: true,
});
const button2: string = (row2.layout[0] as WidgetLayoutProps).widgetId;
const input2: string = (row2.layout[1] as WidgetLayoutProps).widgetId;
/**
* Create a AlignedColumn layout that will parent the two rows.
*/
const column: LayoutComponentProps = generateLayoutComponentMock(
{
layout: [row1, row2],
layoutType: LayoutComponentTypes.ALIGNED_LAYOUT_COLUMN,
},
false,
);
/**
* Create dimensions data
*/
const dimensions: LayoutElementPositions = {
[row1.layoutId]: {
height: 80,
left: 10,
top: 10,
width: 300,
offsetLeft: 10,
offsetTop: 10,
},
[button1]: {
height: 40,
left: 10,
top: 10,
width: 100,
offsetLeft: 10,
offsetTop: 10,
},
[input1]: {
height: 70,
left: 120,
top: 10,
width: 170,
offsetLeft: 120,
offsetTop: 10,
},
[row2.layoutId]: {
height: 80,
left: 10,
top: 90,
width: 300,
offsetLeft: 10,
offsetTop: 90,
},
[button2]: {
height: 40,
left: 10,
top: 10,
width: 100,
offsetLeft: 10,
offsetTop: 10,
},
[input2]: {
height: 70,
left: 120,
top: 10,
width: 170,
offsetLeft: 120,
offsetTop: 10,
},
[column.layoutId]: {
height: 200,
left: 0,
top: 0,
width: 320,
offsetLeft: 0,
offsetTop: 0,
},
};
/**
* Get highlights for the AlignedColumn layout.
*/
const res: AnvilHighlightInfo[] = deriveAlignedColumnHighlights(
column,
"0",
[],
column.layoutId,
)(dimensions, [
{
widgetId: "1",
type: "INPUT_WIDGET",
responsiveBehavior: ResponsiveBehavior.Fill,
},
]);
/**
* # of highlights:
* Row 1 - 3 (before every widget and after the last one)
* Row 2 - 3 (before every widget and after the last one)
* AlignedColumn - 3 (before every layout and after the last one)
*/
expect(res.length).toEqual(6);
// First a horizontal highlight to mark the vertical position above the first child layout.
expect(res[0].isVertical).toBeFalsy();
// Then highlights from the child layout.
expect(res[1].isVertical).toBeTruthy();
expect(res[3].isVertical).toBeTruthy();
expect(res[0].posY).toEqual(
dimensions[row1.layoutId].top - HIGHLIGHT_SIZE,
);
expect(res[0].dropZone.top).toEqual(
dimensions[row1.layoutId].top - HIGHLIGHT_SIZE,
);
expect(res[4].isVertical).toBeFalsy();
expect(res[4].posY).toEqual(
dimensions[row2.layoutId].top - HIGHLIGHT_SIZE,
);
expect(res[4].dropZone.top).toEqual(
(dimensions[row2.layoutId].top - dimensions[row1.layoutId].top) *
VERTICAL_DROP_ZONE_MULTIPLIER,
);
expect(res[4].dropZone.bottom).toEqual(res[5].dropZone.top);
expect(res[5].dropZone.bottom).toEqual(
dimensions[column.layoutId].height - res[5].posY,
);
});
});
});
|
214 | 0 | petrpan-code/appsmithorg/appsmith/app/client/src/layoutSystems/anvil/utils/layouts | petrpan-code/appsmithorg/appsmith/app/client/src/layoutSystems/anvil/utils/layouts/highlights/alignedRowHighlights.test.ts | import { generateAlignedRowMock } from "mocks/layoutComponents/layoutComponentMock";
import type {
AnvilHighlightInfo,
LayoutComponentProps,
WidgetLayoutProps,
} from "../../anvilTypes";
import type {
LayoutElementPosition,
LayoutElementPositions,
} from "layoutSystems/common/types";
import { deriveAlignedRowHighlights } from "./alignedRowHighlights";
import {
FlexLayerAlignment,
ResponsiveBehavior,
} from "layoutSystems/common/utils/constants";
import {
HIGHLIGHT_SIZE,
HORIZONTAL_DROP_ZONE_MULTIPLIER,
} from "../../constants";
import LayoutFactory from "layoutSystems/anvil/layoutComponents/LayoutFactory";
import AlignedWidgetRow from "layoutSystems/anvil/layoutComponents/components/AlignedWidgetRow";
import type { BaseWidgetProps } from "widgets/BaseWidgetHOC/withBaseWidgetHOC";
import { mockButtonProps } from "mocks/widgetProps/button";
import { getAlignmentLayoutId } from "../layoutUtils";
describe("AlignedRow highlights", () => {
beforeAll(() => {
LayoutFactory.initialize([AlignedWidgetRow]);
});
describe("initial highlights", () => {
it("should return three initial highlights if layout is empty", () => {
const layout: LayoutComponentProps = generateAlignedRowMock({
layout: [],
});
const { layoutId } = layout;
const startPosition: LayoutElementPosition = {
height: 40,
left: 0,
top: 0,
width: 400,
offsetLeft: 0,
offsetTop: 0,
};
const centerPosition: LayoutElementPosition = {
height: 40,
left: 404,
top: 0,
width: 400,
offsetLeft: 404,
offsetTop: 0,
};
const endPosition: LayoutElementPosition = {
height: 40,
left: 808,
top: 0,
width: 400,
offsetLeft: 808,
offsetTop: 0,
};
const dimensions: LayoutElementPositions = {
[layoutId]: {
height: 40,
left: 0,
top: 0,
width: 1208,
offsetLeft: 0,
offsetTop: 0,
},
[`${layoutId}-0`]: startPosition,
[`${layoutId}-1`]: centerPosition,
[`${layoutId}-2`]: endPosition,
};
const res: AnvilHighlightInfo[] = deriveAlignedRowHighlights(
layout,
"0",
[],
)(dimensions, [
{
widgetId: "10",
type: "BUTTON_WIDGET",
responsiveBehavior: ResponsiveBehavior.Hug,
},
]);
expect(res.length).toEqual(3);
expect(res[0].alignment).toEqual(FlexLayerAlignment.Start);
expect(res[0].posX).toEqual(startPosition.left + HIGHLIGHT_SIZE / 2);
expect(res[0].posY).toEqual(startPosition.top);
expect(res[0].height).toEqual(startPosition.height);
expect(res[0].dropZone.left).toEqual(
Math.max(res[0].posX, HIGHLIGHT_SIZE),
);
expect(res[1].alignment).toEqual(FlexLayerAlignment.Center);
expect(res[1].posX).toEqual(
centerPosition.left + (centerPosition.width - HIGHLIGHT_SIZE) / 2,
);
expect(res[1].posY).toEqual(centerPosition.top);
expect(res[1].height).toEqual(centerPosition.height);
expect(res[1].dropZone.left).toEqual(
(res[1].posX - res[0].posX) * HORIZONTAL_DROP_ZONE_MULTIPLIER,
);
expect(res[0].dropZone.right).toEqual(res[1].dropZone.left);
expect(res[2].alignment).toEqual(FlexLayerAlignment.End);
expect(res[2].posX).toEqual(
dimensions[layoutId].left + dimensions[layoutId].width - HIGHLIGHT_SIZE,
);
expect(res[2].posY).toEqual(centerPosition.top);
expect(res[2].height).toEqual(centerPosition.height);
expect(res[2].dropZone.left).toEqual(
(res[2].posX - res[1].posX) * HORIZONTAL_DROP_ZONE_MULTIPLIER,
);
expect(res[1].dropZone.right).toEqual(res[2].dropZone.left);
});
});
describe("fill child widget", () => {
it("should not render highlights for alignments", () => {
const layout: LayoutComponentProps = generateAlignedRowMock();
const { layoutId } = layout;
const button: string = (layout.layout[0] as WidgetLayoutProps).widgetId;
const input: string = (layout.layout[1] as WidgetLayoutProps).widgetId;
const layoutPosition: LayoutElementPosition = {
height: 78,
left: 0,
top: 0,
width: 1208,
offsetLeft: 0,
offsetTop: 0,
};
const dimensions: LayoutElementPositions = {
[layoutId]: layoutPosition,
[button]: {
height: 40,
left: 10,
top: 4,
width: 120,
offsetLeft: 10,
offsetTop: 4,
},
[input]: {
height: 70,
left: 140,
top: 4,
width: 1058,
offsetLeft: 140,
offsetTop: 4,
},
};
const res: AnvilHighlightInfo[] = deriveAlignedRowHighlights(
layout,
"0",
[],
)(dimensions, [
{
widgetId: "10",
type: "BUTTON_WIDGET",
responsiveBehavior: ResponsiveBehavior.Hug,
},
]);
expect(res.length).toEqual(3);
expect(res[0].alignment).toEqual(FlexLayerAlignment.Start);
expect(res[0].posX).toEqual(dimensions[button].left - HIGHLIGHT_SIZE);
expect(res[0].posY).toEqual(dimensions[button].top);
expect(res[0].height).toEqual(dimensions[input].height);
expect(res[0].dropZone.left).toEqual(
dimensions[button].left - HIGHLIGHT_SIZE,
);
expect(res[1].alignment).toEqual(FlexLayerAlignment.Start);
expect(res[1].posX).toEqual(dimensions[input].left - HIGHLIGHT_SIZE);
expect(res[1].posY).toEqual(dimensions[input].top);
expect(res[1].height).toEqual(dimensions[input].height);
expect(res[1].dropZone.left).toEqual(res[0].dropZone.right);
expect(res[1].dropZone.left).toEqual(
(res[1].posX - res[0].posX) * HORIZONTAL_DROP_ZONE_MULTIPLIER,
);
expect(res[2].alignment).toEqual(FlexLayerAlignment.Start);
expect(res[2].posX).toEqual(
dimensions[input].left + dimensions[input].width,
);
expect(res[2].posY).toEqual(dimensions[input].top);
expect(res[2].height).toEqual(dimensions[input].height);
});
});
describe("hug child widgets", () => {
it("should derive highlights in proper positions", () => {
const button1: BaseWidgetProps = mockButtonProps();
const button2: BaseWidgetProps = mockButtonProps();
// Create AlignedWidgetRow layout with two buttons at start and center alignments.
const layout: LayoutComponentProps = generateAlignedRowMock({
layout: [
{ widgetId: button1.widgetId, alignment: FlexLayerAlignment.Start },
{ widgetId: button2.widgetId, alignment: FlexLayerAlignment.Center },
],
});
const { layoutId } = layout;
const layoutPosition: LayoutElementPosition = {
height: 48,
left: 0,
top: 0,
width: 1208,
offsetLeft: 0,
offsetTop: 0,
};
const dimensions: LayoutElementPositions = {
[layoutId]: layoutPosition,
[getAlignmentLayoutId(layoutId, FlexLayerAlignment.Start)]: {
height: 48,
left: 0,
top: 0,
width: 400,
offsetLeft: 0,
offsetTop: 0,
},
[getAlignmentLayoutId(layoutId, FlexLayerAlignment.Center)]: {
height: 48,
left: 404,
top: 0,
width: 400,
offsetLeft: 404,
offsetTop: 0,
},
[getAlignmentLayoutId(layoutId, FlexLayerAlignment.End)]: {
height: 48,
left: 808,
top: 0,
width: 400,
offsetLeft: 808,
offsetTop: 0,
},
[button1.widgetId]: {
height: 40,
left: 10,
top: 4,
width: 120,
offsetLeft: 10,
offsetTop: 4,
},
[button2.widgetId]: {
height: 40,
left: 540,
top: 4,
width: 120,
offsetLeft: 540,
offsetTop: 4,
},
};
const res: AnvilHighlightInfo[] = deriveAlignedRowHighlights(
layout,
"0",
[],
)(dimensions, [
{
widgetId: "10",
type: "BUTTON_WIDGET",
responsiveBehavior: ResponsiveBehavior.Hug,
},
]);
expect(res.length).toEqual(5);
expect(res[0].alignment).toEqual(FlexLayerAlignment.Start);
expect(res[0].posX).toEqual(
dimensions[button1.widgetId].left - HIGHLIGHT_SIZE,
);
expect(res[0].posY).toEqual(dimensions[button1.widgetId].top);
expect(res[0].height).toEqual(dimensions[button1.widgetId].height);
expect(res[0].dropZone.left).toBeLessThan(
dimensions[button1.widgetId].left,
);
expect(res[1].alignment).toEqual(FlexLayerAlignment.Start);
expect(res[1].posX).toEqual(
dimensions[button1.widgetId].left + dimensions[button1.widgetId].width,
);
expect(res[1].dropZone.left).toEqual(res[0].dropZone.right);
expect(res[2].alignment).toEqual(FlexLayerAlignment.Center);
expect(res[2].posX).toEqual(
dimensions[button2.widgetId].left - HIGHLIGHT_SIZE,
);
expect(res[2].posY).toEqual(dimensions[button1.widgetId].top);
expect(res[2].height).toEqual(dimensions[button1.widgetId].height);
});
});
});
|
216 | 0 | petrpan-code/appsmithorg/appsmith/app/client/src/layoutSystems/anvil/utils/layouts | petrpan-code/appsmithorg/appsmith/app/client/src/layoutSystems/anvil/utils/layouts/highlights/columnHighlights.test.ts | import { generateLayoutComponentMock } from "mocks/layoutComponents/layoutComponentMock";
import {
LayoutComponentTypes,
type AnvilHighlightInfo,
type LayoutComponentProps,
type WidgetLayoutProps,
type DraggedWidget,
} from "../../anvilTypes";
import { HIGHLIGHT_SIZE, VERTICAL_DROP_ZONE_MULTIPLIER } from "../../constants";
import { registerLayoutComponents } from "../layoutUtils";
import {
FlexLayerAlignment,
ResponsiveBehavior,
} from "layoutSystems/common/utils/constants";
import { deriveColumnHighlights } from "./columnHighlights";
import type { LayoutElementPositions } from "layoutSystems/common/types";
import { getStartPosition } from "./highlightUtils";
describe("columnHighlights", () => {
const draggedWidgets: DraggedWidget[] = [
{
widgetId: "1",
type: "BUTTON_WIDGET",
responsiveBehavior: ResponsiveBehavior.Hug,
},
];
beforeAll(() => {
registerLayoutComponents();
});
describe("widget highlights", () => {
it("should derive highlights for a column", () => {
const layout: LayoutComponentProps = generateLayoutComponentMock({
layoutType: LayoutComponentTypes.WIDGET_COLUMN,
});
const buttonId: string = (layout.layout[0] as WidgetLayoutProps).widgetId;
const inputId: string = (layout.layout[1] as WidgetLayoutProps).widgetId;
const positions: LayoutElementPositions = {
[layout.layoutId]: {
height: 500,
left: 0,
top: 0,
width: 300,
offsetLeft: 0,
offsetTop: 0,
},
[buttonId]: {
height: 40,
left: 10,
top: 10,
width: 120,
offsetLeft: 10,
offsetTop: 10,
},
[inputId]: {
height: 70,
left: 10,
top: 60,
width: 290,
offsetLeft: 10,
offsetTop: 60,
},
};
const res: AnvilHighlightInfo[] = deriveColumnHighlights(
layout,
"0",
[],
layout.layoutId,
)(positions, draggedWidgets);
expect(res.length).toEqual(3);
// highlights should be horizontal.
expect(res[0].width).toBeGreaterThan(res[0].height);
expect(res[0].isVertical).toBeFalsy();
// Width of all horizontal highlights should be the same.
expect(res[0].width).toEqual(positions[layout.layoutId].width);
expect(res[1].width).toEqual(positions[layout.layoutId].width);
expect(res[2].width).toEqual(positions[layout.layoutId].width);
expect(res[0].height).toEqual(HIGHLIGHT_SIZE);
// highlights should be placed before every widget
expect(res[0].posY).toBeLessThan(positions[buttonId].top);
expect(res[1].posY).toBeLessThan(positions[inputId].top);
// and at the bottom of the last widget
expect(res[2].posY).toBeGreaterThan(
positions[inputId].top + positions[inputId].height,
);
});
it("should discount dragged child widgets from highlight calculation", () => {
const layout: LayoutComponentProps = generateLayoutComponentMock({
layoutType: LayoutComponentTypes.WIDGET_COLUMN,
});
const buttonId: string = (layout.layout[0] as WidgetLayoutProps).widgetId;
const inputId: string = (layout.layout[1] as WidgetLayoutProps).widgetId;
const positions: LayoutElementPositions = {
[layout.layoutId]: {
height: 500,
left: 0,
top: 0,
width: 300,
offsetLeft: 0,
offsetTop: 0,
},
[buttonId]: {
height: 40,
left: 10,
top: 10,
width: 120,
offsetLeft: 10,
offsetTop: 10,
},
[inputId]: {
height: 70,
left: 10,
top: 60,
width: 290,
offsetLeft: 10,
offsetTop: 60,
},
};
const res: AnvilHighlightInfo[] = deriveColumnHighlights(
layout,
"0",
[],
layout.layoutId,
)(positions, [
...draggedWidgets,
{
widgetId: buttonId,
type: "BUTTON_WIDGET",
responsiveBehavior: ResponsiveBehavior.Hug,
},
]);
// One highlight is discounted on account of child button widget being dragged.
expect(res.length).toEqual(2);
// First highlight should be placed before input widget
expect(res[0].posY).toBeLessThan(positions[inputId].top);
expect(res[0].rowIndex).toEqual(0);
// Second highlight should be placed after input widget
expect(res[1].posY).toBeGreaterThan(
positions[inputId].top + positions[inputId].height,
);
expect(res[1].rowIndex).toEqual(1);
});
it("should calculate drop zones properly", () => {
const layout: LayoutComponentProps = generateLayoutComponentMock({
layoutType: LayoutComponentTypes.WIDGET_COLUMN,
});
const buttonId: string = (layout.layout[0] as WidgetLayoutProps).widgetId;
const inputId: string = (layout.layout[1] as WidgetLayoutProps).widgetId;
const positions: LayoutElementPositions = {
[layout.layoutId]: {
height: 500,
left: 0,
top: 0,
width: 300,
offsetLeft: 0,
offsetTop: 0,
},
[buttonId]: {
height: 40,
left: 10,
top: 10,
width: 120,
offsetLeft: 10,
offsetTop: 10,
},
[inputId]: {
height: 70,
left: 10,
top: 60,
width: 290,
offsetLeft: 10,
offsetTop: 60,
},
};
const res: AnvilHighlightInfo[] = deriveColumnHighlights(
layout,
"0",
[],
layout.layoutId,
)(positions, draggedWidgets);
/**
* Horizontal highlights have top and bottom drop zones,
* which denote the vertical space above and below the horizontal highlight respectively.
*
* [Top]
* Highlight: ------------
* [Bottom]
*/
// Top drop zone of first highlight should span the entire space between the start of the layout and the first child.
expect(res[0].dropZone.top).toEqual(
positions[buttonId].top -
positions[layout.layoutId].top -
HIGHLIGHT_SIZE,
);
// Bottom drop zone of first highlight should be equal to the space between the top of this widget and the next.
expect(res[0].dropZone.bottom).toEqual(
(positions[inputId].top - positions[buttonId].top) *
VERTICAL_DROP_ZONE_MULTIPLIER,
);
expect(res[1].dropZone.top).toEqual(
(positions[inputId].top - positions[buttonId].top) *
VERTICAL_DROP_ZONE_MULTIPLIER,
);
expect(res[1].dropZone.bottom).toEqual(
(res[2].posY - res[1].posY) * VERTICAL_DROP_ZONE_MULTIPLIER,
);
expect(res[2].dropZone.top).toEqual(res[1].dropZone.bottom);
expect(res[2].dropZone.bottom).toEqual(
positions[layout.layoutId].height - res[2].posY,
);
});
});
describe("initial highlights", () => {
it("should return a highlight with the correct dimensions", () => {
const layout: LayoutComponentProps = generateLayoutComponentMock({
isDropTarget: true,
layoutType: LayoutComponentTypes.WIDGET_COLUMN,
layout: [],
});
const positions: LayoutElementPositions = {
[layout.layoutId]: {
height: 400,
left: 0,
top: 0,
width: 300,
offsetLeft: 0,
offsetTop: 0,
},
};
const res: AnvilHighlightInfo[] = deriveColumnHighlights(
layout,
"0",
[],
layout.layoutId,
)(positions, draggedWidgets);
expect(res[0].width).toEqual(positions[layout.layoutId].width);
expect(res[0].alignment).toEqual(FlexLayerAlignment.Start);
expect(res[0].posY).toEqual(HIGHLIGHT_SIZE / 2);
});
it("should return a highlight with the correct dimensions for a center aligned empty drop target column", () => {
const layout: LayoutComponentProps = generateLayoutComponentMock({
isDropTarget: true,
layoutType: LayoutComponentTypes.WIDGET_COLUMN,
layout: [],
layoutStyle: {
justifyContent: "center",
},
});
const positions: LayoutElementPositions = {
[layout.layoutId]: {
height: 400,
left: 0,
top: 0,
width: 300,
offsetLeft: 0,
offsetTop: 0,
},
};
const res: AnvilHighlightInfo[] = deriveColumnHighlights(
layout,
"0",
[],
layout.layoutId,
)(positions, draggedWidgets);
expect(res).toBeDefined();
expect(res[0].width).toEqual(positions[layout.layoutId].width);
expect(res[0].posY).toEqual(
getStartPosition(
FlexLayerAlignment.Center,
positions[layout.layoutId].height,
),
);
});
it("should return a highlight with the correct dimensions for a end aligned empty drop target column", () => {
const layout: LayoutComponentProps = generateLayoutComponentMock({
isDropTarget: true,
layoutType: LayoutComponentTypes.WIDGET_COLUMN,
layout: [],
layoutStyle: {
justifyContent: "end",
},
});
const positions: LayoutElementPositions = {
[layout.layoutId]: {
height: 400,
left: 0,
top: 0,
width: 300,
offsetLeft: 0,
offsetTop: 0,
},
};
const res: AnvilHighlightInfo[] = deriveColumnHighlights(
layout,
"0",
[],
layout.layoutId,
)(positions, draggedWidgets);
expect(res[0].width).toEqual(positions[layout.layoutId].width);
expect(res[0].posY).toEqual(
positions[layout.layoutId].height - HIGHLIGHT_SIZE,
);
});
});
describe("layout highlights", () => {
it("1. should combine highlights of child layouts in the final output", () => {
/**
* Create 2 rows with two widgets in each of them.
*/
const row1: LayoutComponentProps = generateLayoutComponentMock();
const button1: string = (row1.layout[0] as WidgetLayoutProps).widgetId;
const input1: string = (row1.layout[1] as WidgetLayoutProps).widgetId;
const row2: LayoutComponentProps = generateLayoutComponentMock();
const button2: string = (row2.layout[0] as WidgetLayoutProps).widgetId;
const input2: string = (row2.layout[1] as WidgetLayoutProps).widgetId;
/**
* Create a Column layout that will parent the two rows.
*/
const column: LayoutComponentProps = generateLayoutComponentMock(
{
layout: [row1, row2],
layoutType: LayoutComponentTypes.LAYOUT_COLUMN,
},
false,
);
/**
* Create dimensions data
*/
const dimensions: LayoutElementPositions = {
[row1.layoutId]: {
height: 80,
left: 10,
top: 10,
width: 300,
offsetLeft: 10,
offsetTop: 10,
},
[button1]: {
height: 40,
left: 10,
top: 10,
width: 100,
offsetLeft: 10,
offsetTop: 10,
},
[input1]: {
height: 70,
left: 120,
top: 10,
width: 170,
offsetLeft: 120,
offsetTop: 10,
},
[row2.layoutId]: {
height: 80,
left: 10,
top: 90,
width: 300,
offsetLeft: 10,
offsetTop: 90,
},
[button2]: {
height: 40,
left: 10,
top: 10,
width: 100,
offsetLeft: 10,
offsetTop: 10,
},
[input2]: {
height: 70,
left: 120,
top: 10,
width: 170,
offsetLeft: 120,
offsetTop: 10,
},
[column.layoutId]: {
height: 200,
left: 0,
top: 0,
width: 320,
offsetLeft: 0,
offsetTop: 0,
},
};
/**
* Get highlights for the column layout.
*/
const res: AnvilHighlightInfo[] = deriveColumnHighlights(
column,
"0",
[],
column.layoutId,
)(dimensions, draggedWidgets);
/**
* # of highlights:
* Row 1 - 3 (before every widget and after the last one)
* Row 2 - 3 (before every widget and after the last one)
* Column - 3 (before every layout and after the last one)
*/
expect(res.length).toEqual(9);
// First a horizontal highlight to mark the vertical position above the first child layout.
expect(res[0].isVertical).toBeFalsy();
// Then highlights from the child layout.
expect(res[1].isVertical).toBeTruthy();
expect(res[3].isVertical).toBeTruthy();
expect(res[0].posY).toEqual(
dimensions[row1.layoutId].top - HIGHLIGHT_SIZE,
);
expect(res[0].dropZone.top).toEqual(
dimensions[row1.layoutId].top - HIGHLIGHT_SIZE,
);
expect(res[4].isVertical).toBeFalsy();
expect(res[4].posY).toEqual(
dimensions[row2.layoutId].top - HIGHLIGHT_SIZE,
);
expect(res[4].dropZone.top).toEqual(
(dimensions[row2.layoutId].top - dimensions[row1.layoutId].top) *
VERTICAL_DROP_ZONE_MULTIPLIER,
);
expect(res[4].dropZone.bottom).toEqual(
(res[8].posY - res[4].posY) * VERTICAL_DROP_ZONE_MULTIPLIER,
);
});
});
});
|
221 | 0 | petrpan-code/appsmithorg/appsmith/app/client/src/layoutSystems/anvil/utils/layouts | petrpan-code/appsmithorg/appsmith/app/client/src/layoutSystems/anvil/utils/layouts/highlights/rowHighlights.test.ts | import {
FlexLayerAlignment,
ResponsiveBehavior,
} from "layoutSystems/common/utils/constants";
import {
LayoutComponentTypes,
type AnvilHighlightInfo,
type GetDimensions,
type LayoutComponentProps,
type LayoutProps,
type WidgetLayoutProps,
} from "../../anvilTypes";
import {
checkIntersection,
deriveRowHighlights,
extractMetaInformation,
getHighlightsForRow,
type RowMetaInformation,
} from "./rowHighlights";
import {
HIGHLIGHT_SIZE,
HORIZONTAL_DROP_ZONE_MULTIPLIER,
INFINITE_DROP_ZONE,
} from "../../constants";
import { generateLayoutComponentMock } from "mocks/layoutComponents/layoutComponentMock";
import type { LayoutElementPositions } from "layoutSystems/common/types";
import { getRelativeDimensions } from "./dimensionUtils";
import { registerLayoutComponents } from "../layoutUtils";
describe("rowHighlights tests", () => {
beforeAll(() => {
registerLayoutComponents();
});
const baseProps: LayoutProps = {
layoutId: "layoutID",
layout: [],
layoutType: LayoutComponentTypes.WIDGET_ROW,
};
describe("checkIntersection", () => {
it("returns true if the lines intersect the same space", () => {
// Lines starting at the same point.
expect(checkIntersection([0, 1], [0, 2])).toBeTruthy();
expect(checkIntersection([0, 2], [0, 1])).toBeTruthy();
// A larger line that can encompass the counterpart.
expect(checkIntersection([0, 4], [1, 2])).toBeTruthy();
expect(checkIntersection([1, 2], [0, 4])).toBeTruthy();
// Lines starting at different points and of different heights.
expect(checkIntersection([0, 3], [1, 5])).toBeTruthy();
expect(checkIntersection([1, 5], [0, 3])).toBeTruthy();
});
it("returns false if the lines do not intersect the same space", () => {
expect(checkIntersection([0, 1], [2, 3])).toBeFalsy();
expect(checkIntersection([2, 3], [0, 1])).toBeFalsy();
expect(checkIntersection([0, 1], [1, 2])).toBeFalsy();
expect(checkIntersection([1, 2], [0, 1])).toBeFalsy();
});
});
describe("extractMetaInformation", () => {
it("should find the tallest widget in a row", () => {
const data: WidgetLayoutProps[] = [
{ widgetId: "1", alignment: FlexLayerAlignment.Start },
{ widgetId: "2", alignment: FlexLayerAlignment.Start },
{ widgetId: "3", alignment: FlexLayerAlignment.Start },
];
const dimensions: LayoutElementPositions = {
"0": {
top: 0,
left: 0,
width: 200,
height: 200,
offsetLeft: 0,
offsetTop: 0,
},
"1": {
top: 0,
left: 4,
width: 100,
height: 40,
offsetLeft: 4,
offsetTop: 0,
},
"2": {
top: 0,
left: 110,
width: 100,
height: 60,
offsetLeft: 110,
offsetTop: 0,
},
"3": {
top: 30,
left: 220,
width: 100,
height: 30,
offsetLeft: 220,
offsetTop: 30,
},
};
const getDimensions: GetDimensions = getRelativeDimensions(dimensions);
const res: RowMetaInformation = extractMetaInformation(
data,
getDimensions,
);
// There should be 1 row.
expect(res.metaData.length).toEqual(1);
// All three widgets should be in the same row.
expect(res.metaData[0].length).toEqual(data.length);
// There should be one tallest widget per row.
expect(res.tallestWidgets.length).toEqual(res.metaData.length);
// The tallest widget should be the second widget.
expect(res.tallestWidgets[0].widgetId).toEqual(data[1].widgetId);
});
it("should identify wrapping and determine information for each wrapped row", () => {
const data: WidgetLayoutProps[] = [
{ widgetId: "1", alignment: FlexLayerAlignment.Start },
{ widgetId: "2", alignment: FlexLayerAlignment.Start },
{ widgetId: "3", alignment: FlexLayerAlignment.Start },
{ widgetId: "4", alignment: FlexLayerAlignment.Start },
];
const dimensions: LayoutElementPositions = {
"0": {
top: 0,
left: 0,
width: 300,
height: 200,
offsetLeft: 0,
offsetTop: 0,
},
"1": {
top: 0,
left: 4,
width: 100,
height: 40,
offsetLeft: 4,
offsetTop: 0,
},
"2": {
top: 0,
left: 110,
width: 100,
height: 60,
offsetLeft: 110,
offsetTop: 0,
},
"3": {
top: 70,
left: 10,
width: 100,
height: 30,
offsetLeft: 10,
offsetTop: 70,
},
"4": {
top: 70,
left: 110,
width: 100,
height: 80,
offsetLeft: 110,
offsetTop: 70,
},
};
const getDimensions: GetDimensions = getRelativeDimensions(dimensions);
const res: RowMetaInformation = extractMetaInformation(
data,
getDimensions,
);
// There should be 2 rows.
expect(res.metaData.length).toEqual(2);
// There should two widgets in each row.
expect(res.metaData[0].length).toEqual(2);
expect(res.metaData[0].length).toEqual(2);
// There should be one tallest widget per row.
expect(res.tallestWidgets.length).toEqual(res.metaData.length);
// The tallest widget should be the second widget.
expect(res.tallestWidgets[0].widgetId).toEqual(data[1].widgetId);
expect(res.tallestWidgets[1].widgetId).toEqual(data[3].widgetId);
});
it("should identify reverse wrapping", () => {
const data: WidgetLayoutProps[] = [
{ widgetId: "1", alignment: FlexLayerAlignment.Start },
{ widgetId: "2", alignment: FlexLayerAlignment.Start },
{ widgetId: "3", alignment: FlexLayerAlignment.Start },
{ widgetId: "4", alignment: FlexLayerAlignment.Start },
];
const dimensions: LayoutElementPositions = {
"0": {
top: 0,
left: 0,
width: 200,
height: 200,
offsetLeft: 0,
offsetTop: 0,
},
"1": {
top: 70,
left: 4,
width: 100,
height: 40,
offsetLeft: 4,
offsetTop: 70,
},
"2": {
top: 70,
left: 110,
width: 100,
height: 60,
offsetLeft: 110,
offsetTop: 70,
},
"3": {
top: 0,
left: 10,
width: 100,
height: 30,
offsetLeft: 10,
offsetTop: 0,
},
"4": {
top: 0,
left: 110,
width: 100,
height: 80,
offsetLeft: 110,
offsetTop: 0,
},
};
const getDimensions: GetDimensions = getRelativeDimensions(dimensions);
const res: RowMetaInformation = extractMetaInformation(
data,
getDimensions,
);
// There should be 2 rows.
expect(res.metaData.length).toEqual(2);
// There should two widgets in each row.
expect(res.metaData[0].length).toEqual(2);
expect(res.metaData[0].length).toEqual(2);
// There should be one tallest widget per row.
expect(res.tallestWidgets.length).toEqual(res.metaData.length);
// The tallest widget should be the second widget.
expect(res.tallestWidgets[0].widgetId).toEqual(data[1].widgetId);
expect(res.tallestWidgets[1].widgetId).toEqual(data[3].widgetId);
});
});
describe("getHighlightsForRow", () => {
const baseHighlight: AnvilHighlightInfo = {
alignment: FlexLayerAlignment.Start,
canvasId: "",
dropZone: {},
height: 0,
isVertical: true,
layoutOrder: ["1"],
posX: 0,
posY: 0,
rowIndex: 0,
width: HIGHLIGHT_SIZE,
};
it("should derive highlights for a row", () => {
const data: WidgetLayoutProps[] = [
{ widgetId: "1", alignment: FlexLayerAlignment.Start },
{ widgetId: "2", alignment: FlexLayerAlignment.Start },
{ widgetId: "3", alignment: FlexLayerAlignment.Start },
];
const dimensions: LayoutElementPositions = {
layoutID: {
top: 0,
left: 0,
width: 340,
height: 100,
offsetLeft: 0,
offsetTop: 0,
},
"1": {
top: 0,
left: 4,
width: 100,
height: 40,
offsetLeft: 4,
offsetTop: 0,
},
"2": {
top: 0,
left: 110,
width: 100,
height: 60,
offsetLeft: 110,
offsetTop: 0,
},
"3": {
top: 30,
left: 220,
width: 100,
height: 30,
offsetLeft: 220,
offsetTop: 30,
},
};
const getDimensions: GetDimensions = getRelativeDimensions(dimensions);
const res: RowMetaInformation = extractMetaInformation(
data,
getDimensions,
);
const highlights = getHighlightsForRow(
res.metaData[0],
res.tallestWidgets[0],
{ ...baseProps, layout: data },
baseHighlight,
[],
getDimensions,
);
expect(highlights.length).toEqual(data.length + 1);
// Height of all highlights in the row should be equal to the tallest widget.
expect(highlights[0].height).toEqual(
dimensions[res.tallestWidgets[0].widgetId].height,
);
expect(highlights[1].height).toEqual(
dimensions[res.tallestWidgets[0].widgetId].height,
);
expect(highlights[0].dropZone.left).toEqual(dimensions["1"].left);
expect(highlights[highlights.length - 1].dropZone.right).toEqual(
INFINITE_DROP_ZONE,
);
// Drop zone on either side of the highlight should extend up to 35% of the gap between itself and it's neighbor in that direction.
expect(highlights[1].dropZone.left).toEqual(
(dimensions[res.metaData[0][1].widgetId].left -
dimensions[res.metaData[0][0].widgetId].left) *
HORIZONTAL_DROP_ZONE_MULTIPLIER,
);
});
});
describe("deriveRowHighlights", () => {
it("should derive highlights for a row", () => {
const data: WidgetLayoutProps[] = [
{ widgetId: "1", alignment: FlexLayerAlignment.Start },
{ widgetId: "2", alignment: FlexLayerAlignment.Start },
{ widgetId: "3", alignment: FlexLayerAlignment.Start },
];
const dimensions: LayoutElementPositions = {
layoutID: {
top: 0,
left: 0,
width: 340,
height: 100,
offsetLeft: 0,
offsetTop: 0,
},
"1": {
top: 0,
left: 4,
width: 100,
height: 40,
offsetLeft: 4,
offsetTop: 0,
},
"2": {
top: 0,
left: 110,
width: 100,
height: 60,
offsetLeft: 110,
offsetTop: 0,
},
"3": {
top: 30,
left: 220,
width: 100,
height: 30,
offsetLeft: 220,
offsetTop: 30,
},
};
const getDimensions: GetDimensions = getRelativeDimensions(dimensions);
const res: RowMetaInformation = extractMetaInformation(
data,
getDimensions,
);
const highlights = deriveRowHighlights(
{ ...baseProps, layout: data },
"0",
[],
"layoutID",
)(dimensions, [
{
widgetId: "10",
type: "BUTTON_WIDGET",
responsiveBehavior: ResponsiveBehavior.Hug,
},
]);
expect(highlights.length).toEqual(data.length + 1);
// Height of all highlights in the row should be equal to the tallest widget.
expect(highlights[0].height).toEqual(
dimensions[res.tallestWidgets[0].widgetId].height,
);
expect(highlights[1].height).toEqual(
dimensions[res.tallestWidgets[0].widgetId].height,
);
// Drop zone at the end should be maximum
expect(highlights[0].dropZone.left).toEqual(dimensions["1"].left);
expect(highlights[highlights.length - 1].dropZone.right).toEqual(
INFINITE_DROP_ZONE,
);
// Drop zone on either side of the highlight should extend up to 35% of the gap between itself and it's neighbor in that direction.
expect(highlights[1].dropZone.left).toEqual(
(dimensions[res.metaData[0][1].widgetId].left -
dimensions[res.metaData[0][0].widgetId].left) *
HORIZONTAL_DROP_ZONE_MULTIPLIER,
);
});
it("should derive highlights for a wrapped row", () => {
const data: WidgetLayoutProps[] = [
{ widgetId: "1", alignment: FlexLayerAlignment.Start },
{ widgetId: "2", alignment: FlexLayerAlignment.Start },
{ widgetId: "3", alignment: FlexLayerAlignment.Start },
];
const dimensions: LayoutElementPositions = {
layoutID: {
top: 0,
left: 0,
width: 230,
height: 100,
offsetLeft: 0,
offsetTop: 0,
},
"1": {
top: 0,
left: 4,
width: 100,
height: 40,
offsetLeft: 4,
offsetTop: 0,
},
"2": {
top: 0,
left: 110,
width: 100,
height: 60,
offsetLeft: 110,
offsetTop: 0,
},
"3": {
top: 70,
left: 10,
width: 100,
height: 30,
offsetLeft: 10,
offsetTop: 70,
},
};
const getDimensions: GetDimensions = getRelativeDimensions(dimensions);
const res: RowMetaInformation = extractMetaInformation(
data,
getDimensions,
);
const highlights = deriveRowHighlights(
{ ...baseProps, layout: data },
"0",
[],
"layoutID",
)(dimensions, [
{
widgetId: "10",
type: "BUTTON_WIDGET",
responsiveBehavior: ResponsiveBehavior.Hug,
},
]);
/**
* As the layout is wrapped into two rows.
* There should be two extra highlights to mark the right most drop position in each row.
*/
expect(highlights.length).toEqual(data.length + 2);
// Height of all highlights in the row should be equal to the tallest widget.
expect(highlights[0].height).toEqual(dimensions["2"].height);
expect(highlights[4].height).toEqual(dimensions["3"].height);
// Drop zone at the end should be maximum
expect(highlights[0].dropZone.left).toEqual(dimensions["1"].left);
expect(highlights[highlights.length - 1].dropZone.right).toEqual(
INFINITE_DROP_ZONE,
);
// Drop zone on either side of the highlight should extend up to 35% of the gap between itself and it's neighbor in that direction.
expect(highlights[1].dropZone.left).toEqual(
(dimensions[res.metaData[0][1].widgetId].left -
dimensions[res.metaData[0][0].widgetId].left) *
HORIZONTAL_DROP_ZONE_MULTIPLIER,
);
// Starting rowIndex of second row should be the same as ending rowIndex of the first row as they point to the same space.
expect(highlights[2].rowIndex).toEqual(highlights[3].rowIndex);
});
it("should derive highlights for a reverse wrapped row", () => {
const data: WidgetLayoutProps[] = [
{ widgetId: "1", alignment: FlexLayerAlignment.Start },
{ widgetId: "2", alignment: FlexLayerAlignment.Start },
{ widgetId: "3", alignment: FlexLayerAlignment.Start },
];
const dimensions: LayoutElementPositions = {
layoutID: {
top: 0,
left: 0,
width: 230,
height: 100,
offsetLeft: 0,
offsetTop: 0,
},
"1": {
top: 40,
left: 4,
width: 100,
height: 40,
offsetLeft: 4,
offsetTop: 40,
},
"2": {
top: 40,
left: 110,
width: 100,
height: 60,
offsetLeft: 110,
offsetTop: 40,
},
"3": {
top: 0,
left: 10,
width: 100,
height: 30,
offsetLeft: 10,
offsetTop: 0,
},
};
const getDimensions: GetDimensions = getRelativeDimensions(dimensions);
const res: RowMetaInformation = extractMetaInformation(
data,
getDimensions,
);
const highlights = deriveRowHighlights(
{ ...baseProps, layout: data },
"0",
[],
"layoutID",
)(dimensions, [
{
widgetId: "10",
type: "BUTTON_WIDGET",
responsiveBehavior: ResponsiveBehavior.Hug,
},
]);
/**
* As the layout is wrapped into two rows.
* There should be two extra highlights to mark the right most drop position in each row.
*/
expect(highlights.length).toEqual(data.length + 2);
// Height of all highlights in the row should be equal to the tallest widget.
expect(highlights[0].height).toEqual(dimensions["2"].height);
expect(highlights[4].height).toEqual(dimensions["3"].height);
// Drop zone at the end should be maximum
expect(highlights[0].dropZone.left).toEqual(dimensions["1"].left);
expect(highlights[highlights.length - 1].dropZone.right).toEqual(
INFINITE_DROP_ZONE,
);
// Drop zone on either side of the highlight should extend up to 35% of the gap between itself and it's neighbor in that direction.
expect(highlights[1].dropZone.left).toEqual(
(dimensions[res.metaData[0][1].widgetId].left -
dimensions[res.metaData[0][0].widgetId].left) *
HORIZONTAL_DROP_ZONE_MULTIPLIER,
);
// Starting rowIndex of second row should be the same as ending rowIndex of the first row as they point to the same space.
expect(highlights[2].rowIndex).toEqual(highlights[3].rowIndex);
// Reverse wrapping
expect(highlights[4].posY).toBeLessThan(highlights[0].posY);
});
});
describe("initial highlights", () => {
it("should derive highlights for empty drop target layouts", () => {
const layout: LayoutComponentProps = generateLayoutComponentMock({
isDropTarget: true,
layout: [],
});
const positions: LayoutElementPositions = {
[layout.layoutId]: {
height: 100,
left: 10,
top: 10,
width: 500,
offsetLeft: 0,
offsetTop: 0,
},
};
const res: AnvilHighlightInfo[] = deriveRowHighlights(
layout,
"0",
[],
layout.layoutId,
)(positions, [
{
widgetId: "1",
type: "BUTTON_WIDGET",
responsiveBehavior: ResponsiveBehavior.Hug,
},
]);
expect(res[0].posY).toEqual(0);
expect(res[0].alignment).toEqual(FlexLayerAlignment.Start);
expect(res[0].posX).toEqual(HIGHLIGHT_SIZE / 2);
expect(res[0].height).toEqual(positions[layout.layoutId].height);
expect(res[0].width).toEqual(HIGHLIGHT_SIZE);
expect(res[0].dropZone?.right).toEqual(
positions[layout.layoutId].width - HIGHLIGHT_SIZE / 2,
);
});
it("should derive highlights for empty center aligned, drop target layouts", () => {
const layout: LayoutComponentProps = generateLayoutComponentMock({
isDropTarget: true,
layout: [],
layoutStyle: {
justifyContent: "center",
},
});
const positions: LayoutElementPositions = {
[layout.layoutId]: {
height: 100,
left: 10,
top: 10,
width: 500,
offsetLeft: 0,
offsetTop: 0,
},
};
const res: AnvilHighlightInfo[] = deriveRowHighlights(
layout,
"0",
[],
layout.layoutId,
)(positions, [
{
widgetId: "1",
type: "BUTTON_WIDGET",
responsiveBehavior: ResponsiveBehavior.Hug,
},
]);
const posX: number =
(positions[layout.layoutId].width - HIGHLIGHT_SIZE) / 2;
expect(res[0].posY).toEqual(0);
expect(res[0].alignment).toEqual(FlexLayerAlignment.Center);
expect(res[0].posX).toEqual(posX);
expect(res[0].height).toEqual(positions[layout.layoutId].height);
expect(res[0].width).toEqual(HIGHLIGHT_SIZE);
expect(res[0].dropZone?.right).toEqual(
positions[layout.layoutId].width - posX,
);
});
it("should derive highlights for empty end aligned, drop target layouts", () => {
const layout: LayoutComponentProps = generateLayoutComponentMock({
isDropTarget: true,
layout: [],
layoutStyle: {
justifyContent: "end",
},
});
const positions: LayoutElementPositions = {
[layout.layoutId]: {
height: 100,
left: 10,
top: 10,
width: 500,
offsetLeft: 0,
offsetTop: 0,
},
};
const res: AnvilHighlightInfo[] = deriveRowHighlights(
layout,
"0",
[],
layout.layoutId,
)(positions, [
{
widgetId: "1",
type: "BUTTON_WIDGET",
responsiveBehavior: ResponsiveBehavior.Hug,
},
]);
const posX: number = positions[layout.layoutId].width - HIGHLIGHT_SIZE;
expect(res).toBeDefined();
expect(res[0].posY).toEqual(0);
expect(res[0].alignment).toEqual(FlexLayerAlignment.End);
expect(res[0].posX).toEqual(posX);
expect(res[0].height).toEqual(positions[layout.layoutId].height);
expect(res[0].width).toEqual(HIGHLIGHT_SIZE);
expect(res[0].dropZone?.right).toEqual(INFINITE_DROP_ZONE);
expect(res[0].dropZone?.left).toEqual(posX);
});
});
describe("getHighlightsForLayoutRow", () => {
it("should derive and collate highlights for child layouts", () => {
/**
* Create a drop target (DT) layout with two child widgets.
*
* Row (R1)
* Button (B1)
* Input (I1)
*/
const layoutOne: LayoutComponentProps = generateLayoutComponentMock({
isDropTarget: false,
});
const button1: string = (layoutOne.layout[0] as WidgetLayoutProps)
.widgetId;
const input1: string = (layoutOne.layout[1] as WidgetLayoutProps)
.widgetId;
/**
* Create another drop target (DT) layout with two child widgets.
*
* Row (R2)
* Button (B2)
* Input (I2)
*/
const layoutTwo: LayoutComponentProps = generateLayoutComponentMock({
isDropTarget: false,
});
const button2: string = (layoutTwo.layout[0] as WidgetLayoutProps)
.widgetId;
const input2: string = (layoutTwo.layout[1] as WidgetLayoutProps)
.widgetId;
/**
* Create a parent layout with two child layouts.
*
* Row (R3) (not Drop Target)
* R1
* R2
*/
const layout: LayoutComponentProps = generateLayoutComponentMock(
{
isDropTarget: true,
layout: [layoutOne, layoutTwo],
},
false,
);
/**
* Create a map of widget positions.
*/
const positions: LayoutElementPositions = {
[layoutOne.layoutId]: {
height: 100,
left: 10,
top: 10,
width: 500,
offsetLeft: 10,
offsetTop: 10,
},
[button1]: {
height: 40,
left: 10,
top: 10,
width: 100,
offsetLeft: 10,
offsetTop: 10,
},
[input1]: {
height: 100,
left: 60,
top: 10,
width: 430,
offsetLeft: 60,
offsetTop: 10,
},
[layoutTwo.layoutId]: {
height: 100,
left: 510,
top: 10,
width: 500,
offsetLeft: 510,
offsetTop: 10,
},
[button2]: {
height: 40,
left: 10,
top: 10,
width: 100,
offsetLeft: 10,
offsetTop: 10,
},
[input2]: {
height: 100,
left: 60,
top: 10,
width: 430,
offsetLeft: 60,
offsetTop: 10,
},
[layout.layoutId]: {
height: 100,
left: 0,
top: 0,
width: 1020,
offsetLeft: 0,
offsetTop: 0,
},
};
const res: AnvilHighlightInfo[] = deriveRowHighlights(
layout,
"0",
[],
layout.layoutId,
)(positions, [
{
widgetId: "1",
type: "BUTTON_WIDGET",
responsiveBehavior: ResponsiveBehavior.Hug,
},
]);
/**
* Algorithm with calculate highlights for each child Row layout and combine them together.
* Each row has 2 widgets => 3 highlights each.
*/
expect(res).toBeDefined();
expect(res.length).toBe(9);
expect(res[1].layoutOrder[0]).toEqual(layoutOne.layoutId);
expect(res[5].layoutOrder[0]).toEqual(layoutTwo.layoutId);
});
it("should discount dragged child widgets in highlights calculation", () => {
/**
* Create a drop target (DT) layout with two child widgets.
*
* Row (R1)
* Button (B1)
* Input (I1)
*/
const layout: LayoutComponentProps = generateLayoutComponentMock({
isDropTarget: true,
});
const button1: string = (layout.layout[0] as WidgetLayoutProps).widgetId;
const input1: string = (layout.layout[1] as WidgetLayoutProps).widgetId;
/**
* Create a map of widget positions.
*/
const positions: LayoutElementPositions = {
[layout.layoutId]: {
height: 100,
left: 0,
top: 10,
width: 500,
offsetLeft: 0,
offsetTop: 10,
},
[button1]: {
height: 40,
left: 10,
top: 10,
width: 100,
offsetLeft: 10,
offsetTop: 10,
},
[input1]: {
height: 100,
left: 120,
top: 10,
width: 370,
offsetLeft: 120,
offsetTop: 10,
},
};
/**
* Calculate highlights when the first child widget is being dragged.
*/
const res: AnvilHighlightInfo[] = deriveRowHighlights(
layout,
"0",
[],
layout.layoutId,
)(positions, [
{
widgetId: button1,
type: "BUTTON_WIDGET",
responsiveBehavior: ResponsiveBehavior.Hug,
},
]);
// highlights for the dragged widget should be discounted.
expect(res.length).toEqual(2);
// First highlight should be placed before input widget
expect(res[0].posX).toBeLessThan(positions[input1].left);
expect(res[0].posX).toBeGreaterThan(
positions[button1].left + positions[button1].width,
);
// Second highlight should be placed after input widget
expect(res[1].posX).toEqual(
positions[input1].left + positions[input1].width,
);
});
});
});
|
223 | 0 | petrpan-code/appsmithorg/appsmith/app/client/src/layoutSystems/anvil/utils/layouts | petrpan-code/appsmithorg/appsmith/app/client/src/layoutSystems/anvil/utils/layouts/update/additionUtils.test.ts | import { generateLayoutComponentMock } from "mocks/layoutComponents/layoutComponentMock";
import {
addWidgetsToTemplate,
getAffectedLayout,
prepareWidgetsForAddition,
updateAffectedLayout,
} from "./additionUtils";
import { mockAnvilHighlightInfo } from "mocks/mockHighlightInfo";
import { FlexLayerAlignment } from "layoutSystems/common/utils/constants";
import type {
AnvilHighlightInfo,
LayoutComponentProps,
LayoutProps,
WidgetLayoutProps,
} from "../../anvilTypes";
import { extractWidgetIdsFromLayoutProps } from "../layoutUtils";
describe("Layouts - additionUtils tests", () => {
describe("getAffectedLayout", () => {
it("should extract correct layout json from the parent layout", () => {
const layout: LayoutComponentProps = generateLayoutComponentMock(
{},
false,
);
const childLayoutOne: LayoutProps = layout.layout[0] as LayoutProps;
expect(
getAffectedLayout([layout], [layout.layoutId, childLayoutOne.layoutId]),
).toEqual(childLayoutOne);
});
it("should return undefined if order is empty", () => {
const layout: LayoutComponentProps = generateLayoutComponentMock(
{},
false,
);
expect(getAffectedLayout([layout], [])).toBeUndefined();
});
});
describe("updateAffectedLayout", () => {
it("should update the layout json in the correct place", () => {
const layout: LayoutComponentProps = generateLayoutComponentMock(
{},
false,
);
const childLayoutOne: LayoutProps = layout.layout[0] as LayoutProps;
const updatedLayout: LayoutProps = {
...childLayoutOne,
layout: [],
};
const res: LayoutProps[] = updateAffectedLayout([layout], updatedLayout, [
layout.layoutId,
updatedLayout.layoutId,
]);
expect((res[0].layout[0] as LayoutProps).layout.length).toEqual(0);
});
it("should update the layout json in the correct place in a deeply nested layout", () => {
/**
* Create Parent layout
* Row
* Row
* Row
*/
const layoutOne: LayoutComponentProps = generateLayoutComponentMock(
{},
false,
);
// Create another nest layout
const layoutTwo: LayoutComponentProps = generateLayoutComponentMock(
{},
false,
);
const childLayoutOne: LayoutProps = layoutTwo.layout[0] as LayoutProps;
// Update first child layout of layoutTwo to have empty layout property
const updatedChildLayoutOne: LayoutProps = {
...childLayoutOne,
layout: [],
};
// Add layoutTwo to parentLayout (layoutOne)
const updatedLayout: LayoutProps = {
...layoutOne,
layout: [...(layoutOne.layout as LayoutProps[]), layoutTwo],
};
/**
* Final structure:
* Row (layoutOne)
* Row
* Row
* Row (layoutTwo)
* Row (childLayoutOne)
* Row
*/
const res: LayoutProps[] = updateAffectedLayout(
[updatedLayout],
updatedChildLayoutOne,
[layoutOne.layoutId, layoutTwo.layoutId, childLayoutOne.layoutId],
);
expect(
((res[0].layout[2] as LayoutProps).layout[0] as LayoutProps).layout
.length,
).toEqual(0);
});
});
describe("addWidgetsToTemplate", () => {
it("should generate a layoutId for the template", () => {
const template: LayoutComponentProps = generateLayoutComponentMock({
layoutId: "",
});
expect(template.layoutId.length).toEqual(0);
const highlight: AnvilHighlightInfo = mockAnvilHighlightInfo();
const res: LayoutProps = addWidgetsToTemplate(template, highlight, []);
expect(res.layoutId.length).toBeGreaterThan(0);
});
it("should add widgets to the layout json", () => {
const template: LayoutComponentProps = generateLayoutComponentMock();
const highlight: AnvilHighlightInfo = mockAnvilHighlightInfo();
const res: LayoutProps = addWidgetsToTemplate(
{ ...template, layout: [] }, // Empty the layout prop of the mock template.
highlight,
[{ widgetId: "1", alignment: FlexLayerAlignment.Start }],
);
expect(res.layout.length).toEqual(1);
expect((res.layout[0] as WidgetLayoutProps).widgetId).toEqual("1");
});
it("should add widgets to a nested child layout", () => {
/**
* Row
* Row (insertChild)
* Row (insertChild)
*/
const template: LayoutComponentProps = generateLayoutComponentMock(
{},
false,
);
// Remove insertChild from first child layout.
const updatedTemplate: LayoutProps = {
...template,
layout: [
{
...(template.layout[0] as LayoutProps),
insertChild: false,
},
{
...(template.layout[1] as LayoutProps),
insertChild: true,
layout: [],
},
],
};
const highlight: AnvilHighlightInfo = mockAnvilHighlightInfo({
alignment: FlexLayerAlignment.End,
});
const res: LayoutProps = addWidgetsToTemplate(
updatedTemplate, // Empty the layout prop of the mock template.
highlight,
[{ widgetId: "1", alignment: FlexLayerAlignment.End }],
);
/**
* Row
* Row
* Row
* "1"
*/
expect(
((res.layout[1] as LayoutProps).layout as WidgetLayoutProps[]).length,
).toEqual(1);
expect(
((res.layout[1] as LayoutProps).layout as WidgetLayoutProps[])
.map((each: WidgetLayoutProps) => each.widgetId)
.includes("1"),
).toBeTruthy();
});
});
describe("prepareWidgetsForAddition", () => {
it("should return empty array if widgets are not provided", () => {
const layout: LayoutComponentProps = generateLayoutComponentMock();
const res: WidgetLayoutProps[] | LayoutProps[] =
prepareWidgetsForAddition(
{} as any,
layout,
mockAnvilHighlightInfo(),
[],
);
expect(res.length).toEqual(0);
});
it("should return the list of widgets if Component doesn't have a childTemplate", () => {
const layout: LayoutComponentProps = generateLayoutComponentMock();
const res: WidgetLayoutProps[] | LayoutProps[] =
prepareWidgetsForAddition(
{ getChildTemplate: () => null } as any,
layout,
mockAnvilHighlightInfo(),
[{ widgetId: "1", alignment: FlexLayerAlignment.Start }],
);
expect(res.length).toEqual(1);
});
it("should return updated childTemplate if present", () => {
const layoutProps: LayoutComponentProps = generateLayoutComponentMock();
const res: WidgetLayoutProps[] | LayoutProps[] =
prepareWidgetsForAddition(
{ getChildTemplate: () => ({ ...layoutProps, layout: [] }) } as any,
layoutProps,
mockAnvilHighlightInfo(),
[{ widgetId: "1", alignment: FlexLayerAlignment.Start }],
);
expect((res[0] as LayoutProps).layoutId.length).toBeGreaterThan(0);
expect(
extractWidgetIdsFromLayoutProps(res[0] as LayoutProps).includes("1"),
).toBeTruthy();
});
});
});
|
225 | 0 | petrpan-code/appsmithorg/appsmith/app/client/src/layoutSystems/anvil/utils/layouts | petrpan-code/appsmithorg/appsmith/app/client/src/layoutSystems/anvil/utils/layouts/update/deletionUtils.test.ts | import {
generateAlignedRowMock,
generateLayoutComponentMock,
} from "mocks/layoutComponents/layoutComponentMock";
import type {
LayoutComponentProps,
LayoutProps,
WidgetLayoutProps,
} from "../../anvilTypes";
import {
extractWidgetIdsFromLayoutProps,
registerLayoutComponents,
} from "../layoutUtils";
import {
deleteWidgetFromLayout,
deleteWidgetFromPreset,
} from "./deletionUtils";
import { FlexLayerAlignment } from "layoutSystems/common/utils/constants";
describe("Layouts - deletionUtils tests", () => {
beforeAll(() => {
registerLayoutComponents();
});
describe("deleteWidgetFromLayout", () => {
it("should return layoutProps as is, if widgetId is falsy", () => {
const layout: LayoutComponentProps = generateLayoutComponentMock();
expect(deleteWidgetFromLayout(layout, "")).toEqual(layout);
});
it("should remove widget from the layout", () => {
const layout: LayoutComponentProps = generateLayoutComponentMock();
const originalLength: number = layout.layout.length;
const widgetId: string = (layout.layout[0] as WidgetLayoutProps).widgetId;
const res: LayoutProps | undefined = deleteWidgetFromLayout(
layout as LayoutProps,
widgetId,
);
if (!res) return;
expect(res.layout.length).toEqual(originalLength - 1);
expect(
extractWidgetIdsFromLayoutProps(res).includes(widgetId),
).toBeFalsy();
});
it("should return undefined if layout is temporary and empty after deletion", () => {
const layout: LayoutComponentProps = generateLayoutComponentMock({
isPermanent: false,
});
// layout has two widgets
const originalLength: number = layout.layout.length;
let res: LayoutProps | undefined = deleteWidgetFromLayout(
layout,
(layout.layout[0] as WidgetLayoutProps).widgetId,
);
if (!res) return;
expect(res.layout.length).toEqual(originalLength - 1);
expect(
extractWidgetIdsFromLayoutProps(res).includes(
(layout.layout[0] as WidgetLayoutProps).widgetId,
),
).toBeFalsy();
// Delete the other widget
res = deleteWidgetFromLayout(
res,
(res.layout[0] as WidgetLayoutProps).widgetId,
);
expect(res).toBeUndefined();
});
it("should return empty layout on deleting last widget, if the layout is permanent", () => {
const layout: LayoutComponentProps = generateLayoutComponentMock({
isPermanent: true,
});
// layout has two widgets
const originalLength: number = layout.layout.length;
let res: LayoutProps | undefined = deleteWidgetFromLayout(
layout,
(layout.layout[0] as WidgetLayoutProps).widgetId,
);
if (!res) return;
expect(res.layout.length).toEqual(originalLength - 1);
expect(
extractWidgetIdsFromLayoutProps(res).includes(
(layout.layout[0] as WidgetLayoutProps).widgetId,
),
).toBeFalsy();
// Delete the other widget
res = deleteWidgetFromLayout(
res,
(res.layout[0] as WidgetLayoutProps).widgetId,
);
if (!res) return;
expect(res.layout.length).toEqual(0);
});
it("should return undefined if AlignedRow is temporary and empty after deletion", () => {
const layout: LayoutComponentProps = generateAlignedRowMock({
isPermanent: false,
});
// start alignment has two widgets
const originalStartLength: number = (
layout.layout as WidgetLayoutProps[]
).filter(
(each: WidgetLayoutProps) =>
each.alignment === FlexLayerAlignment.Start,
).length;
const widgetId: string = (layout.layout[0] as WidgetLayoutProps).widgetId;
let res: LayoutProps | undefined = deleteWidgetFromLayout(
layout,
widgetId,
);
if (!res) return;
expect((res.layout as WidgetLayoutProps[]).length).toEqual(
originalStartLength - 1,
);
expect(
extractWidgetIdsFromLayoutProps(res).includes(widgetId),
).toBeFalsy();
// Delete the other widget
res = deleteWidgetFromLayout(
res,
(res.layout[0] as WidgetLayoutProps).widgetId,
);
expect(res).toBeUndefined();
});
it("should return empty AlignedRow on deleting last widget, if the layout is permanent", () => {
const layout: LayoutComponentProps = generateAlignedRowMock({
isPermanent: true,
});
// start alignment has two widgets
const originalStartLength: number = (
layout.layout as WidgetLayoutProps[]
).filter(
(each: WidgetLayoutProps) =>
each.alignment === FlexLayerAlignment.Start,
).length;
let res: LayoutProps | undefined = deleteWidgetFromLayout(
layout,
(layout.layout[0] as WidgetLayoutProps).widgetId,
);
if (!res) return;
expect((res.layout as WidgetLayoutProps[]).length).toEqual(
originalStartLength - 1,
);
expect(
extractWidgetIdsFromLayoutProps(res).includes(
(layout.layout[0] as WidgetLayoutProps).widgetId,
),
).toBeFalsy();
// Delete the other widget
res = deleteWidgetFromLayout(
res,
(res.layout[0] as WidgetLayoutProps).widgetId,
);
if (!res) return;
expect(res.layout.length).toEqual(0);
});
it("should return the layout as is if widgetId is not present in the layout", () => {
const layout: LayoutComponentProps = generateAlignedRowMock();
const res: LayoutProps | undefined = deleteWidgetFromLayout(
layout,
"randomWidgetId",
);
expect(res).toEqual(layout);
expect(res?.layout.length).toEqual(layout.layout.length);
});
});
describe("deleteWidgetFromPreset", () => {
it("should delete widget from appropriate child layout", () => {
/**
* Row
* Row
* Button
* Input
* Row
* Button
* Input
*/
const layout: LayoutComponentProps = generateLayoutComponentMock(
{},
false,
);
const layout2: LayoutComponentProps = generateLayoutComponentMock();
const res: LayoutProps[] = deleteWidgetFromPreset(
[layout2, layout],
((layout.layout[0] as LayoutProps).layout[0] as WidgetLayoutProps)
.widgetId,
);
expect((res[1].layout[0] as LayoutProps).layout.length).toEqual(
(layout.layout[0] as LayoutProps).layout.length - 1,
);
expect(res[0].layout.length).toEqual(
(layout2.layout as WidgetLayoutProps[]).length,
);
});
it("should filter empty temporary layouts after deletion", () => {
/**
* Row
* Row
* Button
* Input
* Row
* Button
* Input
*/
const layout: LayoutComponentProps = generateLayoutComponentMock(
{},
false,
);
// layout2 has two child widgets
const layout2: LayoutComponentProps = generateLayoutComponentMock({
isPermanent: false,
});
// delete the first widget
let res: LayoutProps[] = deleteWidgetFromPreset(
[layout2, layout],
(layout2.layout[0] as WidgetLayoutProps).widgetId,
);
expect(res.length).toEqual(2);
// delete the other widget
res = deleteWidgetFromPreset(
res,
(res[0].layout[0] as WidgetLayoutProps).widgetId,
);
expect(res.length).toEqual(1);
expect(res[0].layoutId).toEqual(layout.layoutId);
});
});
});
|
227 | 0 | petrpan-code/appsmithorg/appsmith/app/client/src/layoutSystems/anvil/utils/layouts | petrpan-code/appsmithorg/appsmith/app/client/src/layoutSystems/anvil/utils/layouts/update/moveUtils.test.ts | import { generateLayoutComponentMock } from "mocks/layoutComponents/layoutComponentMock";
import type { BaseWidgetProps } from "widgets/BaseWidgetHOC/withBaseWidgetHOC";
import type { LayoutComponentProps, WidgetLayoutProps } from "../../anvilTypes";
import { mockCanvasProps } from "mocks/widgetProps/canvas";
import type { CanvasWidgetsReduxState } from "reducers/entityReducers/canvasWidgetsReducer";
import { moveWidgets, updateWidgetRelationships } from "./moveUtils";
import { mockAnvilHighlightInfo } from "mocks/mockHighlightInfo";
import {
extractWidgetIdsFromLayoutProps,
registerLayoutComponents,
} from "../layoutUtils";
describe("Layouts - moveUtils test", () => {
beforeAll(() => {
registerLayoutComponents();
});
describe("updateWidgetRelationships", () => {
it("should disconnect widgets from old parent and add to new parent", () => {
const canvas1: BaseWidgetProps = mockCanvasProps();
const layout1: LayoutComponentProps = generateLayoutComponentMock();
if (!layout1.childrenMap) return;
canvas1.children = [
(layout1.layout[0] as WidgetLayoutProps).widgetId,
(layout1.layout[1] as WidgetLayoutProps).widgetId,
];
canvas1.layout = [layout1];
const canvas2: BaseWidgetProps = mockCanvasProps();
const movedWidget: WidgetLayoutProps = layout1
.layout[0] as WidgetLayoutProps;
const state: CanvasWidgetsReduxState = {
[canvas1.widgetId]: canvas1,
[movedWidget.widgetId]: {
...layout1?.childrenMap[movedWidget.widgetId],
parentId: canvas1.widgetId,
},
[(layout1.layout[1] as WidgetLayoutProps).widgetId]: {
...layout1?.childrenMap[
(layout1.layout[1] as WidgetLayoutProps).widgetId
],
parentId: canvas1.widgetId,
},
[canvas2.widgetId]: canvas2,
};
const res: CanvasWidgetsReduxState = updateWidgetRelationships(
state,
[movedWidget.widgetId],
mockAnvilHighlightInfo({ canvasId: canvas2.widgetId }),
);
expect(res[canvas1.widgetId].children?.length).toEqual(1);
expect(res[movedWidget.widgetId].parentId).toEqual(canvas2.widgetId);
expect(res[canvas1.widgetId].layout[0].layout.length).toEqual(1);
});
it("should not update any relationship if the widgets are moved within the same parent", () => {
const canvas1: BaseWidgetProps = mockCanvasProps();
const layout1: LayoutComponentProps = generateLayoutComponentMock();
if (!layout1.childrenMap) return;
canvas1.children = [layout1.layout[0], layout1.layout[1]];
canvas1.layout = [layout1];
const movedWidget: WidgetLayoutProps = layout1
.layout[0] as WidgetLayoutProps;
const state: CanvasWidgetsReduxState = {
[canvas1.widgetId]: canvas1,
[movedWidget.widgetId]: {
...layout1?.childrenMap[movedWidget.widgetId],
parentId: canvas1.widgetId,
},
[(layout1.layout[1] as WidgetLayoutProps).widgetId]: {
...layout1?.childrenMap[
(layout1.layout[1] as WidgetLayoutProps).widgetId
],
parentId: canvas1.widgetId,
},
};
expect(state[canvas1.widgetId].children?.length).toEqual(2);
expect(state[movedWidget.widgetId].parentId).toEqual(canvas1.widgetId);
const res: CanvasWidgetsReduxState = updateWidgetRelationships(
state,
[movedWidget.widgetId],
mockAnvilHighlightInfo({ canvasId: canvas1.widgetId }),
);
expect(res[canvas1.widgetId].children?.length).toEqual(2);
expect(res[movedWidget.widgetId].parentId).toEqual(canvas1.widgetId);
});
});
describe("moveWidgets", () => {
it("should update relationships and layouts properly", () => {
const canvas1: BaseWidgetProps = mockCanvasProps();
const layout1: LayoutComponentProps = generateLayoutComponentMock();
if (!layout1.childrenMap) return;
canvas1.children = [
(layout1.layout[0] as WidgetLayoutProps).widgetId,
(layout1.layout[1] as WidgetLayoutProps).widgetId,
];
canvas1.layout = [layout1];
const canvas2: BaseWidgetProps = mockCanvasProps();
canvas2.children = [];
canvas2.layout = [generateLayoutComponentMock({ layout: [] })];
const movedWidget: WidgetLayoutProps = layout1
.layout[0] as WidgetLayoutProps;
const state: CanvasWidgetsReduxState = {
[canvas1.widgetId]: canvas1,
[movedWidget.widgetId]: {
...layout1?.childrenMap[movedWidget.widgetId],
parentId: canvas1.widgetId,
},
[(layout1.layout[1] as WidgetLayoutProps).widgetId]: {
...layout1?.childrenMap[
(layout1.layout[1] as WidgetLayoutProps).widgetId
],
parentId: canvas1.widgetId,
},
[canvas2.widgetId]: canvas2,
};
const res: CanvasWidgetsReduxState = moveWidgets(
state,
[movedWidget.widgetId],
mockAnvilHighlightInfo({
canvasId: canvas2.widgetId,
layoutOrder: [canvas2.layout[0].layoutId],
}),
);
expect(res[canvas1.widgetId].children?.length).toEqual(1);
expect(res[movedWidget.widgetId].parentId).toEqual(canvas2.widgetId);
expect(res[canvas1.widgetId].layout[0].layout.length).toEqual(1);
expect(res[canvas2.widgetId].children?.length).toEqual(1);
expect(res[canvas2.widgetId].layout[0].layout.length).toEqual(1);
expect(
extractWidgetIdsFromLayoutProps(
res[canvas2.widgetId].layout[0],
).includes(movedWidget.widgetId),
).toBeTruthy();
});
it("should update relationships and layouts properly for multiple moved widgets", () => {
const canvas1: BaseWidgetProps = mockCanvasProps();
const layout1: LayoutComponentProps = generateLayoutComponentMock({
isPermanent: true,
});
canvas1.children = [
(layout1.layout[0] as WidgetLayoutProps).widgetId,
(layout1.layout[1] as WidgetLayoutProps).widgetId,
];
canvas1.layout = [layout1];
const canvas2: BaseWidgetProps = mockCanvasProps();
const layout2: LayoutComponentProps = generateLayoutComponentMock();
canvas2.children = [
(layout2.layout[0] as WidgetLayoutProps).widgetId,
(layout2.layout[1] as WidgetLayoutProps).widgetId,
];
canvas2.layout = [layout2];
if (!layout1.childrenMap || !layout2.childrenMap) return;
const movedWidgetIds: string[] = [
...canvas1.children,
canvas2.children[1],
];
const state: CanvasWidgetsReduxState = {
[canvas1.widgetId]: canvas1,
[(layout1.layout[0] as WidgetLayoutProps).widgetId]: {
...layout1?.childrenMap[
(layout1.layout[0] as WidgetLayoutProps).widgetId
],
parentId: canvas1.widgetId,
},
[(layout1.layout[1] as WidgetLayoutProps).widgetId]: {
...layout1?.childrenMap[
(layout1.layout[1] as WidgetLayoutProps).widgetId
],
parentId: canvas1.widgetId,
},
[canvas2.widgetId]: canvas2,
[(layout2.layout[0] as WidgetLayoutProps).widgetId]: {
...layout2?.childrenMap[
(layout2.layout[0] as WidgetLayoutProps).widgetId
],
parentId: canvas1.widgetId,
},
[(layout2.layout[1] as WidgetLayoutProps).widgetId]: {
...layout2?.childrenMap[
(layout2.layout[1] as WidgetLayoutProps).widgetId
],
parentId: canvas1.widgetId,
},
};
const res: CanvasWidgetsReduxState = moveWidgets(
state,
movedWidgetIds,
mockAnvilHighlightInfo({
canvasId: canvas2.widgetId,
layoutOrder: [canvas2.layout[0].layoutId],
}),
);
expect(res[canvas1.widgetId].children?.length).toEqual(0);
expect(res[movedWidgetIds[0]].parentId).toEqual(canvas2.widgetId);
expect(res[canvas1.widgetId].layout[0].layout.length).toEqual(0);
expect(res[canvas2.widgetId].children?.length).toEqual(4);
expect(res[canvas2.widgetId].layout[0].layout.length).toEqual(4);
expect(
extractWidgetIdsFromLayoutProps(
res[canvas2.widgetId].layout[0],
).includes(movedWidgetIds[1]),
).toBeTruthy();
});
});
});
|
256 | 0 | petrpan-code/appsmithorg/appsmith/app/client/src/layoutSystems/autolayout | petrpan-code/appsmithorg/appsmith/app/client/src/layoutSystems/autolayout/utils/autoLayoutDraggingUtils.test.ts | import type { CanvasWidgetsReduxState } from "reducers/entityReducers/canvasWidgetsReducer";
import {
addNewLayer,
createFlexLayer,
removeWidgetsFromCurrentLayers,
updateExistingLayer,
updateRelationships,
} from "./autoLayoutDraggingUtils";
import { getLayerIndexOfWidget } from "./AutoLayoutUtils";
import { data } from "./testData";
import type { FlexLayer } from "./types";
import { FlexLayerAlignment } from "layoutSystems/common/utils/constants";
describe("test AutoLayoutDraggingUtils methods", () => {
describe("test createFlexLayer method", () => {
it("should return a new FlexLayer for given widgets and alignment", () => {
const widgets = { ...data };
const layer: FlexLayer = createFlexLayer(
[widgets["tg6jcd1kjp"].widgetId],
widgets,
FlexLayerAlignment.Start,
);
expect(layer).toEqual({
children: [{ id: "tg6jcd1kjp", align: FlexLayerAlignment.Start }],
});
});
it("should exclude widgets that don't exist", () => {
const widgets = { ...data };
const layer: FlexLayer = createFlexLayer(
["33"],
widgets,
FlexLayerAlignment.Start,
);
expect(layer).toEqual({
children: [],
});
});
});
describe("test removeWidgetsFromCurrentLayers method", () => {
it("should remove the widget from given flex layers", () => {
const widgets = { ...data };
const layers: any[] = widgets["a3lldg1wg9"].flexLayers;
const result: FlexLayer[] = removeWidgetsFromCurrentLayers(
["pt32jvs72k"],
layers,
);
const layerIndex = getLayerIndexOfWidget(result, "pt32jvs72k");
expect(result[0].children.length).toEqual(1);
expect(layerIndex).toEqual(-1);
});
it("should return an empty array if the input layers are empty", () => {
expect(removeWidgetsFromCurrentLayers(["pt32jvs72k"], [])).toEqual([]);
});
it("should return input flexLayers as is if moved widgets are not found amongst them", () => {
const widgets = { ...data };
const layers: any[] = widgets["a3lldg1wg9"].flexLayers;
const result: FlexLayer[] = removeWidgetsFromCurrentLayers(
["33", "44"],
layers,
);
expect(result[0].children.length).toEqual(2);
expect(result).toEqual(layers);
});
});
describe("test updateRelationships method", () => {
const mainCanvasWidth = 960;
it("should remove moved widgets from old parent's layers and assign new parent to the widgets", () => {
const widgets = { ...data };
const movedWidget = "pt32jvs72k";
const oldParent = widgets[movedWidget].parentId;
const result: CanvasWidgetsReduxState = updateRelationships(
[movedWidget],
widgets,
"0",
false,
false,
mainCanvasWidth,
);
expect(result[movedWidget].parentId === "0").toBeTruthy;
if (result[oldParent]) {
expect(result[oldParent]?.children?.includes(movedWidget)).toBeFalsy;
const layerIndex = getLayerIndexOfWidget(
result[oldParent]?.flexLayers,
"pt32jvs72k",
);
expect(layerIndex).toEqual(-1);
}
});
it("should not update previous parent's children or moved widget's parentId id onlyUpdateFlexLayers is set to true", () => {
const widgets = { ...data };
const movedWidget = "pt32jvs72k";
const oldParent = widgets[movedWidget].parentId;
const result: CanvasWidgetsReduxState = updateRelationships(
[movedWidget],
widgets,
"0",
true,
false,
mainCanvasWidth,
);
expect(result[movedWidget].parentId === "0").toBeFalsy;
if (result[oldParent]) {
expect(result[oldParent]?.children?.includes(movedWidget)).toBeTruthy;
const layerIndex = getLayerIndexOfWidget(
result[oldParent]?.flexLayers,
"pt32jvs72k",
);
expect(layerIndex).toEqual(-1);
}
});
});
describe("test addNewLayer method", () => {
it("should add a new layer to flexLayers array at the given layerIndex", () => {
const widgets = { ...data };
const movedWidget = "pt32jvs72k";
const newParentId = "0";
const newLayer: FlexLayer = {
children: [{ id: movedWidget, align: FlexLayerAlignment.Center }],
};
const result: CanvasWidgetsReduxState = addNewLayer(
newLayer,
widgets,
newParentId,
widgets[newParentId].flexLayers as FlexLayer[],
0,
);
const updatedParent = result[newParentId];
expect(updatedParent.flexLayers.length).toEqual(2);
const layerIndex = getLayerIndexOfWidget(
updatedParent?.flexLayers,
"pt32jvs72k",
);
expect(layerIndex).toEqual(0);
});
it("should add new layer at the end of the flex layers if layerIndex is invalid", () => {
const widgets = { ...data };
const movedWidget = "pt32jvs72k";
const newParentId = "0";
const newLayer: FlexLayer = {
children: [{ id: movedWidget, align: FlexLayerAlignment.Center }],
};
const result: CanvasWidgetsReduxState = addNewLayer(
newLayer,
widgets,
newParentId,
widgets[newParentId].flexLayers as FlexLayer[],
5,
);
const updatedParent = result[newParentId];
expect(updatedParent.flexLayers.length).toEqual(2);
const layerIndex = getLayerIndexOfWidget(
updatedParent?.flexLayers,
"pt32jvs72k",
);
expect(layerIndex).toEqual(1);
});
});
describe("test updateExistingLayer method", () => {
it("should update existing layer by merging the new layer at the given layerIndex", () => {
const widgets = { ...data };
const movedWidget = "pt32jvs72k";
const newParentId = "0";
const newLayer: FlexLayer = {
children: [{ id: movedWidget, align: FlexLayerAlignment.Center }],
};
const result: CanvasWidgetsReduxState = updateExistingLayer(
newLayer,
widgets,
newParentId,
widgets[newParentId].flexLayers as FlexLayer[],
0,
0,
);
const updatedParent = result[newParentId];
expect(updatedParent.flexLayers.length).toEqual(1);
expect(updatedParent.flexLayers[0].children.length).toEqual(3);
const layerIndex = getLayerIndexOfWidget(
updatedParent?.flexLayers,
"pt32jvs72k",
);
expect(layerIndex).toEqual(0);
});
});
});
|
258 | 0 | petrpan-code/appsmithorg/appsmith/app/client/src/layoutSystems/autolayout | petrpan-code/appsmithorg/appsmith/app/client/src/layoutSystems/autolayout/utils/autoLayoutUtils.test.ts | import type { AlignmentColumnData } from "../../autolayout/utils/types";
import type {
CanvasWidgetsReduxState,
FlattenedWidgetProps,
} from "reducers/entityReducers/canvasWidgetsReducer";
import {
getAlignmentMarginInfo,
getCanvasDimensions,
getFlexLayersForSelectedWidgets,
getLayerIndexOfWidget,
getNewFlexLayers,
pasteWidgetInFlexLayers,
updateFlexLayersOnDelete,
} from "./AutoLayoutUtils";
import { data, dataForgetCanvasDimensions } from "./testData";
import { FlexLayerAlignment } from "../../common/utils/constants";
import { AUTO_LAYOUT_CONTAINER_PADDING } from "constants/WidgetConstants";
import type { FlexLayer, LayerChild } from "./types";
describe("test AutoLayoutUtils methods", () => {
const mainCanvasWidth = 960;
describe("test updateFlexLayersOnDelete method", () => {
it("should remove deleted widgets from flex layers of the parent", () => {
const widgets = { ...data };
const deletedWidgetId = "pt32jvs72k";
const parentId = "a3lldg1wg9";
const result: CanvasWidgetsReduxState = updateFlexLayersOnDelete(
widgets,
deletedWidgetId,
parentId,
false,
mainCanvasWidth,
);
expect(result[parentId].flexLayers?.length).toEqual(1);
const layerIndex = getLayerIndexOfWidget(
result[parentId]?.flexLayers,
deletedWidgetId,
);
expect(layerIndex).toEqual(-1);
});
it("should return the layers as is, if the deleted widget does not exist in them", () => {
const widgets = { ...data };
const deletedWidgetId = "33";
const parentId = "a3lldg1wg9";
const result: CanvasWidgetsReduxState = updateFlexLayersOnDelete(
widgets,
deletedWidgetId,
parentId,
false,
mainCanvasWidth,
);
expect(result[parentId].flexLayers?.length).toEqual(1);
expect(result[parentId].flexLayers[0]?.children.length).toEqual(2);
});
it("should discard empty layers after removing deleted widgets", () => {
const widgets = { ...data };
const parentId = "a3lldg1wg9";
const updatedWidgets: CanvasWidgetsReduxState = updateFlexLayersOnDelete(
widgets,
"pt32jvs72k",
parentId,
false,
mainCanvasWidth,
);
const result: CanvasWidgetsReduxState = updateFlexLayersOnDelete(
updatedWidgets,
"tg6jcd1kjp",
parentId,
false,
mainCanvasWidth,
);
expect(result[parentId].flexLayers?.length).toEqual(0);
});
});
describe("test pasteWidgetInFlexLayers method", () => {
it("should add the pasted widget to a new layer at the bottom of the parent, if the new parent is different from the original", () => {
let widgets = { ...data };
const originalWidgetId = "pt32jvs72k";
const newParentId = "2ydfwnmayi";
expect(widgets[newParentId].flexLayers?.length).toEqual(0);
const copiedWidget = {
...widgets["pt32jvs72k"],
widgetId: "abcdef123",
widgetName: widgets["pt32jvs72k"].widgetName + "Copy",
key:
widgets["pt32jvs72k"].key.slice(
0,
widgets["pt32jvs72k"].key.length - 2,
) + "yz",
parentId: newParentId,
};
widgets = { ...widgets, [copiedWidget.widgetId]: copiedWidget };
const result: CanvasWidgetsReduxState = pasteWidgetInFlexLayers(
widgets,
newParentId,
copiedWidget,
originalWidgetId,
false,
mainCanvasWidth,
);
expect(result[newParentId].flexLayers?.length).toEqual(1);
expect(
getLayerIndexOfWidget(
result[newParentId]?.flexLayers,
copiedWidget.widgetId,
),
).toEqual(0);
});
it("should paste the copied widget in the same layer and to the right of the original widget, if the parentId remains the same", () => {
let widgets = { ...data };
const originalWidgetId = "pt32jvs72k";
const parentId = "a3lldg1wg9";
/**
* Update original parent's flexLayers to ramp up the layer count.
* => split each child into a new layer.
*/
const layers: FlexLayer[] = [];
for (const layer of widgets[parentId].flexLayers) {
for (const child of layer.children) {
layers.push({
children: [child as LayerChild],
});
}
}
widgets = {
...widgets,
[parentId]: { ...widgets[parentId], flexLayers: layers },
};
expect(widgets[parentId].flexLayers?.length).toEqual(2);
const copiedWidget = {
...widgets["pt32jvs72k"],
widgetId: "abcdef123",
widgetName: widgets["pt32jvs72k"].widgetName + "Copy",
key:
widgets["pt32jvs72k"].key.slice(
0,
widgets["pt32jvs72k"].key.length - 2,
) + "yz",
parentId: parentId,
};
widgets = { ...widgets, [copiedWidget.widgetId]: copiedWidget };
const result: CanvasWidgetsReduxState = pasteWidgetInFlexLayers(
widgets,
parentId,
copiedWidget,
originalWidgetId,
false,
mainCanvasWidth,
);
// layer count should remain the same. => no new layer is created.
expect(result[parentId].flexLayers?.length).toEqual(2);
// new widget should be pasted in the same layer as the original
expect(
getLayerIndexOfWidget(
result[parentId]?.flexLayers,
copiedWidget.widgetId,
),
).toEqual(
getLayerIndexOfWidget(result[parentId]?.flexLayers, originalWidgetId),
);
});
});
describe("test getCanvasDimensions method", () => {
/**
* +---------------------------------------------------------------------------------------+
* | MainContainer |
* | +-----------------------------------------------------------------------------------+ |
* | | Container1 | |
* | +-----------------------------------------------------------------------------------+ |
* | +------------------+ +------------------+ +------------------+ +--------------------+ |
* | | Container2 | | | | | | | |
* | +------------------+ +------------------+ +------------------+ +--------------------+ |
* | +-----------------------------------------------------------------------------------+ |
* | | +----------------+ +------------------+ +------------------+ +------------------+ | |
* | | | Container3 | | | | | | | | |
* | | +----------------+ +------------------+ +------------------+ +------------------+ | |
* | +-----------------------------------------------------------------------------------+ |
* +---------------------------------------------------------------------------------------+
*/
const mainCanvasWidth = 1166;
const widgets = dataForgetCanvasDimensions;
const mainContainerPadding = 4 * 2;
const containerPadding = (4 + AUTO_LAYOUT_CONTAINER_PADDING) * 2;
it("should return proper dimension for MainContainer", () => {
const button0parent = widgets["kv4o6eopdn"]
.parentId as keyof typeof widgets;
const { canvasWidth } = getCanvasDimensions(
widgets[button0parent] as any,
widgets as any,
mainCanvasWidth,
false,
);
expect(canvasWidth).toEqual(mainCanvasWidth - mainContainerPadding);
});
it("should return proper dimension for Container1", () => {
const button1parent = widgets["phf8e237zg"]
.parentId as keyof typeof widgets;
const { canvasWidth } = getCanvasDimensions(
widgets[button1parent] as any,
widgets as any,
mainCanvasWidth,
false,
);
expect(canvasWidth).toEqual(
mainCanvasWidth - mainContainerPadding - containerPadding,
);
});
it("should return proper dimension for Container2", () => {
const button2parent = widgets["alvcydt4he"]
.parentId as keyof typeof widgets;
const { canvasWidth } = getCanvasDimensions(
widgets[button2parent] as any,
widgets as any,
mainCanvasWidth,
false,
);
expect(canvasWidth).toEqual(
(mainCanvasWidth - mainContainerPadding) / 4 - containerPadding,
);
});
it("should return proper dimension for Container3", () => {
const button3parent = widgets["cq25w8hz6n"]
.parentId as keyof typeof widgets;
const { canvasWidth } = getCanvasDimensions(
widgets[button3parent] as any,
widgets as any,
mainCanvasWidth,
false,
);
expect(canvasWidth).toEqual(
(mainCanvasWidth - mainContainerPadding - containerPadding) / 4 -
containerPadding,
);
});
});
it("should test getFlexLayersForSelectedWidgets", () => {
const parentCanvas = {
flexLayers: [
{
children: [
{
id: "1",
align: FlexLayerAlignment.Start,
},
{
id: "2",
align: FlexLayerAlignment.Start,
},
{
id: "3",
align: FlexLayerAlignment.Center,
},
],
},
{
children: [
{
id: "4",
align: FlexLayerAlignment.Start,
},
],
},
{
children: [
{
id: "5",
align: FlexLayerAlignment.Center,
},
{
id: "6",
align: FlexLayerAlignment.End,
},
],
},
],
} as any as FlattenedWidgetProps;
const selectedWidgets = ["2", "3", "6"];
const selectedFlexLayers = [
{
children: [
{
id: "2",
align: FlexLayerAlignment.Start,
},
{
id: "3",
align: FlexLayerAlignment.Center,
},
],
},
{
children: [
{
id: "6",
align: FlexLayerAlignment.End,
},
],
},
];
expect(
getFlexLayersForSelectedWidgets(selectedWidgets, parentCanvas),
).toEqual(selectedFlexLayers);
});
it("should test getNewFlexLayers", () => {
const flexLayers = [
{
children: [
{
id: "1",
align: FlexLayerAlignment.Start,
},
{
id: "2",
align: FlexLayerAlignment.Start,
},
{
id: "3",
align: FlexLayerAlignment.Center,
},
],
},
{
children: [
{
id: "4",
align: FlexLayerAlignment.Start,
},
],
},
{
children: [
{
id: "5",
align: FlexLayerAlignment.Center,
},
{
id: "6",
align: FlexLayerAlignment.End,
},
],
},
];
const widgetIdMap = {
"1": "11",
"2": "22",
"3": "33",
"4": "44",
"5": "55",
"6": "66",
};
const newFlexLayers = [
{
children: [
{
id: "11",
align: FlexLayerAlignment.Start,
},
{
id: "22",
align: FlexLayerAlignment.Start,
},
{
id: "33",
align: FlexLayerAlignment.Center,
},
],
},
{
children: [
{
id: "44",
align: FlexLayerAlignment.Start,
},
],
},
{
children: [
{
id: "55",
align: FlexLayerAlignment.Center,
},
{
id: "66",
align: FlexLayerAlignment.End,
},
],
},
];
expect(getNewFlexLayers(flexLayers, widgetIdMap)).toEqual(newFlexLayers);
});
it("test getAlignmentMarginInfo'", () => {
const info: AlignmentColumnData[] = [
{
alignment: FlexLayerAlignment.Start,
columns: 64,
},
{
alignment: FlexLayerAlignment.Center,
columns: 20,
},
{
alignment: FlexLayerAlignment.End,
columns: 80,
},
];
// startColumns = 0
// [0,20,20]
info[0].columns = 0;
info[1].columns = 20;
info[2].columns = 20;
expect(getAlignmentMarginInfo(info)).toEqual([false, false, false]);
// [0,80,20]
info[1].columns = 80;
expect(getAlignmentMarginInfo(info)).toEqual([false, true, false]);
// [0,80,80]
info[2].columns = 80;
expect(getAlignmentMarginInfo(info)).toEqual([false, true, false]);
// [0,20,80]
info[1].columns = 20;
expect(getAlignmentMarginInfo(info)).toEqual([false, true, false]);
// [0,0,20]
info[1].columns = 0;
expect(getAlignmentMarginInfo(info)).toEqual([false, false, false]);
// [0,20,0]
info[1].columns = 20;
info[2].columns = 0;
expect(getAlignmentMarginInfo(info)).toEqual([false, false, false]);
// centerColumns = 0
// [20,0,20]
info[0].columns = 20;
info[1].columns = 0;
info[2].columns = 20;
expect(getAlignmentMarginInfo(info)).toEqual([false, false, false]);
// [80,0,20]
info[0].columns = 80;
expect(getAlignmentMarginInfo(info)).toEqual([true, false, false]);
// [80,0,80]
info[2].columns = 80;
expect(getAlignmentMarginInfo(info)).toEqual([true, false, false]);
// [20,0,80]
info[0].columns = 20;
expect(getAlignmentMarginInfo(info)).toEqual([true, false, false]);
// [20,0,0]
info[2].columns = 0;
expect(getAlignmentMarginInfo(info)).toEqual([false, false, false]);
// [80,0,0]
info[0].columns = 80;
expect(getAlignmentMarginInfo(info)).toEqual([false, false, false]);
// endColumns = 0
// [20,20,0]
info[0].columns = 20;
info[1].columns = 20;
info[2].columns = 0;
expect(getAlignmentMarginInfo(info)).toEqual([false, false, false]);
// [80,20,0]
info[0].columns = 80;
expect(getAlignmentMarginInfo(info)).toEqual([true, false, false]);
// [80,80,0]
info[1].columns = 80;
expect(getAlignmentMarginInfo(info)).toEqual([true, false, false]);
// [20,80,0]
info[0].columns = 20;
expect(getAlignmentMarginInfo(info)).toEqual([true, false, false]);
// [40,30,0]
info[0].columns = 40;
info[1].columns = 30;
expect(getAlignmentMarginInfo(info)).toEqual([true, false, false]);
// [40,30,64]
info[2].columns = 64;
expect(getAlignmentMarginInfo(info)).toEqual([true, true, false]);
});
});
|
262 | 0 | petrpan-code/appsmithorg/appsmith/app/client/src/layoutSystems/autolayout | petrpan-code/appsmithorg/appsmith/app/client/src/layoutSystems/autolayout/utils/heightUpdates.test.ts | import { updateWidgetPositions } from "./positionUtils";
import * as utils from "./flexWidgetUtils";
import {
MAIN_CONTAINER_WIDGET_WITH_BUTTON,
buttonData,
} from "./data/heightTestData";
import { EMPTY_TABS_DATA, TABS_DATA } from "./data/tabsData";
describe("auto-layout: heightUpdates", () => {
beforeEach(() => {
jest
.spyOn(utils, "getWidgetMinMaxDimensionsInPixel")
// eslint-disable-next-line @typescript-eslint/no-unused-vars
.mockImplementation((widget: any, width: number) => {
if (widget?.type === "CONTAINER_WIDGET")
return {
minWidth: 280,
minHeight: 50,
maxWidth: undefined,
maxHeight: undefined,
};
return {
minWidth: undefined,
minHeight: undefined,
maxWidth: undefined,
maxHeight: undefined,
};
});
});
it("Canvas and container should increase in height on adding new widgets in a new row", () => {
const data: { [k: string]: any } = { ...MAIN_CONTAINER_WIDGET_WITH_BUTTON };
let updatedWidgets = updateWidgetPositions(data, "3", false, 4896);
expect(updatedWidgets["2"].bottomRow).toBe(6);
// Add a button in a new row
const newButton = buttonData("5", "3");
const data2 = {
...data,
"5": newButton,
"3": {
...data["3"],
children: ["4", "5"],
flexLayers: [
{
children: [
{
id: "4",
align: "start",
},
],
},
{
children: [
{
id: "5",
align: "start",
},
],
},
],
},
};
updatedWidgets = updateWidgetPositions(data2, "3", false, 4896);
/**
* buttonHeight = 4
* rowGap = 1.2
* buffer = 2
* total = 4 + 4 + 1.2 + 2 = 11.2
*/
expect(updatedWidgets["2"].bottomRow).toBeGreaterThan(6);
expect(Math.round(updatedWidgets["2"].bottomRow)).toBe(11);
});
it("canvas and container should decrease in height on removing widgets", () => {
const data: { [k: string]: any } = { ...MAIN_CONTAINER_WIDGET_WITH_BUTTON };
// Add a button in a new row
const newButton = buttonData("5", "3");
const data2 = {
...data,
"5": newButton,
"3": {
...data["3"],
children: ["4", "5"],
flexLayers: [
{
children: [
{
id: "4",
align: "start",
},
],
},
{
children: [
{
id: "5",
align: "start",
},
],
},
],
},
};
let updatedWidgets = updateWidgetPositions(data2, "3", false, 4896);
/**
* buttonHeight = 4
* rowGap = 1.2
* buffer = 2
* total = 4 + 4 + 1.2 + 2 = 11.2
*/
expect(Math.round(updatedWidgets["2"].bottomRow)).toBe(11);
// Remove the button
const data3 = {
"0": data["0"],
"2": data["2"],
"3": {
...data["3"],
children: ["4"],
flexLayers: [
{
children: [
{
id: "4",
align: "start",
},
],
},
],
},
"4": data["4"],
};
updatedWidgets = updateWidgetPositions(data3, "3", false, 4896);
expect(updatedWidgets["2"].bottomRow).toBe(6);
});
it("should update canvas height on deleting all children", () => {
const data: { [k: string]: any } = { ...MAIN_CONTAINER_WIDGET_WITH_BUTTON };
// Add a button in a new row
const newButton = buttonData("5", "3");
const data2 = {
...data,
"5": newButton,
"3": {
...data["3"],
children: ["4", "5"],
flexLayers: [
{
children: [
{
id: "4",
align: "start",
},
],
},
{
children: [
{
id: "5",
align: "start",
},
],
},
],
},
};
let updatedWidgets = updateWidgetPositions(data2, "3", false, 4896);
expect(Math.round(updatedWidgets["2"].bottomRow)).toBe(11);
// Remove all child widgets
const data3 = {
"0": data["0"],
"2": data["2"],
"3": {
...data["3"],
children: [],
flexLayers: [],
},
"4": data["4"],
};
updatedWidgets = updateWidgetPositions(data3, "3", false, 4896);
/**
* Container (minHeight = 5)
* Canvas
*
* total height = 5
*/
expect(updatedWidgets["2"].bottomRow).toBe(5);
});
});
describe("auto-layout dynamic height: tabs widget", () => {
beforeEach(() => {
jest
.spyOn(utils, "getWidgetMinMaxDimensionsInPixel")
// eslint-disable-next-line @typescript-eslint/no-unused-vars
.mockImplementation((widget: any, width: number) => {
if (widget?.type === "TABS_WIDGET")
return {
minWidth: 280,
minHeight: 300,
maxWidth: undefined,
maxHeight: undefined,
};
return {
minWidth: undefined,
minHeight: undefined,
maxWidth: undefined,
maxHeight: undefined,
};
});
});
it("should assign a height of 30 rows (minHeight) to an empty tabs widget", () => {
const data: { [k: string]: any } = EMPTY_TABS_DATA;
const updatedWidgets = updateWidgetPositions(
data,
"2",
false,
4896,
false,
{ "1": { selectedTabWidgetId: "2" } },
);
/**
* minHeight of TabsWidget = 30;
* Buffer for Tabs header = 4;
* Height of canvas = 30 - 4 = 26 * 10 = 260;
*/
expect(updatedWidgets["1"].bottomRow).toBe(30);
expect(updatedWidgets["2"].bottomRow).toBe(260);
});
it("should update height of Tabs widget based on selected tab height", () => {
const data: { [k: string]: any } = TABS_DATA;
let selectedTabWidgetId = "2";
const updatedWidgets = updateWidgetPositions(
data,
selectedTabWidgetId,
false,
4896,
false,
{ "1": { selectedTabWidgetId: selectedTabWidgetId } },
);
/**
* TABS
* CANVAS
* AUDIO RECORDER (height = 7)
* TABLE (height = 30)
*
* canvas height = 7 + 30 + 1.2 (row gap) + 2 (buffer) = 40.2 * 10 = 402
* tabs height = 40.2 + 4 (buffer for tabs header) = 44.2
*/
expect(updatedWidgets["1"].bottomRow).toBe(44.2);
expect(updatedWidgets["2"].bottomRow).toBe(402);
// Switch to second tab which is empty
selectedTabWidgetId = "3";
const updatedWidgets2 = updateWidgetPositions(
data,
selectedTabWidgetId,
false,
4896,
false,
{ "1": { selectedTabWidgetId: selectedTabWidgetId } },
);
expect(updatedWidgets2["1"].bottomRow).toBe(30);
expect(updatedWidgets2["3"].bottomRow).toBe(260);
});
it("should account for the height of the tabs header", () => {
const data: { [k: string]: any } = TABS_DATA;
const selectedTabWidgetId = "2";
const updatedWidgets = updateWidgetPositions(
data,
selectedTabWidgetId,
false,
4896,
false,
{ "1": { selectedTabWidgetId: selectedTabWidgetId } },
);
/**
* TABS
* CANVAS
* AUDIO RECORDER (height = 7)
* TABLE (height = 30)
*
* canvas height = 7 + 30 + 1.2 (row gap) + 2 (buffer) = 40.2 * 10 = 402
* tabs height = 40.2 + 4 (buffer for tabs header) = 44.2
*/
expect(updatedWidgets["1"].bottomRow).toBe(44.2);
expect(updatedWidgets["2"].bottomRow).toBe(402);
// set shouldShowTabs to false
const data2: { [k: string]: any } = {
...TABS_DATA,
"1": {
...TABS_DATA["1"],
shouldShowTabs: false,
},
"2": {
...TABS_DATA["2"],
bottomRow: 300, // height of tabs widget is being set by a prior saga, so changing bottomRow here to trigger parent height update.
},
};
const updatedWidgets2 = updateWidgetPositions(
data2,
selectedTabWidgetId,
false,
4896,
false,
{ "1": { selectedTabWidgetId: selectedTabWidgetId } },
);
// height of canvas remains the same.
expect(updatedWidgets2["2"].bottomRow).toBe(402);
expect(updatedWidgets2["1"].bottomRow).toBe(40.2);
});
it("should not add buffer for header if showShouldTabs is false", () => {
const data: { [k: string]: any } = {
...TABS_DATA,
"1": {
...TABS_DATA["1"],
shouldShowTabs: false,
},
"2": {
...TABS_DATA["2"],
bottomRow: 300,
},
};
const updatedWidgets = updateWidgetPositions(
data,
"2",
false,
4896,
false,
{ "1": { selectedTabWidgetId: "2" } },
);
expect(updatedWidgets["2"].bottomRow).toBe(402);
expect(updatedWidgets["1"].bottomRow).toBe(40.2);
});
it("should use the first child canvas for height calculation if selectedTabWidgetId is undefined", () => {
const data: { [k: string]: any } = {
...TABS_DATA,
"1": {
...TABS_DATA["1"],
shouldShowTabs: false,
},
};
const updatedWidgets = updateWidgetPositions(
data,
"1",
false,
4896,
false,
{ "1": { selectedTabWidgetId: undefined } },
);
expect(updatedWidgets["2"].bottomRow).toBe(402);
expect(updatedWidgets["1"].bottomRow).toBe(40.2);
});
it("should stretch on mobile viewport to accommodate widget wrapping", () => {
// Place the two child fill widgets in the same row so that they wrap on mobile viewport.
const data: { [k: string]: any } = {
...TABS_DATA,
"2": {
...TABS_DATA["2"],
flexLayers: [
{
children: [
{
id: "4",
align: "start",
},
{
id: "5",
align: "start",
},
],
},
],
},
};
const updatedWidgets = updateWidgetPositions(
data,
"2",
false,
4896,
false,
{
"1": { selectedTabWidgetId: "2" },
},
);
const bottomRow = updatedWidgets["1"].bottomRow;
const updatedWidgets2 = updateWidgetPositions(data, "2", true, 478, false, {
"1": { selectedTabWidgetId: "2" },
});
const mobileBottomRow = updatedWidgets2["1"].mobileBottomRow;
expect(mobileBottomRow).toBeGreaterThan(bottomRow);
});
});
|
264 | 0 | petrpan-code/appsmithorg/appsmith/app/client/src/layoutSystems/autolayout | petrpan-code/appsmithorg/appsmith/app/client/src/layoutSystems/autolayout/utils/highlightUtils.test.ts | import { FLEXBOX_PADDING, RenderModes } from "constants/WidgetConstants";
import {
FlexLayerAlignment,
ResponsiveBehavior,
ROW_GAP,
} from "layoutSystems/common/utils/constants";
import { getWidgetHeight } from "./flexWidgetUtils";
import type { VerticalHighlightsPayload } from "./highlightUtils";
import {
deriveHighlightsFromLayers,
generateHighlightsForAlignment,
generateVerticalHighlights,
} from "./highlightUtils";
import type { HighlightInfo } from "layoutSystems/common/utils/types";
describe("test HighlightUtils methods", () => {
describe("test deriveHighlightsFromLayers method", () => {
it("should generate horizontal highlights for empty canvas", () => {
const widgets = {
"1": {
widgetId: "1",
leftColumn: 0,
rightColumn: 64,
alignment: FlexLayerAlignment.Start,
topRow: 0,
bottomRow: 70,
type: "CANVAS_WIDGET",
widgetName: "Canvas1",
renderMode: RenderModes.CANVAS,
version: 1,
parentColumnSpace: 1,
parentRowSpace: 1,
isLoading: false,
mobileTopRow: 0,
mobileBottomRow: 70,
mobileLeftColumn: 0,
mobileRightColumn: 640,
responsiveBehavior: ResponsiveBehavior.Fill,
parentId: "",
flexLayers: [],
children: [],
},
};
const highlights: HighlightInfo[] = deriveHighlightsFromLayers(
widgets,
"1",
9.875,
);
expect(highlights.length).toEqual(3);
expect(highlights[0].isVertical).toBeFalsy;
// width of each horizontal highlight = container width / 3 - padding.
expect(Math.round(highlights[0].width)).toEqual(211);
expect(highlights[0].height).toEqual(4);
// x position of each horizontal highlight = (container width / 3) * index + padding.
expect(Math.round(highlights[1].posX)).toEqual(215);
expect(Math.round(highlights[2].posX)).toEqual(425);
});
it("should add horizontal heights before every layer and below the last layer", () => {
const widgets = {
"1": {
widgetId: "1",
leftColumn: 0,
rightColumn: 64,
alignment: FlexLayerAlignment.Start,
topRow: 0,
bottomRow: 70,
type: "CANVAS_WIDGET",
widgetName: "Canvas1",
renderMode: RenderModes.CANVAS,
version: 1,
parentColumnSpace: 1,
parentRowSpace: 1,
isLoading: false,
mobileTopRow: 0,
mobileBottomRow: 70,
mobileLeftColumn: 0,
mobileRightColumn: 640,
responsiveBehavior: ResponsiveBehavior.Fill,
parentId: "",
flexLayers: [
{ children: [{ id: "2", align: FlexLayerAlignment.Start }] },
],
children: ["2"],
},
"2": {
widgetId: "2",
leftColumn: 0,
rightColumn: 16,
alignment: FlexLayerAlignment.Start,
topRow: 0,
bottomRow: 4,
type: "BUTTON_WIDGET",
widgetName: "Button1",
renderMode: RenderModes.CANVAS,
version: 1,
parentColumnSpace: 1.546875,
parentRowSpace: 10,
isLoading: false,
mobileTopRow: 0,
mobileBottomRow: 4,
mobileLeftColumn: 0,
mobileRightColumn: 16,
responsiveBehavior: ResponsiveBehavior.Hug,
parentId: "1",
},
};
const offsetTop = ROW_GAP;
const highlights: HighlightInfo[] = deriveHighlightsFromLayers(
widgets,
"1",
10,
);
expect(highlights.length).toEqual(10);
expect(
highlights[0].isVertical ||
highlights[1].isVertical ||
highlights[2].isVertical,
).toBeFalsy;
expect(
highlights[7].isVertical ||
highlights[8].isVertical ||
highlights[9].isVertical,
).toBeFalsy;
expect(highlights[0].posY).toEqual(FLEXBOX_PADDING);
expect(highlights[7].posY).toEqual(
highlights[0].posY +
(widgets["2"].bottomRow - widgets["2"].topRow) *
widgets["2"].parentRowSpace +
ROW_GAP -
offsetTop,
);
expect(highlights[0].layerIndex).toEqual(0);
expect(highlights[0].isNewLayer).toBeTruthy;
expect(highlights[7].layerIndex).toEqual(1);
expect(highlights[7].isNewLayer).toBeTruthy;
});
});
describe("test generateHighlightsForAlignment method", () => {
it("should add vertical highlights before every widget in the alignment, and at the end of the last widget", () => {
const children = [
{
widgetId: "2",
leftColumn: 0,
rightColumn: 16,
alignment: FlexLayerAlignment.Start,
topRow: 0,
bottomRow: 4,
type: "BUTTON_WIDGET",
widgetName: "Button1",
renderMode: RenderModes.CANVAS,
version: 1,
parentColumnSpace: 10,
parentRowSpace: 10,
isLoading: false,
mobileTopRow: 0,
mobileBottomRow: 4,
mobileLeftColumn: 0,
mobileRightColumn: 16,
responsiveBehavior: ResponsiveBehavior.Hug,
parentId: "1",
},
];
const result: HighlightInfo[] = generateHighlightsForAlignment({
arr: children,
childCount: 0,
layerIndex: 0,
alignment: FlexLayerAlignment.Start,
maxHeight: 40,
offsetTop: 4,
parentColumnSpace: 10,
avoidInitialHighlight: false,
isMobile: false,
startPosition: 0,
canvasId: "1",
});
expect(result.length).toEqual(2);
expect(result[0].posX).toEqual(2);
expect(result[0].posY).toEqual(4);
expect(result[0].width).toEqual(4);
expect(result[0].height).toEqual(
getWidgetHeight(children[0], false) * children[0].parentRowSpace,
);
expect(result[1].posX).toEqual(
children[0].rightColumn * children[0].parentColumnSpace +
FLEXBOX_PADDING / 2,
);
expect(result[1].isNewLayer).toBeFalsy;
expect(result[1].isVertical).toBeTruthy;
expect(result[1].layerIndex).toEqual(0);
});
it("should create vertical highlights as tall as the tallest child in the row", () => {
const children = [
{
widgetId: "2",
leftColumn: 0,
rightColumn: 16,
alignment: FlexLayerAlignment.Start,
topRow: 0,
bottomRow: 4,
type: "BUTTON_WIDGET",
widgetName: "Button1",
renderMode: RenderModes.CANVAS,
version: 1,
parentColumnSpace: 10,
parentRowSpace: 10,
isLoading: false,
mobileTopRow: 0,
mobileBottomRow: 4,
mobileLeftColumn: 0,
mobileRightColumn: 16,
responsiveBehavior: ResponsiveBehavior.Hug,
parentId: "1",
},
{
widgetId: "3",
leftColumn: 0,
rightColumn: 16,
alignment: FlexLayerAlignment.Start,
topRow: 0,
bottomRow: 6,
type: "BUTTON_WIDGET",
widgetName: "Button2",
renderMode: RenderModes.CANVAS,
version: 1,
parentColumnSpace: 10,
parentRowSpace: 10,
isLoading: false,
mobileTopRow: 0,
mobileBottomRow: 6,
mobileLeftColumn: 0,
mobileRightColumn: 16,
responsiveBehavior: ResponsiveBehavior.Hug,
parentId: "1",
},
];
const result: HighlightInfo[] = generateHighlightsForAlignment({
arr: children,
childCount: 0,
layerIndex: 0,
alignment: FlexLayerAlignment.Start,
maxHeight:
getWidgetHeight(children[1], false) * children[1].parentRowSpace,
offsetTop: 4,
parentColumnSpace: 10,
avoidInitialHighlight: false,
isMobile: false,
startPosition: 0,
canvasId: "1",
});
expect(result.length).toEqual(3);
expect(result[0].height).toEqual(
getWidgetHeight(children[1], false) * children[1].parentRowSpace,
);
});
it("should not render initial highlight is avoidInitialHighlight is true", () => {
const result: HighlightInfo[] = generateHighlightsForAlignment({
arr: [],
childCount: 0,
layerIndex: 0,
alignment: FlexLayerAlignment.Start,
maxHeight: 40,
offsetTop: 4,
parentColumnSpace: 10,
avoidInitialHighlight: true,
isMobile: false,
startPosition: 0,
canvasId: "1",
});
expect(result.length).toEqual(0);
});
});
describe("test generateVerticalHighlights method", () => {
it("should not render initial highlight for an empty center alignment if one of the other alignments are encroaching its space", () => {
const widgets = {
"1": {
widgetId: "1",
leftColumn: 0,
rightColumn: 64,
alignment: FlexLayerAlignment.Start,
topRow: 0,
bottomRow: 70,
type: "CANVAS_WIDGET",
widgetName: "Canvas1",
renderMode: RenderModes.CANVAS,
version: 1,
parentColumnSpace: 1,
parentRowSpace: 1,
isLoading: false,
mobileTopRow: 0,
mobileBottomRow: 70,
mobileLeftColumn: 0,
mobileRightColumn: 640,
responsiveBehavior: ResponsiveBehavior.Fill,
parentId: "",
flexLayers: [
{
children: [
{ id: "2", align: FlexLayerAlignment.Start },
{ id: "3", align: FlexLayerAlignment.Start },
],
},
],
children: ["2", "3"],
},
"2": {
widgetId: "2",
leftColumn: 0,
rightColumn: 16,
alignment: FlexLayerAlignment.Start,
topRow: 0,
bottomRow: 4,
type: "BUTTON_WIDGET",
widgetName: "Button1",
renderMode: RenderModes.CANVAS,
version: 1,
parentColumnSpace: 10,
parentRowSpace: 10,
isLoading: false,
mobileTopRow: 0,
mobileBottomRow: 4,
mobileLeftColumn: 0,
mobileRightColumn: 16,
responsiveBehavior: ResponsiveBehavior.Hug,
parentId: "1",
},
"3": {
widgetId: "3",
leftColumn: 16,
rightColumn: 26,
alignment: FlexLayerAlignment.Start,
topRow: 0,
bottomRow: 6,
type: "BUTTON_WIDGET",
widgetName: "Button2",
renderMode: RenderModes.CANVAS,
version: 1,
parentColumnSpace: 10,
parentRowSpace: 10,
isLoading: false,
mobileTopRow: 0,
mobileBottomRow: 6,
mobileLeftColumn: 16,
mobileRightColumn: 26,
responsiveBehavior: ResponsiveBehavior.Hug,
parentId: "1",
},
};
const result: VerticalHighlightsPayload = generateVerticalHighlights({
widgets,
layer: widgets["1"].flexLayers[0],
childCount: 0,
layerIndex: 0,
offsetTop: 4,
canvasId: "1",
columnSpace: 10,
draggedWidgets: [],
isMobile: false,
});
expect(result.highlights.length).toEqual(4);
expect(result.childCount).toEqual(2);
});
it("should not render highlights for flex wrapped alignments that span multiple rows", () => {
const widgets = {
"1": {
widgetId: "1",
leftColumn: 0,
rightColumn: 64,
alignment: FlexLayerAlignment.Start,
topRow: 0,
bottomRow: 70,
type: "CANVAS_WIDGET",
widgetName: "Canvas1",
renderMode: RenderModes.CANVAS,
version: 1,
parentColumnSpace: 1,
parentRowSpace: 1,
isLoading: false,
mobileTopRow: 0,
mobileBottomRow: 70,
mobileLeftColumn: 0,
mobileRightColumn: 640,
responsiveBehavior: ResponsiveBehavior.Fill,
parentId: "",
flexLayers: [
{
children: [
{ id: "2", align: FlexLayerAlignment.Start },
{ id: "3", align: FlexLayerAlignment.Start },
],
},
],
children: ["2", "3"],
},
"2": {
widgetId: "2",
leftColumn: 0,
rightColumn: 16,
alignment: FlexLayerAlignment.Start,
topRow: 0,
bottomRow: 4,
type: "BUTTON_WIDGET",
widgetName: "Button1",
renderMode: RenderModes.CANVAS,
version: 1,
parentColumnSpace: 10,
parentRowSpace: 10,
isLoading: false,
mobileTopRow: 0,
mobileBottomRow: 4,
mobileLeftColumn: 0,
mobileRightColumn: 16,
responsiveBehavior: ResponsiveBehavior.Hug,
parentId: "1",
},
"3": {
widgetId: "3",
leftColumn: 16,
rightColumn: 64,
alignment: FlexLayerAlignment.Start,
topRow: 0,
bottomRow: 6,
type: "INPUT_WIDGET",
widgetName: "Button2",
renderMode: RenderModes.CANVAS,
version: 1,
parentColumnSpace: 10,
parentRowSpace: 10,
isLoading: false,
mobileTopRow: 4,
mobileBottomRow: 10,
mobileLeftColumn: 0,
mobileRightColumn: 64,
responsiveBehavior: ResponsiveBehavior.Fill,
parentId: "1",
},
};
const result: VerticalHighlightsPayload = generateVerticalHighlights({
widgets,
layer: widgets["1"].flexLayers[0],
childCount: 0,
layerIndex: 0,
offsetTop: 4,
canvasId: "1",
columnSpace: 9.875,
draggedWidgets: [],
isMobile: true,
});
expect(result.highlights.length).toEqual(3);
expect(result.highlights[1].posY).toEqual(
widgets["3"].mobileTopRow * widgets["3"].parentRowSpace +
FLEXBOX_PADDING,
);
expect(result.highlights[1].height).toEqual(60);
expect(result.highlights[2].posX).toEqual(634);
expect(result.highlights[2].posY).toEqual(
widgets["3"].mobileTopRow * widgets["3"].parentRowSpace +
FLEXBOX_PADDING,
);
expect(result.childCount).toEqual(2);
});
});
});
|
266 | 0 | petrpan-code/appsmithorg/appsmith/app/client/src/layoutSystems/autolayout | petrpan-code/appsmithorg/appsmith/app/client/src/layoutSystems/autolayout/utils/positionUtils.test.ts | import {
FlexLayerAlignment,
Positioning,
ResponsiveBehavior,
} from "layoutSystems/common/utils/constants";
import type { AlignmentInfo, Row } from "../../autolayout/utils/types";
import { RenderModes } from "constants/WidgetConstants";
import type { CanvasWidgetsReduxState } from "reducers/entityReducers/canvasWidgetsReducer";
import {
extractAlignmentInfo,
getAlignmentSizeInfo,
getStartingPosition,
getWrappedAlignmentInfo,
getWrappedRows,
placeWidgetsWithoutWrap,
placeWrappedWidgets,
updateWidgetPositions,
} from "./positionUtils";
import { LayoutSystemTypes } from "layoutSystems/types";
import { LabelPosition } from "components/constants";
import * as utils from "./flexWidgetUtils";
import type { FlexLayer } from "./types";
describe("test PositionUtils methods", () => {
const mainCanvasWidth = 960;
describe("test extractAlignmentInfo method", () => {
it("should extract children and required columns for each alignment", () => {
const widgets = {
"1": {
widgetId: "1",
leftColumn: 0,
rightColumn: 16,
alignment: FlexLayerAlignment.Start,
topRow: 0,
bottomRow: 4,
type: "",
widgetName: "",
renderMode: RenderModes.CANVAS,
version: 1,
parentColumnSpace: 10,
parentRowSpace: 10,
isLoading: false,
},
"2": {
widgetId: "2",
leftColumn: 16,
rightColumn: 40,
alignment: FlexLayerAlignment.Start,
topRow: 0,
bottomRow: 7,
type: "",
widgetName: "",
renderMode: RenderModes.CANVAS,
version: 1,
parentColumnSpace: 10,
parentRowSpace: 10,
isLoading: false,
},
"3": {
widgetId: "3",
leftColumn: 48,
rightColumn: 64,
alignment: FlexLayerAlignment.End,
topRow: 0,
bottomRow: 7,
type: "",
widgetName: "",
renderMode: RenderModes.CANVAS,
version: 1,
parentColumnSpace: 10,
parentRowSpace: 10,
isLoading: false,
},
};
const layer: FlexLayer = {
children: [
{ id: "1", align: FlexLayerAlignment.Start },
{ id: "2", align: FlexLayerAlignment.Start },
{ id: "3", align: FlexLayerAlignment.End },
],
};
expect(extractAlignmentInfo(widgets, layer, false, 64, 1, false)).toEqual(
{
info: [
{
alignment: FlexLayerAlignment.Start,
columns: 40,
children: [
{ widget: widgets["1"], columns: 16, rows: 4 },
{ widget: widgets["2"], columns: 24, rows: 7 },
],
},
{
alignment: FlexLayerAlignment.Center,
columns: 0,
children: [],
},
{
alignment: FlexLayerAlignment.End,
columns: 16,
children: [{ widget: widgets["3"], columns: 16, rows: 7 }],
},
],
fillWidgetLength: 64,
},
);
});
it("should calculate columns for fill widgets", () => {
const widgets = {
"1": {
widgetId: "1",
leftColumn: 0,
rightColumn: 16,
alignment: FlexLayerAlignment.Start,
topRow: 0,
bottomRow: 4,
type: "",
widgetName: "",
renderMode: RenderModes.CANVAS,
version: 1,
parentColumnSpace: 10,
parentRowSpace: 10,
isLoading: false,
responsiveBehavior: ResponsiveBehavior.Hug,
},
"2": {
widgetId: "2",
leftColumn: 16,
rightColumn: 64,
alignment: FlexLayerAlignment.Start,
topRow: 0,
bottomRow: 7,
type: "",
widgetName: "",
renderMode: RenderModes.CANVAS,
version: 1,
parentColumnSpace: 10,
parentRowSpace: 10,
isLoading: false,
responsiveBehavior: ResponsiveBehavior.Fill,
},
"3": {
widgetId: "3",
leftColumn: 48,
rightColumn: 64,
alignment: FlexLayerAlignment.End,
topRow: 0,
bottomRow: 7,
type: "",
widgetName: "",
renderMode: RenderModes.CANVAS,
version: 1,
parentColumnSpace: 10,
parentRowSpace: 10,
isLoading: false,
responsiveBehavior: ResponsiveBehavior.Fill,
},
};
const layer: FlexLayer = {
children: [
{ id: "1", align: FlexLayerAlignment.Start },
{ id: "2", align: FlexLayerAlignment.Start },
{ id: "3", align: FlexLayerAlignment.End },
],
};
expect(
extractAlignmentInfo(widgets, layer, false, 64, 1, false)
.fillWidgetLength,
).toEqual(24);
});
it("should assign 64 columns to each fill widget on mobile viewport", () => {
const widgets = {
"1": {
widgetId: "1",
leftColumn: 0,
rightColumn: 16,
alignment: FlexLayerAlignment.Start,
topRow: 0,
bottomRow: 4,
type: "",
widgetName: "",
renderMode: RenderModes.CANVAS,
version: 1,
parentColumnSpace: 10,
parentRowSpace: 10,
isLoading: false,
responsiveBehavior: ResponsiveBehavior.Fill,
},
"2": {
widgetId: "2",
leftColumn: 16,
rightColumn: 64,
alignment: FlexLayerAlignment.Start,
topRow: 0,
bottomRow: 7,
type: "",
widgetName: "",
renderMode: RenderModes.CANVAS,
version: 1,
parentColumnSpace: 10,
parentRowSpace: 10,
isLoading: false,
responsiveBehavior: ResponsiveBehavior.Fill,
},
"3": {
widgetId: "3",
leftColumn: 48,
rightColumn: 64,
alignment: FlexLayerAlignment.End,
topRow: 0,
bottomRow: 7,
type: "",
widgetName: "",
renderMode: RenderModes.CANVAS,
version: 1,
parentColumnSpace: 10,
parentRowSpace: 10,
isLoading: false,
responsiveBehavior: ResponsiveBehavior.Fill,
},
};
const layer: FlexLayer = {
children: [
{ id: "1", align: FlexLayerAlignment.Start },
{ id: "2", align: FlexLayerAlignment.Start },
{ id: "3", align: FlexLayerAlignment.End },
],
};
const { fillWidgetLength, info } = extractAlignmentInfo(
widgets,
layer,
true,
64,
1,
true,
);
expect(fillWidgetLength).toEqual(64);
expect(info[0].columns).toEqual(128);
});
it("should allocate columns for fill widgets that match min widths if enough space is unavailable", () => {
const widgets = {
"1": {
widgetId: "1",
leftColumn: 0,
rightColumn: 32,
alignment: FlexLayerAlignment.Start,
topRow: 0,
bottomRow: 4,
type: "DOCUMENT_VIEWER_WIDGET",
widgetName: "",
renderMode: RenderModes.CANVAS,
version: 1,
parentColumnSpace: 10,
parentRowSpace: 10,
isLoading: false,
responsiveBehavior: ResponsiveBehavior.Hug,
autoLayout: {
widgetSize: [
{
viewportMinWidth: 0,
configuration: () => {
return {
minWidth: "280px",
minHeight: "280px",
};
},
},
],
},
},
"2": {
widgetId: "2",
leftColumn: 32,
rightColumn: 64,
alignment: FlexLayerAlignment.Start,
topRow: 0,
bottomRow: 7,
type: "CURRENCY_INPUT_WIDGET",
widgetName: "Currency1",
renderMode: RenderModes.CANVAS,
version: 1,
parentColumnSpace: 10,
parentRowSpace: 10,
isLoading: false,
responsiveBehavior: ResponsiveBehavior.Fill,
autoLayout: {
disabledPropsDefaults: {
labelPosition: LabelPosition.Top,
labelTextSize: "0.875rem",
},
defaults: {
rows: 6.6,
},
autoDimension: {
height: true,
},
widgetSize: [
{
viewportMinWidth: 0,
configuration: () => {
return {
minWidth: "120px",
};
},
},
],
disableResizeHandles: {
vertical: true,
},
},
},
"3": {
widgetId: "3",
leftColumn: 64,
rightColumn: 96,
alignment: FlexLayerAlignment.End,
topRow: 0,
bottomRow: 7,
type: "CONTAINER_WIDGET",
widgetName: "Container1",
renderMode: RenderModes.CANVAS,
version: 1,
parentColumnSpace: 10,
parentRowSpace: 10,
isLoading: false,
responsiveBehavior: ResponsiveBehavior.Fill,
},
};
jest
.spyOn(utils, "getWidgetMinMaxDimensionsInPixel")
// eslint-disable-next-line @typescript-eslint/no-unused-vars
.mockImplementation((widget: any, width: number) => {
if (
["DOCUMENT_VIEWER_WIDGET", "CONTAINER_WIDGET"].includes(
widget?.type,
)
)
return {
minWidth: 280,
minHeight: 280,
maxWidth: undefined,
maxHeight: undefined,
};
if (widget?.type === "CURRENCY_INPUT_WIDGET")
return {
minWidth: 120,
minHeight: 40,
maxWidth: undefined,
maxHeight: undefined,
};
return {
minWidth: undefined,
minHeight: undefined,
maxWidth: undefined,
maxHeight: undefined,
};
});
const layer: FlexLayer = {
children: [
{ id: "1", align: FlexLayerAlignment.Start },
{ id: "2", align: FlexLayerAlignment.Start },
{ id: "3", align: FlexLayerAlignment.End },
],
};
const result = extractAlignmentInfo(widgets, layer, false, 600, 1, false);
/**
* Canvas width = 600
* # of fill widgets = 3
* standard fill widget length (f) = 600 / 3 = 200
* min widths in descending order -> 280, 280, 120.
*
* In descending order of min widths:
* available space: 600
* 1st fill widget length (DocumentViewer) -> 280 > 200 -> 280
* available space: 600 - 280 = 320
* standard fill widget length (f) = 320 / 2 = 160
*
* 2nd fill widget length (ContainerWidget) -> 280 > 160 -> 280
* available space: 320 - 280 = 40
* standard fill widget length (f) = 40 / 1 = 40
*
* 3rd fill widget length (CurrencyInput) -> 120 > 40 -> 120
*
* => widgets will overflow the canvas.
*/
// DocumnetViewer + CurrencyInput
expect(result.info[0].columns).toEqual(280 + 120);
// ContainerWidget
expect(result.info[2].columns).toEqual(280);
});
});
describe("test getAlignmentSizeinfo method", () => {
it("should distribute the space evenly across alignments if they don't need more than their equal share", () => {
const arr: AlignmentInfo[] = [
{ alignment: FlexLayerAlignment.Start, columns: 0, children: [] },
{ alignment: FlexLayerAlignment.Center, columns: 0, children: [] },
{ alignment: FlexLayerAlignment.End, columns: 0, children: [] },
];
const { centerSize, endSize, startSize } = getAlignmentSizeInfo(arr);
expect(startSize).toEqual(endSize);
expect(startSize).toEqual(centerSize);
});
it("should distribute the space evenly across alignments if 1) they don't need more than their equal share, and 2) there are fewer than three alignments in the layer", () => {
const arr: AlignmentInfo[] = [
{ alignment: FlexLayerAlignment.Center, columns: 0, children: [] },
{ alignment: FlexLayerAlignment.End, columns: 0, children: [] },
];
const { centerSize, endSize, startSize } = getAlignmentSizeInfo(arr);
expect(startSize).toEqual(0);
expect(endSize).toEqual(32);
expect(endSize).toEqual(centerSize);
});
it("should assign appropriate columns to an alignment that needs more space, and distribute the remaining space evenly amongst the other alignments", () => {
const arr: AlignmentInfo[] = [
{ alignment: FlexLayerAlignment.Start, columns: 40, children: [] },
{ alignment: FlexLayerAlignment.Center, columns: 0, children: [] },
{ alignment: FlexLayerAlignment.End, columns: 0, children: [] },
];
const { centerSize, endSize, startSize } = getAlignmentSizeInfo(arr);
expect(startSize).toEqual(40);
expect(endSize).toEqual(12);
expect(endSize).toEqual(centerSize);
});
});
describe("test getWrappedAlignmentInfo method", () => {
it("should place all alignments in a single row if combined column requirement <= 64", () => {
const arr: AlignmentInfo[] = [
{ alignment: FlexLayerAlignment.Start, columns: 16, children: [] },
{ alignment: FlexLayerAlignment.Center, columns: 20, children: [] },
{ alignment: FlexLayerAlignment.End, columns: 26, children: [] },
];
const rows: AlignmentInfo[][] = getWrappedAlignmentInfo(arr);
expect(rows.length).toEqual(3);
expect(rows[0].length).toEqual(3);
expect(rows.filter((row) => !row.length).length).toEqual(2);
expect(rows[0]).toEqual(arr);
});
it("should wrap an alignment requiring > 64 columns in a separate row", () => {
const arr: AlignmentInfo[] = [
{ alignment: FlexLayerAlignment.Start, columns: 80, children: [] },
{ alignment: FlexLayerAlignment.Center, columns: 20, children: [] },
{ alignment: FlexLayerAlignment.End, columns: 26, children: [] },
];
const rows: AlignmentInfo[][] = getWrappedAlignmentInfo(arr);
expect(rows.length).toEqual(3);
expect(rows[0].length).toEqual(1);
expect(rows[1].length).toEqual(2);
expect(rows.filter((row) => !row.length).length).toEqual(1);
expect(rows[0]).toEqual([arr[0]]);
expect(rows[1]).toEqual([arr[1], arr[2]]);
});
it("should wrap alignments into multiple rows if combined columns requirement > 64", () => {
const arr: AlignmentInfo[] = [
{ alignment: FlexLayerAlignment.Start, columns: 30, children: [] },
{ alignment: FlexLayerAlignment.Center, columns: 40, children: [] },
{ alignment: FlexLayerAlignment.End, columns: 10, children: [] },
];
const rows: AlignmentInfo[][] = getWrappedAlignmentInfo(arr);
expect(rows.length).toEqual(3);
expect(rows[0].length).toEqual(1);
expect(rows[1].length).toEqual(2);
expect(rows.filter((row) => !row.length).length).toEqual(1);
expect(rows[0]).toEqual([arr[0]]);
expect(rows[1]).toEqual([arr[1], arr[2]]);
});
});
describe("test getStartingPosition method", () => {
it("should return 0 as the starting position for FlexLayerAlignment.Start", () => {
expect(
getStartingPosition(FlexLayerAlignment.Start, 21.3, 21.3, 21.3, 16),
).toEqual(0);
});
it("should return valid starting position for FlexLayerAlignment.Center", () => {
expect(
getStartingPosition(FlexLayerAlignment.Center, 20, 24, 20, 16),
).toEqual(24);
});
it("should return valid starting position for FlexLayerAlignment.End", () => {
expect(
getStartingPosition(FlexLayerAlignment.End, 20, 24, 20, 16),
).toEqual(48);
});
});
describe("test getWrappedRows method", () => {
it("should segregate an alignment's children into multiple rows if combined column requirement > 64", () => {
const arr: AlignmentInfo = {
alignment: FlexLayerAlignment.Start,
columns: 80,
children: [
{
widget: {
widgetId: "1",
leftColumn: 0,
rightColumn: 16,
alignment: FlexLayerAlignment.Start,
topRow: 0,
bottomRow: 4,
type: "",
widgetName: "",
renderMode: RenderModes.CANVAS,
version: 1,
parentColumnSpace: 10,
parentRowSpace: 10,
isLoading: false,
mobileTopRow: 0,
mobileBottomRow: 4,
mobileLeftColumn: 0,
mobileRightColumn: 16,
responsiveBehavior: ResponsiveBehavior.Hug,
},
columns: 16,
rows: 4,
},
{
widget: {
widgetId: "2",
leftColumn: 16,
rightColumn: 64,
alignment: FlexLayerAlignment.Start,
topRow: 0,
bottomRow: 7,
type: "",
widgetName: "",
renderMode: RenderModes.CANVAS,
version: 1,
parentColumnSpace: 10,
parentRowSpace: 10,
isLoading: false,
mobileTopRow: 0,
mobileBottomRow: 7,
mobileLeftColumn: 16,
mobileRightColumn: 80,
responsiveBehavior: ResponsiveBehavior.Fill,
},
columns: 64,
rows: 7,
},
],
};
const rows: Row[] = getWrappedRows(arr, [], true);
expect(rows.length).toEqual(2);
expect(rows[0]).toEqual({
alignment: arr.alignment,
columns: 16,
children: [arr.children[0]],
height: 4,
});
expect(rows[1]).toEqual({
alignment: arr.alignment,
columns: 64,
children: [arr.children[1]],
height: 7,
});
});
});
describe("test placeWidgetsWithoutWrap method", () => {
it("should update positions of widgets - part 1", () => {
const widgets = {
"1": {
widgetId: "1",
leftColumn: 0,
rightColumn: 16,
alignment: FlexLayerAlignment.Start,
topRow: 0,
bottomRow: 4,
type: "",
widgetName: "",
renderMode: RenderModes.CANVAS,
version: 1,
parentColumnSpace: 10,
parentRowSpace: 10,
isLoading: false,
},
"2": {
widgetId: "2",
leftColumn: 0,
rightColumn: 24,
alignment: FlexLayerAlignment.Start,
topRow: 0,
bottomRow: 7,
type: "",
widgetName: "",
renderMode: RenderModes.CANVAS,
version: 1,
parentColumnSpace: 10,
parentRowSpace: 10,
isLoading: false,
},
"3": {
widgetId: "3",
leftColumn: 0,
rightColumn: 16,
alignment: FlexLayerAlignment.End,
topRow: 0,
bottomRow: 7,
type: "",
widgetName: "",
renderMode: RenderModes.CANVAS,
version: 1,
parentColumnSpace: 10,
parentRowSpace: 10,
isLoading: false,
},
};
const arr: AlignmentInfo[] = [
{
alignment: FlexLayerAlignment.Start,
columns: 40,
children: [
{ widget: widgets["1"], columns: 16, rows: 4 },
{ widget: widgets["2"], columns: 24, rows: 7 },
],
},
{
alignment: FlexLayerAlignment.Center,
columns: 0,
children: [],
},
{
alignment: FlexLayerAlignment.End,
columns: 16,
children: [{ widget: widgets["3"], columns: 16, rows: 7 }],
},
];
const result: {
height: number;
widgets: CanvasWidgetsReduxState;
} = placeWidgetsWithoutWrap(widgets, arr, 0, false, 0);
expect(result.height).toEqual(7);
expect(result.widgets["2"].leftColumn).toEqual(16);
expect(result.widgets["2"].rightColumn).toEqual(40);
expect(result.widgets["3"].leftColumn).toEqual(48);
expect(result.widgets["3"].rightColumn).toEqual(64);
});
it("should update positions of widgets - part 2", () => {
const widgets = {
"1": {
widgetId: "1",
leftColumn: 0,
rightColumn: 16,
alignment: FlexLayerAlignment.Center,
topRow: 0,
bottomRow: 4,
type: "",
widgetName: "",
renderMode: RenderModes.CANVAS,
version: 1,
parentColumnSpace: 10,
parentRowSpace: 10,
isLoading: false,
},
"2": {
widgetId: "2",
leftColumn: 0,
rightColumn: 24,
alignment: FlexLayerAlignment.End,
topRow: 0,
bottomRow: 7,
type: "",
widgetName: "",
renderMode: RenderModes.CANVAS,
version: 1,
parentColumnSpace: 10,
parentRowSpace: 10,
isLoading: false,
},
"3": {
widgetId: "3",
leftColumn: 0,
rightColumn: 16,
alignment: FlexLayerAlignment.End,
topRow: 0,
bottomRow: 7,
type: "",
widgetName: "",
renderMode: RenderModes.CANVAS,
version: 1,
parentColumnSpace: 10,
parentRowSpace: 10,
isLoading: false,
},
};
const arr: AlignmentInfo[] = [
{
alignment: FlexLayerAlignment.Start,
columns: 0,
children: [],
},
{
alignment: FlexLayerAlignment.Center,
columns: 16,
children: [{ widget: widgets["1"], columns: 16, rows: 4 }],
},
{
alignment: FlexLayerAlignment.End,
columns: 40,
children: [
{ widget: widgets["2"], columns: 24, rows: 7 },
{ widget: widgets["3"], columns: 16, rows: 7 },
],
},
];
const result: {
height: number;
widgets: CanvasWidgetsReduxState;
} = placeWidgetsWithoutWrap(widgets, arr, 0, false, 0);
expect(result.height).toEqual(7);
expect(result.widgets["1"].leftColumn).toEqual(8);
expect(result.widgets["1"].rightColumn).toEqual(24);
expect(result.widgets["2"].leftColumn).toEqual(24);
expect(result.widgets["2"].rightColumn).toEqual(48);
expect(result.widgets["3"].leftColumn).toEqual(48);
expect(result.widgets["3"].rightColumn).toEqual(64);
});
it("should update positions of widgets - part 3", () => {
const widgets = {
"1": {
widgetId: "1",
leftColumn: 0,
rightColumn: 16,
alignment: FlexLayerAlignment.Center,
topRow: 0,
bottomRow: 4,
type: "",
widgetName: "",
renderMode: RenderModes.CANVAS,
version: 1,
parentColumnSpace: 10,
parentRowSpace: 10,
isLoading: false,
mobileTopRow: 0,
mobileBottomRow: 4,
mobileLeftColumn: 0,
mobileRightColumn: 16,
responsiveBehavior: ResponsiveBehavior.Hug,
},
"2": {
widgetId: "2",
leftColumn: 0,
rightColumn: 24,
alignment: FlexLayerAlignment.End,
topRow: 0,
bottomRow: 7,
type: "",
widgetName: "",
renderMode: RenderModes.CANVAS,
version: 1,
parentColumnSpace: 10,
parentRowSpace: 10,
isLoading: false,
mobileTopRow: 0,
mobileBottomRow: 7,
mobileLeftColumn: 0,
mobileRightColumn: 24,
responsiveBehavior: ResponsiveBehavior.Hug,
},
"3": {
widgetId: "3",
leftColumn: 0,
rightColumn: 16,
alignment: FlexLayerAlignment.End,
topRow: 0,
bottomRow: 7,
type: "",
widgetName: "",
renderMode: RenderModes.CANVAS,
version: 1,
parentColumnSpace: 10,
parentRowSpace: 10,
isLoading: false,
mobileTopRow: 0,
mobileBottomRow: 7,
mobileLeftColumn: 0,
mobileRightColumn: 16,
responsiveBehavior: ResponsiveBehavior.Hug,
},
};
const arr: AlignmentInfo[] = [
{
alignment: FlexLayerAlignment.Start,
columns: 0,
children: [],
},
{
alignment: FlexLayerAlignment.Center,
columns: 16,
children: [{ widget: widgets["1"], columns: 16, rows: 4 }],
},
{
alignment: FlexLayerAlignment.End,
columns: 40,
children: [
{ widget: widgets["2"], columns: 24, rows: 7 },
{ widget: widgets["3"], columns: 16, rows: 7 },
],
},
];
const result: {
height: number;
widgets: CanvasWidgetsReduxState;
} = placeWidgetsWithoutWrap(widgets, arr, 0, true, 0);
expect(result.height).toEqual(7);
expect(result.widgets["1"].mobileLeftColumn).toEqual(8);
expect(result.widgets["1"].mobileRightColumn).toEqual(24);
expect(result.widgets["2"].mobileLeftColumn).toEqual(24);
expect(result.widgets["2"].mobileRightColumn).toEqual(48);
expect(result.widgets["3"].mobileLeftColumn).toEqual(48);
expect(result.widgets["3"].mobileRightColumn).toEqual(64);
});
it("should allocate columns for fill widgets in descending order of their min width requirement", () => {
const widgets = {
"1": {
widgetId: "1",
leftColumn: 0,
rightColumn: 32,
alignment: FlexLayerAlignment.Start,
topRow: 0,
bottomRow: 4,
type: "DOCUMENT_VIEWER_WIDGET",
widgetName: "",
renderMode: RenderModes.CANVAS,
version: 1,
parentColumnSpace: 10,
parentRowSpace: 10,
isLoading: false,
responsiveBehavior: ResponsiveBehavior.Fill,
autoLayout: {
widgetSize: [
{
viewportMinWidth: 0,
configuration: () => {
return {
minWidth: "280px",
minHeight: "280px",
};
},
},
],
},
},
"2": {
widgetId: "2",
leftColumn: 32,
rightColumn: 64,
alignment: FlexLayerAlignment.Start,
topRow: 0,
bottomRow: 7,
type: "CURRENCY_INPUT_WIDGET",
widgetName: "Currency1",
renderMode: RenderModes.CANVAS,
version: 1,
parentColumnSpace: 10,
parentRowSpace: 10,
isLoading: false,
responsiveBehavior: ResponsiveBehavior.Fill,
autoLayout: {
disabledPropsDefaults: {
labelPosition: LabelPosition.Top,
labelTextSize: "0.875rem",
},
defaults: {
rows: 6.6,
},
autoDimension: {
height: true,
},
widgetSize: [
{
viewportMinWidth: 0,
configuration: () => {
return {
minWidth: "120px",
};
},
},
],
disableResizeHandles: {
vertical: true,
},
},
},
"3": {
widgetId: "3",
leftColumn: 64,
rightColumn: 96,
alignment: FlexLayerAlignment.End,
topRow: 0,
bottomRow: 7,
type: "CONTAINER_WIDGET",
widgetName: "Container1",
renderMode: RenderModes.CANVAS,
version: 1,
parentColumnSpace: 10,
parentRowSpace: 10,
isLoading: false,
responsiveBehavior: ResponsiveBehavior.Fill,
},
};
jest
.spyOn(utils, "getWidgetMinMaxDimensionsInPixel")
// eslint-disable-next-line @typescript-eslint/no-unused-vars
.mockImplementation((widget: any, width: number) => {
if (
["DOCUMENT_VIEWER_WIDGET", "CONTAINER_WIDGET"].includes(
widget?.type,
)
)
return {
minWidth: 280,
minHeight: 280,
maxWidth: undefined,
maxHeight: undefined,
};
if (widget?.type === "CURRENCY_INPUT_WIDGET")
return {
minWidth: 120,
minHeight: 40,
maxWidth: undefined,
maxHeight: undefined,
};
return {
minWidth: undefined,
minHeight: undefined,
maxWidth: undefined,
maxHeight: undefined,
};
});
const layer: FlexLayer = {
children: [
{ id: "1", align: FlexLayerAlignment.Start },
{ id: "2", align: FlexLayerAlignment.Start },
{ id: "3", align: FlexLayerAlignment.End },
],
};
const alignmentInfo = extractAlignmentInfo(
widgets,
layer,
false,
640,
10,
false,
);
const res = placeWidgetsWithoutWrap(
widgets,
alignmentInfo.info,
0,
false,
);
/**
* available columns: 64
* column space: 10
* # of fill widgets = 3
* standard fill widget length (f) = 64 / 3 = 21.3333
* min widths in descending order -> 28 (minWidth / columnSpace), 28, 12.
*
* In descending order of min widths:
* available columns: 64
* 1st fill widget length (DocumentViewer) -> 28 > 21.3333 -> 28
* available columns: 64 - 28 = 36
* standard fill widget length (f) = 36 / 2 = 18
*
* 2nd fill widget length (ContainerWidget) -> 28 > 18 -> 28
* available columns: 36 - 28 = 8
* standard fill widget length (f) = 8 / 1 = 8
*
* 3rd fill widget length (CurrencyInput) -> 12 > 8 -> 12
*
* => widgets will overflow the canvas.
* => min widths of each widget is respected.
*/
// DocumentViewer
expect(res.widgets["1"].leftColumn).toEqual(0);
expect(res.widgets["1"].rightColumn).toEqual(28);
// CurrencyInput
expect(res.widgets["2"].leftColumn).toEqual(28);
expect(res.widgets["2"].rightColumn).toEqual(40);
// ContainerWidget
expect(res.widgets["3"].leftColumn).toEqual(40);
expect(res.widgets["3"].rightColumn).toEqual(68);
});
it("should allocate columns for fill widgets in descending order of their min width requirement - Part 2", () => {
const widgets = {
"1": {
widgetId: "1",
leftColumn: 0,
rightColumn: 21.3333,
alignment: FlexLayerAlignment.Start,
topRow: 0,
bottomRow: 4,
type: "DOCUMENT_VIEWER_WIDGET",
widgetName: "",
renderMode: RenderModes.CANVAS,
version: 1,
parentColumnSpace: 10,
parentRowSpace: 10,
isLoading: false,
responsiveBehavior: ResponsiveBehavior.Fill,
},
"2": {
widgetId: "2",
leftColumn: 21.33333,
rightColumn: 42.66666,
alignment: FlexLayerAlignment.Start,
topRow: 0,
bottomRow: 7,
type: "CURRENCY_INPUT_WIDGET",
widgetName: "Currency1",
renderMode: RenderModes.CANVAS,
version: 1,
parentColumnSpace: 10,
parentRowSpace: 10,
isLoading: false,
responsiveBehavior: ResponsiveBehavior.Fill,
},
"3": {
widgetId: "3",
leftColumn: 42.66666,
rightColumn: 63.99999,
alignment: FlexLayerAlignment.Start,
topRow: 0,
bottomRow: 7,
type: "CURRENCY_INPUT_WIDGET",
widgetName: "Currency2",
renderMode: RenderModes.CANVAS,
version: 1,
parentColumnSpace: 10,
parentRowSpace: 10,
isLoading: false,
responsiveBehavior: ResponsiveBehavior.Fill,
},
};
jest
.spyOn(utils, "getWidgetMinMaxDimensionsInPixel")
// eslint-disable-next-line @typescript-eslint/no-unused-vars
.mockImplementation((widget: any, width: number) => {
if (
["DOCUMENT_VIEWER_WIDGET", "CONTAINER_WIDGET"].includes(
widget?.type,
)
)
return {
minWidth: 280,
minHeight: 280,
maxWidth: undefined,
maxHeight: undefined,
};
if (widget?.type === "CURRENCY_INPUT_WIDGET")
return {
minWidth: 120,
minHeight: 40,
maxWidth: undefined,
maxHeight: undefined,
};
return {
minWidth: undefined,
minHeight: undefined,
maxWidth: undefined,
maxHeight: undefined,
};
});
const layer: FlexLayer = {
children: [
{ id: "1", align: FlexLayerAlignment.Start },
{ id: "2", align: FlexLayerAlignment.Start },
{ id: "3", align: FlexLayerAlignment.End },
],
};
const alignmentInfo = extractAlignmentInfo(
widgets,
layer,
false,
640,
10,
false,
);
const res = placeWidgetsWithoutWrap(
widgets,
alignmentInfo.info,
0,
false,
);
/**
* total available columns = 64
* # of fill widgets = 3
* columnSpace = 10
* standard fill widget length (f) = 64 / 3 = 21.333
* min widths in descending order of columns -> 28 (280 / 10), 12, 12.
*
* In descending order of min widths:
* available columns: 64
* 1st fill widget length (DocumentViewer) -> 28 > 21.3333 -> 28
* available columns: 64 - 28 = 36
* standard fill widget length (f) = 36 / 2 = 18
*
* 2nd fill widget length (CurrencyInput) -> 12 < 18 -> 18
* available columns: 36 - 18 = 18
* standard fill widget length (f) = 18 / 1 = 18
*
* 3rd fill widget length (CurrencyInput) -> 12 < 18 -> 180
*
* => widgets don't overflow the canvas.
* => DocumentViewer gets more columns (28) to address its min width requirement.
* => rest of the space gets evenly distributed among the remaining fill widgets, as the it is larger than their min width requirement.
*/
// DocumentViewer
expect(res.widgets["1"].leftColumn).toEqual(0);
expect(res.widgets["1"].rightColumn).toEqual(28);
// CurrencyInput1
expect(res.widgets["2"].leftColumn).toEqual(28);
expect(res.widgets["2"].rightColumn).toEqual(46);
// CurrencyInput2
expect(res.widgets["3"].leftColumn).toEqual(46);
expect(res.widgets["3"].rightColumn).toEqual(64);
});
});
describe("test placeWrappedWidgets method", () => {
it("should update positions of widgets in a flex wrapped alignment", () => {
const widgets = {
"1": {
widgetId: "1",
leftColumn: 0,
rightColumn: 16,
alignment: FlexLayerAlignment.End,
topRow: 0,
bottomRow: 4,
type: "",
widgetName: "",
renderMode: RenderModes.CANVAS,
version: 1,
parentColumnSpace: 10,
parentRowSpace: 10,
isLoading: false,
mobileTopRow: 0,
mobileBottomRow: 4,
mobileLeftColumn: 0,
mobileRightColumn: 16,
responsiveBehavior: ResponsiveBehavior.Hug,
},
"2": {
widgetId: "2",
leftColumn: 0,
rightColumn: 64,
alignment: FlexLayerAlignment.End,
topRow: 0,
bottomRow: 7,
type: "",
widgetName: "",
renderMode: RenderModes.CANVAS,
version: 1,
parentColumnSpace: 10,
parentRowSpace: 10,
isLoading: false,
mobileTopRow: 0,
mobileBottomRow: 7,
mobileLeftColumn: 0,
mobileRightColumn: 64,
responsiveBehavior: ResponsiveBehavior.Fill,
},
"3": {
widgetId: "3",
leftColumn: 0,
rightColumn: 16,
alignment: FlexLayerAlignment.End,
topRow: 0,
bottomRow: 7,
type: "",
widgetName: "",
renderMode: RenderModes.CANVAS,
version: 1,
parentColumnSpace: 10,
parentRowSpace: 10,
isLoading: false,
mobileTopRow: 0,
mobileBottomRow: 7,
mobileLeftColumn: 0,
mobileRightColumn: 16,
responsiveBehavior: ResponsiveBehavior.Hug,
},
};
const result: {
height: number;
widgets: CanvasWidgetsReduxState;
} = placeWrappedWidgets(
widgets,
{
alignment: FlexLayerAlignment.End,
columns: 96,
children: [
{ widget: widgets["1"], columns: 16, rows: 4 },
{ widget: widgets["2"], columns: 64, rows: 7 },
{ widget: widgets["3"], columns: 16, rows: 7 },
],
},
0,
true,
);
expect(result.height).toEqual(18);
expect(result.widgets["1"].mobileLeftColumn).toEqual(48);
expect(result.widgets["1"].mobileRightColumn).toEqual(64);
expect(result.widgets["2"].mobileLeftColumn).toEqual(0);
expect(result.widgets["2"].mobileRightColumn).toEqual(64);
expect(result.widgets["2"].mobileTopRow).toEqual(4);
expect(result.widgets["2"].mobileBottomRow).toEqual(11);
expect(result.widgets["3"].mobileLeftColumn).toEqual(48);
expect(result.widgets["3"].mobileRightColumn).toEqual(64);
expect(result.widgets["3"].mobileTopRow).toEqual(11);
expect(result.widgets["3"].mobileBottomRow).toEqual(18);
});
});
describe("test updateWidgetPositions method", () => {
it("should update positions of widgets within a given parent", () => {
const widgets = {
"1": {
widgetId: "1",
leftColumn: 0,
rightColumn: 16,
alignment: FlexLayerAlignment.End,
topRow: 0,
bottomRow: 4,
type: "",
widgetName: "",
renderMode: RenderModes.CANVAS,
version: 1,
parentColumnSpace: 10,
parentRowSpace: 10,
isLoading: false,
mobileTopRow: 0,
mobileBottomRow: 4,
mobileLeftColumn: 0,
mobileRightColumn: 16,
responsiveBehavior: ResponsiveBehavior.Hug,
},
"2": {
widgetId: "2",
leftColumn: 0,
rightColumn: 24,
alignment: FlexLayerAlignment.End,
topRow: 0,
bottomRow: 7,
type: "",
widgetName: "",
renderMode: RenderModes.CANVAS,
version: 1,
parentColumnSpace: 10,
parentRowSpace: 10,
isLoading: false,
mobileTopRow: 0,
mobileBottomRow: 7,
mobileLeftColumn: 0,
mobileRightColumn: 24,
responsiveBehavior: ResponsiveBehavior.Hug,
},
"3": {
widgetId: "3",
leftColumn: 0,
rightColumn: 640,
alignment: FlexLayerAlignment.Start,
topRow: 0,
bottomRow: 70,
type: "CANVAS_WIDGET",
widgetName: "",
renderMode: RenderModes.CANVAS,
version: 1,
parentColumnSpace: 1,
parentRowSpace: 1,
isLoading: false,
mobileTopRow: 0,
mobileBottomRow: 70,
mobileLeftColumn: 0,
mobileRightColumn: 640,
responsiveBehavior: ResponsiveBehavior.Fill,
parentId: "0",
flexLayers: [
{
children: [
{ id: "1", align: FlexLayerAlignment.End },
{ id: "2", align: FlexLayerAlignment.End },
],
},
],
},
"0": {
widgetId: "0",
leftColumn: 0,
rightColumn: 64,
alignment: FlexLayerAlignment.Start,
topRow: 0,
bottomRow: 7,
type: "CANVAS_WIDGET",
widgetName: "",
renderMode: RenderModes.CANVAS,
version: 1,
parentColumnSpace: 10,
parentRowSpace: 10,
isLoading: false,
mobileTopRow: 0,
mobileBottomRow: 7,
mobileLeftColumn: 0,
mobileRightColumn: 64,
responsiveBehavior: ResponsiveBehavior.Fill,
parentId: "",
positioning: Positioning.Vertical,
layoutSystemType: LayoutSystemTypes.AUTO,
useAutoLayout: true,
flexLayers: [
{ children: [{ id: "3", align: FlexLayerAlignment.Start }] },
],
},
};
const result = updateWidgetPositions(
widgets,
"3",
false,
mainCanvasWidth,
);
expect(result["1"].leftColumn).toEqual(24);
expect(result["1"].rightColumn).toEqual(40);
expect(result["2"].leftColumn).toEqual(40);
expect(result["2"].rightColumn).toEqual(64);
});
});
});
|
281 | 0 | petrpan-code/appsmithorg/appsmith/app/client/src/layoutSystems/common/DSLConversions | petrpan-code/appsmithorg/appsmith/app/client/src/layoutSystems/common/DSLConversions/tests/autoToFixedLayout.test.ts | import type { CanvasWidgetsReduxState } from "reducers/entityReducers/canvasWidgetsReducer";
import { convertNormalizedDSLToFixed } from "../autoToFixedLayout";
describe("test Auto to Fixed Conversion methods", () => {
const autoLayoutWidgets = {
"0": {
widgetName: "MainContainer",
topRow: 0,
bottomRow: 870,
type: "CANVAS_WIDGET",
canExtend: true,
minHeight: 870,
useAutoLayout: true,
leftColumn: 0,
children: [
"3rp273r2sw",
"jej39vfb46",
"qwdu5rldu2",
"hrduq6qeyy",
"y8kkqs25a5",
"p6em4n29z7",
"jxob7zdb75",
"n123229jea",
"fhh2k44omh",
"m9mrywyvpj",
"8o21a70kqn",
],
positioning: "vertical",
direction: "Vertical",
rightColumn: 4896,
detachFromLayout: true,
widgetId: "0",
flexLayers: [
{
children: [
{
id: "3rp273r2sw",
align: "center",
},
],
},
{
children: [
{
id: "jej39vfb46",
align: "start",
},
{
id: "qwdu5rldu2",
align: "start",
},
{
id: "hrduq6qeyy",
align: "start",
},
{
id: "y8kkqs25a5",
align: "start",
},
],
},
{
children: [
{
id: "p6em4n29z7",
align: "start",
},
{
id: "jxob7zdb75",
align: "center",
},
],
},
{
children: [
{
id: "n123229jea",
align: "start",
},
{
id: "fhh2k44omh",
align: "end",
},
],
},
{
children: [
{
id: "m9mrywyvpj",
align: "start",
},
],
},
{
children: [
{
id: "8o21a70kqn",
align: "start",
},
],
},
],
responsiveBehavior: "fill",
},
"3rp273r2sw": {
widgetName: "Button3",
topRow: 0,
bottomRow: 4,
parentRowSpace: 10,
type: "BUTTON_WIDGET",
leftColumn: 24,
rightColumn: 40,
widgetId: "3rp273r2sw",
minWidth: 120,
parentId: "0",
responsiveBehavior: "hug",
alignment: "center",
flexVerticalAlignment: "start",
},
jej39vfb46: {
widgetName: "Button15",
topRow: 4,
bottomRow: 8,
type: "BUTTON_WIDGET",
leftColumn: 0,
rightColumn: 16,
widgetId: "jej39vfb46",
minWidth: 120,
responsiveBehavior: "hug",
alignment: "start",
flexVerticalAlignment: "start",
},
qwdu5rldu2: {
widgetName: "Button5",
topRow: 4,
bottomRow: 8,
parentRowSpace: 10,
type: "BUTTON_WIDGET",
leftColumn: 16,
rightColumn: 32,
widgetId: "qwdu5rldu2",
minWidth: 120,
parentId: "0",
responsiveBehavior: "hug",
alignment: "start",
flexVerticalAlignment: "start",
},
hrduq6qeyy: {
widgetName: "Input2",
topRow: 4,
bottomRow: 11,
type: "INPUT_WIDGET_V2",
leftColumn: 32,
rightColumn: 51,
widgetId: "hrduq6qeyy",
minWidth: 450,
parentId: "0",
responsiveBehavior: "fill",
alignment: "start",
flexVerticalAlignment: "start",
},
y8kkqs25a5: {
widgetName: "Button4",
topRow: 4,
bottomRow: 8,
type: "BUTTON_WIDGET",
leftColumn: 51,
rightColumn: 64,
isDefaultClickDisabled: true,
widgetId: "y8kkqs25a5",
minWidth: 120,
parentId: "0",
responsiveBehavior: "hug",
alignment: "start",
flexVerticalAlignment: "start",
},
p6em4n29z7: {
widgetName: "Button6",
topRow: 11,
bottomRow: 15,
type: "BUTTON_WIDGET",
leftColumn: 0,
rightColumn: 17.375565610859727,
widgetId: "p6em4n29z7",
minWidth: 120,
parentId: "0",
responsiveBehavior: "hug",
alignment: "start",
flexVerticalAlignment: "start",
},
jxob7zdb75: {
widgetName: "Button7",
topRow: 11,
bottomRow: 15,
type: "BUTTON_WIDGET",
leftColumn: 24,
rightColumn: 40,
widgetId: "jxob7zdb75",
minWidth: 120,
responsiveBehavior: "hug",
alignment: "center",
flexVerticalAlignment: "start",
},
n123229jea: {
widgetName: "Button9",
topRow: 15,
bottomRow: 19,
parentRowSpace: 10,
type: "BUTTON_WIDGET",
leftColumn: 0,
rightColumn: 17.375565610859727,
widgetId: "n123229jea",
minWidth: 120,
parentId: "0",
responsiveBehavior: "hug",
alignment: "start",
flexVerticalAlignment: "start",
},
fhh2k44omh: {
widgetName: "Button8",
topRow: 15,
bottomRow: 19,
type: "BUTTON_WIDGET",
leftColumn: 48,
rightColumn: 64,
widgetId: "fhh2k44omh",
minWidth: 120,
parentId: "0",
responsiveBehavior: "hug",
alignment: "end",
flexVerticalAlignment: "start",
},
"5c6gd8ynfa": {
widgetName: "Button10",
topRow: 0,
bottomRow: 4,
type: "BUTTON_WIDGET",
leftColumn: 0,
rightColumn: 17.375565610859727,
widgetId: "5c6gd8ynfa",
minWidth: 120,
parentId: "vv54unn046",
responsiveBehavior: "hug",
alignment: "start",
flexVerticalAlignment: "start",
},
wixla6nh38: {
widgetName: "Input1",
topRow: 0,
bottomRow: 7,
type: "INPUT_WIDGET_V2",
leftColumn: 17.375565610859727,
rightColumn: 64,
widgetId: "wixla6nh38",
minWidth: 450,
parentId: "vv54unn046",
responsiveBehavior: "fill",
alignment: "start",
flexVerticalAlignment: "start",
},
krrqtqc1o3: {
widgetName: "Image1",
topRow: 7,
bottomRow: 19,
type: "IMAGE_WIDGET",
leftColumn: 0,
rightColumn: 15,
widgetId: "krrqtqc1o3",
minWidth: 450,
parentId: "vv54unn046",
responsiveBehavior: "hug",
alignment: "start",
flexVerticalAlignment: "start",
},
"0cb5t22zd2": {
widgetName: "Button11",
topRow: 0,
bottomRow: 4,
type: "BUTTON_WIDGET",
leftColumn: 24,
rightColumn: 40,
widgetId: "0cb5t22zd2",
minWidth: 120,
parentId: "mw6t1nvt67",
responsiveBehavior: "hug",
alignment: "center",
flexVerticalAlignment: "start",
},
u0cd188upj: {
widgetName: "Button12",
topRow: 4,
bottomRow: 8,
type: "BUTTON_WIDGET",
leftColumn: 0,
rightColumn: 17.375565610859727,
widgetId: "u0cd188upj",
minWidth: 120,
parentId: "mw6t1nvt67",
responsiveBehavior: "hug",
alignment: "start",
flexVerticalAlignment: "start",
},
mw6t1nvt67: {
mobileBottomRow: 100,
widgetName: "Canvas2",
topRow: 0,
bottomRow: 100,
type: "CANVAS_WIDGET",
minHeight: 100,
mobileRightColumn: 64,
useAutoLayout: true,
leftColumn: 0,
children: ["0cb5t22zd2", "u0cd188upj"],
positioning: "vertical",
rightColumn: 64,
widgetId: "mw6t1nvt67",
minWidth: 450,
parentId: "eh5p39ko9z",
mobileTopRow: 0,
mobileLeftColumn: 0,
flexLayers: [
{
children: [
{
id: "0cb5t22zd2",
align: "center",
},
],
},
{
children: [
{
id: "u0cd188upj",
align: "start",
},
],
},
],
responsiveBehavior: "fill",
},
eh5p39ko9z: {
widgetName: "Container2",
topRow: 7,
bottomRow: 17,
type: "CONTAINER_WIDGET",
leftColumn: 15,
children: ["mw6t1nvt67"],
rightColumn: 64,
widgetId: "eh5p39ko9z",
minWidth: 450,
parentId: "vv54unn046",
responsiveBehavior: "fill",
alignment: "start",
flexVerticalAlignment: "start",
},
vv54unn046: {
mobileBottomRow: 350,
widgetName: "Canvas1",
topRow: 0,
bottomRow: 210,
type: "CANVAS_WIDGET",
minHeight: 210,
mobileRightColumn: 64,
useAutoLayout: true,
leftColumn: 0,
children: ["5c6gd8ynfa", "wixla6nh38", "krrqtqc1o3", "eh5p39ko9z"],
positioning: "vertical",
rightColumn: 64,
widgetId: "vv54unn046",
minWidth: 450,
parentId: "m9mrywyvpj",
mobileTopRow: 0,
mobileLeftColumn: 0,
flexLayers: [
{
children: [
{
id: "5c6gd8ynfa",
align: "start",
},
{
id: "wixla6nh38",
align: "start",
},
],
},
{
children: [
{
id: "krrqtqc1o3",
align: "start",
},
{
id: "eh5p39ko9z",
align: "start",
},
],
},
],
responsiveBehavior: "fill",
},
m9mrywyvpj: {
widgetName: "Container1",
topRow: 19,
bottomRow: 40,
type: "CONTAINER_WIDGET",
leftColumn: 0,
children: ["vv54unn046"],
rightColumn: 64,
widgetId: "m9mrywyvpj",
minWidth: 450,
parentId: "0",
responsiveBehavior: "fill",
alignment: "start",
flexVerticalAlignment: "start",
},
fjt4m0ern5: {
widgetName: "Text1",
topRow: 1,
bottomRow: 5,
type: "TEXT_WIDGET",
leftColumn: 1.5,
rightColumn: 25.5,
widgetId: "fjt4m0ern5",
minWidth: 450,
parentId: "007w6lokqp",
responsiveBehavior: "fill",
},
nepom5s2di: {
widgetName: "Button13",
topRow: 33,
bottomRow: 37,
type: "BUTTON_WIDGET",
leftColumn: 46,
rightColumn: 62,
widgetId: "nepom5s2di",
minWidth: 120,
parentId: "007w6lokqp",
responsiveBehavior: "hug",
},
zencnl8sel: {
widgetName: "Button14",
topRow: 33,
bottomRow: 37,
type: "BUTTON_WIDGET",
leftColumn: 30,
rightColumn: 46,
widgetId: "zencnl8sel",
minWidth: 120,
parentId: "007w6lokqp",
responsiveBehavior: "hug",
},
"007w6lokqp": {
mobileBottomRow: 390,
widgetName: "Canvas3",
topRow: 0,
bottomRow: 390,
type: "CANVAS_WIDGET",
minHeight: 390,
mobileRightColumn: 64,
leftColumn: 0,
children: ["fjt4m0ern5", "nepom5s2di", "zencnl8sel"],
rightColumn: 300.75,
widgetId: "007w6lokqp",
minWidth: 450,
parentId: "8o21a70kqn",
mobileTopRow: 0,
responsiveBehavior: "fill",
mobileLeftColumn: 0,
flexLayers: [],
},
"8o21a70kqn": {
widgetName: "Form1",
topRow: 40,
bottomRow: 79,
type: "FORM_WIDGET",
leftColumn: 0,
children: ["007w6lokqp"],
positioning: "fixed",
rightColumn: 64,
widgetId: "8o21a70kqn",
minWidth: 450,
parentId: "0",
responsiveBehavior: "fill",
alignment: "start",
flexVerticalAlignment: "start",
},
} as unknown as CanvasWidgetsReduxState;
const fixedLayoutWidgets = {
"0": {
bottomRow: 932,
canExtend: true,
children: [
"3rp273r2sw",
"jej39vfb46",
"qwdu5rldu2",
"hrduq6qeyy",
"y8kkqs25a5",
"p6em4n29z7",
"jxob7zdb75",
"n123229jea",
"fhh2k44omh",
"m9mrywyvpj",
"8o21a70kqn",
],
detachFromLayout: true,
direction: "Vertical",
leftColumn: 0,
minHeight: 870,
positioning: "fixed",
rightColumn: 4896,
topRow: 0,
type: "CANVAS_WIDGET",
useAutoLayout: false,
widgetId: "0",
widgetName: "MainContainer",
},
"007w6lokqp": {
bottomRow: 380,
children: ["fjt4m0ern5", "nepom5s2di", "zencnl8sel"],
flexLayers: [],
leftColumn: 0,
minHeight: 390,
minWidth: 450,
mobileBottomRow: 390,
mobileLeftColumn: 0,
mobileRightColumn: 64,
mobileTopRow: 0,
parentId: "8o21a70kqn",
responsiveBehavior: "fill",
rightColumn: 300.75,
topRow: 0,
type: "CANVAS_WIDGET",
widgetId: "007w6lokqp",
widgetName: "Canvas3",
},
"0cb5t22zd2": {
bottomRow: 4,
leftColumn: 24,
minWidth: 120,
parentId: "mw6t1nvt67",
rightColumn: 40,
topRow: 0,
type: "BUTTON_WIDGET",
widgetId: "0cb5t22zd2",
widgetName: "Button11",
},
"3rp273r2sw": {
bottomRow: 4,
leftColumn: 24,
minWidth: 120,
parentId: "0",
parentRowSpace: 10,
rightColumn: 40,
topRow: 0,
type: "BUTTON_WIDGET",
widgetId: "3rp273r2sw",
widgetName: "Button3",
},
"5c6gd8ynfa": {
bottomRow: 4,
leftColumn: 0,
minWidth: 120,
parentId: "vv54unn046",
rightColumn: 17,
topRow: 0,
type: "BUTTON_WIDGET",
widgetId: "5c6gd8ynfa",
widgetName: "Button10",
},
"8o21a70kqn": {
bottomRow: 85.2,
children: ["007w6lokqp"],
leftColumn: 0,
minWidth: 450,
parentId: "0",
positioning: "fixed",
rightColumn: 64,
topRow: 47.2,
type: "FORM_WIDGET",
widgetId: "8o21a70kqn",
widgetName: "Form1",
},
eh5p39ko9z: {
bottomRow: 19.4,
children: ["mw6t1nvt67"],
leftColumn: 15,
minWidth: 450,
parentId: "vv54unn046",
rightColumn: 64,
topRow: 8.2,
type: "CONTAINER_WIDGET",
widgetId: "eh5p39ko9z",
widgetName: "Container2",
},
fhh2k44omh: {
bottomRow: 22.599999999999998,
leftColumn: 48,
minWidth: 120,
parentId: "0",
rightColumn: 64,
topRow: 18.599999999999998,
type: "BUTTON_WIDGET",
widgetId: "fhh2k44omh",
widgetName: "Button8",
},
fjt4m0ern5: {
bottomRow: 5,
leftColumn: 1.5,
minWidth: 450,
parentId: "007w6lokqp",
rightColumn: 25.5,
topRow: 1,
type: "TEXT_WIDGET",
widgetId: "fjt4m0ern5",
widgetName: "Text1",
},
hrduq6qeyy: {
bottomRow: 12.2,
leftColumn: 32,
minWidth: 450,
parentId: "0",
rightColumn: 51,
topRow: 5.2,
type: "INPUT_WIDGET_V2",
widgetId: "hrduq6qeyy",
widgetName: "Input2",
},
jej39vfb46: {
bottomRow: 9.2,
leftColumn: 0,
minWidth: 120,
rightColumn: 16,
topRow: 5.2,
type: "BUTTON_WIDGET",
widgetId: "jej39vfb46",
widgetName: "Button15",
},
jxob7zdb75: {
bottomRow: 17.4,
leftColumn: 24,
minWidth: 120,
rightColumn: 40,
topRow: 13.399999999999999,
type: "BUTTON_WIDGET",
widgetId: "jxob7zdb75",
widgetName: "Button7",
},
krrqtqc1o3: {
bottomRow: 20.2,
leftColumn: 0,
minWidth: 450,
parentId: "vv54unn046",
rightColumn: 15,
topRow: 8.2,
type: "IMAGE_WIDGET",
widgetId: "krrqtqc1o3",
widgetName: "Image1",
},
m9mrywyvpj: {
bottomRow: 46,
children: ["vv54unn046"],
leftColumn: 0,
minWidth: 450,
parentId: "0",
rightColumn: 64,
topRow: 23.799999999999997,
type: "CONTAINER_WIDGET",
widgetId: "m9mrywyvpj",
widgetName: "Container1",
},
mw6t1nvt67: {
bottomRow: 112.00000000000001,
children: ["0cb5t22zd2", "u0cd188upj"],
leftColumn: 0,
minHeight: 100,
minWidth: 450,
mobileBottomRow: 100,
mobileLeftColumn: 0,
mobileRightColumn: 64,
mobileTopRow: 0,
parentId: "eh5p39ko9z",
positioning: "fixed",
rightColumn: 64,
topRow: 0,
type: "CANVAS_WIDGET",
useAutoLayout: false,
widgetId: "mw6t1nvt67",
widgetName: "Canvas2",
},
n123229jea: {
bottomRow: 22.599999999999998,
leftColumn: 0,
minWidth: 120,
parentId: "0",
parentRowSpace: 10,
rightColumn: 17,
topRow: 18.599999999999998,
type: "BUTTON_WIDGET",
widgetId: "n123229jea",
widgetName: "Button9",
},
nepom5s2di: {
bottomRow: 37,
leftColumn: 46,
minWidth: 120,
parentId: "007w6lokqp",
rightColumn: 62,
topRow: 33,
type: "BUTTON_WIDGET",
widgetId: "nepom5s2di",
widgetName: "Button13",
},
p6em4n29z7: {
bottomRow: 17.4,
leftColumn: 0,
minWidth: 120,
parentId: "0",
rightColumn: 17,
topRow: 13.399999999999999,
type: "BUTTON_WIDGET",
widgetId: "p6em4n29z7",
widgetName: "Button6",
},
qwdu5rldu2: {
bottomRow: 9.2,
leftColumn: 16,
minWidth: 120,
parentId: "0",
parentRowSpace: 10,
rightColumn: 32,
topRow: 5.2,
type: "BUTTON_WIDGET",
widgetId: "qwdu5rldu2",
widgetName: "Button5",
},
u0cd188upj: {
bottomRow: 9.2,
leftColumn: 0,
minWidth: 120,
parentId: "mw6t1nvt67",
rightColumn: 17,
topRow: 5.2,
type: "BUTTON_WIDGET",
widgetId: "u0cd188upj",
widgetName: "Button12",
},
vv54unn046: {
bottomRow: 222,
children: ["5c6gd8ynfa", "wixla6nh38", "krrqtqc1o3", "eh5p39ko9z"],
leftColumn: 0,
minHeight: 210,
minWidth: 450,
mobileBottomRow: 350,
mobileLeftColumn: 0,
mobileRightColumn: 64,
mobileTopRow: 0,
parentId: "m9mrywyvpj",
positioning: "fixed",
rightColumn: 64,
topRow: 0,
type: "CANVAS_WIDGET",
useAutoLayout: false,
widgetId: "vv54unn046",
widgetName: "Canvas1",
},
wixla6nh38: {
bottomRow: 7,
leftColumn: 17,
minWidth: 450,
parentId: "vv54unn046",
rightColumn: 64,
topRow: 0,
type: "INPUT_WIDGET_V2",
widgetId: "wixla6nh38",
widgetName: "Input1",
},
y8kkqs25a5: {
bottomRow: 9.2,
isDefaultClickDisabled: true,
leftColumn: 51,
minWidth: 120,
parentId: "0",
rightColumn: 64,
topRow: 5.2,
type: "BUTTON_WIDGET",
widgetId: "y8kkqs25a5",
widgetName: "Button4",
},
zencnl8sel: {
bottomRow: 37,
leftColumn: 30,
minWidth: 120,
parentId: "007w6lokqp",
rightColumn: 46,
topRow: 33,
type: "BUTTON_WIDGET",
widgetId: "zencnl8sel",
widgetName: "Button14",
},
};
const fixedLayoutMobileWidgets = {
"0": {
bottomRow: 870,
canExtend: true,
children: [
"3rp273r2sw",
"jej39vfb46",
"qwdu5rldu2",
"hrduq6qeyy",
"y8kkqs25a5",
"p6em4n29z7",
"jxob7zdb75",
"n123229jea",
"fhh2k44omh",
"m9mrywyvpj",
"8o21a70kqn",
],
detachFromLayout: true,
direction: "Vertical",
leftColumn: 0,
minHeight: 870,
mobileBottomRow: 1168,
mobileTopRow: 0,
positioning: "fixed",
rightColumn: 4896,
topRow: 0,
type: "CANVAS_WIDGET",
useAutoLayout: false,
widgetId: "0",
widgetName: "MainContainer",
},
"007w6lokqp": {
bottomRow: 390,
children: ["fjt4m0ern5", "nepom5s2di", "zencnl8sel"],
flexLayers: [],
leftColumn: 0,
minHeight: 390,
minWidth: 450,
mobileBottomRow: 380,
mobileLeftColumn: 0,
mobileRightColumn: 64,
mobileTopRow: 0,
parentId: "8o21a70kqn",
responsiveBehavior: "fill",
rightColumn: 300.75,
topRow: 0,
type: "CANVAS_WIDGET",
widgetId: "007w6lokqp",
widgetName: "Canvas3",
},
"0cb5t22zd2": {
bottomRow: 4,
leftColumn: 24,
minWidth: 120,
parentId: "mw6t1nvt67",
rightColumn: 40,
topRow: 0,
type: "BUTTON_WIDGET",
widgetId: "0cb5t22zd2",
widgetName: "Button11",
},
"3rp273r2sw": {
bottomRow: 4,
leftColumn: 24,
minWidth: 120,
parentId: "0",
parentRowSpace: 10,
rightColumn: 40,
topRow: 0,
type: "BUTTON_WIDGET",
widgetId: "3rp273r2sw",
widgetName: "Button3",
},
"5c6gd8ynfa": {
bottomRow: 4,
leftColumn: 0,
minWidth: 120,
parentId: "vv54unn046",
rightColumn: 17,
topRow: 0,
type: "BUTTON_WIDGET",
widgetId: "5c6gd8ynfa",
widgetName: "Button10",
},
"8o21a70kqn": {
bottomRow: 108.8,
children: ["007w6lokqp"],
leftColumn: 0,
minWidth: 450,
parentId: "0",
positioning: "fixed",
rightColumn: 64,
topRow: 70.8,
type: "FORM_WIDGET",
widgetId: "8o21a70kqn",
widgetName: "Form1",
},
eh5p39ko9z: {
bottomRow: 36.2,
children: ["mw6t1nvt67"],
leftColumn: 0,
minWidth: 450,
parentId: "vv54unn046",
rightColumn: 64,
topRow: 25.400000000000002,
type: "CONTAINER_WIDGET",
widgetId: "eh5p39ko9z",
widgetName: "Container2",
},
fhh2k44omh: {
bottomRow: 31.000000000000004,
leftColumn: 48,
minWidth: 120,
parentId: "0",
rightColumn: 64,
topRow: 27.000000000000004,
type: "BUTTON_WIDGET",
widgetId: "fhh2k44omh",
widgetName: "Button8",
},
fjt4m0ern5: {
bottomRow: 5,
leftColumn: 1.5,
minWidth: 450,
parentId: "007w6lokqp",
rightColumn: 25.5,
topRow: 1,
type: "TEXT_WIDGET",
widgetId: "fjt4m0ern5",
widgetName: "Text1",
},
hrduq6qeyy: {
bottomRow: 16.6,
leftColumn: 0,
minWidth: 450,
parentId: "0",
rightColumn: 64,
topRow: 9.600000000000001,
type: "INPUT_WIDGET_V2",
widgetId: "hrduq6qeyy",
widgetName: "Input2",
},
jej39vfb46: {
bottomRow: 8.8,
leftColumn: 0,
minWidth: 120,
rightColumn: 16,
topRow: 4.8,
type: "BUTTON_WIDGET",
widgetId: "jej39vfb46",
widgetName: "Button15",
},
jxob7zdb75: {
bottomRow: 26.200000000000003,
leftColumn: 24,
minWidth: 120,
rightColumn: 40,
topRow: 22.200000000000003,
type: "BUTTON_WIDGET",
widgetId: "jxob7zdb75",
widgetName: "Button7",
},
krrqtqc1o3: {
bottomRow: 24.6,
leftColumn: 0,
minWidth: 450,
parentId: "vv54unn046",
rightColumn: 15,
topRow: 12.600000000000001,
type: "IMAGE_WIDGET",
widgetId: "krrqtqc1o3",
widgetName: "Image1",
},
m9mrywyvpj: {
bottomRow: 70,
children: ["vv54unn046"],
leftColumn: 0,
minWidth: 450,
parentId: "0",
rightColumn: 64,
topRow: 31.800000000000004,
type: "CONTAINER_WIDGET",
widgetId: "m9mrywyvpj",
widgetName: "Container1",
},
mw6t1nvt67: {
bottomRow: 100,
children: ["0cb5t22zd2", "u0cd188upj"],
leftColumn: 0,
minHeight: 100,
minWidth: 450,
mobileBottomRow: 108,
mobileLeftColumn: 0,
mobileRightColumn: 64,
mobileTopRow: 0,
parentId: "eh5p39ko9z",
positioning: "fixed",
rightColumn: 64,
topRow: 0,
type: "CANVAS_WIDGET",
useAutoLayout: false,
widgetId: "mw6t1nvt67",
widgetName: "Canvas2",
},
n123229jea: {
bottomRow: 31.000000000000004,
leftColumn: 0,
minWidth: 120,
parentId: "0",
parentRowSpace: 10,
rightColumn: 17,
topRow: 27.000000000000004,
type: "BUTTON_WIDGET",
widgetId: "n123229jea",
widgetName: "Button9",
},
nepom5s2di: {
bottomRow: 37,
leftColumn: 46,
minWidth: 120,
parentId: "007w6lokqp",
rightColumn: 62,
topRow: 33,
type: "BUTTON_WIDGET",
widgetId: "nepom5s2di",
widgetName: "Button13",
},
p6em4n29z7: {
bottomRow: 26.200000000000003,
leftColumn: 0,
minWidth: 120,
parentId: "0",
rightColumn: 17,
topRow: 22.200000000000003,
type: "BUTTON_WIDGET",
widgetId: "p6em4n29z7",
widgetName: "Button6",
},
qwdu5rldu2: {
bottomRow: 8.8,
leftColumn: 16,
minWidth: 120,
parentId: "0",
parentRowSpace: 10,
rightColumn: 32,
topRow: 4.8,
type: "BUTTON_WIDGET",
widgetId: "qwdu5rldu2",
widgetName: "Button5",
},
u0cd188upj: {
bottomRow: 8.8,
leftColumn: 0,
minWidth: 120,
parentId: "mw6t1nvt67",
rightColumn: 17,
topRow: 4.8,
type: "BUTTON_WIDGET",
widgetId: "u0cd188upj",
widgetName: "Button12",
},
vv54unn046: {
bottomRow: 210,
children: ["5c6gd8ynfa", "wixla6nh38", "krrqtqc1o3", "eh5p39ko9z"],
leftColumn: 0,
minHeight: 210,
minWidth: 450,
mobileBottomRow: 382,
mobileLeftColumn: 0,
mobileRightColumn: 64,
mobileTopRow: 0,
parentId: "m9mrywyvpj",
positioning: "fixed",
rightColumn: 64,
topRow: 0,
type: "CANVAS_WIDGET",
useAutoLayout: false,
widgetId: "vv54unn046",
widgetName: "Canvas1",
},
wixla6nh38: {
bottomRow: 11.8,
leftColumn: 0,
minWidth: 450,
parentId: "vv54unn046",
rightColumn: 64,
topRow: 4.8,
type: "INPUT_WIDGET_V2",
widgetId: "wixla6nh38",
widgetName: "Input1",
},
y8kkqs25a5: {
bottomRow: 21.400000000000002,
isDefaultClickDisabled: true,
leftColumn: 0,
minWidth: 120,
parentId: "0",
rightColumn: 13,
topRow: 17.400000000000002,
type: "BUTTON_WIDGET",
widgetId: "y8kkqs25a5",
widgetName: "Button4",
},
zencnl8sel: {
bottomRow: 37,
leftColumn: 30,
minWidth: 120,
parentId: "007w6lokqp",
rightColumn: 46,
topRow: 33,
type: "BUTTON_WIDGET",
widgetId: "zencnl8sel",
widgetName: "Button14",
},
};
it("Convert Normalized auto DSL to fixed Normalized DSl without wrap", () => {
expect(convertNormalizedDSLToFixed(autoLayoutWidgets, "DESKTOP")).toEqual(
fixedLayoutWidgets,
);
});
it("Convert Normalized auto DSL to fixed Normalized DSl in mobile layout", () => {
expect(convertNormalizedDSLToFixed(autoLayoutWidgets, "MOBILE")).toEqual(
fixedLayoutMobileWidgets,
);
});
});
|
Subsets and Splits