level_0
int64 0
10k
| index
int64 0
0
| repo_id
stringlengths 22
152
| file_path
stringlengths 41
203
| content
stringlengths 11
11.5M
|
---|---|---|---|---|
6,269 | 0 | petrpan-code/apache/superset/superset-frontend/plugins/plugin-chart-echarts/test | petrpan-code/apache/superset/superset-frontend/plugins/plugin-chart-echarts/test/Funnel/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 buildQuery from '../../src/Funnel/buildQuery';
describe('Funnel buildQuery', () => {
const formData = {
datasource: '5__table',
granularity_sqla: 'ds',
metric: 'foo',
groupby: ['bar'],
viz_type: 'my_chart',
};
it('should build query fields from form data', () => {
const queryContext = buildQuery(formData);
const [query] = queryContext.queries;
expect(query.metrics).toEqual(['foo']);
expect(query.columns).toEqual(['bar']);
});
});
|
6,270 | 0 | petrpan-code/apache/superset/superset-frontend/plugins/plugin-chart-echarts/test | petrpan-code/apache/superset/superset-frontend/plugins/plugin-chart-echarts/test/Funnel/transformProps.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 {
ChartProps,
getNumberFormatter,
supersetTheme,
} from '@superset-ui/core';
import transformProps, {
formatFunnelLabel,
} from '../../src/Funnel/transformProps';
import {
EchartsFunnelChartProps,
EchartsFunnelLabelTypeType,
} from '../../src/Funnel/types';
describe('Funnel transformProps', () => {
const formData = {
colorScheme: 'bnbColors',
datasource: '3__table',
granularity_sqla: 'ds',
metric: 'sum__num',
groupby: ['foo', 'bar'],
};
const chartProps = new ChartProps({
formData,
width: 800,
height: 600,
queriesData: [
{
data: [
{ foo: 'Sylvester', bar: 1, sum__num: 10 },
{ foo: 'Arnold', bar: 2, sum__num: 2.5 },
],
},
],
theme: supersetTheme,
});
it('should transform chart props for viz', () => {
expect(transformProps(chartProps as EchartsFunnelChartProps)).toEqual(
expect.objectContaining({
width: 800,
height: 600,
echartOptions: expect.objectContaining({
series: [
expect.objectContaining({
data: expect.arrayContaining([
expect.objectContaining({
name: 'Arnold, 2',
value: 2.5,
}),
expect.objectContaining({
name: 'Sylvester, 1',
value: 10,
}),
]),
}),
],
}),
}),
);
});
});
describe('formatFunnelLabel', () => {
it('should generate a valid funnel chart label', () => {
const numberFormatter = getNumberFormatter();
const params = { name: 'My Label', value: 1234, percent: 12.34 };
expect(
formatFunnelLabel({
params,
numberFormatter,
labelType: EchartsFunnelLabelTypeType.Key,
}),
).toEqual('My Label');
expect(
formatFunnelLabel({
params,
numberFormatter,
labelType: EchartsFunnelLabelTypeType.Value,
}),
).toEqual('1.23k');
expect(
formatFunnelLabel({
params,
numberFormatter,
labelType: EchartsFunnelLabelTypeType.Percent,
}),
).toEqual('12.34%');
expect(
formatFunnelLabel({
params,
numberFormatter,
labelType: EchartsFunnelLabelTypeType.KeyValue,
}),
).toEqual('My Label: 1.23k');
expect(
formatFunnelLabel({
params,
numberFormatter,
labelType: EchartsFunnelLabelTypeType.KeyPercent,
}),
).toEqual('My Label: 12.34%');
expect(
formatFunnelLabel({
params,
numberFormatter,
labelType: EchartsFunnelLabelTypeType.KeyValuePercent,
}),
).toEqual('My Label: 1.23k (12.34%)');
expect(
formatFunnelLabel({
params: { ...params, name: '<NULL>' },
numberFormatter,
labelType: EchartsFunnelLabelTypeType.Key,
}),
).toEqual('<NULL>');
expect(
formatFunnelLabel({
params: { ...params, name: '<NULL>' },
numberFormatter,
labelType: EchartsFunnelLabelTypeType.Key,
sanitizeName: true,
}),
).toEqual('<NULL>');
});
});
|
6,271 | 0 | petrpan-code/apache/superset/superset-frontend/plugins/plugin-chart-echarts/test | petrpan-code/apache/superset/superset-frontend/plugins/plugin-chart-echarts/test/Gauge/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 buildQuery from '../../src/Gauge/buildQuery';
describe('Gauge buildQuery', () => {
const baseFormData = {
datasource: '5__table',
metric: 'foo',
viz_type: 'my_chart',
};
it('should build query fields with no group by column', () => {
const formData = { ...baseFormData, groupby: undefined };
const queryContext = buildQuery(formData);
const [query] = queryContext.queries;
expect(query.columns).toEqual([]);
});
it('should build query fields with single group by column', () => {
const formData = { ...baseFormData, groupby: ['foo'] };
const queryContext = buildQuery(formData);
const [query] = queryContext.queries;
expect(query.columns).toEqual(['foo']);
});
it('should build query fields with multiple group by columns', () => {
const formData = { ...baseFormData, groupby: ['foo', 'bar'] };
const queryContext = buildQuery(formData);
const [query] = queryContext.queries;
expect(query.columns).toEqual(['foo', 'bar']);
});
});
|
6,272 | 0 | petrpan-code/apache/superset/superset-frontend/plugins/plugin-chart-echarts/test | petrpan-code/apache/superset/superset-frontend/plugins/plugin-chart-echarts/test/Gauge/transformProps.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 { ChartProps, SqlaFormData, supersetTheme } from '@superset-ui/core';
import transformProps from '../../src/Gauge/transformProps';
import { EchartsGaugeChartProps } from '../../src/Gauge/types';
describe('Echarts Gauge transformProps', () => {
const baseFormData: SqlaFormData = {
datasource: '26__table',
viz_type: 'gauge_chart',
metric: 'count',
adhocFilters: [],
rowLimit: 10,
minVal: 0,
maxVal: 100,
startAngle: 225,
endAngle: -45,
colorScheme: 'SUPERSET_DEFAULT',
fontSize: 14,
numberFormat: 'SMART_NUMBER',
valueFormatter: '{value}',
showPointer: true,
animation: true,
showAxisTick: false,
showSplitLine: false,
splitNumber: 10,
showProgress: true,
overlap: true,
roundCap: false,
};
it('should transform chart props for no group by column', () => {
const formData: SqlaFormData = { ...baseFormData, groupby: [] };
const queriesData = [
{
colnames: ['count'],
data: [
{
count: 16595,
},
],
},
];
const chartPropsConfig = {
formData,
width: 800,
height: 600,
queriesData,
theme: supersetTheme,
};
const chartProps = new ChartProps(chartPropsConfig);
expect(transformProps(chartProps as EchartsGaugeChartProps)).toEqual(
expect.objectContaining({
width: 800,
height: 600,
echartOptions: expect.objectContaining({
series: expect.arrayContaining([
expect.objectContaining({
data: [
{
value: 16595,
name: '',
itemStyle: {
color: '#1f77b4',
},
title: {
offsetCenter: ['0%', '20%'],
fontSize: 14,
},
detail: {
offsetCenter: ['0%', '32.6%'],
fontSize: 16.8,
},
},
],
}),
]),
}),
}),
);
});
it('should transform chart props for single group by column', () => {
const formData: SqlaFormData = {
...baseFormData,
groupby: ['year'],
};
const queriesData = [
{
colnames: ['year', 'count'],
data: [
{
year: 1988,
count: 15,
},
{
year: 1995,
count: 219,
},
],
},
];
const chartPropsConfig = {
formData,
width: 800,
height: 600,
queriesData,
theme: supersetTheme,
};
const chartProps = new ChartProps(chartPropsConfig);
expect(transformProps(chartProps as EchartsGaugeChartProps)).toEqual(
expect.objectContaining({
width: 800,
height: 600,
echartOptions: expect.objectContaining({
series: expect.arrayContaining([
expect.objectContaining({
data: [
{
value: 15,
name: 'year: 1988',
itemStyle: {
color: '#1f77b4',
},
title: {
offsetCenter: ['0%', '20%'],
fontSize: 14,
},
detail: {
offsetCenter: ['0%', '32.6%'],
fontSize: 16.8,
},
},
{
value: 219,
name: 'year: 1995',
itemStyle: {
color: '#ff7f0e',
},
title: {
offsetCenter: ['0%', '48%'],
fontSize: 14,
},
detail: {
offsetCenter: ['0%', '60.6%'],
fontSize: 16.8,
},
},
],
}),
]),
}),
}),
);
});
it('should transform chart props for multiple group by columns', () => {
const formData: SqlaFormData = {
...baseFormData,
groupby: ['year', 'platform'],
};
const queriesData = [
{
colnames: ['year', 'platform', 'count'],
data: [
{
year: 2011,
platform: 'PC',
count: 140,
},
{
year: 2008,
platform: 'PC',
count: 76,
},
],
},
];
const chartPropsConfig = {
formData,
width: 800,
height: 600,
queriesData,
theme: supersetTheme,
};
const chartProps = new ChartProps(chartPropsConfig);
expect(transformProps(chartProps as EchartsGaugeChartProps)).toEqual(
expect.objectContaining({
width: 800,
height: 600,
echartOptions: expect.objectContaining({
series: expect.arrayContaining([
expect.objectContaining({
data: [
{
value: 140,
name: 'year: 2011, platform: PC',
itemStyle: {
color: '#1f77b4',
},
title: {
offsetCenter: ['0%', '20%'],
fontSize: 14,
},
detail: {
offsetCenter: ['0%', '32.6%'],
fontSize: 16.8,
},
},
{
value: 76,
name: 'year: 2008, platform: PC',
itemStyle: {
color: '#ff7f0e',
},
title: {
offsetCenter: ['0%', '48%'],
fontSize: 14,
},
detail: {
offsetCenter: ['0%', '60.6%'],
fontSize: 16.8,
},
},
],
}),
]),
}),
}),
);
});
it('should transform chart props for intervals', () => {
const formData: SqlaFormData = {
...baseFormData,
groupby: ['year', 'platform'],
intervals: '50,100',
intervalColorIndices: '1,2',
};
const queriesData = [
{
colnames: ['year', 'platform', 'count'],
data: [
{
year: 2011,
platform: 'PC',
count: 140,
},
{
year: 2008,
platform: 'PC',
count: 76,
},
],
},
];
const chartPropsConfig = {
formData,
width: 800,
height: 600,
queriesData,
theme: supersetTheme,
};
const chartProps = new ChartProps(chartPropsConfig);
expect(transformProps(chartProps as EchartsGaugeChartProps)).toEqual(
expect.objectContaining({
width: 800,
height: 600,
echartOptions: expect.objectContaining({
series: expect.arrayContaining([
expect.objectContaining({
axisLine: {
lineStyle: {
width: 14,
color: [
[0.5, '#1f77b4'],
[1, '#ff7f0e'],
],
},
roundCap: false,
},
data: [
{
value: 140,
name: 'year: 2011, platform: PC',
itemStyle: {
color: '#1f77b4',
},
title: {
offsetCenter: ['0%', '20%'],
fontSize: 14,
},
detail: {
offsetCenter: ['0%', '32.6%'],
fontSize: 16.8,
},
},
{
value: 76,
name: 'year: 2008, platform: PC',
itemStyle: {
color: '#ff7f0e',
},
title: {
offsetCenter: ['0%', '48%'],
fontSize: 14,
},
detail: {
offsetCenter: ['0%', '60.6%'],
fontSize: 16.8,
},
},
],
}),
]),
}),
}),
);
});
});
|
6,273 | 0 | petrpan-code/apache/superset/superset-frontend/plugins/plugin-chart-echarts/test | petrpan-code/apache/superset/superset-frontend/plugins/plugin-chart-echarts/test/Graph/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 buildQuery from '../../src/Graph/buildQuery';
describe('Graph buildQuery', () => {
const formData = {
datasource: '5__table',
granularity_sqla: 'ds',
source: 'dummy_source',
target: 'dummy_target',
metrics: ['foo', 'bar'],
viz_type: 'my_chart',
};
it('should build groupby with source and target categories', () => {
const formDataWithCategories = {
...formData,
source: 'dummy_source',
target: 'dummy_target',
source_category: 'dummy_source_category',
target_category: 'dummy_target_category',
};
const queryContext = buildQuery(formDataWithCategories);
const [query] = queryContext.queries;
expect(query.columns).toEqual([
'dummy_source',
'dummy_target',
'dummy_source_category',
'dummy_target_category',
]);
expect(query.metrics).toEqual(['foo', 'bar']);
});
it('should build groupby with source category', () => {
const formDataWithCategories = {
...formData,
source: 'dummy_source',
target: 'dummy_target',
source_category: 'dummy_source_category',
};
const queryContext = buildQuery(formDataWithCategories);
const [query] = queryContext.queries;
expect(query.columns).toEqual([
'dummy_source',
'dummy_target',
'dummy_source_category',
]);
expect(query.metrics).toEqual(['foo', 'bar']);
});
it('should build groupby with target category', () => {
const formDataWithCategories = {
...formData,
source: 'dummy_source',
target: 'dummy_target',
target_category: 'dummy_target_category',
};
const queryContext = buildQuery(formDataWithCategories);
const [query] = queryContext.queries;
expect(query.columns).toEqual([
'dummy_source',
'dummy_target',
'dummy_target_category',
]);
expect(query.metrics).toEqual(['foo', 'bar']);
});
it('should build groupby without any category', () => {
const formDataWithCategories = {
...formData,
source: 'dummy_source',
target: 'dummy_target',
};
const queryContext = buildQuery(formDataWithCategories);
const [query] = queryContext.queries;
expect(query.columns).toEqual(['dummy_source', 'dummy_target']);
expect(query.metrics).toEqual(['foo', 'bar']);
});
});
|
6,274 | 0 | petrpan-code/apache/superset/superset-frontend/plugins/plugin-chart-echarts/test | petrpan-code/apache/superset/superset-frontend/plugins/plugin-chart-echarts/test/Graph/transformProps.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 { ChartProps, SqlaFormData, supersetTheme } from '@superset-ui/core';
import transformProps from '../../src/Graph/transformProps';
import { DEFAULT_GRAPH_SERIES_OPTION } from '../../src/Graph/constants';
import { EchartsGraphChartProps } from '../../src/Graph/types';
describe('EchartsGraph transformProps', () => {
it('should transform chart props for viz without category', () => {
const formData: SqlaFormData = {
colorScheme: 'bnbColors',
datasource: '3__table',
granularity_sqla: 'ds',
metric: 'count',
source: 'source_column',
target: 'target_column',
category: null,
viz_type: 'graph',
};
const queriesData = [
{
colnames: ['source_column', 'target_column', 'count'],
data: [
{
source_column: 'source_value_1',
target_column: 'target_value_1',
count: 6,
},
{
source_column: 'source_value_2',
target_column: 'target_value_2',
count: 5,
},
],
},
];
const chartPropsConfig = {
formData,
width: 800,
height: 600,
queriesData,
theme: supersetTheme,
};
const chartProps = new ChartProps(chartPropsConfig);
expect(transformProps(chartProps as EchartsGraphChartProps)).toEqual(
expect.objectContaining({
width: 800,
height: 600,
echartOptions: expect.objectContaining({
legend: expect.objectContaining({
data: [],
}),
series: expect.arrayContaining([
expect.objectContaining({
data: [
{
col: 'source_column',
category: undefined,
id: '0',
label: { show: true },
name: 'source_value_1',
select: {
itemStyle: { borderWidth: 3, opacity: 1 },
label: { fontWeight: 'bolder' },
},
symbolSize: 50,
tooltip: {
appendToBody: true,
formatter: '{b}: {c}',
position: expect.anything(),
},
value: 6,
},
{
col: 'target_column',
category: undefined,
id: '1',
label: { show: true },
name: 'target_value_1',
select: {
itemStyle: { borderWidth: 3, opacity: 1 },
label: { fontWeight: 'bolder' },
},
symbolSize: 50,
tooltip: {
appendToBody: true,
formatter: '{b}: {c}',
position: expect.anything(),
},
value: 6,
},
{
col: 'source_column',
category: undefined,
id: '2',
label: { show: true },
name: 'source_value_2',
select: {
itemStyle: { borderWidth: 3, opacity: 1 },
label: { fontWeight: 'bolder' },
},
symbolSize: 10,
tooltip: {
appendToBody: true,
formatter: '{b}: {c}',
position: expect.anything(),
},
value: 5,
},
{
col: 'target_column',
category: undefined,
id: '3',
label: { show: true },
name: 'target_value_2',
select: {
itemStyle: { borderWidth: 3, opacity: 1 },
label: { fontWeight: 'bolder' },
},
symbolSize: 10,
tooltip: {
appendToBody: true,
formatter: '{b}: {c}',
position: expect.anything(),
},
value: 5,
},
],
}),
expect.objectContaining({
links: [
{
emphasis: { lineStyle: { width: 12 } },
lineStyle: { width: 6 },
select: {
lineStyle: { opacity: 1, width: 9.600000000000001 },
},
source: '0',
target: '1',
value: 6,
},
{
emphasis: { lineStyle: { width: 5 } },
lineStyle: { width: 1.5 },
select: { lineStyle: { opacity: 1, width: 5 } },
source: '2',
target: '3',
value: 5,
},
],
}),
]),
}),
}),
);
});
it('should transform chart props for viz with category and falsey normalization', () => {
const formData: SqlaFormData = {
colorScheme: 'bnbColors',
datasource: '3__table',
granularity_sqla: 'ds',
metric: 'count',
source: 'source_column',
target: 'target_column',
sourceCategory: 'source_category_column',
targetCategory: 'target_category_column',
viz_type: 'graph',
};
const queriesData = [
{
colnames: [
'source_column',
'target_column',
'source_category_column',
'target_category_column',
'count',
],
data: [
{
source_column: 'source_value',
target_column: 'target_value',
source_category_column: 'category_value_1',
target_category_column: 'category_value_2',
count: 6,
},
{
source_column: 'source_value',
target_column: 'target_value',
source_category_column: 'category_value_1',
target_category_column: 'category_value_2',
count: 5,
},
],
},
];
const chartPropsConfig = {
formData,
width: 800,
height: 600,
queriesData,
theme: supersetTheme,
};
const chartProps = new ChartProps(chartPropsConfig);
expect(transformProps(chartProps as EchartsGraphChartProps)).toEqual(
expect.objectContaining({
width: 800,
height: 600,
echartOptions: expect.objectContaining({
legend: expect.objectContaining({
data: ['category_value_1', 'category_value_2'],
}),
series: expect.arrayContaining([
expect.objectContaining({
data: [
{
id: '0',
col: 'source_column',
name: 'source_value',
value: 11,
symbolSize: 10,
category: 'category_value_1',
select: DEFAULT_GRAPH_SERIES_OPTION.select,
tooltip: {
appendToBody: true,
formatter: '{b}: {c}',
position: expect.anything(),
},
label: { show: true },
},
{
id: '1',
col: 'target_column',
name: 'target_value',
value: 11,
symbolSize: 10,
category: 'category_value_2',
select: DEFAULT_GRAPH_SERIES_OPTION.select,
tooltip: {
appendToBody: true,
formatter: '{b}: {c}',
position: expect.anything(),
},
label: { show: true },
},
],
}),
]),
}),
}),
);
});
});
|
6,275 | 0 | petrpan-code/apache/superset/superset-frontend/plugins/plugin-chart-echarts/test | petrpan-code/apache/superset/superset-frontend/plugins/plugin-chart-echarts/test/MixedTimeseries/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 {
ComparisonType,
FreeFormAdhocFilter,
RollingType,
TimeGranularity,
} from '@superset-ui/core';
import buildQuery from '../../src/MixedTimeseries/buildQuery';
const formDataMixedChart = {
datasource: 'dummy',
viz_type: 'my_chart',
// query
// -- common
time_range: '1980 : 2000',
time_grain_sqla: TimeGranularity.WEEK,
granularity_sqla: 'ds',
// -- query a
groupby: ['foo'],
metrics: ['sum(sales)'],
adhoc_filters: [
{
clause: 'WHERE',
expressionType: 'SQL',
sqlExpression: "foo in ('a', 'b')",
} as FreeFormAdhocFilter,
],
limit: 5,
row_limit: 10,
timeseries_limit_metric: 'count',
order_desc: true,
truncate_metric: true,
show_empty_columns: true,
// -- query b
groupby_b: [],
metrics_b: ['count'],
adhoc_filters_b: [
{
clause: 'WHERE',
expressionType: 'SQL',
sqlExpression: "name in ('c', 'd')",
} as FreeFormAdhocFilter,
],
limit_b: undefined,
row_limit_b: 100,
timeseries_limit_metric_b: undefined,
order_desc_b: false,
truncate_metric_b: true,
show_empty_columns_b: true,
// chart configs
show_value: false,
show_valueB: undefined,
};
const formDataMixedChartWithAA = {
...formDataMixedChart,
rolling_type: RollingType.Cumsum,
time_compare: ['1 years ago'],
comparison_type: ComparisonType.Values,
resample_rule: '1AS',
resample_method: 'zerofill',
rolling_type_b: RollingType.Sum,
rolling_periods_b: 1,
min_periods_b: 1,
comparison_type_b: ComparisonType.Difference,
time_compare_b: ['3 years ago'],
resample_rule_b: '1A',
resample_method_b: 'asfreq',
};
test('should compile query object A', () => {
const query = buildQuery(formDataMixedChart).queries[0];
expect(query).toEqual({
time_range: '1980 : 2000',
since: undefined,
until: undefined,
granularity: 'ds',
filters: [],
extras: {
having: '',
time_grain_sqla: 'P1W',
where: "(foo in ('a', 'b'))",
},
applied_time_extras: {},
columns: ['foo'],
metrics: ['sum(sales)'],
annotation_layers: [],
row_limit: 10,
row_offset: undefined,
series_columns: ['foo'],
series_limit: 5,
series_limit_metric: undefined,
url_params: {},
custom_params: {},
custom_form_data: {},
is_timeseries: true,
time_offsets: [],
post_processing: [
{
operation: 'pivot',
options: {
aggregates: {
'sum(sales)': {
operator: 'mean',
},
},
columns: ['foo'],
drop_missing_columns: false,
index: ['__timestamp'],
},
},
{
operation: 'rename',
options: {
columns: {
'sum(sales)': null,
},
inplace: true,
level: 0,
},
},
{
operation: 'flatten',
},
],
orderby: [['count', false]],
});
});
test('should compile query object B', () => {
const query = buildQuery(formDataMixedChart).queries[1];
expect(query).toEqual({
time_range: '1980 : 2000',
since: undefined,
until: undefined,
granularity: 'ds',
filters: [],
extras: {
having: '',
time_grain_sqla: 'P1W',
where: "(name in ('c', 'd'))",
},
applied_time_extras: {},
columns: [],
metrics: ['count'],
annotation_layers: [],
row_limit: 100,
row_offset: undefined,
series_columns: [],
series_limit: 0,
series_limit_metric: undefined,
url_params: {},
custom_params: {},
custom_form_data: {},
is_timeseries: true,
time_offsets: [],
post_processing: [
{
operation: 'pivot',
options: {
aggregates: {
count: {
operator: 'mean',
},
},
columns: [],
drop_missing_columns: false,
index: ['__timestamp'],
},
},
{
operation: 'flatten',
},
],
orderby: [['count', true]],
});
});
test('should compile AA in query A', () => {
const query = buildQuery(formDataMixedChartWithAA).queries[0];
// time comparison
expect(query.time_offsets).toEqual(['1 years ago']);
// pivot
expect(
query.post_processing?.find(operator => operator?.operation === 'pivot'),
).toEqual({
operation: 'pivot',
options: {
index: ['__timestamp'],
columns: ['foo'],
drop_missing_columns: false,
aggregates: {
'sum(sales)': { operator: 'mean' },
'sum(sales)__1 years ago': { operator: 'mean' },
},
},
});
// cumsum
expect(
// prettier-ignore
query
.post_processing
?.find(operator => operator?.operation === 'cum')
?.operation,
).toEqual('cum');
// resample
expect(
// prettier-ignore
query
.post_processing
?.find(operator => operator?.operation === 'resample'),
).toEqual({
operation: 'resample',
options: {
method: 'asfreq',
rule: '1AS',
fill_value: 0,
},
});
});
test('should compile AA in query B', () => {
const query = buildQuery(formDataMixedChartWithAA).queries[1];
// time comparison
expect(query.time_offsets).toEqual(['3 years ago']);
// rolling total
expect(
// prettier-ignore
query
.post_processing
?.find(operator => operator?.operation === 'rolling'),
).toEqual({
operation: 'rolling',
options: {
rolling_type: 'sum',
window: 1,
min_periods: 1,
columns: {
count: 'count',
'count__3 years ago': 'count__3 years ago',
},
},
});
// resample
expect(
// prettier-ignore
query
.post_processing
?.find(operator => operator?.operation === 'resample'),
).toEqual({
operation: 'resample',
options: {
method: 'asfreq',
rule: '1A',
fill_value: null,
},
});
});
test('should convert a queryObject with x-axis although FF is disabled', () => {
let windowSpy: any;
beforeAll(() => {
// @ts-ignore
windowSpy = jest.spyOn(window, 'window', 'get').mockImplementation(() => ({
featureFlags: {
GENERIC_CHART_AXES: false,
},
}));
});
afterAll(() => {
windowSpy.mockRestore();
});
const { queries } = buildQuery({
...formDataMixedChart,
x_axis: 'my_index',
});
expect(queries[0]).toEqual({
time_range: '1980 : 2000',
since: undefined,
until: undefined,
granularity: 'ds',
filters: [],
extras: {
having: '',
where: "(foo in ('a', 'b'))",
time_grain_sqla: 'P1W',
},
applied_time_extras: {},
columns: [
{
columnType: 'BASE_AXIS',
expressionType: 'SQL',
label: 'my_index',
sqlExpression: 'my_index',
timeGrain: 'P1W',
},
'foo',
],
metrics: ['sum(sales)'],
annotation_layers: [],
row_limit: 10,
row_offset: undefined,
series_columns: ['foo'],
series_limit: 5,
series_limit_metric: undefined,
url_params: {},
custom_params: {},
custom_form_data: {},
time_offsets: [],
post_processing: [
{
operation: 'pivot',
options: {
aggregates: {
'sum(sales)': {
operator: 'mean',
},
},
columns: ['foo'],
drop_missing_columns: false,
index: ['my_index'],
},
},
{
operation: 'rename',
options: {
columns: {
'sum(sales)': null,
},
inplace: true,
level: 0,
},
},
{
operation: 'flatten',
},
],
orderby: [['count', false]],
});
// check the main props on the second query
expect(queries[1]).toEqual(
expect.objectContaining({
columns: [
{
columnType: 'BASE_AXIS',
expressionType: 'SQL',
label: 'my_index',
sqlExpression: 'my_index',
timeGrain: 'P1W',
},
],
granularity: 'ds',
series_columns: [],
metrics: ['count'],
post_processing: [
{
operation: 'pivot',
options: {
aggregates: {
count: {
operator: 'mean',
},
},
columns: [],
drop_missing_columns: false,
index: ['my_index'],
},
},
{
operation: 'flatten',
},
],
}),
);
});
test("shouldn't convert a queryObject with axis although FF is enabled", () => {
const windowSpy = jest
.spyOn(window, 'window', 'get')
// @ts-ignore
.mockImplementation(() => ({
featureFlags: {
GENERIC_CHART_AXES: true,
},
}));
const { queries } = buildQuery(formDataMixedChart);
expect(queries[0]).toEqual(
expect.objectContaining({
granularity: 'ds',
columns: ['foo'],
series_columns: ['foo'],
metrics: ['sum(sales)'],
is_timeseries: true,
extras: {
time_grain_sqla: 'P1W',
having: '',
where: "(foo in ('a', 'b'))",
},
post_processing: [
{
operation: 'pivot',
options: {
aggregates: {
'sum(sales)': {
operator: 'mean',
},
},
columns: ['foo'],
drop_missing_columns: false,
index: ['__timestamp'],
},
},
{
operation: 'rename',
options: { columns: { 'sum(sales)': null }, inplace: true, level: 0 },
},
{
operation: 'flatten',
},
],
}),
);
expect(queries[1]).toEqual(
expect.objectContaining({
granularity: 'ds',
columns: [],
series_columns: [],
metrics: ['count'],
is_timeseries: true,
extras: {
time_grain_sqla: 'P1W',
having: '',
where: "(name in ('c', 'd'))",
},
post_processing: [
{
operation: 'pivot',
options: {
aggregates: {
count: {
operator: 'mean',
},
},
columns: [],
drop_missing_columns: false,
index: ['__timestamp'],
},
},
{
operation: 'flatten',
},
],
}),
);
windowSpy.mockRestore();
});
test('ensure correct pivot columns with GENERIC_CHART_AXES enabled', () => {
const windowSpy = jest
.spyOn(window, 'window', 'get')
// @ts-ignore
.mockImplementation(() => ({
featureFlags: {
GENERIC_CHART_AXES: true,
},
}));
const query = buildQuery({ ...formDataMixedChartWithAA, x_axis: 'ds' })
.queries[0];
expect(query.time_offsets).toEqual(['1 years ago']);
// pivot
expect(
query.post_processing?.find(operator => operator?.operation === 'pivot'),
).toEqual({
operation: 'pivot',
options: {
index: ['ds'],
columns: ['foo'],
drop_missing_columns: false,
aggregates: {
'sum(sales)': { operator: 'mean' },
'sum(sales)__1 years ago': { operator: 'mean' },
},
},
});
windowSpy.mockRestore();
});
|
6,276 | 0 | petrpan-code/apache/superset/superset-frontend/plugins/plugin-chart-echarts/test | petrpan-code/apache/superset/superset-frontend/plugins/plugin-chart-echarts/test/Pie/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 buildQuery from '../../src/Pie/buildQuery';
describe('Pie buildQuery', () => {
const formData = {
datasource: '5__table',
granularity_sqla: 'ds',
metric: 'foo',
groupby: ['bar'],
viz_type: 'my_chart',
};
it('should build query fields from form data', () => {
const queryContext = buildQuery(formData);
const [query] = queryContext.queries;
expect(query.metrics).toEqual(['foo']);
expect(query.columns).toEqual(['bar']);
});
});
|
6,277 | 0 | petrpan-code/apache/superset/superset-frontend/plugins/plugin-chart-echarts/test | petrpan-code/apache/superset/superset-frontend/plugins/plugin-chart-echarts/test/Pie/transformProps.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 {
ChartProps,
getNumberFormatter,
SqlaFormData,
supersetTheme,
} from '@superset-ui/core';
import transformProps, { formatPieLabel } from '../../src/Pie/transformProps';
import { EchartsPieChartProps, EchartsPieLabelType } from '../../src/Pie/types';
describe('Pie transformProps', () => {
const formData: SqlaFormData = {
colorScheme: 'bnbColors',
datasource: '3__table',
granularity_sqla: 'ds',
metric: 'sum__num',
groupby: ['foo', 'bar'],
viz_type: 'my_viz',
};
const chartProps = new ChartProps({
formData,
width: 800,
height: 600,
queriesData: [
{
data: [
{ foo: 'Sylvester', bar: 1, sum__num: 10 },
{ foo: 'Arnold', bar: 2, sum__num: 2.5 },
],
},
],
theme: supersetTheme,
});
it('should transform chart props for viz', () => {
expect(transformProps(chartProps as EchartsPieChartProps)).toEqual(
expect.objectContaining({
width: 800,
height: 600,
echartOptions: expect.objectContaining({
series: [
expect.objectContaining({
avoidLabelOverlap: true,
data: expect.arrayContaining([
expect.objectContaining({
name: 'Arnold, 2',
value: 2.5,
}),
expect.objectContaining({
name: 'Sylvester, 1',
value: 10,
}),
]),
}),
],
}),
}),
);
});
});
describe('formatPieLabel', () => {
it('should generate a valid pie chart label', () => {
const numberFormatter = getNumberFormatter();
const params = { name: 'My Label', value: 1234, percent: 12.34 };
expect(
formatPieLabel({
params,
numberFormatter,
labelType: EchartsPieLabelType.Key,
}),
).toEqual('My Label');
expect(
formatPieLabel({
params,
numberFormatter,
labelType: EchartsPieLabelType.Value,
}),
).toEqual('1.23k');
expect(
formatPieLabel({
params,
numberFormatter,
labelType: EchartsPieLabelType.Percent,
}),
).toEqual('12.34%');
expect(
formatPieLabel({
params,
numberFormatter,
labelType: EchartsPieLabelType.KeyValue,
}),
).toEqual('My Label: 1.23k');
expect(
formatPieLabel({
params,
numberFormatter,
labelType: EchartsPieLabelType.KeyPercent,
}),
).toEqual('My Label: 12.34%');
expect(
formatPieLabel({
params,
numberFormatter,
labelType: EchartsPieLabelType.KeyValuePercent,
}),
).toEqual('My Label: 1.23k (12.34%)');
expect(
formatPieLabel({
params: { ...params, name: '<NULL>' },
numberFormatter,
labelType: EchartsPieLabelType.Key,
}),
).toEqual('<NULL>');
expect(
formatPieLabel({
params: { ...params, name: '<NULL>' },
numberFormatter,
labelType: EchartsPieLabelType.Key,
sanitizeName: true,
}),
).toEqual('<NULL>');
});
});
|
6,278 | 0 | petrpan-code/apache/superset/superset-frontend/plugins/plugin-chart-echarts/test | petrpan-code/apache/superset/superset-frontend/plugins/plugin-chart-echarts/test/Timeseries/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 { SqlaFormData } from '@superset-ui/core';
import buildQuery from '../../src/Timeseries/buildQuery';
describe('Timeseries buildQuery', () => {
const formData = {
datasource: '5__table',
granularity_sqla: 'ds',
metrics: ['bar', 'baz'],
viz_type: 'my_chart',
};
it('should build groupby with series in form data', () => {
const queryContext = buildQuery(formData);
const [query] = queryContext.queries;
expect(query.metrics).toEqual(['bar', 'baz']);
});
it('should order by timeseries limit if orderby unspecified', () => {
const queryContext = buildQuery({
...formData,
timeseries_limit_metric: 'bar',
order_desc: true,
});
const [query] = queryContext.queries;
expect(query.metrics).toEqual(['bar', 'baz']);
expect(query.series_limit_metric).toEqual('bar');
expect(query.order_desc).toEqual(true);
expect(query.orderby).toEqual([['bar', false]]);
});
it('should not order by timeseries limit if orderby provided', () => {
const queryContext = buildQuery({
...formData,
timeseries_limit_metric: 'bar',
order_desc: true,
orderby: [['foo', true]],
});
const [query] = queryContext.queries;
expect(query.metrics).toEqual(['bar', 'baz']);
expect(query.series_limit_metric).toEqual('bar');
expect(query.order_desc).toEqual(true);
expect(query.orderby).toEqual([['foo', true]]);
});
});
describe('GENERIC_CHART_AXES is enabled', () => {
let windowSpy: any;
beforeAll(() => {
// @ts-ignore
windowSpy = jest.spyOn(window, 'window', 'get').mockImplementation(() => ({
featureFlags: {
GENERIC_CHART_AXES: true,
},
}));
});
afterAll(() => {
windowSpy.mockRestore();
});
const formData: SqlaFormData = {
datasource: '5__table',
viz_type: 'table',
granularity_sqla: 'time_column',
time_grain_sqla: 'P1Y',
time_range: '1 year ago : 2013',
groupby: ['col1'],
metrics: ['count(*)'],
};
it("shouldn't convert queryObject", () => {
const { queries } = buildQuery(formData);
expect(queries[0]).toEqual(
expect.objectContaining({
granularity: 'time_column',
time_range: '1 year ago : 2013',
extras: { time_grain_sqla: 'P1Y', having: '', where: '' },
columns: ['col1'],
series_columns: ['col1'],
metrics: ['count(*)'],
is_timeseries: true,
post_processing: [
{
operation: 'pivot',
options: {
aggregates: { 'count(*)': { operator: 'mean' } },
columns: ['col1'],
drop_missing_columns: true,
index: ['__timestamp'],
},
},
{ operation: 'flatten' },
],
}),
);
});
it('should convert queryObject', () => {
const { queries } = buildQuery({ ...formData, x_axis: 'time_column' });
expect(queries[0]).toEqual(
expect.objectContaining({
granularity: 'time_column',
time_range: '1 year ago : 2013',
extras: { having: '', where: '', time_grain_sqla: 'P1Y' },
columns: [
{
columnType: 'BASE_AXIS',
expressionType: 'SQL',
label: 'time_column',
sqlExpression: 'time_column',
timeGrain: 'P1Y',
},
'col1',
],
series_columns: ['col1'],
metrics: ['count(*)'],
post_processing: [
{
operation: 'pivot',
options: {
aggregates: { 'count(*)': { operator: 'mean' } },
columns: ['col1'],
drop_missing_columns: true,
index: ['time_column'],
},
},
{ operation: 'flatten' },
],
}),
);
});
});
describe('GENERIC_CHART_AXES is disabled', () => {
let windowSpy: any;
beforeAll(() => {
// @ts-ignore
windowSpy = jest.spyOn(window, 'window', 'get').mockImplementation(() => ({
featureFlags: {
GENERIC_CHART_AXES: false,
},
}));
});
afterAll(() => {
windowSpy.mockRestore();
});
const formData: SqlaFormData = {
datasource: '5__table',
viz_type: 'table',
granularity_sqla: 'time_column',
time_grain_sqla: 'P1Y',
time_range: '1 year ago : 2013',
groupby: ['col1'],
metrics: ['count(*)'],
};
it("shouldn't convert queryObject", () => {
const { queries } = buildQuery(formData);
expect(queries[0]).toEqual(
expect.objectContaining({
granularity: 'time_column',
time_range: '1 year ago : 2013',
extras: { time_grain_sqla: 'P1Y', having: '', where: '' },
columns: ['col1'],
series_columns: ['col1'],
metrics: ['count(*)'],
is_timeseries: true,
post_processing: [
{
operation: 'pivot',
options: {
aggregates: { 'count(*)': { operator: 'mean' } },
columns: ['col1'],
drop_missing_columns: true,
index: ['__timestamp'],
},
},
{ operation: 'flatten' },
],
}),
);
});
it('should convert queryObject', () => {
const { queries } = buildQuery({ ...formData, x_axis: 'time_column' });
expect(queries[0]).toEqual(
expect.objectContaining({
granularity: 'time_column',
time_range: '1 year ago : 2013',
extras: { having: '', where: '', time_grain_sqla: 'P1Y' },
columns: [
{
columnType: 'BASE_AXIS',
expressionType: 'SQL',
label: 'time_column',
sqlExpression: 'time_column',
timeGrain: 'P1Y',
},
'col1',
],
series_columns: ['col1'],
metrics: ['count(*)'],
post_processing: [
{
operation: 'pivot',
options: {
aggregates: { 'count(*)': { operator: 'mean' } },
columns: ['col1'],
drop_missing_columns: true,
index: ['time_column'],
},
},
{ operation: 'flatten' },
],
}),
);
});
});
|
6,279 | 0 | petrpan-code/apache/superset/superset-frontend/plugins/plugin-chart-echarts/test | petrpan-code/apache/superset/superset-frontend/plugins/plugin-chart-echarts/test/Timeseries/transformProps.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 {
AnnotationSourceType,
AnnotationStyle,
AnnotationType,
ChartProps,
EventAnnotationLayer,
FormulaAnnotationLayer,
IntervalAnnotationLayer,
SqlaFormData,
supersetTheme,
TimeseriesAnnotationLayer,
} from '@superset-ui/core';
import { EchartsTimeseriesChartProps } from '../../src/types';
import transformProps from '../../src/Timeseries/transformProps';
describe('EchartsTimeseries transformProps', () => {
const formData: SqlaFormData = {
colorScheme: 'bnbColors',
datasource: '3__table',
granularity_sqla: 'ds',
metric: 'sum__num',
groupby: ['foo', 'bar'],
viz_type: 'my_viz',
};
const queriesData = [
{
data: [
{ 'San Francisco': 1, 'New York': 2, __timestamp: 599616000000 },
{ 'San Francisco': 3, 'New York': 4, __timestamp: 599916000000 },
],
},
];
const chartPropsConfig = {
formData,
width: 800,
height: 600,
queriesData,
theme: supersetTheme,
};
it('should transform chart props for viz', () => {
const chartProps = new ChartProps(chartPropsConfig);
expect(transformProps(chartProps as EchartsTimeseriesChartProps)).toEqual(
expect.objectContaining({
width: 800,
height: 600,
echartOptions: expect.objectContaining({
legend: expect.objectContaining({
data: ['San Francisco', 'New York'],
}),
series: expect.arrayContaining([
expect.objectContaining({
data: [
[599616000000, 1],
[599916000000, 3],
],
name: 'San Francisco',
}),
expect.objectContaining({
data: [
[599616000000, 2],
[599916000000, 4],
],
name: 'New York',
}),
]),
}),
}),
);
});
it('should transform chart props for horizontal viz', () => {
const chartProps = new ChartProps({
...chartPropsConfig,
formData: {
...formData,
orientation: 'horizontal',
},
});
expect(transformProps(chartProps as EchartsTimeseriesChartProps)).toEqual(
expect.objectContaining({
width: 800,
height: 600,
echartOptions: expect.objectContaining({
legend: expect.objectContaining({
data: ['San Francisco', 'New York'],
}),
series: expect.arrayContaining([
expect.objectContaining({
data: [
[1, 599616000000],
[3, 599916000000],
],
name: 'San Francisco',
}),
expect.objectContaining({
data: [
[2, 599616000000],
[4, 599916000000],
],
name: 'New York',
}),
]),
yAxis: expect.objectContaining({ inverse: true }),
}),
}),
);
});
it('should add a formula annotation to viz', () => {
const formula: FormulaAnnotationLayer = {
name: 'My Formula',
annotationType: AnnotationType.Formula,
value: 'x+1',
style: AnnotationStyle.Solid,
show: true,
showLabel: true,
};
const chartProps = new ChartProps({
...chartPropsConfig,
formData: {
...formData,
annotationLayers: [formula],
},
});
expect(transformProps(chartProps as EchartsTimeseriesChartProps)).toEqual(
expect.objectContaining({
width: 800,
height: 600,
echartOptions: expect.objectContaining({
legend: expect.objectContaining({
data: ['San Francisco', 'New York', 'My Formula'],
}),
series: expect.arrayContaining([
expect.objectContaining({
data: [
[599616000000, 1],
[599916000000, 3],
],
name: 'San Francisco',
}),
expect.objectContaining({
data: [
[599616000000, 2],
[599916000000, 4],
],
name: 'New York',
}),
expect.objectContaining({
data: [
[599616000000, 599616000001],
[599916000000, 599916000001],
],
name: 'My Formula',
}),
]),
}),
}),
);
});
it('should add an interval, event and timeseries annotation to viz', () => {
const event: EventAnnotationLayer = {
annotationType: AnnotationType.Event,
name: 'My Event',
show: true,
showLabel: true,
sourceType: AnnotationSourceType.Native,
style: AnnotationStyle.Solid,
value: 1,
};
const interval: IntervalAnnotationLayer = {
annotationType: AnnotationType.Interval,
name: 'My Interval',
show: true,
showLabel: true,
sourceType: AnnotationSourceType.Table,
titleColumn: '',
timeColumn: 'start',
intervalEndColumn: '',
descriptionColumns: [],
style: AnnotationStyle.Dashed,
value: 2,
};
const timeseries: TimeseriesAnnotationLayer = {
annotationType: AnnotationType.Timeseries,
name: 'My Timeseries',
show: true,
showLabel: true,
sourceType: AnnotationSourceType.Line,
style: AnnotationStyle.Solid,
titleColumn: '',
value: 3,
};
const annotationData = {
'My Event': {
columns: [
'start_dttm',
'end_dttm',
'short_descr',
'long_descr',
'json_metadata',
],
records: [
{
start_dttm: 0,
end_dttm: 1000,
short_descr: '',
long_descr: '',
json_metadata: null,
},
],
},
'My Interval': {
columns: ['start', 'end', 'title'],
records: [
{
start: 2000,
end: 3000,
title: 'My Title',
},
],
},
'My Timeseries': [
{
key: 'My Line',
values: [
{
x: 10000,
y: 11000,
},
{
x: 20000,
y: 21000,
},
],
},
],
};
const chartProps = new ChartProps({
...chartPropsConfig,
formData: {
...formData,
annotationLayers: [event, interval, timeseries],
},
annotationData,
queriesData: [
{
...queriesData[0],
annotation_data: annotationData,
},
],
});
expect(transformProps(chartProps as EchartsTimeseriesChartProps)).toEqual(
expect.objectContaining({
echartOptions: expect.objectContaining({
legend: expect.objectContaining({
data: ['San Francisco', 'New York', 'My Line'],
}),
series: expect.arrayContaining([
expect.objectContaining({
type: 'line',
id: 'My Line',
}),
expect.objectContaining({
type: 'line',
id: 'Event - My Event',
}),
expect.objectContaining({
type: 'line',
id: 'Interval - My Interval',
}),
]),
}),
}),
);
});
it('Should add a baseline series for stream graph', () => {
const streamQueriesData = [
{
data: [
{
'San Francisco': 120,
'New York': 220,
Boston: 150,
Miami: 270,
Denver: 800,
__timestamp: 599616000000,
},
{
'San Francisco': 150,
'New York': 190,
Boston: 240,
Miami: 350,
Denver: 700,
__timestamp: 599616000001,
},
{
'San Francisco': 130,
'New York': 300,
Boston: 250,
Miami: 410,
Denver: 650,
__timestamp: 599616000002,
},
{
'San Francisco': 90,
'New York': 340,
Boston: 300,
Miami: 480,
Denver: 590,
__timestamp: 599616000003,
},
{
'San Francisco': 260,
'New York': 200,
Boston: 420,
Miami: 490,
Denver: 760,
__timestamp: 599616000004,
},
{
'San Francisco': 250,
'New York': 250,
Boston: 380,
Miami: 360,
Denver: 400,
__timestamp: 599616000005,
},
{
'San Francisco': 160,
'New York': 210,
Boston: 330,
Miami: 440,
Denver: 580,
__timestamp: 599616000006,
},
],
},
];
const streamFormData = { ...formData, stack: 'Stream' };
const props = {
...chartPropsConfig,
formData: streamFormData,
queriesData: streamQueriesData,
};
const chartProps = new ChartProps(props);
expect(
(
transformProps(chartProps as EchartsTimeseriesChartProps).echartOptions
.series as any[]
)[0],
).toEqual({
areaStyle: {
opacity: 0,
},
lineStyle: {
opacity: 0,
},
name: 'baseline',
showSymbol: false,
silent: true,
smooth: false,
stack: 'obs',
stackStrategy: 'all',
step: undefined,
tooltip: {
show: false,
},
type: 'line',
data: [
[599616000000, -415.7692307692308],
[599616000001, -403.6219915054271],
[599616000002, -476.32314093071443],
[599616000003, -514.2120298196033],
[599616000004, -485.7378514158475],
[599616000005, -419.6402904402378],
[599616000006, -442.9833136960517],
],
});
});
});
describe('Does transformProps transform series correctly', () => {
type seriesDataType = [Date, number];
type labelFormatterType = (params: {
value: seriesDataType;
dataIndex: number;
seriesIndex: number;
}) => string;
type seriesType = {
label: { show: boolean; formatter: labelFormatterType };
data: seriesDataType[];
name: string;
};
const formData: SqlaFormData = {
viz_type: 'my_viz',
colorScheme: 'bnbColors',
datasource: '3__table',
granularity_sqla: 'ds',
metric: 'sum__num',
groupby: ['foo', 'bar'],
showValue: true,
stack: true,
onlyTotal: false,
percentageThreshold: 50,
};
const queriesData = [
{
data: [
{
'San Francisco': 1,
'New York': 2,
Boston: 1,
__timestamp: 599616000000,
},
{
'San Francisco': 3,
'New York': 4,
Boston: 1,
__timestamp: 599916000000,
},
{
'San Francisco': 5,
'New York': 8,
Boston: 6,
__timestamp: 600216000000,
},
{
'San Francisco': 2,
'New York': 7,
Boston: 2,
__timestamp: 600516000000,
},
],
},
];
const chartPropsConfig = {
formData,
width: 800,
height: 600,
queriesData,
theme: supersetTheme,
};
const totalStackedValues = queriesData[0].data.reduce(
(totals, currentStack) => {
const total = Object.keys(currentStack).reduce((stackSum, key) => {
if (key === '__timestamp') return stackSum;
return stackSum + currentStack[key];
}, 0);
totals.push(total);
return totals;
},
[] as number[],
);
it('should show labels when showValue is true', () => {
const chartProps = new ChartProps(chartPropsConfig);
const transformedSeries = transformProps(
chartProps as EchartsTimeseriesChartProps,
).echartOptions.series as seriesType[];
transformedSeries.forEach(series => {
expect(series.label.show).toBe(true);
});
});
it('should not show labels when showValue is false', () => {
const updatedChartPropsConfig = {
...chartPropsConfig,
formData: { ...formData, showValue: false },
};
const chartProps = new ChartProps(updatedChartPropsConfig);
const transformedSeries = transformProps(
chartProps as EchartsTimeseriesChartProps,
).echartOptions.series as seriesType[];
transformedSeries.forEach(series => {
expect(series.label.show).toBe(false);
});
});
it('should show only totals when onlyTotal is true', () => {
const updatedChartPropsConfig = {
...chartPropsConfig,
formData: { ...formData, onlyTotal: true },
};
const chartProps = new ChartProps(updatedChartPropsConfig);
const transformedSeries = transformProps(
chartProps as EchartsTimeseriesChartProps,
).echartOptions.series as seriesType[];
const showValueIndexes: number[] = [];
transformedSeries.forEach((entry, seriesIndex) => {
const { data = [] } = entry;
(data as [Date, number][]).forEach((datum, dataIndex) => {
if (datum[1] !== null) {
showValueIndexes[dataIndex] = seriesIndex;
}
});
});
transformedSeries.forEach((series, seriesIndex) => {
expect(series.label.show).toBe(true);
series.data.forEach((value, dataIndex) => {
const params = {
value,
dataIndex,
seriesIndex,
};
let expectedLabel: string;
if (seriesIndex === showValueIndexes[dataIndex]) {
expectedLabel = String(totalStackedValues[dataIndex]);
} else {
expectedLabel = '';
}
expect(series.label.formatter(params)).toBe(expectedLabel);
});
});
});
it('should show labels on values >= percentageThreshold if onlyTotal is false', () => {
const chartProps = new ChartProps(chartPropsConfig);
const transformedSeries = transformProps(
chartProps as EchartsTimeseriesChartProps,
).echartOptions.series as seriesType[];
const expectedThresholds = totalStackedValues.map(
total => ((formData.percentageThreshold || 0) / 100) * total,
);
transformedSeries.forEach((series, seriesIndex) => {
expect(series.label.show).toBe(true);
series.data.forEach((value, dataIndex) => {
const params = {
value,
dataIndex,
seriesIndex,
};
const expectedLabel =
value[1] >= expectedThresholds[dataIndex] ? String(value[1]) : '';
expect(series.label.formatter(params)).toBe(expectedLabel);
});
});
});
it('should not apply percentage threshold when showValue is true and stack is false', () => {
const updatedChartPropsConfig = {
...chartPropsConfig,
formData: { ...formData, stack: false },
};
const chartProps = new ChartProps(updatedChartPropsConfig);
const transformedSeries = transformProps(
chartProps as EchartsTimeseriesChartProps,
).echartOptions.series as seriesType[];
transformedSeries.forEach((series, seriesIndex) => {
expect(series.label.show).toBe(true);
series.data.forEach((value, dataIndex) => {
const params = {
value,
dataIndex,
seriesIndex,
};
const expectedLabel = String(value[1]);
expect(series.label.formatter(params)).toBe(expectedLabel);
});
});
});
it('should remove time shift labels from label_map', () => {
const updatedChartPropsConfig = {
...chartPropsConfig,
formData: {
...formData,
timeCompare: ['1 year ago'],
},
queriesData: [
{
...queriesData[0],
label_map: {
'1 year ago, foo1, bar1': ['1 year ago', 'foo1', 'bar1'],
'1 year ago, foo2, bar2': ['1 year ago', 'foo2', 'bar2'],
'foo1, bar1': ['foo1', 'bar1'],
'foo2, bar2': ['foo2', 'bar2'],
},
},
],
};
const chartProps = new ChartProps(updatedChartPropsConfig);
const transformedProps = transformProps(
chartProps as EchartsTimeseriesChartProps,
);
expect(transformedProps.labelMap).toEqual({
'1 year ago, foo1, bar1': ['foo1', 'bar1'],
'1 year ago, foo2, bar2': ['foo2', 'bar2'],
'foo1, bar1': ['foo1', 'bar1'],
'foo2, bar2': ['foo2', 'bar2'],
});
});
});
|
6,280 | 0 | petrpan-code/apache/superset/superset-frontend/plugins/plugin-chart-echarts/test | petrpan-code/apache/superset/superset-frontend/plugins/plugin-chart-echarts/test/Tree/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 buildQuery from '../../src/Tree/buildQuery';
describe('Tree buildQuery', () => {
it('should build query', () => {
const formData = {
datasource: '5__table',
granularity_sqla: 'ds',
id: 'id_col',
parent: 'relation_col',
name: 'name_col',
metrics: ['foo', 'bar'],
viz_type: 'my_chart',
};
const queryContext = buildQuery(formData);
const [query] = queryContext.queries;
expect(query.columns).toEqual(['id_col', 'relation_col', 'name_col']);
expect(query.metrics).toEqual(['foo', 'bar']);
});
it('should build query without name column', () => {
const formData = {
datasource: '5__table',
granularity_sqla: 'ds',
id: 'id_col',
parent: 'relation_col',
metrics: ['foo', 'bar'],
viz_type: 'my_chart',
};
const queryContext = buildQuery(formData);
const [query] = queryContext.queries;
expect(query.columns).toEqual(['id_col', 'relation_col']);
expect(query.metrics).toEqual(['foo', 'bar']);
});
});
|
6,281 | 0 | petrpan-code/apache/superset/superset-frontend/plugins/plugin-chart-echarts/test | petrpan-code/apache/superset/superset-frontend/plugins/plugin-chart-echarts/test/Tree/transformProps.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 { ChartProps, supersetTheme } from '@superset-ui/core';
import transformProps from '../../src/Tree/transformProps';
import { EchartsTreeChartProps } from '../../src/Tree/types';
describe('EchartsTree transformProps', () => {
const formData = {
colorScheme: 'bnbColors',
datasource: '3__table',
granularity_sqla: 'ds',
metric: 'count',
id: 'id_column',
parent: 'relation_column',
name: 'name_column',
rootNodeId: '1',
};
const chartPropsConfig = {
formData,
width: 800,
height: 600,
theme: supersetTheme,
};
it('should transform when parent present before child', () => {
const queriesData = [
{
colnames: ['id_column', 'relation_column', 'name_column', 'count'],
data: [
{
id_column: '1',
relation_column: null,
name_column: 'root',
count: 10,
},
{
id_column: '2',
relation_column: '1',
name_column: 'first_child',
count: 10,
},
{
id_column: '3',
relation_column: '2',
name_column: 'second_child',
count: 10,
},
{
id_column: '4',
relation_column: '3',
name_column: 'third_child',
count: 10,
},
],
},
];
const chartProps = new ChartProps({ ...chartPropsConfig, queriesData });
expect(transformProps(chartProps as EchartsTreeChartProps)).toEqual(
expect.objectContaining({
width: 800,
height: 600,
echartOptions: expect.objectContaining({
series: expect.arrayContaining([
expect.objectContaining({
data: [
{
name: 'root',
children: [
{
name: 'first_child',
value: 10,
children: [
{
name: 'second_child',
value: 10,
children: [
{ name: 'third_child', value: 10, children: [] },
],
},
],
},
],
},
],
}),
]),
}),
}),
);
});
it('should transform when child is present before parent', () => {
const queriesData = [
{
colnames: ['id_column', 'relation_column', 'name_column', 'count'],
data: [
{
id_column: '1',
relation_column: null,
name_column: 'root',
count: 10,
},
{
id_column: '2',
relation_column: '4',
name_column: 'second_child',
count: 20,
},
{
id_column: '3',
relation_column: '4',
name_column: 'second_child',
count: 30,
},
{
id_column: '4',
relation_column: '1',
name_column: 'first_child',
count: 40,
},
],
},
];
const chartProps = new ChartProps({ ...chartPropsConfig, queriesData });
expect(transformProps(chartProps as EchartsTreeChartProps)).toEqual(
expect.objectContaining({
width: 800,
height: 600,
echartOptions: expect.objectContaining({
series: expect.arrayContaining([
expect.objectContaining({
data: [
{
name: 'root',
children: [
{
name: 'first_child',
value: 40,
children: [
{
name: 'second_child',
value: 20,
children: [],
},
{
name: 'second_child',
value: 30,
children: [],
},
],
},
],
},
],
}),
]),
}),
}),
);
});
it('ignore node if not attached to root', () => {
const formData = {
colorScheme: 'bnbColors',
datasource: '3__table',
granularity_sqla: 'ds',
metric: 'count',
id: 'id_column',
parent: 'relation_column',
name: 'name_column',
rootNodeId: '2',
};
const chartPropsConfig = {
formData,
width: 800,
height: 600,
theme: supersetTheme,
};
const queriesData = [
{
colnames: ['id_column', 'relation_column', 'name_column', 'count'],
data: [
{
id_column: '1',
relation_column: null,
name_column: 'root',
count: 10,
},
{
id_column: '2',
relation_column: '1',
name_column: 'first_child',
count: 10,
},
{
id_column: '3',
relation_column: '2',
name_column: 'second_child',
count: 10,
},
{
id_column: '4',
relation_column: '3',
name_column: 'third_child',
count: 20,
},
],
},
];
const chartProps = new ChartProps({ ...chartPropsConfig, queriesData });
expect(transformProps(chartProps as EchartsTreeChartProps)).toEqual(
expect.objectContaining({
width: 800,
height: 600,
echartOptions: expect.objectContaining({
series: expect.arrayContaining([
expect.objectContaining({
data: [
{
name: 'first_child',
children: [
{
name: 'second_child',
value: 10,
children: [
{
name: 'third_child',
value: 20,
children: [],
},
],
},
],
},
],
}),
]),
}),
}),
);
});
it('should transform props if name column is not specified', () => {
const formData = {
colorScheme: 'bnbColors',
datasource: '3__table',
granularity_sqla: 'ds',
metric: 'count',
id: 'id_column',
parent: 'relation_column',
rootNodeId: '1',
};
const chartPropsConfig = {
formData,
width: 800,
height: 600,
theme: supersetTheme,
};
const queriesData = [
{
colnames: ['id_column', 'relation_column', 'count'],
data: [
{
id_column: '1',
relation_column: null,
count: 10,
},
{
id_column: '2',
relation_column: '1',
count: 10,
},
{
id_column: '3',
relation_column: '2',
count: 10,
},
{
id_column: '4',
relation_column: '3',
count: 20,
},
],
},
];
const chartProps = new ChartProps({ ...chartPropsConfig, queriesData });
expect(transformProps(chartProps as EchartsTreeChartProps)).toEqual(
expect.objectContaining({
width: 800,
height: 600,
echartOptions: expect.objectContaining({
series: expect.arrayContaining([
expect.objectContaining({
data: [
{
name: '1',
children: [
{
name: '2',
value: 10,
children: [
{
name: '3',
value: 10,
children: [
{
name: '4',
value: 20,
children: [],
},
],
},
],
},
],
},
],
}),
]),
}),
}),
);
});
it('should find root node with null parent when root node name is not provided', () => {
const formData = {
colorScheme: 'bnbColors',
datasource: '3__table',
granularity_sqla: 'ds',
metric: 'count',
id: 'id_column',
parent: 'relation_column',
name: 'name_column',
};
const chartPropsConfig = {
formData,
width: 800,
height: 600,
theme: supersetTheme,
};
const queriesData = [
{
colnames: ['id_column', 'relation_column', 'name_column', 'count'],
data: [
{
id_column: '2',
relation_column: '4',
name_column: 'second_child',
count: 20,
},
{
id_column: '3',
relation_column: '4',
name_column: 'second_child',
count: 30,
},
{
id_column: '4',
relation_column: '1',
name_column: 'first_child',
count: 40,
},
{
id_column: '1',
relation_column: null,
name_column: 'root',
count: 10,
},
],
},
];
const chartProps = new ChartProps({ ...chartPropsConfig, queriesData });
expect(transformProps(chartProps as EchartsTreeChartProps)).toEqual(
expect.objectContaining({
width: 800,
height: 600,
echartOptions: expect.objectContaining({
series: expect.arrayContaining([
expect.objectContaining({
data: [
{
name: 'root',
children: [
{
name: 'first_child',
value: 40,
children: [
{
name: 'second_child',
value: 20,
children: [],
},
{
name: 'second_child',
value: 30,
children: [],
},
],
},
],
},
],
}),
]),
}),
}),
);
});
});
|
6,282 | 0 | petrpan-code/apache/superset/superset-frontend/plugins/plugin-chart-echarts/test | petrpan-code/apache/superset/superset-frontend/plugins/plugin-chart-echarts/test/Treemap/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 buildQuery from '../../src/Treemap/buildQuery';
describe('Treemap buildQuery', () => {
const formData = {
datasource: '5__table',
granularity_sqla: 'ds',
metric: 'foo',
groupby: ['bar'],
viz_type: 'my_chart',
};
it('should build query fields from form data', () => {
const queryContext = buildQuery(formData);
const [query] = queryContext.queries;
expect(query.metrics).toEqual(['foo']);
expect(query.columns).toEqual(['bar']);
});
});
|
6,283 | 0 | petrpan-code/apache/superset/superset-frontend/plugins/plugin-chart-echarts/test | petrpan-code/apache/superset/superset-frontend/plugins/plugin-chart-echarts/test/Treemap/transformProps.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 { ChartProps, supersetTheme } from '@superset-ui/core';
import { EchartsTreemapChartProps } from '../../src/Treemap/types';
import transformProps from '../../src/Treemap/transformProps';
describe('Treemap transformProps', () => {
const formData = {
colorScheme: 'bnbColors',
datasource: '3__table',
granularity_sqla: 'ds',
metric: 'sum__num',
groupby: ['foo', 'bar'],
};
const chartProps = new ChartProps({
formData,
width: 800,
height: 600,
queriesData: [
{
data: [
{ foo: 'Sylvester', bar: 'bar1', sum__num: 10 },
{ foo: 'Arnold', bar: 'bar2', sum__num: 2.5 },
],
},
],
theme: supersetTheme,
});
it('should transform chart props for viz', () => {
expect(transformProps(chartProps as EchartsTreemapChartProps)).toEqual(
expect.objectContaining({
width: 800,
height: 600,
echartOptions: expect.objectContaining({
series: [
expect.objectContaining({
data: expect.arrayContaining([
expect.objectContaining({
name: 'sum__num',
children: expect.arrayContaining([
expect.objectContaining({
name: 'Sylvester',
children: expect.arrayContaining([
expect.objectContaining({
name: 'bar1',
value: 10,
}),
]),
}),
]),
}),
]),
}),
],
}),
}),
);
});
});
|
6,284 | 0 | petrpan-code/apache/superset/superset-frontend/plugins/plugin-chart-echarts/test | petrpan-code/apache/superset/superset-frontend/plugins/plugin-chart-echarts/test/Waterfall/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 { SqlaFormData } from '@superset-ui/core';
import buildQuery from '../../src/Waterfall/buildQuery';
describe('Waterfall buildQuery', () => {
const formData = {
datasource: '5__table',
granularity_sqla: 'ds',
metric: 'foo',
x_axis: 'bar',
groupby: ['baz'],
viz_type: 'waterfall',
};
it('should build query fields from form data', () => {
const queryContext = buildQuery(formData as unknown as SqlaFormData);
const [query] = queryContext.queries;
expect(query.metrics).toEqual(['foo']);
expect(query.columns?.[0]).toEqual(
expect.objectContaining({ sqlExpression: 'bar' }),
);
expect(query.columns?.[1]).toEqual('baz');
});
});
|
6,285 | 0 | petrpan-code/apache/superset/superset-frontend/plugins/plugin-chart-echarts/test | petrpan-code/apache/superset/superset-frontend/plugins/plugin-chart-echarts/test/Waterfall/transformProps.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 { ChartProps, supersetTheme } from '@superset-ui/core';
import {
EchartsWaterfallChartProps,
WaterfallChartTransformedProps,
} from '../../src/Waterfall/types';
import transformProps from '../../src/Waterfall/transformProps';
const extractSeries = (props: WaterfallChartTransformedProps) => {
const { echartOptions } = props;
const { series } = echartOptions as unknown as {
series: [{ data: [{ value: number }] }];
};
return series.map(item => item.data).map(item => item.map(i => i.value));
};
describe('Waterfall tranformProps', () => {
const data = [
{ year: '2019', name: 'Sylvester', sum: 10 },
{ year: '2019', name: 'Arnold', sum: 3 },
{ year: '2020', name: 'Sylvester', sum: -10 },
{ year: '2020', name: 'Arnold', sum: 5 },
];
const formData = {
colorScheme: 'bnbColors',
datasource: '3__table',
x_axis: 'year',
metric: 'sum',
increaseColor: { r: 0, b: 0, g: 0 },
decreaseColor: { r: 0, b: 0, g: 0 },
totalColor: { r: 0, b: 0, g: 0 },
};
it('should tranform chart props for viz when breakdown not exist', () => {
const chartProps = new ChartProps({
formData: { ...formData, series: 'bar' },
width: 800,
height: 600,
queriesData: [
{
data,
},
],
theme: supersetTheme,
});
const transformedProps = transformProps(
chartProps as unknown as EchartsWaterfallChartProps,
);
expect(extractSeries(transformedProps)).toEqual([
[0, 8, '-'],
[13, '-', '-'],
['-', 5, '-'],
['-', '-', 8],
]);
});
it('should tranform chart props for viz when breakdown exist', () => {
const chartProps = new ChartProps({
formData: { ...formData, groupby: 'name' },
width: 800,
height: 600,
queriesData: [
{
data,
},
],
theme: supersetTheme,
});
const transformedProps = transformProps(
chartProps as unknown as EchartsWaterfallChartProps,
);
expect(extractSeries(transformedProps)).toEqual([
[0, 10, '-', 3, 3, '-'],
[10, 3, '-', '-', 5, '-'],
['-', '-', '-', 10, '-', '-'],
['-', '-', 13, '-', '-', 8],
]);
});
});
|
6,286 | 0 | petrpan-code/apache/superset/superset-frontend/plugins/plugin-chart-echarts/test | petrpan-code/apache/superset/superset-frontend/plugins/plugin-chart-echarts/test/utils/annotation.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 {
AnnotationData,
AnnotationLayer,
AnnotationOpacity,
AnnotationSourceType,
AnnotationStyle,
AnnotationType,
AxisType,
DataRecord,
FormulaAnnotationLayer,
TimeseriesDataRecord,
} from '@superset-ui/core';
import {
evalFormula,
extractAnnotationLabels,
formatAnnotationLabel,
parseAnnotationOpacity,
} from '../../src/utils/annotation';
describe('formatAnnotationLabel', () => {
it('should handle default cases properly', () => {
expect(formatAnnotationLabel('name')).toEqual('name');
expect(formatAnnotationLabel('name', 'title')).toEqual('name - title');
expect(formatAnnotationLabel('name', 'title', ['description'])).toEqual(
'name - title\n\ndescription',
);
});
it('should handle missing cases properly', () => {
expect(formatAnnotationLabel()).toEqual('');
expect(formatAnnotationLabel(undefined, 'title')).toEqual('title');
expect(formatAnnotationLabel('name', undefined, ['description'])).toEqual(
'name\n\ndescription',
);
expect(
formatAnnotationLabel(undefined, undefined, ['description']),
).toEqual('description');
});
it('should handle multiple descriptions properly', () => {
expect(
formatAnnotationLabel('name', 'title', [
'description 1',
'description 2',
]),
).toEqual('name - title\n\ndescription 1\ndescription 2');
expect(
formatAnnotationLabel(undefined, undefined, [
'description 1',
'description 2',
]),
).toEqual('description 1\ndescription 2');
});
});
describe('extractForecastSeriesContext', () => {
it('should extract the correct series name and type', () => {
expect(parseAnnotationOpacity(AnnotationOpacity.Low)).toEqual(0.2);
expect(parseAnnotationOpacity(AnnotationOpacity.Medium)).toEqual(0.5);
expect(parseAnnotationOpacity(AnnotationOpacity.High)).toEqual(0.8);
expect(parseAnnotationOpacity(AnnotationOpacity.Undefined)).toEqual(1);
expect(parseAnnotationOpacity(undefined)).toEqual(1);
});
});
describe('extractAnnotationLabels', () => {
it('should extract all annotations that can be added to the legend', () => {
const layers: AnnotationLayer[] = [
{
annotationType: AnnotationType.Formula,
name: 'My Formula',
show: true,
style: AnnotationStyle.Solid,
value: 'sin(x)',
showLabel: true,
},
{
annotationType: AnnotationType.Formula,
name: 'My Hidden Formula',
show: false,
style: AnnotationStyle.Solid,
value: 'sin(2x)',
showLabel: true,
},
{
annotationType: AnnotationType.Interval,
name: 'My Interval',
sourceType: AnnotationSourceType.Table,
show: true,
style: AnnotationStyle.Solid,
value: 1,
showLabel: true,
},
{
annotationType: AnnotationType.Timeseries,
name: 'My Line',
show: true,
style: AnnotationStyle.Dashed,
sourceType: AnnotationSourceType.Line,
value: 1,
showLabel: true,
},
{
annotationType: AnnotationType.Timeseries,
name: 'My Hidden Line',
show: false,
style: AnnotationStyle.Dashed,
sourceType: AnnotationSourceType.Line,
value: 1,
showLabel: true,
},
];
const results: AnnotationData = {
'My Interval': {
records: [{ col: 1 }],
},
'My Line': [
{ key: 'Line 1', values: [] },
{ key: 'Line 2', values: [] },
],
};
expect(extractAnnotationLabels(layers, results)).toEqual([
'My Formula',
'Line 1',
'Line 2',
]);
});
});
describe('evalFormula', () => {
const layer: FormulaAnnotationLayer = {
annotationType: AnnotationType.Formula,
name: 'My Formula',
show: true,
style: AnnotationStyle.Solid,
value: 'x+1',
showLabel: true,
};
it('Should evaluate a regular formula', () => {
const data: TimeseriesDataRecord[] = [
{ __timestamp: 0 },
{ __timestamp: 10 },
];
expect(evalFormula(layer, data, '__timestamp', AxisType.time)).toEqual([
[0, 1],
[10, 11],
]);
});
it('Should evaluate a formula containing redundant characters', () => {
const data: TimeseriesDataRecord[] = [
{ __timestamp: 0 },
{ __timestamp: 10 },
];
expect(
evalFormula(
{ ...layer, value: 'y = x* 2 -1' },
data,
'__timestamp',
AxisType.time,
),
).toEqual([
[0, -1],
[10, 19],
]);
});
it('Should evaluate a formula if axis type is category', () => {
const data: DataRecord[] = [{ gender: 'boy' }, { gender: 'girl' }];
expect(
evalFormula(
{ ...layer, value: 'y = 1000' },
data,
'gender',
AxisType.category,
),
).toEqual([
['boy', 1000],
['girl', 1000],
]);
});
});
|
6,287 | 0 | petrpan-code/apache/superset/superset-frontend/plugins/plugin-chart-echarts/test | petrpan-code/apache/superset/superset-frontend/plugins/plugin-chart-echarts/test/utils/controls.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 { parseYAxisBound } from '../../src/utils/controls';
describe('parseYAxisBound', () => {
it('should return undefined for invalid values', () => {
expect(parseYAxisBound(null)).toBeUndefined();
expect(parseYAxisBound(undefined)).toBeUndefined();
expect(parseYAxisBound(NaN)).toBeUndefined();
expect(parseYAxisBound('abc')).toBeUndefined();
});
it('should return numeric value for valid values', () => {
expect(parseYAxisBound(0)).toEqual(0);
expect(parseYAxisBound('0')).toEqual(0);
expect(parseYAxisBound(1)).toEqual(1);
expect(parseYAxisBound('1')).toEqual(1);
expect(parseYAxisBound(10.1)).toEqual(10.1);
expect(parseYAxisBound('10.1')).toEqual(10.1);
});
});
|
6,288 | 0 | petrpan-code/apache/superset/superset-frontend/plugins/plugin-chart-echarts/test | petrpan-code/apache/superset/superset-frontend/plugins/plugin-chart-echarts/test/utils/forecast.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 { getNumberFormatter, NumberFormats } from '@superset-ui/core';
import {
extractForecastSeriesContext,
extractForecastValuesFromTooltipParams,
formatForecastTooltipSeries,
rebaseForecastDatum,
} from '../../src/utils/forecast';
import { ForecastSeriesEnum } from '../../src/types';
describe('extractForecastSeriesContext', () => {
it('should extract the correct series name and type', () => {
expect(extractForecastSeriesContext('abcd')).toEqual({
name: 'abcd',
type: ForecastSeriesEnum.Observation,
});
expect(extractForecastSeriesContext('qwerty__yhat')).toEqual({
name: 'qwerty',
type: ForecastSeriesEnum.ForecastTrend,
});
expect(extractForecastSeriesContext('X Y Z___yhat_upper')).toEqual({
name: 'X Y Z_',
type: ForecastSeriesEnum.ForecastUpper,
});
expect(extractForecastSeriesContext('1 2 3__yhat_lower')).toEqual({
name: '1 2 3',
type: ForecastSeriesEnum.ForecastLower,
});
});
});
describe('rebaseForecastDatum', () => {
it('should subtract lower confidence level from upper value', () => {
expect(
rebaseForecastDatum([
{
__timestamp: new Date('2001-01-01'),
abc: 10,
abc__yhat_lower: 1,
abc__yhat_upper: 20,
},
{
__timestamp: new Date('2001-01-01'),
abc: 10,
abc__yhat_lower: -10,
abc__yhat_upper: 20,
},
{
__timestamp: new Date('2002-01-01'),
abc: 10,
abc__yhat_lower: null,
abc__yhat_upper: 20,
},
{
__timestamp: new Date('2003-01-01'),
abc: 10,
abc__yhat_lower: 1,
abc__yhat_upper: null,
},
]),
).toEqual([
{
__timestamp: new Date('2001-01-01'),
abc: 10,
abc__yhat_lower: 1,
abc__yhat_upper: 19,
},
{
__timestamp: new Date('2001-01-01'),
abc: 10,
abc__yhat_lower: -10,
abc__yhat_upper: 30,
},
{
__timestamp: new Date('2002-01-01'),
abc: 10,
abc__yhat_lower: null,
abc__yhat_upper: 20,
},
{
__timestamp: new Date('2003-01-01'),
abc: 10,
abc__yhat_lower: 1,
abc__yhat_upper: null,
},
]);
});
it('should rename all series based on verboseMap but leave __timestamp alone', () => {
expect(
rebaseForecastDatum(
[
{
__timestamp: new Date('2001-01-01'),
abc: 10,
abc__yhat_lower: 1,
abc__yhat_upper: 20,
},
{
__timestamp: new Date('2002-01-01'),
abc: 10,
abc__yhat_lower: null,
abc__yhat_upper: 20,
},
{
__timestamp: new Date('2003-01-01'),
abc: 10,
abc__yhat_lower: 1,
abc__yhat_upper: null,
},
],
{
abc: 'Abracadabra',
__timestamp: 'Time',
},
),
).toEqual([
{
__timestamp: new Date('2001-01-01'),
Abracadabra: 10,
Abracadabra__yhat_lower: 1,
Abracadabra__yhat_upper: 19,
},
{
__timestamp: new Date('2002-01-01'),
Abracadabra: 10,
Abracadabra__yhat_lower: null,
Abracadabra__yhat_upper: 20,
},
{
__timestamp: new Date('2003-01-01'),
Abracadabra: 10,
Abracadabra__yhat_lower: 1,
Abracadabra__yhat_upper: null,
},
]);
});
});
test('extractForecastValuesFromTooltipParams should extract the proper data from tooltip params', () => {
expect(
extractForecastValuesFromTooltipParams([
{
marker: '<img>',
seriesId: 'abc',
value: [new Date(0), 10],
},
{
marker: '<img>',
seriesId: 'abc__yhat',
value: [new Date(0), 1],
},
{
marker: '<img>',
seriesId: 'abc__yhat_lower',
value: [new Date(0), 5],
},
{
marker: '<img>',
seriesId: 'abc__yhat_upper',
value: [new Date(0), 6],
},
{
marker: '<img>',
seriesId: 'qwerty',
value: [new Date(0), 2],
},
]),
).toEqual({
abc: {
marker: '<img>',
observation: 10,
forecastTrend: 1,
forecastLower: 5,
forecastUpper: 6,
},
qwerty: {
marker: '<img>',
observation: 2,
},
});
});
test('extractForecastValuesFromTooltipParams should extract valid values', () => {
expect(
extractForecastValuesFromTooltipParams([
{
marker: '<img>',
seriesId: 'foo',
value: [0, 10],
},
{
marker: '<img>',
seriesId: 'bar',
value: [100, 0],
},
]),
).toEqual({
foo: {
marker: '<img>',
observation: 10,
},
bar: {
marker: '<img>',
observation: 0,
},
});
});
const formatter = getNumberFormatter(NumberFormats.INTEGER);
test('formatForecastTooltipSeries should apply format to value', () => {
expect(
formatForecastTooltipSeries({
seriesName: 'abc',
marker: '<img>',
observation: 10.1,
formatter,
}),
).toEqual('<img>abc: 10');
});
test('formatForecastTooltipSeries should show falsy value', () => {
expect(
formatForecastTooltipSeries({
seriesName: 'abc',
marker: '<img>',
observation: 0,
formatter,
}),
).toEqual('<img>abc: 0');
});
test('formatForecastTooltipSeries should format full forecast', () => {
expect(
formatForecastTooltipSeries({
seriesName: 'qwerty',
marker: '<img>',
observation: 10.1,
forecastTrend: 20.1,
forecastLower: 5.1,
forecastUpper: 7.1,
formatter,
}),
).toEqual('<img>qwerty: 10, ŷ = 20 (5, 12)');
});
test('formatForecastTooltipSeries should format forecast without observation', () => {
expect(
formatForecastTooltipSeries({
seriesName: 'qwerty',
marker: '<img>',
forecastTrend: 20,
forecastLower: 5,
forecastUpper: 7,
formatter,
}),
).toEqual('<img>qwerty: ŷ = 20 (5, 12)');
});
test('formatForecastTooltipSeries should format forecast without point estimate', () => {
expect(
formatForecastTooltipSeries({
seriesName: 'qwerty',
marker: '<img>',
observation: 10.1,
forecastLower: 6,
forecastUpper: 7,
formatter,
}),
).toEqual('<img>qwerty: 10 (6, 13)');
});
test('formatForecastTooltipSeries should format forecast with only confidence band', () => {
expect(
formatForecastTooltipSeries({
seriesName: 'qwerty',
marker: '<img>',
forecastLower: 7,
forecastUpper: 8,
formatter,
}),
).toEqual('<img>qwerty: (7, 15)');
});
|
6,289 | 0 | petrpan-code/apache/superset/superset-frontend/plugins/plugin-chart-echarts/test | petrpan-code/apache/superset/superset-frontend/plugins/plugin-chart-echarts/test/utils/formDataSuffix.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 {
retainFormDataSuffix,
removeFormDataSuffix,
} from '../../src/utils/formDataSuffix';
const formData = {
datasource: 'dummy',
viz_type: 'table',
metrics: ['a', 'b'],
columns: ['foo', 'bar'],
limit: 100,
metrics_b: ['c', 'd'],
columns_b: ['hello', 'world'],
limit_b: 200,
};
test('should keep controls with suffix', () => {
expect(retainFormDataSuffix(formData, '_b')).toEqual({
datasource: 'dummy',
viz_type: 'table',
metrics: ['c', 'd'],
columns: ['hello', 'world'],
limit: 200,
});
// no side effect
expect(retainFormDataSuffix(formData, '_b')).not.toEqual(formData);
});
test('should remove controls with suffix', () => {
expect(removeFormDataSuffix(formData, '_b')).toEqual({
datasource: 'dummy',
viz_type: 'table',
metrics: ['a', 'b'],
columns: ['foo', 'bar'],
limit: 100,
});
// no side effect
expect(removeFormDataSuffix(formData, '_b')).not.toEqual(formData);
});
|
6,290 | 0 | petrpan-code/apache/superset/superset-frontend/plugins/plugin-chart-echarts/test | petrpan-code/apache/superset/superset-frontend/plugins/plugin-chart-echarts/test/utils/series.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 { SortSeriesType } from '@superset-ui/chart-controls';
import {
DataRecord,
GenericDataType,
getNumberFormatter,
getTimeFormatter,
supersetTheme as theme,
} from '@superset-ui/core';
import {
calculateLowerLogTick,
dedupSeries,
extractGroupbyLabel,
extractSeries,
extractShowValueIndexes,
formatSeriesName,
getChartPadding,
getLegendProps,
getOverMaxHiddenFormatter,
sanitizeHtml,
sortAndFilterSeries,
sortRows,
} from '../../src/utils/series';
import { LegendOrientation, LegendType } from '../../src/types';
import { defaultLegendPadding } from '../../src/defaults';
import { NULL_STRING } from '../../src/constants';
const expectedThemeProps = {
selector: ['all', 'inverse'],
selectorLabel: {
fontFamily: theme.typography.families.sansSerif,
fontSize: theme.typography.sizes.s,
color: theme.colors.grayscale.base,
borderColor: theme.colors.grayscale.base,
},
};
const sortData: DataRecord[] = [
{ my_x_axis: 'abc', x: 1, y: 0, z: 2 },
{ my_x_axis: 'foo', x: null, y: 10, z: 5 },
{ my_x_axis: null, x: 4, y: 3, z: 7 },
];
const totalStackedValues = [3, 15, 14];
test('sortRows by name ascending', () => {
expect(
sortRows(
sortData,
totalStackedValues,
'my_x_axis',
SortSeriesType.Name,
true,
),
).toEqual([
{ row: { my_x_axis: 'abc', x: 1, y: 0, z: 2 }, totalStackedValue: 3 },
{ row: { my_x_axis: 'foo', x: null, y: 10, z: 5 }, totalStackedValue: 15 },
{ row: { my_x_axis: null, x: 4, y: 3, z: 7 }, totalStackedValue: 14 },
]);
});
test('sortRows by name descending', () => {
expect(
sortRows(
sortData,
totalStackedValues,
'my_x_axis',
SortSeriesType.Name,
false,
),
).toEqual([
{ row: { my_x_axis: null, x: 4, y: 3, z: 7 }, totalStackedValue: 14 },
{ row: { my_x_axis: 'foo', x: null, y: 10, z: 5 }, totalStackedValue: 15 },
{ row: { my_x_axis: 'abc', x: 1, y: 0, z: 2 }, totalStackedValue: 3 },
]);
});
test('sortRows by sum ascending', () => {
expect(
sortRows(
sortData,
totalStackedValues,
'my_x_axis',
SortSeriesType.Sum,
true,
),
).toEqual([
{ row: { my_x_axis: 'abc', x: 1, y: 0, z: 2 }, totalStackedValue: 3 },
{ row: { my_x_axis: null, x: 4, y: 3, z: 7 }, totalStackedValue: 14 },
{ row: { my_x_axis: 'foo', x: null, y: 10, z: 5 }, totalStackedValue: 15 },
]);
});
test('sortRows by sum descending', () => {
expect(
sortRows(
sortData,
totalStackedValues,
'my_x_axis',
SortSeriesType.Sum,
false,
),
).toEqual([
{ row: { my_x_axis: 'foo', x: null, y: 10, z: 5 }, totalStackedValue: 15 },
{ row: { my_x_axis: null, x: 4, y: 3, z: 7 }, totalStackedValue: 14 },
{ row: { my_x_axis: 'abc', x: 1, y: 0, z: 2 }, totalStackedValue: 3 },
]);
});
test('sortRows by avg ascending', () => {
expect(
sortRows(
sortData,
totalStackedValues,
'my_x_axis',
SortSeriesType.Avg,
true,
),
).toEqual([
{ row: { my_x_axis: 'abc', x: 1, y: 0, z: 2 }, totalStackedValue: 3 },
{ row: { my_x_axis: null, x: 4, y: 3, z: 7 }, totalStackedValue: 14 },
{ row: { my_x_axis: 'foo', x: null, y: 10, z: 5 }, totalStackedValue: 15 },
]);
});
test('sortRows by avg descending', () => {
expect(
sortRows(
sortData,
totalStackedValues,
'my_x_axis',
SortSeriesType.Avg,
false,
),
).toEqual([
{ row: { my_x_axis: 'foo', x: null, y: 10, z: 5 }, totalStackedValue: 15 },
{ row: { my_x_axis: null, x: 4, y: 3, z: 7 }, totalStackedValue: 14 },
{ row: { my_x_axis: 'abc', x: 1, y: 0, z: 2 }, totalStackedValue: 3 },
]);
});
test('sortRows by min ascending', () => {
expect(
sortRows(
sortData,
totalStackedValues,
'my_x_axis',
SortSeriesType.Min,
true,
),
).toEqual([
{ row: { my_x_axis: 'abc', x: 1, y: 0, z: 2 }, totalStackedValue: 3 },
{ row: { my_x_axis: null, x: 4, y: 3, z: 7 }, totalStackedValue: 14 },
{ row: { my_x_axis: 'foo', x: null, y: 10, z: 5 }, totalStackedValue: 15 },
]);
});
test('sortRows by min descending', () => {
expect(
sortRows(
sortData,
totalStackedValues,
'my_x_axis',
SortSeriesType.Min,
false,
),
).toEqual([
{ row: { my_x_axis: 'foo', x: null, y: 10, z: 5 }, totalStackedValue: 15 },
{ row: { my_x_axis: null, x: 4, y: 3, z: 7 }, totalStackedValue: 14 },
{ row: { my_x_axis: 'abc', x: 1, y: 0, z: 2 }, totalStackedValue: 3 },
]);
});
test('sortRows by max ascending', () => {
expect(
sortRows(
sortData,
totalStackedValues,
'my_x_axis',
SortSeriesType.Min,
true,
),
).toEqual([
{ row: { my_x_axis: 'abc', x: 1, y: 0, z: 2 }, totalStackedValue: 3 },
{ row: { my_x_axis: null, x: 4, y: 3, z: 7 }, totalStackedValue: 14 },
{ row: { my_x_axis: 'foo', x: null, y: 10, z: 5 }, totalStackedValue: 15 },
]);
});
test('sortRows by max descending', () => {
expect(
sortRows(
sortData,
totalStackedValues,
'my_x_axis',
SortSeriesType.Min,
false,
),
).toEqual([
{ row: { my_x_axis: 'foo', x: null, y: 10, z: 5 }, totalStackedValue: 15 },
{ row: { my_x_axis: null, x: 4, y: 3, z: 7 }, totalStackedValue: 14 },
{ row: { my_x_axis: 'abc', x: 1, y: 0, z: 2 }, totalStackedValue: 3 },
]);
});
test('sortAndFilterSeries by min ascending', () => {
expect(
sortAndFilterSeries(sortData, 'my_x_axis', [], SortSeriesType.Min, true),
).toEqual(['y', 'x', 'z']);
});
test('sortAndFilterSeries by min descending', () => {
expect(
sortAndFilterSeries(sortData, 'my_x_axis', [], SortSeriesType.Min, false),
).toEqual(['z', 'x', 'y']);
});
test('sortAndFilterSeries by max ascending', () => {
expect(
sortAndFilterSeries(sortData, 'my_x_axis', [], SortSeriesType.Max, true),
).toEqual(['x', 'z', 'y']);
});
test('sortAndFilterSeries by max descending', () => {
expect(
sortAndFilterSeries(sortData, 'my_x_axis', [], SortSeriesType.Max, false),
).toEqual(['y', 'z', 'x']);
});
test('sortAndFilterSeries by avg ascending', () => {
expect(
sortAndFilterSeries(sortData, 'my_x_axis', [], SortSeriesType.Avg, true),
).toEqual(['x', 'y', 'z']);
});
test('sortAndFilterSeries by avg descending', () => {
expect(
sortAndFilterSeries(sortData, 'my_x_axis', [], SortSeriesType.Avg, false),
).toEqual(['z', 'y', 'x']);
});
test('sortAndFilterSeries by sum ascending', () => {
expect(
sortAndFilterSeries(sortData, 'my_x_axis', [], SortSeriesType.Sum, true),
).toEqual(['x', 'y', 'z']);
});
test('sortAndFilterSeries by sum descending', () => {
expect(
sortAndFilterSeries(sortData, 'my_x_axis', [], SortSeriesType.Sum, false),
).toEqual(['z', 'y', 'x']);
});
test('sortAndFilterSeries by name ascending', () => {
expect(
sortAndFilterSeries(sortData, 'my_x_axis', [], SortSeriesType.Name, true),
).toEqual(['x', 'y', 'z']);
});
test('sortAndFilterSeries by name descending', () => {
expect(
sortAndFilterSeries(sortData, 'my_x_axis', [], SortSeriesType.Name, false),
).toEqual(['z', 'y', 'x']);
});
describe('extractSeries', () => {
it('should generate a valid ECharts timeseries series object', () => {
const data = [
{
__timestamp: '2000-01-01',
Hulk: null,
abc: 2,
},
{
__timestamp: '2000-02-01',
Hulk: 2,
abc: 10,
},
{
__timestamp: '2000-03-01',
Hulk: 1,
abc: 5,
},
];
const totalStackedValues = [2, 12, 6];
expect(extractSeries(data, { totalStackedValues })).toEqual([
[
{
id: 'Hulk',
name: 'Hulk',
data: [
['2000-01-01', null],
['2000-02-01', 2],
['2000-03-01', 1],
],
},
{
id: 'abc',
name: 'abc',
data: [
['2000-01-01', 2],
['2000-02-01', 10],
['2000-03-01', 5],
],
},
],
totalStackedValues,
1,
]);
});
it('should remove rows that have a null x-value', () => {
const data = [
{
x: 1,
Hulk: null,
abc: 2,
},
{
x: null,
Hulk: 2,
abc: 10,
},
{
x: 2,
Hulk: 1,
abc: 5,
},
];
const totalStackedValues = [3, 12, 8];
expect(
extractSeries(data, {
totalStackedValues,
xAxis: 'x',
removeNulls: true,
}),
).toEqual([
[
{
id: 'Hulk',
name: 'Hulk',
data: [[2, 1]],
},
{
id: 'abc',
name: 'abc',
data: [
[1, 2],
[2, 5],
],
},
],
totalStackedValues,
1,
]);
});
it('should do missing value imputation', () => {
const data = [
{
__timestamp: '2000-01-01',
abc: null,
},
{
__timestamp: '2000-02-01',
abc: null,
},
{
__timestamp: '2000-03-01',
abc: 1,
},
{
__timestamp: '2000-04-01',
abc: null,
},
{
__timestamp: '2000-05-01',
abc: null,
},
{
__timestamp: '2000-06-01',
abc: null,
},
{
__timestamp: '2000-07-01',
abc: 2,
},
{
__timestamp: '2000-08-01',
abc: 3,
},
{
__timestamp: '2000-09-01',
abc: null,
},
{
__timestamp: '2000-10-01',
abc: null,
},
];
const totalStackedValues = [0, 0, 1, 0, 0, 0, 2, 3, 0, 0];
expect(
extractSeries(data, { totalStackedValues, fillNeighborValue: 0 }),
).toEqual([
[
{
id: 'abc',
name: 'abc',
data: [
['2000-01-01', null],
['2000-02-01', 0],
['2000-03-01', 1],
['2000-04-01', 0],
['2000-05-01', null],
['2000-06-01', 0],
['2000-07-01', 2],
['2000-08-01', 3],
['2000-09-01', 0],
['2000-10-01', null],
],
},
],
totalStackedValues,
1,
]);
});
});
describe('extractGroupbyLabel', () => {
it('should join together multiple groupby labels', () => {
expect(
extractGroupbyLabel({
datum: { a: 'abc', b: 'qwerty' },
groupby: ['a', 'b'],
}),
).toEqual('abc, qwerty');
});
it('should handle a single groupby', () => {
expect(
extractGroupbyLabel({ datum: { xyz: 'qqq' }, groupby: ['xyz'] }),
).toEqual('qqq');
});
it('should handle mixed types', () => {
expect(
extractGroupbyLabel({
datum: { strcol: 'abc', intcol: 123, floatcol: 0.123, boolcol: true },
groupby: ['strcol', 'intcol', 'floatcol', 'boolcol'],
}),
).toEqual('abc, 123, 0.123, true');
});
it('should handle null and undefined groupby', () => {
expect(
extractGroupbyLabel({
datum: { strcol: 'abc', intcol: 123, floatcol: 0.123, boolcol: true },
groupby: null,
}),
).toEqual('');
expect(extractGroupbyLabel({})).toEqual('');
});
});
describe('extractShowValueIndexes', () => {
it('should return the latest index for stack', () => {
expect(
extractShowValueIndexes(
[
{
id: 'abc',
name: 'abc',
data: [
['2000-01-01', null],
['2000-02-01', 0],
['2000-03-01', 1],
['2000-04-01', 0],
['2000-05-01', null],
['2000-06-01', 0],
['2000-07-01', 2],
['2000-08-01', 3],
['2000-09-01', null],
['2000-10-01', null],
],
},
{
id: 'def',
name: 'def',
data: [
['2000-01-01', null],
['2000-02-01', 0],
['2000-03-01', null],
['2000-04-01', 0],
['2000-05-01', null],
['2000-06-01', 0],
['2000-07-01', 2],
['2000-08-01', 3],
['2000-09-01', null],
['2000-10-01', 0],
],
},
{
id: 'def',
name: 'def',
data: [
['2000-01-01', null],
['2000-02-01', null],
['2000-03-01', null],
['2000-04-01', null],
['2000-05-01', null],
['2000-06-01', 3],
['2000-07-01', null],
['2000-08-01', null],
['2000-09-01', null],
['2000-10-01', null],
],
},
],
{ stack: true, onlyTotal: false, isHorizontal: false },
),
).toEqual([undefined, 1, 0, 1, undefined, 2, 1, 1, undefined, 1]);
});
it('should handle the negative numbers for total only', () => {
expect(
extractShowValueIndexes(
[
{
id: 'abc',
name: 'abc',
data: [
['2000-01-01', null],
['2000-02-01', 0],
['2000-03-01', -1],
['2000-04-01', 0],
['2000-05-01', null],
['2000-06-01', 0],
['2000-07-01', -2],
['2000-08-01', -3],
['2000-09-01', null],
['2000-10-01', null],
],
},
{
id: 'def',
name: 'def',
data: [
['2000-01-01', null],
['2000-02-01', 0],
['2000-03-01', null],
['2000-04-01', 0],
['2000-05-01', null],
['2000-06-01', 0],
['2000-07-01', 2],
['2000-08-01', -3],
['2000-09-01', null],
['2000-10-01', 0],
],
},
{
id: 'def',
name: 'def',
data: [
['2000-01-01', null],
['2000-02-01', 0],
['2000-03-01', null],
['2000-04-01', 1],
['2000-05-01', null],
['2000-06-01', 0],
['2000-07-01', -2],
['2000-08-01', 3],
['2000-09-01', null],
['2000-10-01', 0],
],
},
],
{ stack: true, onlyTotal: true, isHorizontal: false },
),
).toEqual([undefined, 1, 0, 2, undefined, 1, 1, 2, undefined, 1]);
});
});
describe('formatSeriesName', () => {
const numberFormatter = getNumberFormatter();
const timeFormatter = getTimeFormatter();
it('should handle missing values properly', () => {
expect(formatSeriesName(undefined)).toEqual('<NULL>');
expect(formatSeriesName(null)).toEqual('<NULL>');
});
it('should handle string values properly', () => {
expect(formatSeriesName('abc XYZ!')).toEqual('abc XYZ!');
});
it('should handle boolean values properly', () => {
expect(formatSeriesName(true)).toEqual('true');
});
it('should use default formatting for numeric values without formatter', () => {
expect(formatSeriesName(12345678.9)).toEqual('12345678.9');
});
it('should use numberFormatter for numeric values when formatter is provided', () => {
expect(formatSeriesName(12345678.9, { numberFormatter })).toEqual('12.3M');
});
it('should use default formatting for date values without formatter', () => {
expect(formatSeriesName(new Date('2020-09-11'))).toEqual(
'2020-09-11T00:00:00.000Z',
);
});
it('should use timeFormatter for date values when formatter is provided', () => {
expect(formatSeriesName(new Date('2020-09-11'), { timeFormatter })).toEqual(
'2020-09-11 00:00:00',
);
});
it('should normalize non-UTC string based timestamp', () => {
const annualTimeFormatter = getTimeFormatter('%Y');
expect(
formatSeriesName('1995-01-01 00:00:00.000000', {
timeFormatter: annualTimeFormatter,
coltype: GenericDataType.TEMPORAL,
}),
).toEqual('1995');
});
});
describe('getLegendProps', () => {
it('should return the correct props for scroll type with top orientation without zoom', () => {
expect(
getLegendProps(
LegendType.Scroll,
LegendOrientation.Top,
true,
theme,
false,
),
).toEqual({
show: true,
top: 0,
right: 0,
orient: 'horizontal',
type: 'scroll',
...expectedThemeProps,
});
});
it('should return the correct props for scroll type with top orientation with zoom', () => {
expect(
getLegendProps(
LegendType.Scroll,
LegendOrientation.Top,
true,
theme,
true,
),
).toEqual({
show: true,
top: 0,
right: 55,
orient: 'horizontal',
type: 'scroll',
...expectedThemeProps,
});
});
it('should return the correct props for plain type with left orientation', () => {
expect(
getLegendProps(LegendType.Plain, LegendOrientation.Left, true, theme),
).toEqual({
show: true,
left: 0,
orient: 'vertical',
type: 'plain',
...expectedThemeProps,
});
});
it('should return the correct props for plain type with right orientation without zoom', () => {
expect(
getLegendProps(
LegendType.Plain,
LegendOrientation.Right,
false,
theme,
false,
),
).toEqual({
show: false,
right: 0,
top: 0,
orient: 'vertical',
type: 'plain',
...expectedThemeProps,
});
});
it('should return the correct props for plain type with right orientation with zoom', () => {
expect(
getLegendProps(
LegendType.Plain,
LegendOrientation.Right,
false,
theme,
true,
),
).toEqual({
show: false,
right: 0,
top: 30,
orient: 'vertical',
type: 'plain',
...expectedThemeProps,
});
});
it('should return the correct props for plain type with bottom orientation', () => {
expect(
getLegendProps(LegendType.Plain, LegendOrientation.Bottom, false, theme),
).toEqual({
show: false,
bottom: 0,
orient: 'horizontal',
type: 'plain',
...expectedThemeProps,
});
});
});
describe('getChartPadding', () => {
it('should handle top default', () => {
expect(getChartPadding(true, LegendOrientation.Top)).toEqual({
bottom: 0,
left: 0,
right: 0,
top: defaultLegendPadding[LegendOrientation.Top],
});
});
it('should handle left default', () => {
expect(getChartPadding(true, LegendOrientation.Left)).toEqual({
bottom: 0,
left: defaultLegendPadding[LegendOrientation.Left],
right: 0,
top: 0,
});
});
it('should return the default padding when show is false', () => {
expect(
getChartPadding(false, LegendOrientation.Left, 100, {
top: 10,
bottom: 20,
left: 30,
right: 40,
}),
).toEqual({
bottom: 20,
left: 30,
right: 40,
top: 10,
});
});
it('should return the correct padding for left orientation', () => {
expect(getChartPadding(true, LegendOrientation.Left, 100)).toEqual({
bottom: 0,
left: 100,
right: 0,
top: 0,
});
});
it('should return the correct padding for right orientation', () => {
expect(getChartPadding(true, LegendOrientation.Right, 50)).toEqual({
bottom: 0,
left: 0,
right: 50,
top: 0,
});
});
it('should return the correct padding for top orientation', () => {
expect(getChartPadding(true, LegendOrientation.Top, 20)).toEqual({
bottom: 0,
left: 0,
right: 0,
top: 20,
});
});
it('should return the correct padding for bottom orientation', () => {
expect(getChartPadding(true, LegendOrientation.Bottom, 10)).toEqual({
bottom: 10,
left: 0,
right: 0,
top: 0,
});
});
});
describe('dedupSeries', () => {
it('should deduplicate ids in series', () => {
expect(
dedupSeries([
{
id: 'foo',
},
{
id: 'bar',
},
{
id: 'foo',
},
{
id: 'foo',
},
]),
).toEqual([
{ id: 'foo' },
{ id: 'bar' },
{ id: 'foo (1)' },
{ id: 'foo (2)' },
]);
});
});
describe('sanitizeHtml', () => {
it('should remove html tags from series name', () => {
expect(sanitizeHtml(NULL_STRING)).toEqual('<NULL>');
});
});
describe('getOverMaxHiddenFormatter', () => {
it('should hide value if greater than max', () => {
const formatter = getOverMaxHiddenFormatter({ max: 81000 });
expect(formatter.format(84500)).toEqual('');
});
it('should show value if less or equal than max', () => {
const formatter = getOverMaxHiddenFormatter({ max: 81000 });
expect(formatter.format(81000)).toEqual('81000');
expect(formatter.format(50000)).toEqual('50000');
});
});
test('calculateLowerLogTick', () => {
expect(calculateLowerLogTick(1000000)).toEqual(1000000);
expect(calculateLowerLogTick(456)).toEqual(100);
expect(calculateLowerLogTick(100)).toEqual(100);
expect(calculateLowerLogTick(99)).toEqual(10);
expect(calculateLowerLogTick(2)).toEqual(1);
expect(calculateLowerLogTick(0.005)).toEqual(0.001);
});
|
6,291 | 0 | petrpan-code/apache/superset/superset-frontend/plugins/plugin-chart-echarts/test | petrpan-code/apache/superset/superset-frontend/plugins/plugin-chart-echarts/test/utils/treeBuilder.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 { treeBuilder } from '../../src/utils/treeBuilder';
describe('test treeBuilder', () => {
const data = [
{
foo: 'a-1',
bar: 'a',
count: 2,
count2: 3,
},
{
foo: 'a-2',
bar: 'a',
count: 2,
count2: 3,
},
{
foo: 'b-1',
bar: 'b',
count: 2,
count2: 3,
},
{
foo: 'b-2',
bar: 'b',
count: 2,
count2: 3,
},
{
foo: 'c-1',
bar: 'c',
count: 2,
count2: 3,
},
{
foo: 'c-2',
bar: 'c',
count: 2,
count2: 3,
},
{
foo: 'd-1',
bar: 'd',
count: 2,
count2: 3,
},
];
it('should build tree as expected', () => {
const tree = treeBuilder(data, ['foo', 'bar'], 'count');
expect(tree).toEqual([
{
children: [
{
groupBy: 'bar',
name: 'a',
secondaryValue: 2,
value: 2,
},
],
groupBy: 'foo',
name: 'a-1',
secondaryValue: 2,
value: 2,
},
{
children: [
{
groupBy: 'bar',
name: 'a',
secondaryValue: 2,
value: 2,
},
],
groupBy: 'foo',
name: 'a-2',
secondaryValue: 2,
value: 2,
},
{
children: [
{
groupBy: 'bar',
name: 'b',
secondaryValue: 2,
value: 2,
},
],
groupBy: 'foo',
name: 'b-1',
secondaryValue: 2,
value: 2,
},
{
children: [
{
groupBy: 'bar',
name: 'b',
secondaryValue: 2,
value: 2,
},
],
groupBy: 'foo',
name: 'b-2',
secondaryValue: 2,
value: 2,
},
{
children: [
{
groupBy: 'bar',
name: 'c',
secondaryValue: 2,
value: 2,
},
],
groupBy: 'foo',
name: 'c-1',
secondaryValue: 2,
value: 2,
},
{
children: [
{
groupBy: 'bar',
name: 'c',
secondaryValue: 2,
value: 2,
},
],
groupBy: 'foo',
name: 'c-2',
secondaryValue: 2,
value: 2,
},
{
children: [
{
groupBy: 'bar',
name: 'd',
secondaryValue: 2,
value: 2,
},
],
groupBy: 'foo',
name: 'd-1',
secondaryValue: 2,
value: 2,
},
]);
});
it('should build tree with secondaryValue as expected', () => {
const tree = treeBuilder(data, ['foo', 'bar'], 'count', 'count2');
expect(tree).toEqual([
{
children: [
{
groupBy: 'bar',
name: 'a',
secondaryValue: 3,
value: 2,
},
],
groupBy: 'foo',
name: 'a-1',
secondaryValue: 3,
value: 2,
},
{
children: [
{
groupBy: 'bar',
name: 'a',
secondaryValue: 3,
value: 2,
},
],
groupBy: 'foo',
name: 'a-2',
secondaryValue: 3,
value: 2,
},
{
children: [
{
groupBy: 'bar',
name: 'b',
secondaryValue: 3,
value: 2,
},
],
groupBy: 'foo',
name: 'b-1',
secondaryValue: 3,
value: 2,
},
{
children: [
{
groupBy: 'bar',
name: 'b',
secondaryValue: 3,
value: 2,
},
],
groupBy: 'foo',
name: 'b-2',
secondaryValue: 3,
value: 2,
},
{
children: [
{
groupBy: 'bar',
name: 'c',
secondaryValue: 3,
value: 2,
},
],
groupBy: 'foo',
name: 'c-1',
secondaryValue: 3,
value: 2,
},
{
children: [
{
groupBy: 'bar',
name: 'c',
secondaryValue: 3,
value: 2,
},
],
groupBy: 'foo',
name: 'c-2',
secondaryValue: 3,
value: 2,
},
{
children: [
{
groupBy: 'bar',
name: 'd',
secondaryValue: 3,
value: 2,
},
],
groupBy: 'foo',
name: 'd-1',
secondaryValue: 3,
value: 2,
},
]);
});
});
|
6,318 | 0 | petrpan-code/apache/superset/superset-frontend/plugins/plugin-chart-handlebars | petrpan-code/apache/superset/superset-frontend/plugins/plugin-chart-handlebars/test/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.
*/
import { HandlebarsChartPlugin } from '../src';
/**
* The example tests in this file act as a starting point, and
* we encourage you to build more. These tests check that the
* plugin loads properly, and focus on `transformProps`
* to ake sure that data, controls, and props are all
* treated correctly (e.g. formData from plugin controls
* properly transform the data and/or any resulting props).
*/
describe('@superset-ui/plugin-chart-handlebars', () => {
it('exists', () => {
expect(HandlebarsChartPlugin).toBeDefined();
});
});
|
6,319 | 0 | petrpan-code/apache/superset/superset-frontend/plugins/plugin-chart-handlebars/test | petrpan-code/apache/superset/superset-frontend/plugins/plugin-chart-handlebars/test/plugin/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 { HandlebarsQueryFormData } from '../../src/types';
import buildQuery from '../../src/plugin/buildQuery';
describe('Handlebars buildQuery', () => {
const formData: HandlebarsQueryFormData = {
datasource: '5__table',
granularitySqla: 'ds',
groupby: ['foo'],
viz_type: 'my_chart',
width: 500,
height: 500,
};
it('should build groupby with series in form data', () => {
const queryContext = buildQuery(formData);
const [query] = queryContext.queries;
expect(query.columns).toEqual(['foo']);
});
});
|
6,320 | 0 | petrpan-code/apache/superset/superset-frontend/plugins/plugin-chart-handlebars/test | petrpan-code/apache/superset/superset-frontend/plugins/plugin-chart-handlebars/test/plugin/transformProps.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 { ChartProps, QueryFormData, supersetTheme } from '@superset-ui/core';
import { HandlebarsQueryFormData } from '../../src/types';
import transformProps from '../../src/plugin/transformProps';
describe('Handlebars transformProps', () => {
const formData: HandlebarsQueryFormData = {
colorScheme: 'bnbColors',
datasource: '3__table',
granularitySqla: 'ds',
metric: 'sum__num',
groupby: ['name'],
width: 500,
height: 500,
viz_type: 'handlebars',
};
const data = [{ name: 'Hulk', sum__num: 1, __timestamp: 599616000000 }];
const chartProps = new ChartProps<QueryFormData>({
formData,
width: 800,
height: 600,
queriesData: [{ data }],
theme: supersetTheme,
});
it('should transform chart props for viz', () => {
expect(transformProps(chartProps)).toEqual(
expect.objectContaining({
width: 800,
height: 600,
data,
}),
);
});
});
|
6,338 | 0 | petrpan-code/apache/superset/superset-frontend/plugins/plugin-chart-pivot-table | petrpan-code/apache/superset/superset-frontend/plugins/plugin-chart-pivot-table/test/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.
*/
import { PivotTableChartPlugin } from '../src';
/**
* The example tests in this file act as a starting point, and
* we encourage you to build more. These tests check that the
* plugin loads properly, and focus on `transformProps`
* to ake sure that data, controls, and props are all
* treated correctly (e.g. formData from plugin controls
* properly transform the data and/or any resulting props).
*/
describe('@superset-ui/plugin-chart-pivot-table', () => {
it('exists', () => {
expect(PivotTableChartPlugin).toBeDefined();
});
});
|
6,339 | 0 | petrpan-code/apache/superset/superset-frontend/plugins/plugin-chart-pivot-table/test | petrpan-code/apache/superset/superset-frontend/plugins/plugin-chart-pivot-table/test/plugin/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 { TimeGranularity } from '@superset-ui/core';
import * as supersetCoreModule from '@superset-ui/core';
import buildQuery from '../../src/plugin/buildQuery';
import { PivotTableQueryFormData } from '../../src/types';
const formData: PivotTableQueryFormData = {
groupbyRows: ['row1', 'row2'],
groupbyColumns: ['col1', 'col2'],
metrics: ['metric1', 'metric2'],
tableRenderer: 'Table With Subtotal',
colOrder: 'key_a_to_z',
rowOrder: 'key_a_to_z',
aggregateFunction: 'Sum',
transposePivot: true,
rowSubtotalPosition: true,
colSubtotalPosition: true,
colTotals: true,
colSubTotals: true,
rowTotals: true,
rowSubTotals: true,
valueFormat: 'SMART_NUMBER',
datasource: '5__table',
viz_type: 'my_chart',
width: 800,
height: 600,
combineMetric: false,
verboseMap: {},
columnFormats: {},
currencyFormats: {},
metricColorFormatters: [],
dateFormatters: {},
setDataMask: () => {},
legacy_order_by: 'count',
order_desc: true,
margin: 0,
time_grain_sqla: TimeGranularity.MONTH,
temporal_columns_lookup: { col1: true },
currencyFormat: { symbol: 'USD', symbolPosition: 'prefix' },
};
test('should build groupby with series in form data', () => {
const queryContext = buildQuery(formData);
const [query] = queryContext.queries;
expect(query.columns).toEqual(['col1', 'col2', 'row1', 'row2']);
});
test('should work with old charts after GENERIC_CHART_AXES is enabled', () => {
Object.defineProperty(supersetCoreModule, 'hasGenericChartAxes', {
value: true,
});
const modifiedFormData = {
...formData,
time_grain_sqla: TimeGranularity.MONTH,
granularity_sqla: 'col1',
};
const queryContext = buildQuery(modifiedFormData);
const [query] = queryContext.queries;
expect(query.columns).toEqual([
{
timeGrain: 'P1M',
columnType: 'BASE_AXIS',
sqlExpression: 'col1',
label: 'col1',
expressionType: 'SQL',
},
'col2',
'row1',
'row2',
]);
});
test('should prefer extra_form_data.time_grain_sqla over formData.time_grain_sqla', () => {
Object.defineProperty(supersetCoreModule, 'hasGenericChartAxes', {
value: true,
});
const modifiedFormData = {
...formData,
extra_form_data: { time_grain_sqla: TimeGranularity.QUARTER },
};
const queryContext = buildQuery(modifiedFormData);
const [query] = queryContext.queries;
expect(query.columns?.[0]).toEqual({
timeGrain: TimeGranularity.QUARTER,
columnType: 'BASE_AXIS',
sqlExpression: 'col1',
label: 'col1',
expressionType: 'SQL',
});
});
test('should fallback to formData.time_grain_sqla if extra_form_data.time_grain_sqla is not set', () => {
Object.defineProperty(supersetCoreModule, 'hasGenericChartAxes', {
value: true,
});
const queryContext = buildQuery(formData);
const [query] = queryContext.queries;
expect(query.columns?.[0]).toEqual({
timeGrain: formData.time_grain_sqla,
columnType: 'BASE_AXIS',
sqlExpression: 'col1',
label: 'col1',
expressionType: 'SQL',
});
});
test('should not omit extras.time_grain_sqla from queryContext so dashboards apply them', () => {
Object.defineProperty(supersetCoreModule, 'hasGenericChartAxes', {
value: true,
});
const modifiedFormData = {
...formData,
extra_form_data: { time_grain_sqla: TimeGranularity.QUARTER },
};
const queryContext = buildQuery(modifiedFormData);
const [query] = queryContext.queries;
expect(query.extras?.time_grain_sqla).toEqual(TimeGranularity.QUARTER);
});
|
6,340 | 0 | petrpan-code/apache/superset/superset-frontend/plugins/plugin-chart-pivot-table/test | petrpan-code/apache/superset/superset-frontend/plugins/plugin-chart-pivot-table/test/plugin/transformProps.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 { ChartProps, QueryFormData, supersetTheme } from '@superset-ui/core';
import transformProps from '../../src/plugin/transformProps';
import { MetricsLayoutEnum } from '../../src/types';
describe('PivotTableChart transformProps', () => {
const setDataMask = jest.fn();
const formData = {
groupbyRows: ['row1', 'row2'],
groupbyColumns: ['col1', 'col2'],
metrics: ['metric1', 'metric2'],
tableRenderer: 'Table With Subtotal',
colOrder: 'key_a_to_z',
rowOrder: 'key_a_to_z',
aggregateFunction: 'Sum',
transposePivot: true,
combineMetric: true,
rowSubtotalPosition: true,
colSubtotalPosition: true,
colTotals: true,
rowTotals: true,
valueFormat: 'SMART_NUMBER',
metricsLayout: MetricsLayoutEnum.COLUMNS,
viz_type: '',
datasource: '',
conditionalFormatting: [],
dateFormat: '',
legacy_order_by: 'count',
order_desc: true,
currencyFormat: { symbol: 'USD', symbolPosition: 'prefix' },
};
const chartProps = new ChartProps<QueryFormData>({
formData,
width: 800,
height: 600,
queriesData: [
{
data: [{ name: 'Hulk', sum__num: 1, __timestamp: 599616000000 }],
colnames: ['name', 'sum__num', '__timestamp'],
coltypes: [1, 0, 2],
},
],
hooks: { setDataMask },
filterState: { selectedFilters: {} },
datasource: { verboseMap: {}, columnFormats: {} },
theme: supersetTheme,
});
it('should transform chart props for viz', () => {
expect(transformProps(chartProps)).toEqual({
width: 800,
height: 600,
groupbyRows: ['row1', 'row2'],
groupbyColumns: ['col1', 'col2'],
metrics: ['metric1', 'metric2'],
tableRenderer: 'Table With Subtotal',
colOrder: 'key_a_to_z',
rowOrder: 'key_a_to_z',
aggregateFunction: 'Sum',
transposePivot: true,
combineMetric: true,
rowSubtotalPosition: true,
colSubtotalPosition: true,
colTotals: true,
rowTotals: true,
valueFormat: 'SMART_NUMBER',
data: [{ name: 'Hulk', sum__num: 1, __timestamp: 599616000000 }],
setDataMask,
selectedFilters: {},
verboseMap: {},
metricsLayout: MetricsLayoutEnum.COLUMNS,
metricColorFormatters: [],
dateFormatters: {},
emitCrossFilters: false,
columnFormats: {},
currencyFormats: {},
currencyFormat: { symbol: 'USD', symbolPosition: 'prefix' },
});
});
});
|
6,373 | 0 | petrpan-code/apache/superset/superset-frontend/plugins/plugin-chart-table | petrpan-code/apache/superset/superset-frontend/plugins/plugin-chart-table/test/TableChart.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 { CommonWrapper } from 'enzyme';
import { render, screen } from '@testing-library/react';
import '@testing-library/jest-dom';
import TableChart from '../src/TableChart';
import transformProps from '../src/transformProps';
import DateWithFormatter from '../src/utils/DateWithFormatter';
import testData from './testData';
import { mount, ProviderWrapper } from './enzyme';
describe('plugin-chart-table', () => {
describe('transformProps', () => {
it('should parse pageLength to pageSize', () => {
expect(transformProps(testData.basic).pageSize).toBe(20);
expect(
transformProps({
...testData.basic,
rawFormData: { ...testData.basic.rawFormData, page_length: '20' },
}).pageSize,
).toBe(20);
expect(
transformProps({
...testData.basic,
rawFormData: { ...testData.basic.rawFormData, page_length: '' },
}).pageSize,
).toBe(0);
});
it('should memoize data records', () => {
expect(transformProps(testData.basic).data).toBe(
transformProps(testData.basic).data,
);
});
it('should memoize columns meta', () => {
expect(transformProps(testData.basic).columns).toBe(
transformProps({
...testData.basic,
rawFormData: { ...testData.basic.rawFormData, pageLength: null },
}).columns,
);
});
it('should format timestamp', () => {
// eslint-disable-next-line no-underscore-dangle
const parsedDate = transformProps(testData.basic).data[0]
.__timestamp as DateWithFormatter;
expect(String(parsedDate)).toBe('2020-01-01 12:34:56');
expect(parsedDate.getTime()).toBe(1577882096000);
});
});
describe('TableChart', () => {
let wrap: CommonWrapper; // the ReactDataTable wrapper
let tree: Cheerio;
it('render basic data', () => {
wrap = mount(
<TableChart {...transformProps(testData.basic)} sticky={false} />,
);
tree = wrap.render(); // returns a CheerioWrapper with jQuery-like API
const cells = tree.find('td');
expect(cells).toHaveLength(12);
expect(cells.eq(0).text()).toEqual('2020-01-01 12:34:56');
expect(cells.eq(1).text()).toEqual('Michael');
// number is not in `metrics` list, so it should output raw value
// (in real world Superset, this would mean the column is used in GROUP BY)
expect(cells.eq(2).text()).toEqual('2467063');
// should not render column with `.` in name as `undefined`
expect(cells.eq(3).text()).toEqual('foo');
expect(cells.eq(6).text()).toEqual('2467');
expect(cells.eq(8).text()).toEqual('N/A');
});
it('render advanced data', () => {
wrap = mount(
<TableChart {...transformProps(testData.advanced)} sticky={false} />,
);
tree = wrap.render();
// should successful rerender with new props
const cells = tree.find('td');
expect(tree.find('th').eq(1).text()).toEqual('Sum of Num');
expect(cells.eq(0).text()).toEqual('Michael');
expect(cells.eq(2).text()).toEqual('12.346%');
expect(cells.eq(4).text()).toEqual('2.47k');
});
it('render advanced data with currencies', () => {
render(
ProviderWrapper({
children: (
<TableChart
{...transformProps(testData.advancedWithCurrency)}
sticky={false}
/>
),
}),
);
const cells = document.querySelectorAll('td');
expect(document.querySelectorAll('th')[1]).toHaveTextContent(
'Sum of Num',
);
expect(cells[0]).toHaveTextContent('Michael');
expect(cells[2]).toHaveTextContent('12.346%');
expect(cells[4]).toHaveTextContent('$ 2.47k');
});
it('render raw data', () => {
const props = transformProps({
...testData.raw,
rawFormData: { ...testData.raw.rawFormData },
});
render(
ProviderWrapper({
children: <TableChart {...props} sticky={false} />,
}),
);
const cells = document.querySelectorAll('td');
expect(document.querySelectorAll('th')[0]).toHaveTextContent('num');
expect(cells[0]).toHaveTextContent('1234');
expect(cells[1]).toHaveTextContent('10000');
expect(cells[1]).toHaveTextContent('0');
});
it('render raw data with currencies', () => {
const props = transformProps({
...testData.raw,
rawFormData: {
...testData.raw.rawFormData,
column_config: {
num: {
currencyFormat: { symbol: 'USD', symbolPosition: 'prefix' },
},
},
},
});
render(
ProviderWrapper({
children: <TableChart {...props} sticky={false} />,
}),
);
const cells = document.querySelectorAll('td');
expect(document.querySelectorAll('th')[0]).toHaveTextContent('num');
expect(cells[0]).toHaveTextContent('$ 1.23k');
expect(cells[1]).toHaveTextContent('$ 10k');
expect(cells[2]).toHaveTextContent('$ 0');
});
it('render empty data', () => {
wrap.setProps({ ...transformProps(testData.empty), sticky: false });
tree = wrap.render();
expect(tree.text()).toContain('No records found');
});
it('render color with column color formatter', () => {
render(
ProviderWrapper({
children: (
<TableChart
{...transformProps({
...testData.advanced,
rawFormData: {
...testData.advanced.rawFormData,
conditional_formatting: [
{
colorScheme: '#ACE1C4',
column: 'sum__num',
operator: '>',
targetValue: 2467,
},
],
},
})}
/>
),
}),
);
expect(getComputedStyle(screen.getByTitle('2467063')).background).toBe(
'rgba(172, 225, 196, 1)',
);
expect(getComputedStyle(screen.getByTitle('2467')).background).toBe('');
});
it('render cell without color', () => {
const dataWithEmptyCell = testData.advanced.queriesData[0];
dataWithEmptyCell.data.push({
__timestamp: null,
name: 'Noah',
sum__num: null,
'%pct_nice': 0.643,
'abc.com': 'bazzinga',
});
render(
ProviderWrapper({
children: (
<TableChart
{...transformProps({
...testData.advanced,
queriesData: [dataWithEmptyCell],
rawFormData: {
...testData.advanced.rawFormData,
conditional_formatting: [
{
colorScheme: '#ACE1C4',
column: 'sum__num',
operator: '<',
targetValue: 12342,
},
],
},
})}
/>
),
}),
);
expect(getComputedStyle(screen.getByTitle('2467')).background).toBe(
'rgba(172, 225, 196, 0.812)',
);
expect(getComputedStyle(screen.getByTitle('2467063')).background).toBe(
'',
);
expect(getComputedStyle(screen.getByText('N/A')).background).toBe('');
});
});
it('render cell bars properly, and only when it is toggled on in both regular and percent metrics', () => {
const props = transformProps({
...testData.raw,
rawFormData: { ...testData.raw.rawFormData },
});
props.columns[0].isMetric = true;
render(
ProviderWrapper({
children: <TableChart {...props} sticky={false} />,
}),
);
let cells = document.querySelectorAll('div.cell-bar');
cells.forEach(cell => {
expect(cell).toHaveClass('positive');
});
props.columns[0].isMetric = false;
props.columns[0].isPercentMetric = true;
render(
ProviderWrapper({
children: <TableChart {...props} sticky={false} />,
}),
);
cells = document.querySelectorAll('div.cell-bar');
cells.forEach(cell => {
expect(cell).toHaveClass('positive');
});
props.showCellBars = false;
render(
ProviderWrapper({
children: <TableChart {...props} sticky={false} />,
}),
);
cells = document.querySelectorAll('td');
cells.forEach(cell => {
expect(cell).toHaveClass('test-c7w8t3');
});
props.columns[0].isPercentMetric = false;
props.columns[0].isMetric = true;
render(
ProviderWrapper({
children: <TableChart {...props} sticky={false} />,
}),
);
cells = document.querySelectorAll('td');
cells.forEach(cell => {
expect(cell).toHaveClass('test-c7w8t3');
});
});
});
|
6,374 | 0 | petrpan-code/apache/superset/superset-frontend/plugins/plugin-chart-table | petrpan-code/apache/superset/superset-frontend/plugins/plugin-chart-table/test/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 { QueryMode, TimeGranularity } from '@superset-ui/core';
import * as supersetCoreModule from '@superset-ui/core';
import buildQuery from '../src/buildQuery';
import { TableChartFormData } from '../src/types';
const basicFormData: TableChartFormData = {
viz_type: 'table',
datasource: '11__table',
};
describe('plugin-chart-table', () => {
describe('buildQuery', () => {
it('should add post-processing and ignore duplicate metrics', () => {
const query = buildQuery({
...basicFormData,
query_mode: QueryMode.aggregate,
metrics: ['aaa', 'aaa'],
percent_metrics: ['bbb', 'bbb'],
}).queries[0];
expect(query.metrics).toEqual(['aaa', 'bbb']);
expect(query.post_processing).toEqual([
{
operation: 'contribution',
options: {
columns: ['bbb'],
rename_columns: ['%bbb'],
},
},
]);
});
it('should not add metrics in raw records mode', () => {
const query = buildQuery({
...basicFormData,
query_mode: QueryMode.raw,
columns: ['a'],
metrics: ['aaa', 'aaa'],
percent_metrics: ['bbb', 'bbb'],
}).queries[0];
expect(query.metrics).toBeUndefined();
expect(query.post_processing).toEqual([]);
});
it('should not add post-processing when there is no percent metric', () => {
const query = buildQuery({
...basicFormData,
query_mode: QueryMode.aggregate,
metrics: ['aaa'],
percent_metrics: [],
}).queries[0];
expect(query.metrics).toEqual(['aaa']);
expect(query.post_processing).toEqual([]);
});
it('should not add post-processing in raw records mode', () => {
const query = buildQuery({
...basicFormData,
query_mode: QueryMode.raw,
metrics: ['aaa'],
columns: ['rawcol'],
percent_metrics: ['ccc'],
}).queries[0];
expect(query.metrics).toBeUndefined();
expect(query.columns).toEqual(['rawcol']);
expect(query.post_processing).toEqual([]);
});
it('should prefer extra_form_data.time_grain_sqla over formData.time_grain_sqla', () => {
Object.defineProperty(supersetCoreModule, 'hasGenericChartAxes', {
value: true,
});
const query = buildQuery({
...basicFormData,
groupby: ['col1'],
query_mode: QueryMode.aggregate,
time_grain_sqla: TimeGranularity.MONTH,
extra_form_data: { time_grain_sqla: TimeGranularity.QUARTER },
temporal_columns_lookup: { col1: true },
}).queries[0];
expect(query.columns?.[0]).toEqual({
timeGrain: TimeGranularity.QUARTER,
columnType: 'BASE_AXIS',
sqlExpression: 'col1',
label: 'col1',
expressionType: 'SQL',
});
});
it('should fallback to formData.time_grain_sqla if extra_form_data.time_grain_sqla is not set', () => {
Object.defineProperty(supersetCoreModule, 'hasGenericChartAxes', {
value: true,
});
const query = buildQuery({
...basicFormData,
time_grain_sqla: TimeGranularity.MONTH,
groupby: ['col1'],
query_mode: QueryMode.aggregate,
temporal_columns_lookup: { col1: true },
}).queries[0];
expect(query.columns?.[0]).toEqual({
timeGrain: TimeGranularity.MONTH,
columnType: 'BASE_AXIS',
sqlExpression: 'col1',
label: 'col1',
expressionType: 'SQL',
});
});
});
});
|
6,376 | 0 | petrpan-code/apache/superset/superset-frontend/plugins/plugin-chart-table | petrpan-code/apache/superset/superset-frontend/plugins/plugin-chart-table/test/sortAlphanumericCaseInsensitive.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 { defaultOrderByFn, Row } from 'react-table';
import { sortAlphanumericCaseInsensitive } from '../src/DataTable/utils/sortAlphanumericCaseInsensitive';
type RecursivePartial<T> = {
[P in keyof T]?: T[P] | RecursivePartial<T[P]>;
};
const testData = [
{
values: {
col: 'test value',
},
},
{
values: {
col: 'a lowercase test value',
},
},
{
values: {
col: '5',
},
},
{
values: {
col: NaN,
},
},
{
values: {
col: '1234',
},
},
{
values: {
col: Infinity,
},
},
{
values: {
col: '.!# value starting with non-letter characters',
},
},
{
values: {
col: 'An uppercase test value',
},
},
{
values: {
col: undefined,
},
},
{
values: {
col: null,
},
},
];
describe('sortAlphanumericCaseInsensitive', () => {
it('Sort rows', () => {
const sorted = [...testData].sort((a, b) =>
// @ts-ignore
sortAlphanumericCaseInsensitive(a, b, 'col'),
);
expect(sorted).toEqual([
{
values: {
col: null,
},
},
{
values: {
col: undefined,
},
},
{
values: {
col: Infinity,
},
},
{
values: {
col: NaN,
},
},
{
values: {
col: '.!# value starting with non-letter characters',
},
},
{
values: {
col: '1234',
},
},
{
values: {
col: '5',
},
},
{
values: {
col: 'a lowercase test value',
},
},
{
values: {
col: 'An uppercase test value',
},
},
{
values: {
col: 'test value',
},
},
]);
});
});
const testDataMulti: Array<RecursivePartial<Row<object>>> = [
{
values: {
colA: 'group 1',
colB: '10',
},
},
{
values: {
colA: 'group 1',
colB: '15',
},
},
{
values: {
colA: 'group 1',
colB: '20',
},
},
{
values: {
colA: 'group 2',
colB: '10',
},
},
{
values: {
colA: 'group 3',
colB: '10',
},
},
{
values: {
colA: 'group 3',
colB: '15',
},
},
{
values: {
colA: 'group 3',
colB: '10',
},
},
];
describe('sortAlphanumericCaseInsensitiveMulti', () => {
it('Sort rows', () => {
const sorted = defaultOrderByFn(
[...testDataMulti] as Array<Row<object>>,
[
(a, b) => sortAlphanumericCaseInsensitive(a, b, 'colA'),
(a, b) => sortAlphanumericCaseInsensitive(a, b, 'colB'),
],
[true, false],
);
expect(sorted).toEqual([
{
values: {
colA: 'group 1',
colB: '20',
},
},
{
values: {
colA: 'group 1',
colB: '15',
},
},
{
values: {
colA: 'group 1',
colB: '10',
},
},
{
values: {
colA: 'group 2',
colB: '10',
},
},
{
values: {
colA: 'group 3',
colB: '15',
},
},
{
values: {
colA: 'group 3',
colB: '10',
},
},
{
values: {
colA: 'group 3',
colB: '10',
},
},
]);
});
});
|
6,378 | 0 | petrpan-code/apache/superset/superset-frontend/plugins/plugin-chart-table | petrpan-code/apache/superset/superset-frontend/plugins/plugin-chart-table/test/tsconfig.json | {
"compilerOptions": {
"composite": false,
"emitDeclarationOnly": false,
"noEmit": true,
"rootDir": "../../../"
},
"extends": "../../../tsconfig.json",
"include": [
"**/*",
"../types/**/*",
"../../../types/**/*"
],
"references": [
{
"path": ".."
}
]
}
|
6,396 | 0 | petrpan-code/apache/superset/superset-frontend/plugins/plugin-chart-word-cloud | petrpan-code/apache/superset/superset-frontend/plugins/plugin-chart-word-cloud/test/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.
*/
import { WordCloudChartPlugin, LegacyWordCloudChartPlugin } from '../src';
describe('plugin-chart-word-cloud', () => {
it('exports WordCloudChartPlugin', () => {
expect(WordCloudChartPlugin).toBeDefined();
});
it('exports LegacyWordCloudChartPlugin', () => {
expect(LegacyWordCloudChartPlugin).toBeDefined();
});
});
|
6,397 | 0 | petrpan-code/apache/superset/superset-frontend/plugins/plugin-chart-word-cloud | petrpan-code/apache/superset/superset-frontend/plugins/plugin-chart-word-cloud/test/tsconfig.json | {
"compilerOptions": {
"composite": false,
"emitDeclarationOnly": false,
"noEmit": true,
"rootDir": "."
},
"extends": "../../../tsconfig.json",
"include": [
"**/*",
"../types/**/*",
"../../../types/**/*"
],
"references": [
{
"path": ".."
}
]
}
|
6,398 | 0 | petrpan-code/apache/superset/superset-frontend/plugins/plugin-chart-word-cloud/test | petrpan-code/apache/superset/superset-frontend/plugins/plugin-chart-word-cloud/test/legacyPlugin/transformProps.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 { ChartProps, supersetTheme } from '@superset-ui/core';
import transformProps from '../../src/legacyPlugin/transformProps';
describe('WordCloud transformProps', () => {
const formData = {
colorScheme: 'bnbColors',
datasource: '3__table',
granularity_sqla: 'ds',
metric: 'sum__num',
rotation: 'square',
series: 'name',
sizeFrom: 10,
sizeTo: 70,
};
const chartProps = new ChartProps({
formData,
width: 800,
height: 600,
queriesData: [
{
data: [{ name: 'Hulk', sum__num: 1 }],
},
],
theme: supersetTheme,
});
it('should transform chart props for word cloud viz', () => {
expect(transformProps(chartProps)).toEqual({
width: 800,
height: 600,
encoding: {
color: {
field: 'name',
scale: {
scheme: 'bnbColors',
},
type: 'nominal',
},
fontSize: {
field: 'sum__num',
scale: {
range: [10, 70],
zero: true,
},
type: 'quantitative',
},
text: {
field: 'name',
},
},
rotation: 'square',
data: [{ name: 'Hulk', sum__num: 1 }],
});
});
});
|
6,399 | 0 | petrpan-code/apache/superset/superset-frontend/plugins/plugin-chart-word-cloud/test | petrpan-code/apache/superset/superset-frontend/plugins/plugin-chart-word-cloud/test/plugin/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 { WordCloudFormData } from '../../src';
import buildQuery from '../../src/plugin/buildQuery';
describe('WordCloud buildQuery', () => {
const formData: WordCloudFormData = {
datasource: '5__table',
granularity_sqla: 'ds',
series: 'foo',
viz_type: 'word_cloud',
};
it('should build columns from series in form data', () => {
const queryContext = buildQuery(formData);
const [query] = queryContext.queries;
expect(query.columns).toEqual(['foo']);
});
});
|
6,451 | 0 | petrpan-code/apache/superset/superset-frontend/src/SqlLab/components | petrpan-code/apache/superset/superset-frontend/src/SqlLab/components/AceEditorWrapper/AceEditorWrapper.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 configureStore from 'redux-mock-store';
import thunk from 'redux-thunk';
import { render, waitFor } from 'spec/helpers/testing-library';
import { QueryEditor } from 'src/SqlLab/types';
import { Store } from 'redux';
import { initialState, defaultQueryEditor } from 'src/SqlLab/fixtures';
import AceEditorWrapper from 'src/SqlLab/components/AceEditorWrapper';
import { AsyncAceEditorProps } from 'src/components/AsyncAceEditor';
const middlewares = [thunk];
const mockStore = configureStore(middlewares);
jest.mock('src/components/DeprecatedSelect', () => () => (
<div data-test="mock-deprecated-select" />
));
jest.mock('src/components/Select/Select', () => () => (
<div data-test="mock-deprecated-select-select" />
));
jest.mock('src/components/Select/AsyncSelect', () => () => (
<div data-test="mock-deprecated-async-select" />
));
jest.mock('src/components/AsyncAceEditor', () => ({
FullSQLEditor: (props: AsyncAceEditorProps) => (
<div data-test="react-ace">{JSON.stringify(props)}</div>
),
}));
const setup = (queryEditor: QueryEditor, store?: Store) =>
render(
<AceEditorWrapper
queryEditorId={queryEditor.id}
height="100px"
hotkeys={[]}
onChange={jest.fn()}
onBlur={jest.fn()}
autocomplete
/>,
{
useRedux: true,
...(store && { store }),
},
);
describe('AceEditorWrapper', () => {
it('renders ace editor including sql value', async () => {
const { getByTestId } = setup(defaultQueryEditor, mockStore(initialState));
await waitFor(() => expect(getByTestId('react-ace')).toBeInTheDocument());
expect(getByTestId('react-ace')).toHaveTextContent(
JSON.stringify({ value: defaultQueryEditor.sql }).slice(1, -1),
);
});
it('renders current sql for unrelated unsaved changes', () => {
const expectedSql = 'SELECT updated_column\nFROM updated_table\nWHERE';
const { getByTestId } = setup(
defaultQueryEditor,
mockStore({
...initialState,
sqlLab: {
...initialState.sqlLab,
unsavedQueryEditor: {
id: `${defaultQueryEditor.id}-other`,
sql: expectedSql,
},
},
}),
);
expect(getByTestId('react-ace')).not.toHaveTextContent(
JSON.stringify({ value: expectedSql }).slice(1, -1),
);
expect(getByTestId('react-ace')).toHaveTextContent(
JSON.stringify({ value: defaultQueryEditor.sql }).slice(1, -1),
);
});
});
|
6,453 | 0 | petrpan-code/apache/superset/superset-frontend/src/SqlLab/components | petrpan-code/apache/superset/superset-frontend/src/SqlLab/components/AceEditorWrapper/useAnnotations.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 { initialState } from 'src/SqlLab/fixtures';
import COMMON_ERR_MESSAGES from 'src/utils/errorMessages';
import { useAnnotations } from './useAnnotations';
const fakeApiResult = {
result: [
{
end_column: null,
line_number: 3,
message: 'ERROR: syntax error at or near ";"',
start_column: null,
},
],
};
const expectDbId = 'db1';
const expectSchema = 'my_schema';
const expectSql = 'SELECT * from example_table';
const expectTemplateParams = '{"a": 1, "v": "str"}';
const expectValidatorEngine = 'defined_validator';
const queryValidationApiRoute = `glob:*/api/v1/database/${expectDbId}/validate_sql/`;
jest.mock('@superset-ui/core', () => ({
...jest.requireActual('@superset-ui/core'),
t: (str: string) => str,
}));
afterEach(() => {
fetchMock.reset();
act(() => {
store.dispatch(api.util.resetApiState());
});
});
beforeEach(() => {
fetchMock.post(queryValidationApiRoute, fakeApiResult);
});
const initialize = (withValidator = false) => {
if (withValidator) {
return renderHook(
() =>
useAnnotations({
sql: expectSql,
dbId: expectDbId,
schema: expectSchema,
templateParams: expectTemplateParams,
}),
{
wrapper: createWrapper({
useRedux: true,
initialState: {
...initialState,
sqlLab: {
...initialState.sqlLab,
databases: {
[expectDbId]: {
backend: expectValidatorEngine,
},
},
},
common: {
conf: {
SQL_VALIDATORS_BY_ENGINE: {
[expectValidatorEngine]: true,
},
},
},
},
}),
},
);
}
return renderHook(
() =>
useAnnotations({
sql: expectSql,
dbId: expectDbId,
schema: expectSchema,
templateParams: expectTemplateParams,
}),
{
wrapper: createWrapper({
useRedux: true,
store,
}),
},
);
};
test('skips fetching validation if validator is undefined', () => {
const { result } = initialize();
expect(result.current.data).toEqual([]);
expect(fetchMock.calls(queryValidationApiRoute)).toHaveLength(0);
});
test('returns validation if validator is configured', async () => {
const { result, waitFor } = initialize(true);
await waitFor(() =>
expect(fetchMock.calls(queryValidationApiRoute)).toHaveLength(1),
);
expect(result.current.data).toEqual(
fakeApiResult.result.map(err => ({
type: 'error',
row: (err.line_number || 0) - 1,
column: (err.start_column || 0) - 1,
text: err.message,
})),
);
});
test('returns server error description', async () => {
const errorMessage = 'Unexpected validation api error';
fetchMock.post(
queryValidationApiRoute,
{
throws: new Error(errorMessage),
},
{ overwriteRoutes: true },
);
const { result, waitFor } = initialize(true);
await waitFor(
() =>
expect(result.current.data).toEqual([
{
type: 'error',
row: 0,
column: 0,
text: `The server failed to validate your query.\n${errorMessage}`,
},
]),
{ timeout: 5000 },
);
});
test('returns sesion expire description when CSRF token expired', async () => {
const errorMessage = 'CSRF token expired';
fetchMock.post(
queryValidationApiRoute,
{
throws: new Error(errorMessage),
},
{ overwriteRoutes: true },
);
const { result, waitFor } = initialize(true);
await waitFor(
() =>
expect(result.current.data).toEqual([
{
type: 'error',
row: 0,
column: 0,
text: `The server failed to validate your query.\n${COMMON_ERR_MESSAGES.SESSION_TIMED_OUT}`,
},
]),
{ timeout: 5000 },
);
});
|
6,455 | 0 | petrpan-code/apache/superset/superset-frontend/src/SqlLab/components | petrpan-code/apache/superset/superset-frontend/src/SqlLab/components/AceEditorWrapper/useKeywords.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,
createStore,
} from 'spec/helpers/testing-library';
import { api } from 'src/hooks/apiResources/queryApi';
import { schemaApiUtil } from 'src/hooks/apiResources/schemas';
import { tableApiUtil } from 'src/hooks/apiResources/tables';
import { addTable } from 'src/SqlLab/actions/sqlLab';
import { initialState } from 'src/SqlLab/fixtures';
import reducers from 'spec/helpers/reducerIndex';
import {
SCHEMA_AUTOCOMPLETE_SCORE,
TABLE_AUTOCOMPLETE_SCORE,
COLUMN_AUTOCOMPLETE_SCORE,
SQL_FUNCTIONS_AUTOCOMPLETE_SCORE,
} from 'src/SqlLab/constants';
import { useKeywords } from './useKeywords';
const fakeSchemaApiResult = ['schema1', 'schema2'];
const fakeTableApiResult = {
count: 2,
result: [
{
id: 1,
value: 'fake api result1',
label: 'fake api label1',
type: 'table',
},
{
id: 2,
value: 'fake api result2',
label: 'fake api label2',
type: 'table',
},
],
};
const fakeFunctionNamesApiResult = {
function_names: ['abs', 'avg', 'sum'],
};
const expectDbId = 1;
const expectSchema = 'schema1';
beforeEach(() => {
act(() => {
store.dispatch(
schemaApiUtil.upsertQueryData(
'schemas',
{
dbId: expectDbId,
forceRefresh: false,
},
fakeSchemaApiResult.map(value => ({
value,
label: value,
title: value,
})),
),
);
store.dispatch(
tableApiUtil.upsertQueryData(
'tables',
{ dbId: expectDbId, schema: expectSchema },
{
options: fakeTableApiResult.result,
hasMore: false,
},
),
);
});
});
afterEach(() => {
fetchMock.reset();
act(() => {
store.dispatch(api.util.resetApiState());
});
});
test('returns keywords including fetched function_names data', async () => {
const dbFunctionNamesApiRoute = `glob:*/api/v1/database/${expectDbId}/function_names/`;
fetchMock.get(dbFunctionNamesApiRoute, fakeFunctionNamesApiResult);
const { result, waitFor } = renderHook(
() =>
useKeywords({
queryEditorId: 'testqueryid',
dbId: expectDbId,
schema: expectSchema,
}),
{
wrapper: createWrapper({
useRedux: true,
store,
}),
},
);
await waitFor(() =>
expect(fetchMock.calls(dbFunctionNamesApiRoute).length).toBe(1),
);
fakeSchemaApiResult.forEach(schema => {
expect(result.current).toContainEqual(
expect.objectContaining({
name: schema,
score: SCHEMA_AUTOCOMPLETE_SCORE,
meta: 'schema',
}),
);
});
fakeTableApiResult.result.forEach(({ value }) => {
expect(result.current).toContainEqual(
expect.objectContaining({
value,
score: TABLE_AUTOCOMPLETE_SCORE,
meta: 'table',
}),
);
});
fakeFunctionNamesApiResult.function_names.forEach(func => {
expect(result.current).toContainEqual(
expect.objectContaining({
name: func,
value: func,
meta: 'function',
score: SQL_FUNCTIONS_AUTOCOMPLETE_SCORE,
}),
);
});
});
test('skip fetching if autocomplete skipped', () => {
const { result } = renderHook(
() =>
useKeywords(
{
queryEditorId: 'testqueryid',
dbId: expectDbId,
schema: expectSchema,
},
true,
),
{
wrapper: createWrapper({
useRedux: true,
store,
}),
},
);
expect(result.current).toEqual([]);
expect(fetchMock.calls()).toEqual([]);
});
test('returns column keywords among selected tables', async () => {
const expectTable = 'table1';
const expectColumn = 'column1';
const expectQueryEditorId = 'testqueryid';
const unexpectedColumn = 'column2';
const unexpectedTable = 'table2';
const dbFunctionNamesApiRoute = `glob:*/api/v1/database/${expectDbId}/function_names/`;
const storeWithSqlLab = createStore(initialState, reducers);
fetchMock.get(dbFunctionNamesApiRoute, fakeFunctionNamesApiResult);
act(() => {
storeWithSqlLab.dispatch(
tableApiUtil.upsertQueryData(
'tableMetadata',
{ dbId: expectDbId, schema: expectSchema, table: expectTable },
{
name: expectTable,
columns: [
{
name: expectColumn,
type: 'VARCHAR',
},
],
},
),
);
storeWithSqlLab.dispatch(
tableApiUtil.upsertQueryData(
'tableMetadata',
{ dbId: expectDbId, schema: expectSchema, table: unexpectedTable },
{
name: unexpectedTable,
columns: [
{
name: unexpectedColumn,
type: 'VARCHAR',
},
],
},
),
);
storeWithSqlLab.dispatch(
addTable({ id: expectQueryEditorId }, expectTable, expectSchema),
);
});
const { result, waitFor } = renderHook(
() =>
useKeywords({
queryEditorId: expectQueryEditorId,
dbId: expectDbId,
schema: expectSchema,
}),
{
wrapper: createWrapper({
useRedux: true,
store: storeWithSqlLab,
}),
},
);
await waitFor(() =>
expect(result.current).toContainEqual(
expect.objectContaining({
name: expectColumn,
value: expectColumn,
score: COLUMN_AUTOCOMPLETE_SCORE,
meta: 'column',
}),
),
);
expect(result.current).not.toContainEqual(
expect.objectContaining({
name: unexpectedColumn,
}),
);
act(() => {
storeWithSqlLab.dispatch(
addTable({ id: expectQueryEditorId }, unexpectedTable, expectSchema),
);
});
await waitFor(() =>
expect(result.current).toContainEqual(
expect.objectContaining({
name: unexpectedColumn,
}),
),
);
});
test('returns long keywords with docText', async () => {
const expectLongKeywordDbId = 2;
const longKeyword = 'veryveryveryveryverylongtablename';
const dbFunctionNamesApiRoute = `glob:*/api/v1/database/${expectLongKeywordDbId}/function_names/`;
fetchMock.get(dbFunctionNamesApiRoute, { function_names: [] });
act(() => {
store.dispatch(
schemaApiUtil.upsertQueryData(
'schemas',
{
dbId: expectLongKeywordDbId,
forceRefresh: false,
},
['short', longKeyword].map(value => ({
value,
label: value,
title: value,
})),
),
);
});
const { result, waitFor } = renderHook(
() =>
useKeywords({
queryEditorId: 'testqueryid',
dbId: expectLongKeywordDbId,
}),
{
wrapper: createWrapper({
useRedux: true,
store,
}),
},
);
await waitFor(() =>
expect(result.current).toContainEqual(
expect.objectContaining({
name: longKeyword,
value: longKeyword,
docText: longKeyword,
}),
),
);
});
|
6,459 | 0 | petrpan-code/apache/superset/superset-frontend/src/SqlLab/components | petrpan-code/apache/superset/superset-frontend/src/SqlLab/components/ColumnElement/ColumnElement.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 ColumnElement from 'src/SqlLab/components/ColumnElement';
import { mockedActions, table } from 'src/SqlLab/fixtures';
describe('ColumnElement', () => {
const mockedProps = {
actions: mockedActions,
column: table.columns[0],
};
it('is valid with props', () => {
expect(React.isValidElement(<ColumnElement {...mockedProps} />)).toBe(true);
});
it('renders a proper primary key', () => {
const wrapper = mount(<ColumnElement column={table.columns[0]} />);
expect(wrapper.find('i.fa-key')).toExist();
expect(wrapper.find('.col-name').first().text()).toBe('id');
});
it('renders a multi-key column', () => {
const wrapper = mount(<ColumnElement column={table.columns[1]} />);
expect(wrapper.find('i.fa-link')).toExist();
expect(wrapper.find('i.fa-bookmark')).toExist();
expect(wrapper.find('.col-name').first().text()).toBe('first_name');
});
it('renders a column with no keys', () => {
const wrapper = mount(<ColumnElement column={table.columns[2]} />);
expect(wrapper.find('i')).not.toExist();
expect(wrapper.find('.col-name').first().text()).toBe('last_name');
});
});
|
6,461 | 0 | petrpan-code/apache/superset/superset-frontend/src/SqlLab/components | petrpan-code/apache/superset/superset-frontend/src/SqlLab/components/EditorAutoSync/EditorAutoSync.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.
*/
/**
* 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, waitFor } from 'spec/helpers/testing-library';
import ToastContainer from 'src/components/MessageToasts/ToastContainer';
import { initialState, defaultQueryEditor } from 'src/SqlLab/fixtures';
import { logging } from '@superset-ui/core';
import EditorAutoSync from '.';
jest.mock('@superset-ui/core', () => ({
...jest.requireActual('@superset-ui/core'),
logging: {
warn: jest.fn(),
},
}));
const editorTabLastUpdatedAt = Date.now();
const unsavedSqlLabState = {
...initialState.sqlLab,
unsavedQueryEditor: {
id: defaultQueryEditor.id,
name: 'updated tab name',
updatedAt: editorTabLastUpdatedAt + 100,
},
editorTabLastUpdatedAt,
};
beforeAll(() => {
jest.useFakeTimers();
});
afterAll(() => {
jest.useRealTimers();
});
test('sync the unsaved editor tab state when there are new changes since the last update', async () => {
const updateEditorTabState = `glob:*/tabstateview/${defaultQueryEditor.id}`;
fetchMock.put(updateEditorTabState, 200);
expect(fetchMock.calls(updateEditorTabState)).toHaveLength(0);
render(<EditorAutoSync />, {
useRedux: true,
initialState: {
...initialState,
sqlLab: unsavedSqlLabState,
},
});
await waitFor(() => jest.runAllTimers());
expect(fetchMock.calls(updateEditorTabState)).toHaveLength(1);
fetchMock.restore();
});
test('skip syncing the unsaved editor tab state when the updates are already synced', async () => {
const updateEditorTabState = `glob:*/tabstateview/${defaultQueryEditor.id}`;
fetchMock.put(updateEditorTabState, 200);
expect(fetchMock.calls(updateEditorTabState)).toHaveLength(0);
render(<EditorAutoSync />, {
useRedux: true,
initialState: {
...initialState,
sqlLab: {
...initialState.sqlLab,
unsavedQueryEditor: {
id: defaultQueryEditor.id,
name: 'updated tab name',
updatedAt: editorTabLastUpdatedAt - 100,
},
editorTabLastUpdatedAt,
},
},
});
await waitFor(() => jest.runAllTimers());
expect(fetchMock.calls(updateEditorTabState)).toHaveLength(0);
fetchMock.restore();
});
test('renders an error toast when the sync failed', async () => {
const updateEditorTabState = `glob:*/tabstateview/${defaultQueryEditor.id}`;
fetchMock.put(updateEditorTabState, {
throws: new Error('errorMessage'),
});
expect(fetchMock.calls(updateEditorTabState)).toHaveLength(0);
render(
<>
<EditorAutoSync />
<ToastContainer />
</>,
{
useRedux: true,
initialState: {
...initialState,
sqlLab: unsavedSqlLabState,
},
},
);
await waitFor(() => jest.runAllTimers());
expect(logging.warn).toHaveBeenCalledTimes(1);
expect(logging.warn).toHaveBeenCalledWith(
'An error occurred while saving your editor state.',
expect.anything(),
);
fetchMock.restore();
});
|
6,463 | 0 | petrpan-code/apache/superset/superset-frontend/src/SqlLab/components | petrpan-code/apache/superset/superset-frontend/src/SqlLab/components/EstimateQueryCostButton/EstimateQueryCostButton.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 configureStore from 'redux-mock-store';
import thunk from 'redux-thunk';
import { fireEvent, render } from 'spec/helpers/testing-library';
import { Store } from 'redux';
import {
initialState,
defaultQueryEditor,
extraQueryEditor1,
} from 'src/SqlLab/fixtures';
import EstimateQueryCostButton, {
EstimateQueryCostButtonProps,
} from 'src/SqlLab/components/EstimateQueryCostButton';
const middlewares = [thunk];
const mockStore = configureStore(middlewares);
jest.mock('src/components/DeprecatedSelect', () => () => (
<div data-test="mock-deprecated-select" />
));
jest.mock('src/components/Select/Select', () => () => (
<div data-test="mock-deprecated-select-select" />
));
jest.mock('src/components/Select/AsyncSelect', () => () => (
<div data-test="mock-deprecated-async-select" />
));
const setup = (props: Partial<EstimateQueryCostButtonProps>, store?: Store) =>
render(
<EstimateQueryCostButton
queryEditorId={defaultQueryEditor.id}
getEstimate={jest.fn()}
{...props}
/>,
{
useRedux: true,
...(store && { store }),
},
);
describe('EstimateQueryCostButton', () => {
it('renders EstimateQueryCostButton', async () => {
const { queryByText } = setup({}, mockStore(initialState));
expect(queryByText('Estimate cost')).toBeTruthy();
});
it('renders label for selected query', async () => {
const { queryByText } = setup(
{ queryEditorId: extraQueryEditor1.id },
mockStore(initialState),
);
expect(queryByText('Estimate selected query cost')).toBeTruthy();
});
it('renders label for selected query from unsaved', async () => {
const { queryByText } = setup(
{},
mockStore({
...initialState,
sqlLab: {
...initialState.sqlLab,
unsavedQueryEditor: {
id: defaultQueryEditor.id,
selectedText: 'SELECT',
},
},
}),
);
expect(queryByText('Estimate selected query cost')).toBeTruthy();
});
it('renders estimation error result', async () => {
const { queryByText, getByText } = setup(
{},
mockStore({
...initialState,
sqlLab: {
...initialState.sqlLab,
queryCostEstimates: {
[defaultQueryEditor.id]: {
error: 'Estimate error',
},
},
},
}),
);
expect(queryByText('Estimate cost')).toBeTruthy();
fireEvent.click(getByText('Estimate cost'));
expect(queryByText('Estimate error')).toBeTruthy();
});
it('renders estimation success result', async () => {
const { queryByText, getByText } = setup(
{},
mockStore({
...initialState,
sqlLab: {
...initialState.sqlLab,
queryCostEstimates: {
[defaultQueryEditor.id]: {
completed: true,
cost: [{ 'Total cost': '1.2' }],
},
},
},
}),
);
expect(queryByText('Estimate cost')).toBeTruthy();
fireEvent.click(getByText('Estimate cost'));
expect(queryByText('Total cost')).toBeTruthy();
});
});
|
6,465 | 0 | petrpan-code/apache/superset/superset-frontend/src/SqlLab/components | petrpan-code/apache/superset/superset-frontend/src/SqlLab/components/ExploreCtasResultsButton/ExploreCtasResultsButton.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 configureStore from 'redux-mock-store';
import fetchMock from 'fetch-mock';
import thunk from 'redux-thunk';
import { fireEvent, render, waitFor } from 'spec/helpers/testing-library';
import { Store } from 'redux';
import { SupersetClientClass } from '@superset-ui/core';
import { initialState } from 'src/SqlLab/fixtures';
import ExploreCtasResultsButton, {
ExploreCtasResultsButtonProps,
} from 'src/SqlLab/components/ExploreCtasResultsButton';
const middlewares = [thunk];
const mockStore = configureStore(middlewares);
const getOrCreateTableEndpoint = `glob:*/api/v1/dataset/get_or_create/`;
const setup = (props: Partial<ExploreCtasResultsButtonProps>, store?: Store) =>
render(
<ExploreCtasResultsButton
table="test"
schema="test_schema"
dbId={12346}
{...props}
/>,
{
useRedux: true,
...(store && { store }),
},
);
describe('ExploreCtasResultsButton', () => {
const postFormSpy = jest.spyOn(SupersetClientClass.prototype, 'postForm');
postFormSpy.mockImplementation(jest.fn());
it('renders', async () => {
const { queryByText } = setup({}, mockStore(initialState));
expect(queryByText('Explore')).toBeTruthy();
});
it('visualize results', async () => {
const { getByText } = setup({}, mockStore(initialState));
postFormSpy.mockClear();
fetchMock.reset();
fetchMock.post(getOrCreateTableEndpoint, { result: { table_id: 1234 } });
fireEvent.click(getByText('Explore'));
await waitFor(() => {
expect(postFormSpy).toHaveBeenCalledTimes(1);
expect(postFormSpy).toHaveBeenCalledWith('http://localhost/explore/', {
form_data:
'{"datasource":"1234__table","metrics":["count"],"groupby":[],"viz_type":"table","since":"100 years ago","all_columns":[],"row_limit":1000}',
});
});
});
it('visualize results fails', async () => {
const { getByText } = setup({}, mockStore(initialState));
postFormSpy.mockClear();
fetchMock.reset();
fetchMock.post(getOrCreateTableEndpoint, {
throws: new Error('Unexpected all to v1 API'),
});
fireEvent.click(getByText('Explore'));
await waitFor(() => {
expect(postFormSpy).toHaveBeenCalledTimes(0);
});
});
});
|
6,467 | 0 | petrpan-code/apache/superset/superset-frontend/src/SqlLab/components | petrpan-code/apache/superset/superset-frontend/src/SqlLab/components/ExploreResultsButton/ExploreResultsButton.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 ExploreResultsButton, {
ExploreResultsButtonProps,
} from 'src/SqlLab/components/ExploreResultsButton';
import { OnClickHandler } from 'src/components/Button';
const setup = (
onClickFn: OnClickHandler,
props: Partial<ExploreResultsButtonProps> = {},
) =>
render(<ExploreResultsButton onClick={onClickFn} {...props} />, {
useRedux: true,
});
describe('ExploreResultsButton', () => {
it('renders', async () => {
const { queryByText } = setup(jest.fn(), {
database: { allows_subquery: true },
});
expect(queryByText('Create Chart')).toBeTruthy();
expect(screen.getByRole('button', { name: 'Create Chart' })).toBeEnabled();
});
it('renders disabled if subquery not allowed', async () => {
const { queryByText } = setup(jest.fn());
expect(queryByText('Create Chart')).toBeTruthy();
expect(screen.getByRole('button', { name: 'Create Chart' })).toBeDisabled();
});
});
|
6,469 | 0 | petrpan-code/apache/superset/superset-frontend/src/SqlLab/components | petrpan-code/apache/superset/superset-frontend/src/SqlLab/components/HighlightedSql/HighlightedSql.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 HighlightedSql from 'src/SqlLab/components/HighlightedSql';
import { fireEvent, render } from 'spec/helpers/testing-library';
const sql =
"SELECT * FROM test WHERE something='fkldasjfklajdslfkjadlskfjkldasjfkladsjfkdjsa'";
test('renders HighlightedSql component with sql prop', () => {
expect(React.isValidElement(<HighlightedSql sql={sql} />)).toBe(true);
});
test('renders a ModalTrigger component', () => {
const { getByTestId } = render(<HighlightedSql sql={sql} />);
expect(getByTestId('span-modal-trigger')).toBeInTheDocument();
});
test('renders a ModalTrigger component with shrink prop and maxWidth prop set to 20', () => {
const { getByTestId } = render(
<HighlightedSql sql={sql} shrink maxWidth={20} />,
);
expect(getByTestId('span-modal-trigger')).toBeInTheDocument();
});
test('renders two code elements in modal when rawSql prop is provided', () => {
const { getByRole, queryByRole, getByTestId } = render(
<HighlightedSql sql={sql} rawSql="SELECT * FORM foo" shrink maxWidth={5} />,
);
expect(queryByRole('dialog')).not.toBeInTheDocument();
fireEvent.click(getByTestId('span-modal-trigger'));
expect(queryByRole('dialog')).toBeInTheDocument();
const codeElements = getByRole('dialog').getElementsByTagName('code');
expect(codeElements.length).toEqual(2);
});
|
6,471 | 0 | petrpan-code/apache/superset/superset-frontend/src/SqlLab/components | petrpan-code/apache/superset/superset-frontend/src/SqlLab/components/KeyboardShortcutButton/KeyboardShortcutButton.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 { fireEvent, render } from 'spec/helpers/testing-library';
import KeyboardShortcutButton, { KEY_MAP } from '.';
test('renders shortcut description', () => {
const { getByText, getByRole } = render(
<KeyboardShortcutButton>Show shortcuts</KeyboardShortcutButton>,
);
fireEvent.click(getByRole('button'));
expect(getByText('Keyboard shortcuts')).toBeInTheDocument();
Object.keys(KEY_MAP)
.filter(key => Boolean(KEY_MAP[key]))
.forEach(key => {
expect(getByText(key)).toBeInTheDocument();
});
});
|
6,473 | 0 | petrpan-code/apache/superset/superset-frontend/src/SqlLab/components | petrpan-code/apache/superset/superset-frontend/src/SqlLab/components/QueryAutoRefresh/QueryAutoRefresh.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 configureStore from 'redux-mock-store';
import thunk from 'redux-thunk';
import { render, waitFor } from 'spec/helpers/testing-library';
import {
CLEAR_INACTIVE_QUERIES,
REFRESH_QUERIES,
} from 'src/SqlLab/actions/sqlLab';
import QueryAutoRefresh, {
isQueryRunning,
shouldCheckForQueries,
QUERY_UPDATE_FREQ,
} from 'src/SqlLab/components/QueryAutoRefresh';
import { successfulQuery, runningQuery } from 'src/SqlLab/fixtures';
import { QueryDictionary } from 'src/SqlLab/types';
const middlewares = [thunk];
const mockStore = configureStore(middlewares);
// NOTE: The uses of @ts-ignore in this file is to enable testing of bad inputs to verify the
// function / component handles bad data elegantly
describe('QueryAutoRefresh', () => {
const runningQueries: QueryDictionary = {};
runningQueries[runningQuery.id] = runningQuery;
const successfulQueries: QueryDictionary = {};
successfulQueries[successfulQuery.id] = successfulQuery;
const queriesLastUpdate = Date.now();
const refreshApi = 'glob:*/api/v1/query/updated_since?*';
afterEach(() => {
fetchMock.reset();
});
it('isQueryRunning returns true for valid running query', () => {
const running = isQueryRunning(runningQuery);
expect(running).toBe(true);
});
it('isQueryRunning returns false for valid not-running query', () => {
const running = isQueryRunning(successfulQuery);
expect(running).toBe(false);
});
it('isQueryRunning returns false for invalid query', () => {
// @ts-ignore
let running = isQueryRunning(null);
expect(running).toBe(false);
// @ts-ignore
running = isQueryRunning(undefined);
expect(running).toBe(false);
// @ts-ignore
running = isQueryRunning('I Should Be An Object');
expect(running).toBe(false);
// @ts-ignore
running = isQueryRunning({ state: { badFormat: true } });
expect(running).toBe(false);
});
it('shouldCheckForQueries is true for valid running query', () => {
expect(shouldCheckForQueries(runningQueries)).toBe(true);
});
it('shouldCheckForQueries is false for valid completed query', () => {
expect(shouldCheckForQueries(successfulQueries)).toBe(false);
});
it('shouldCheckForQueries is false for invalid inputs', () => {
// @ts-ignore
expect(shouldCheckForQueries(null)).toBe(false);
// @ts-ignore
expect(shouldCheckForQueries(undefined)).toBe(false);
expect(
// @ts-ignore
shouldCheckForQueries({
// @ts-ignore
'1234': null,
// @ts-ignore
'23425': 'hello world',
// @ts-ignore
'345': [],
// @ts-ignore
'57346': undefined,
}),
).toBe(false);
});
it('Attempts to refresh when given pending query', async () => {
const store = mockStore();
fetchMock.get(refreshApi, {
result: [
{
id: runningQuery.id,
status: 'success',
},
],
});
render(
<QueryAutoRefresh
queries={runningQueries}
queriesLastUpdate={queriesLastUpdate}
/>,
{ useRedux: true, store },
);
await waitFor(
() =>
expect(store.getActions()).toContainEqual(
expect.objectContaining({
type: REFRESH_QUERIES,
}),
),
{ timeout: QUERY_UPDATE_FREQ + 100 },
);
});
it('Attempts to clear inactive queries when updated queries are empty', async () => {
const store = mockStore();
fetchMock.get(refreshApi, {
result: [],
});
render(
<QueryAutoRefresh
queries={runningQueries}
queriesLastUpdate={queriesLastUpdate}
/>,
{ useRedux: true, store },
);
await waitFor(
() =>
expect(store.getActions()).toContainEqual(
expect.objectContaining({
type: CLEAR_INACTIVE_QUERIES,
}),
),
{ timeout: QUERY_UPDATE_FREQ + 100 },
);
expect(
store.getActions().filter(({ type }) => type === REFRESH_QUERIES),
).toHaveLength(0);
expect(fetchMock.calls(refreshApi)).toHaveLength(1);
});
it('Does not fail and attempts to refresh when given pending query and invlaid query', async () => {
const store = mockStore();
fetchMock.get(refreshApi, {
result: [
{
id: runningQuery.id,
status: 'success',
},
],
});
render(
<QueryAutoRefresh
// @ts-ignore
queries={{ ...runningQueries, g324t: null }}
queriesLastUpdate={queriesLastUpdate}
/>,
{ useRedux: true, store },
);
await waitFor(
() =>
expect(store.getActions()).toContainEqual(
expect.objectContaining({
type: REFRESH_QUERIES,
}),
),
{ timeout: QUERY_UPDATE_FREQ + 100 },
);
});
it('Does NOT Attempt to refresh when given only completed queries', async () => {
const store = mockStore();
fetchMock.get(refreshApi, {
result: [
{
id: runningQuery.id,
status: 'success',
},
],
});
render(
<QueryAutoRefresh
queries={successfulQueries}
queriesLastUpdate={queriesLastUpdate}
/>,
{ useRedux: true, store },
);
await waitFor(
() =>
expect(store.getActions()).toContainEqual(
expect.objectContaining({
type: CLEAR_INACTIVE_QUERIES,
}),
),
{ timeout: QUERY_UPDATE_FREQ + 100 },
);
expect(fetchMock.calls(refreshApi)).toHaveLength(0);
});
});
|
6,475 | 0 | petrpan-code/apache/superset/superset-frontend/src/SqlLab/components | petrpan-code/apache/superset/superset-frontend/src/SqlLab/components/QueryHistory/QueryHistory.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 QueryHistory from 'src/SqlLab/components/QueryHistory';
const mockedProps = {
queries: [],
displayLimit: 1000,
latestQueryId: 'yhMUZCGb',
};
const setup = (overrides = {}) => (
<QueryHistory {...mockedProps} {...overrides} />
);
describe('QueryHistory', () => {
it('Renders an empty state for query history', () => {
render(setup());
const emptyStateText = screen.getByText(
/run a query to display query history/i,
);
expect(emptyStateText).toBeVisible();
});
});
|
6,477 | 0 | petrpan-code/apache/superset/superset-frontend/src/SqlLab/components | petrpan-code/apache/superset/superset-frontend/src/SqlLab/components/QueryLimitSelect/QueryLimitSelect.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 configureStore from 'redux-mock-store';
import thunk from 'redux-thunk';
import { Store } from 'redux';
import { render, fireEvent, waitFor } from 'spec/helpers/testing-library';
import userEvent from '@testing-library/user-event';
import { initialState, defaultQueryEditor } from 'src/SqlLab/fixtures';
import QueryLimitSelect, {
QueryLimitSelectProps,
convertToNumWithSpaces,
} from 'src/SqlLab/components/QueryLimitSelect';
const middlewares = [thunk];
const mockStore = configureStore(middlewares);
jest.mock('src/components/DeprecatedSelect', () => () => (
<div data-test="mock-deprecated-select" />
));
jest.mock('src/components/Select/Select', () => () => (
<div data-test="mock-deprecated-select-select" />
));
jest.mock('src/components/Select/AsyncSelect', () => () => (
<div data-test="mock-deprecated-async-select" />
));
const defaultQueryLimit = 100;
const setup = (props?: Partial<QueryLimitSelectProps>, store?: Store) =>
render(
<QueryLimitSelect
queryEditorId={defaultQueryEditor.id}
maxRow={100000}
defaultQueryLimit={defaultQueryLimit}
{...props}
/>,
{
useRedux: true,
...(store && { store }),
},
);
describe('QueryLimitSelect', () => {
it('renders current query limit size', () => {
const queryLimit = 10;
const { getByText } = setup(
{
queryEditorId: defaultQueryEditor.id,
},
mockStore({
...initialState,
sqlLab: {
...initialState.sqlLab,
queryEditors: [
{
...defaultQueryEditor,
queryLimit,
},
],
},
}),
);
expect(getByText(queryLimit)).toBeInTheDocument();
});
it('renders default query limit for initial queryEditor', () => {
const { getByText } = setup({}, mockStore(initialState));
expect(getByText(defaultQueryLimit)).toBeInTheDocument();
});
it('renders queryLimit from unsavedQueryEditor', () => {
const queryLimit = 10000;
const { getByText } = setup(
{},
mockStore({
...initialState,
sqlLab: {
...initialState.sqlLab,
unsavedQueryEditor: {
id: defaultQueryEditor.id,
queryLimit,
},
},
}),
);
expect(getByText(convertToNumWithSpaces(queryLimit))).toBeInTheDocument();
});
it('renders dropdown select', async () => {
const { baseElement, getAllByRole, getByRole } = setup(
{ maxRow: 50000 },
mockStore(initialState),
);
const dropdown = baseElement.getElementsByClassName(
'ant-dropdown-trigger',
)[0];
userEvent.click(dropdown);
await waitFor(() => expect(getByRole('menu')).toBeInTheDocument());
const expectedLabels = [10, 100, 1000, 10000, 50000].map(i =>
convertToNumWithSpaces(i),
);
const actualLabels = getAllByRole('menuitem').map(elem =>
elem.textContent?.trim(),
);
expect(actualLabels).toEqual(expectedLabels);
});
it('renders dropdown select correctly when maxRow is less than 10', async () => {
const { baseElement, getAllByRole, getByRole } = setup(
{ maxRow: 5 },
mockStore(initialState),
);
const dropdown = baseElement.getElementsByClassName(
'ant-dropdown-trigger',
)[0];
userEvent.click(dropdown);
await waitFor(() => expect(getByRole('menu')).toBeInTheDocument());
const expectedLabels = [5].map(i => convertToNumWithSpaces(i));
const actualLabels = getAllByRole('menuitem').map(elem =>
elem.textContent?.trim(),
);
expect(actualLabels).toEqual(expectedLabels);
});
it('renders dropdown select correctly when maxRow is a multiple of 10', async () => {
const { baseElement, getAllByRole, getByRole } = setup(
{ maxRow: 10000 },
mockStore(initialState),
);
const dropdown = baseElement.getElementsByClassName(
'ant-dropdown-trigger',
)[0];
userEvent.click(dropdown);
await waitFor(() => expect(getByRole('menu')).toBeInTheDocument());
const expectedLabels = [10, 100, 1000, 10000].map(i =>
convertToNumWithSpaces(i),
);
const actualLabels = getAllByRole('menuitem').map(elem =>
elem.textContent?.trim(),
);
expect(actualLabels).toEqual(expectedLabels);
});
it('dispatches QUERY_EDITOR_SET_QUERY_LIMIT action on dropdown menu click', async () => {
const store = mockStore(initialState);
const expectedIndex = 1;
const { baseElement, getAllByRole, getByRole } = setup({}, store);
const dropdown = baseElement.getElementsByClassName(
'ant-dropdown-trigger',
)[0];
userEvent.click(dropdown);
await waitFor(() => expect(getByRole('menu')).toBeInTheDocument());
const menu = getAllByRole('menuitem')[expectedIndex];
expect(store.getActions()).toEqual([]);
fireEvent.click(menu);
await waitFor(() =>
expect(store.getActions()).toEqual([
{
type: 'QUERY_EDITOR_SET_QUERY_LIMIT',
queryLimit: 100,
queryEditor: {
id: defaultQueryEditor.id,
},
},
]),
);
});
});
|
6,479 | 0 | petrpan-code/apache/superset/superset-frontend/src/SqlLab/components | petrpan-code/apache/superset/superset-frontend/src/SqlLab/components/QueryStateLabel/QueryStateLabel.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 type { QueryState } from '@superset-ui/core';
import { render } from 'spec/helpers/testing-library';
import QueryStateLabel from '.';
jest.mock('src/components/Label', () => () => <div data-test="mock-label" />);
const mockedProps = {
query: {
state: 'running' as QueryState,
},
};
test('is valid', () => {
expect(React.isValidElement(<QueryStateLabel {...mockedProps} />)).toBe(true);
});
test('has an Overlay and a Popover', () => {
const { getByTestId } = render(<QueryStateLabel {...mockedProps} />);
expect(getByTestId('mock-label')).toBeInTheDocument();
});
|
6,481 | 0 | petrpan-code/apache/superset/superset-frontend/src/SqlLab/components | petrpan-code/apache/superset/superset-frontend/src/SqlLab/components/QueryTable/QueryTable.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 { styledMount as mount } from 'spec/helpers/theming';
import QueryTable from 'src/SqlLab/components/QueryTable';
import TableView from 'src/components/TableView';
import TableCollection from 'src/components/TableCollection';
import { Provider } from 'react-redux';
import { runningQuery, successfulQuery, user } from 'src/SqlLab/fixtures';
const mockedProps = {
queries: [runningQuery, successfulQuery],
displayLimit: 100,
latestQueryId: 'ryhMUZCGb',
};
test('is valid', () => {
expect(React.isValidElement(<QueryTable displayLimit={100} />)).toBe(true);
});
test('is valid with props', () => {
expect(React.isValidElement(<QueryTable {...mockedProps} />)).toBe(true);
});
test('renders a proper table', () => {
const mockStore = configureStore([thunk]);
const store = mockStore({
user,
});
const wrapper = mount(
<Provider store={store}>
<QueryTable {...mockedProps} />
</Provider>,
);
const tableWrapper = wrapper.find(TableView).find(TableCollection);
expect(wrapper.find(TableView)).toExist();
expect(tableWrapper.find('table')).toExist();
expect(tableWrapper.find('table').find('thead').find('tr')).toHaveLength(1);
expect(tableWrapper.find('table').find('tbody').find('tr')).toHaveLength(2);
});
|
6,484 | 0 | petrpan-code/apache/superset/superset-frontend/src/SqlLab/components | petrpan-code/apache/superset/superset-frontend/src/SqlLab/components/ResultSet/ResultSet.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 configureStore from 'redux-mock-store';
import { Store } from 'redux';
import thunk from 'redux-thunk';
import fetchMock from 'fetch-mock';
import ResultSet from 'src/SqlLab/components/ResultSet';
import {
cachedQuery,
failedQueryWithErrorMessage,
failedQueryWithErrors,
queries,
runningQuery,
stoppedQuery,
initialState,
user,
queryWithNoQueryLimit,
} from 'src/SqlLab/fixtures';
const mockedProps = {
cache: true,
query: queries[0],
height: 140,
database: { allows_virtual_table_explore: true },
user,
defaultQueryLimit: 1000,
};
const stoppedQueryProps = { ...mockedProps, query: stoppedQuery };
const runningQueryProps = { ...mockedProps, query: runningQuery };
const fetchingQueryProps = {
...mockedProps,
query: {
dbId: 1,
cached: false,
ctas: false,
id: 'ryhHUZCGb',
progress: 100,
state: 'fetching',
startDttm: Date.now() - 500,
},
};
const cachedQueryProps = { ...mockedProps, query: cachedQuery };
const failedQueryWithErrorMessageProps = {
...mockedProps,
query: failedQueryWithErrorMessage,
};
const failedQueryWithErrorsProps = {
...mockedProps,
query: failedQueryWithErrors,
};
const newProps = {
query: {
cached: false,
resultsKey: 'new key',
results: {
data: [{ a: 1 }],
},
},
};
const asyncQueryProps = {
...mockedProps,
database: { allow_run_async: true },
};
const asyncRefetchDataPreviewProps = {
...asyncQueryProps,
query: {
state: 'success',
results: undefined,
isDataPreview: true,
},
};
const asyncRefetchResultsTableProps = {
...asyncQueryProps,
query: {
state: 'success',
results: undefined,
resultsKey: 'async results key',
},
};
fetchMock.get('glob:*/api/v1/dataset/?*', { result: [] });
const middlewares = [thunk];
const mockStore = configureStore(middlewares);
const setup = (props?: any, store?: Store) =>
render(<ResultSet {...props} />, {
useRedux: true,
...(store && { store }),
});
describe('ResultSet', () => {
test('renders a Table', async () => {
const { getByTestId } = setup(mockedProps, mockStore(initialState));
const table = getByTestId('table-container');
expect(table).toBeInTheDocument();
});
test('should render success query', async () => {
const { queryAllByText, getByTestId } = setup(
mockedProps,
mockStore(initialState),
);
const table = getByTestId('table-container');
expect(table).toBeInTheDocument();
const firstColumn = queryAllByText(
mockedProps.query.results?.columns[0].column_name ?? '',
)[0];
const secondColumn = queryAllByText(
mockedProps.query.results?.columns[1].column_name ?? '',
)[0];
expect(firstColumn).toBeInTheDocument();
expect(secondColumn).toBeInTheDocument();
const exploreButton = getByTestId('explore-results-button');
expect(exploreButton).toBeInTheDocument();
});
test('should render empty results', async () => {
const props = {
...mockedProps,
query: { ...mockedProps.query, results: { data: [] } },
};
await waitFor(() => {
setup(props, mockStore(initialState));
});
const alert = screen.getByRole('alert');
expect(alert).toBeInTheDocument();
expect(alert).toHaveTextContent('The query returned no data');
});
test('should call reRunQuery if timed out', async () => {
const store = mockStore(initialState);
const propsWithError = {
...mockedProps,
query: { ...queries[0], errorMessage: 'Your session timed out' },
};
setup(propsWithError, store);
expect(store.getActions()).toHaveLength(1);
expect(store.getActions()[0].query.errorMessage).toEqual(
'Your session timed out',
);
expect(store.getActions()[0].type).toEqual('START_QUERY');
});
test('should not call reRunQuery if no error', async () => {
const store = mockStore(initialState);
setup(mockedProps, store);
expect(store.getActions()).toEqual([]);
});
test('should render cached query', async () => {
const store = mockStore(initialState);
const { rerender } = setup(cachedQueryProps, store);
// @ts-ignore
rerender(<ResultSet {...newProps} />);
expect(store.getActions()).toHaveLength(2);
expect(store.getActions()[0].query.results).toEqual(
cachedQueryProps.query.results,
);
expect(store.getActions()[0].type).toEqual('CLEAR_QUERY_RESULTS');
});
test('should render stopped query', async () => {
await waitFor(() => {
setup(stoppedQueryProps, mockStore(initialState));
});
const alert = screen.getByRole('alert');
expect(alert).toBeInTheDocument();
});
test('should render running/pending/fetching query', async () => {
const { getByTestId } = setup(runningQueryProps, mockStore(initialState));
const progressBar = getByTestId('progress-bar');
expect(progressBar).toBeInTheDocument();
});
test('should render fetching w/ 100 progress query', async () => {
const { getByRole, getByText } = setup(
fetchingQueryProps,
mockStore(initialState),
);
const loading = getByRole('status');
expect(loading).toBeInTheDocument();
expect(getByText('fetching')).toBeInTheDocument();
});
test('should render a failed query with an error message', async () => {
await waitFor(() => {
setup(failedQueryWithErrorMessageProps, mockStore(initialState));
});
expect(screen.getByText('Database error')).toBeInTheDocument();
expect(screen.getByText('Something went wrong')).toBeInTheDocument();
});
test('should render a failed query with an errors object', async () => {
await waitFor(() => {
setup(failedQueryWithErrorsProps, mockStore(initialState));
});
expect(screen.getByText('Database error')).toBeInTheDocument();
});
test('renders if there is no limit in query.results but has queryLimit', async () => {
const { getByRole } = setup(mockedProps, mockStore(initialState));
expect(getByRole('table')).toBeInTheDocument();
});
test('renders if there is a limit in query.results but not queryLimit', async () => {
const props = { ...mockedProps, query: queryWithNoQueryLimit };
const { getByRole } = setup(props, mockStore(initialState));
expect(getByRole('table')).toBeInTheDocument();
});
test('Async queries - renders "Fetch data preview" button when data preview has no results', () => {
setup(asyncRefetchDataPreviewProps, mockStore(initialState));
expect(
screen.getByRole('button', {
name: /fetch data preview/i,
}),
).toBeVisible();
expect(screen.queryByRole('grid')).toBe(null);
});
test('Async queries - renders "Refetch results" button when a query has no results', () => {
setup(asyncRefetchResultsTableProps, mockStore(initialState));
expect(
screen.getByRole('button', {
name: /refetch results/i,
}),
).toBeVisible();
expect(screen.queryByRole('grid')).toBe(null);
});
test('Async queries - renders on the first call', () => {
setup(asyncQueryProps, mockStore(initialState));
expect(screen.getByRole('table')).toBeVisible();
expect(
screen.queryByRole('button', {
name: /fetch data preview/i,
}),
).toBe(null);
expect(
screen.queryByRole('button', {
name: /refetch results/i,
}),
).toBe(null);
});
});
|
6,486 | 0 | petrpan-code/apache/superset/superset-frontend/src/SqlLab/components | petrpan-code/apache/superset/superset-frontend/src/SqlLab/components/RunQueryActionButton/RunQueryActionButton.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 configureStore from 'redux-mock-store';
import thunk from 'redux-thunk';
import { Store } from 'redux';
import { render, fireEvent, waitFor } from 'spec/helpers/testing-library';
import { initialState, defaultQueryEditor } from 'src/SqlLab/fixtures';
import RunQueryActionButton, {
RunQueryActionButtonProps,
} from 'src/SqlLab/components/RunQueryActionButton';
const middlewares = [thunk];
const mockStore = configureStore(middlewares);
jest.mock('src/components/DeprecatedSelect', () => () => (
<div data-test="mock-deprecated-select" />
));
jest.mock('src/components/Select/Select', () => () => (
<div data-test="mock-deprecated-select-select" />
));
jest.mock('src/components/Select/AsyncSelect', () => () => (
<div data-test="mock-deprecated-async-select" />
));
const defaultProps = {
queryEditorId: defaultQueryEditor.id,
allowAsync: false,
dbId: 1,
queryState: 'ready',
runQuery: () => {},
selectedText: null,
stopQuery: () => {},
overlayCreateAsMenu: null,
};
const setup = (props?: Partial<RunQueryActionButtonProps>, store?: Store) =>
render(<RunQueryActionButton {...defaultProps} {...props} />, {
useRedux: true,
...(store && { store }),
});
it('renders a single Button', () => {
const { getByRole } = setup({}, mockStore(initialState));
expect(getByRole('button')).toBeInTheDocument();
});
it('renders a label for Run Query', () => {
const { getByText } = setup({}, mockStore(initialState));
expect(getByText('Run')).toBeInTheDocument();
});
it('renders a label for Selected Query', () => {
const { getByText } = setup(
{},
mockStore({
...initialState,
sqlLab: {
...initialState.sqlLab,
unsavedQueryEditor: {
id: defaultQueryEditor.id,
selectedText: 'select * from\n-- this is comment\nwhere',
},
},
}),
);
expect(getByText('Run selection')).toBeInTheDocument();
});
it('disable button when sql from unsaved changes is empty', () => {
const { getByRole } = setup(
{},
mockStore({
...initialState,
sqlLab: {
...initialState.sqlLab,
unsavedQueryEditor: {
id: defaultQueryEditor.id,
sql: '',
},
},
}),
);
const button = getByRole('button');
expect(button).toBeDisabled();
});
it('disable button when selectedText only contains blank contents', () => {
const { getByRole } = setup(
{},
mockStore({
...initialState,
sqlLab: {
...initialState.sqlLab,
unsavedQueryEditor: {
id: defaultQueryEditor.id,
selectedText: '-- this is comment\n\n \t',
},
},
}),
);
const button = getByRole('button');
expect(button).toBeDisabled();
});
it('enable default button for unrelated unsaved changes', () => {
const { getByRole } = setup(
{},
mockStore({
...initialState,
sqlLab: {
...initialState.sqlLab,
unsavedQueryEditor: {
id: `${defaultQueryEditor.id}-other`,
sql: '',
},
},
}),
);
const button = getByRole('button');
expect(button).toBeEnabled();
});
it('dispatch runQuery on click', async () => {
const runQuery = jest.fn();
const { getByRole } = setup({ runQuery }, mockStore(initialState));
const button = getByRole('button');
expect(runQuery).toHaveBeenCalledTimes(0);
fireEvent.click(button);
await waitFor(() => expect(runQuery).toHaveBeenCalledTimes(1));
});
it('dispatch stopQuery on click while running state', async () => {
const stopQuery = jest.fn();
const { getByRole } = setup(
{ queryState: 'running', stopQuery },
mockStore(initialState),
);
const button = getByRole('button');
expect(stopQuery).toHaveBeenCalledTimes(0);
fireEvent.click(button);
await waitFor(() => expect(stopQuery).toHaveBeenCalledTimes(1));
});
|
6,488 | 0 | petrpan-code/apache/superset/superset-frontend/src/SqlLab/components | petrpan-code/apache/superset/superset-frontend/src/SqlLab/components/SaveDatasetActionButton/SaveDatasetActionButton.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 { Menu } from 'src/components/Menu';
import SaveDatasetActionButton from 'src/SqlLab/components/SaveDatasetActionButton';
const overlayMenu = (
<Menu>
<Menu.Item>Save dataset</Menu.Item>
</Menu>
);
describe('SaveDatasetActionButton', () => {
test('renders a split save button', async () => {
render(
<SaveDatasetActionButton
setShowSave={() => true}
overlayMenu={overlayMenu}
/>,
);
const saveBtn = screen.getByRole('button', { name: /save/i });
const caretBtn = screen.getByRole('button', { name: /caret-down/i });
expect(
await screen.findByRole('button', { name: /save/i }),
).toBeInTheDocument();
expect(saveBtn).toBeVisible();
expect(caretBtn).toBeVisible();
});
test('renders a "save dataset" dropdown menu item when user clicks caret button', async () => {
render(
<SaveDatasetActionButton
setShowSave={() => true}
overlayMenu={overlayMenu}
/>,
);
const caretBtn = screen.getByRole('button', { name: /caret-down/i });
expect(
await screen.findByRole('button', { name: /caret-down/i }),
).toBeInTheDocument();
userEvent.click(caretBtn);
const saveDatasetMenuItem = screen.getByText(/save dataset/i);
expect(saveDatasetMenuItem).toBeInTheDocument();
});
});
|
6,490 | 0 | petrpan-code/apache/superset/superset-frontend/src/SqlLab/components | petrpan-code/apache/superset/superset-frontend/src/SqlLab/components/SaveDatasetModal/SaveDatasetModal.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 {
fireEvent,
render,
screen,
cleanup,
waitFor,
} from 'spec/helpers/testing-library';
import userEvent from '@testing-library/user-event';
import fetchMock from 'fetch-mock';
import { SaveDatasetModal } from 'src/SqlLab/components/SaveDatasetModal';
import { createDatasource } from 'src/SqlLab/actions/sqlLab';
import { user, testQuery, mockdatasets } from 'src/SqlLab/fixtures';
const mockedProps = {
visible: true,
onHide: () => {},
buttonTextOnSave: 'Save',
buttonTextOnOverwrite: 'Overwrite',
datasource: testQuery,
};
fetchMock.get('glob:*/api/v1/dataset/?*', {
result: mockdatasets,
dataset_count: 3,
});
jest.useFakeTimers();
// Mock the user
const useSelectorMock = jest.spyOn(reactRedux, 'useSelector');
beforeEach(() => {
useSelectorMock.mockClear();
cleanup();
});
// Mock the createDatasource action
const useDispatchMock = jest.spyOn(reactRedux, 'useDispatch');
jest.mock('src/SqlLab/actions/sqlLab', () => ({
createDatasource: jest.fn(),
}));
jest.mock('src/explore/exploreUtils/formData', () => ({
postFormData: jest.fn(),
}));
describe('SaveDatasetModal', () => {
it('renders a "Save as new" field', () => {
render(<SaveDatasetModal {...mockedProps} />, { useRedux: true });
const saveRadioBtn = screen.getByRole('radio', {
name: /save as new unimportant/i,
});
const fieldLabel = screen.getByText(/save as new/i);
const inputField = screen.getByRole('textbox');
const inputFieldText = screen.getByDisplayValue(/unimportant/i);
expect(saveRadioBtn).toBeVisible();
expect(fieldLabel).toBeVisible();
expect(inputField).toBeVisible();
expect(inputFieldText).toBeVisible();
});
it('renders an "Overwrite existing" field', () => {
render(<SaveDatasetModal {...mockedProps} />, { useRedux: true });
const overwriteRadioBtn = screen.getByRole('radio', {
name: /overwrite existing/i,
});
const fieldLabel = screen.getByText(/overwrite existing/i);
const inputField = screen.getByRole('combobox');
const placeholderText = screen.getByText(/select or type dataset name/i);
expect(overwriteRadioBtn).toBeVisible();
expect(fieldLabel).toBeVisible();
expect(inputField).toBeVisible();
expect(placeholderText).toBeVisible();
});
it('renders a close button', () => {
render(<SaveDatasetModal {...mockedProps} />, { useRedux: true });
expect(screen.getByRole('button', { name: /close/i })).toBeVisible();
});
it('renders a save button when "Save as new" is selected', () => {
render(<SaveDatasetModal {...mockedProps} />, { useRedux: true });
// "Save as new" is selected when the modal opens by default
expect(screen.getByRole('button', { name: /save/i })).toBeVisible();
});
it('renders an overwrite button when "Overwrite existing" is selected', () => {
render(<SaveDatasetModal {...mockedProps} />, { useRedux: true });
// Click the overwrite radio button to reveal the overwrite confirmation and back buttons
const overwriteRadioBtn = screen.getByRole('radio', {
name: /overwrite existing/i,
});
userEvent.click(overwriteRadioBtn);
expect(screen.getByRole('button', { name: /overwrite/i })).toBeVisible();
});
it('renders the overwrite button as disabled until an existing dataset is selected', async () => {
useSelectorMock.mockReturnValue({ ...user });
render(<SaveDatasetModal {...mockedProps} />, { useRedux: true });
// Click the overwrite radio button
const overwriteRadioBtn = screen.getByRole('radio', {
name: /overwrite existing/i,
});
userEvent.click(overwriteRadioBtn);
// Overwrite confirmation button should be disabled at this point
const overwriteConfirmationBtn = screen.getByRole('button', {
name: /overwrite/i,
});
expect(overwriteConfirmationBtn).toBeDisabled();
// Click the overwrite select component
const select = screen.getByRole('combobox', { name: /existing dataset/i })!;
userEvent.click(select);
await waitFor(() =>
expect(screen.queryByText('Loading...')).not.toBeVisible(),
);
// Select the first "existing dataset" from the listbox
const option = screen.getAllByText('coolest table 0')[1];
userEvent.click(option);
// Overwrite button should now be enabled
expect(overwriteConfirmationBtn).toBeEnabled();
});
it('renders a confirm overwrite screen when overwrite is clicked', async () => {
useSelectorMock.mockReturnValue({ ...user });
render(<SaveDatasetModal {...mockedProps} />, { useRedux: true });
// Click the overwrite radio button
const overwriteRadioBtn = screen.getByRole('radio', {
name: /overwrite existing/i,
});
userEvent.click(overwriteRadioBtn);
// Click the overwrite select component
const select = screen.getByRole('combobox', { name: /existing dataset/i });
userEvent.click(select);
await waitFor(() =>
expect(screen.queryByText('Loading...')).not.toBeVisible(),
);
// Select the first "existing dataset" from the listbox
const option = screen.getAllByText('coolest table 0')[1];
userEvent.click(option);
// Click the overwrite button to access the confirmation screen
const overwriteConfirmationBtn = screen.getByRole('button', {
name: /overwrite/i,
});
userEvent.click(overwriteConfirmationBtn);
// Overwrite screen text
expect(screen.getByText(/save or overwrite dataset/i)).toBeVisible();
expect(
screen.getByText(/are you sure you want to overwrite this dataset\?/i),
).toBeVisible();
// Overwrite screen buttons
expect(screen.getByRole('button', { name: /close/i })).toBeVisible();
expect(screen.getByRole('button', { name: /back/i })).toBeVisible();
expect(screen.getByRole('button', { name: /overwrite/i })).toBeVisible();
});
it('sends the schema when creating the dataset', async () => {
const dummyDispatch = jest.fn().mockResolvedValue({});
useDispatchMock.mockReturnValue(dummyDispatch);
useSelectorMock.mockReturnValue({ ...user });
render(<SaveDatasetModal {...mockedProps} />, { useRedux: true });
const inputFieldText = screen.getByDisplayValue(/unimportant/i);
fireEvent.change(inputFieldText, { target: { value: 'my dataset' } });
const saveConfirmationBtn = screen.getByRole('button', {
name: /save/i,
});
userEvent.click(saveConfirmationBtn);
expect(createDatasource).toHaveBeenCalledWith({
datasourceName: 'my dataset',
dbId: 1,
schema: 'main',
sql: 'SELECT *',
templateParams: undefined,
});
});
});
|
6,492 | 0 | petrpan-code/apache/superset/superset-frontend/src/SqlLab/components | petrpan-code/apache/superset/superset-frontend/src/SqlLab/components/SaveQuery/SaveQuery.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 configureStore from 'redux-mock-store';
import thunk from 'redux-thunk';
import { render, screen, waitFor } from 'spec/helpers/testing-library';
import userEvent from '@testing-library/user-event';
import SaveQuery from 'src/SqlLab/components/SaveQuery';
import { initialState, databases } from 'src/SqlLab/fixtures';
const mockedProps = {
queryEditorId: '123',
animation: false,
database: { ...databases.result[0], allows_virtual_table_explore: false },
onUpdate: () => {},
onSave: () => {},
saveQueryWarning: null,
columns: [],
};
const mockState = {
...initialState,
sqlLab: {
...initialState.sqlLab,
queryEditors: [
{
id: mockedProps.queryEditorId,
dbId: 1,
schema: 'main',
sql: 'SELECT * FROM t',
},
],
},
};
const splitSaveBtnProps = {
...mockedProps,
database: {
...mockedProps.database,
allows_virtual_table_explore: true,
},
};
const middlewares = [thunk];
const mockStore = configureStore(middlewares);
describe('SavedQuery', () => {
it('doesnt render save button when allows_virtual_table_explore is undefined', async () => {
const noRenderProps = {
...mockedProps,
database: {
...mockedProps.database,
allows_virtual_table_explore: undefined,
},
};
render(<SaveQuery {...noRenderProps} />, {
useRedux: true,
store: mockStore(mockState),
});
expect(() => {
screen.getByRole('button', { name: /save/i });
}).toThrow(
'Unable to find an accessible element with the role "button" and name `/save/i`',
);
});
it('renders a non-split save button when allows_virtual_table_explore is not enabled', () => {
render(<SaveQuery {...mockedProps} />, {
useRedux: true,
store: mockStore(mockState),
});
const saveBtn = screen.getByRole('button', { name: /save/i });
expect(saveBtn).toBeVisible();
});
it('renders a save query modal when user clicks save button', () => {
render(<SaveQuery {...mockedProps} />, {
useRedux: true,
store: mockStore(mockState),
});
const saveBtn = screen.getByRole('button', { name: /save/i });
userEvent.click(saveBtn);
const saveQueryModalHeader = screen.getByRole('heading', {
name: /save query/i,
});
expect(saveQueryModalHeader).toBeVisible();
});
it('renders the save query modal UI', () => {
render(<SaveQuery {...mockedProps} />, {
useRedux: true,
store: mockStore(mockState),
});
const saveBtn = screen.getByRole('button', { name: /save/i });
userEvent.click(saveBtn);
const closeBtn = screen.getByRole('button', { name: /close/i });
const saveQueryModalHeader = screen.getByRole('heading', {
name: /save query/i,
});
const nameLabel = screen.getByText(/name/i);
const descriptionLabel = screen.getByText(/description/i);
const textBoxes = screen.getAllByRole('textbox');
const nameTextbox = textBoxes[0];
const descriptionTextbox = textBoxes[1];
// There are now two save buttons, the initial save button and the modal save button
const saveBtns = screen.getAllByRole('button', { name: /save/i });
const cancelBtn = screen.getByRole('button', { name: /cancel/i });
expect(closeBtn).toBeVisible();
expect(saveQueryModalHeader).toBeVisible();
expect(nameLabel).toBeVisible();
expect(descriptionLabel).toBeVisible();
expect(textBoxes.length).toBe(2);
expect(nameTextbox).toBeVisible();
expect(descriptionTextbox).toBeVisible();
expect(saveBtns.length).toBe(2);
expect(saveBtns[0]).toBeVisible();
expect(saveBtns[1]).toBeVisible();
expect(cancelBtn).toBeVisible();
});
it('renders a "save as new" and "update" button if query already exists', () => {
render(<SaveQuery {...mockedProps} />, {
useRedux: true,
store: mockStore({
...mockState,
sqlLab: {
...mockState.sqlLab,
unsavedQueryEditor: {
id: mockedProps.queryEditorId,
remoteId: '42',
},
},
}),
});
const saveBtn = screen.getByRole('button', { name: /save/i });
userEvent.click(saveBtn);
const saveAsNewBtn = screen.getByRole('button', { name: /save as new/i });
const updateBtn = screen.getByRole('button', { name: /update/i });
expect(saveAsNewBtn).toBeVisible();
expect(updateBtn).toBeVisible();
});
it('renders a split save button when allows_virtual_table_explore is enabled', async () => {
render(<SaveQuery {...splitSaveBtnProps} />, {
useRedux: true,
store: mockStore(mockState),
});
await waitFor(() => {
const saveBtn = screen.getByRole('button', { name: /save/i });
const caretBtn = screen.getByRole('button', { name: /caret-down/i });
expect(saveBtn).toBeVisible();
expect(caretBtn).toBeVisible();
});
});
it('renders a save dataset modal when user clicks "save dataset" menu item', async () => {
render(<SaveQuery {...splitSaveBtnProps} />, {
useRedux: true,
store: mockStore(mockState),
});
await waitFor(() => {
const caretBtn = screen.getByRole('button', { name: /caret-down/i });
userEvent.click(caretBtn);
const saveDatasetMenuItem = screen.getByText(/save dataset/i);
userEvent.click(saveDatasetMenuItem);
});
const saveDatasetHeader = screen.getByText(/save or overwrite dataset/i);
expect(saveDatasetHeader).toBeVisible();
});
it('renders the save dataset modal UI', async () => {
render(<SaveQuery {...splitSaveBtnProps} />, {
useRedux: true,
store: mockStore(mockState),
});
await waitFor(() => {
const caretBtn = screen.getByRole('button', { name: /caret-down/i });
userEvent.click(caretBtn);
const saveDatasetMenuItem = screen.getByText(/save dataset/i);
userEvent.click(saveDatasetMenuItem);
});
const closeBtn = screen.getByRole('button', { name: /close/i });
const saveDatasetHeader = screen.getByText(/save or overwrite dataset/i);
const saveRadio = screen.getByRole('radio', {
name: /save as new untitled/i,
});
const saveLabel = screen.getByText(/save as new/i);
const saveTextbox = screen.getByRole('textbox');
const overwriteRadio = screen.getByRole('radio', {
name: /overwrite existing/i,
});
const overwriteLabel = screen.getByText(/overwrite existing/i);
const overwriteCombobox = screen.getByRole('combobox');
const overwritePlaceholderText = screen.getByText(
/select or type dataset name/i,
);
expect(saveDatasetHeader).toBeVisible();
expect(closeBtn).toBeVisible();
expect(saveRadio).toBeVisible();
expect(saveLabel).toBeVisible();
expect(saveTextbox).toBeVisible();
expect(overwriteRadio).toBeVisible();
expect(overwriteLabel).toBeVisible();
expect(overwriteCombobox).toBeVisible();
expect(overwritePlaceholderText).toBeVisible();
});
});
|
6,495 | 0 | petrpan-code/apache/superset/superset-frontend/src/SqlLab/components | petrpan-code/apache/superset/superset-frontend/src/SqlLab/components/ShareSqlLabQuery/ShareSqlLabQuery.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 configureStore from 'redux-mock-store';
import thunk from 'redux-thunk';
import fetchMock from 'fetch-mock';
import * as uiCore from '@superset-ui/core';
import { Provider } from 'react-redux';
import { supersetTheme, ThemeProvider } from '@superset-ui/core';
import { render, screen, act } from '@testing-library/react';
import '@testing-library/jest-dom/extend-expect';
import userEvent from '@testing-library/user-event';
import * as utils from 'src/utils/common';
import ShareSqlLabQuery from 'src/SqlLab/components/ShareSqlLabQuery';
import { initialState } from 'src/SqlLab/fixtures';
const mockStore = configureStore([thunk]);
const defaultProps = {
queryEditorId: 'qe1',
addDangerToast: jest.fn(),
};
const mockQueryEditor = {
id: defaultProps.queryEditorId,
dbId: 0,
name: 'query title',
schema: 'query_schema',
autorun: false,
sql: 'SELECT * FROM ...',
remoteId: 999,
};
const disabled = {
id: 'disabledEditorId',
remoteId: undefined,
};
const mockState = {
...initialState,
sqlLab: {
...initialState.sqlLab,
queryEditors: [mockQueryEditor, disabled],
},
};
const store = mockStore(mockState);
let isFeatureEnabledMock: jest.SpyInstance;
const standardProvider: React.FC = ({ children }) => (
<ThemeProvider theme={supersetTheme}>
<Provider store={store}>{children}</Provider>
</ThemeProvider>
);
const unsavedQueryEditor = {
id: defaultProps.queryEditorId,
dbId: 9888,
name: 'query title changed',
schema: 'query_schema_updated',
sql: 'SELECT * FROM Updated Limit 100',
autorun: true,
templateParams: '{ "my_value": "foo" }',
};
const standardProviderWithUnsaved: React.FC = ({ children }) => (
<ThemeProvider theme={supersetTheme}>
<Provider
store={mockStore({
...initialState,
sqlLab: {
...initialState.sqlLab,
unsavedQueryEditor,
},
})}
>
{children}
</Provider>
</ThemeProvider>
);
describe('ShareSqlLabQuery', () => {
const storeQueryUrl = 'glob:*/kv/store/';
const storeQueryMockId = '123';
beforeEach(async () => {
fetchMock.post(storeQueryUrl, () => ({ id: storeQueryMockId }), {
overwriteRoutes: true,
});
fetchMock.resetHistory();
jest.clearAllMocks();
});
afterAll(fetchMock.reset);
describe('via /kv/store', () => {
beforeAll(() => {
isFeatureEnabledMock = jest
.spyOn(uiCore, 'isFeatureEnabled')
.mockImplementation(() => true);
});
afterAll(() => {
isFeatureEnabledMock.mockReset();
});
it('calls storeQuery() with the query when getCopyUrl() is called', async () => {
await act(async () => {
render(<ShareSqlLabQuery {...defaultProps} />, {
wrapper: standardProvider,
});
});
const button = screen.getByRole('button');
const { id, remoteId, ...expected } = mockQueryEditor;
const storeQuerySpy = jest.spyOn(utils, 'storeQuery');
userEvent.click(button);
expect(storeQuerySpy.mock.calls).toHaveLength(1);
expect(storeQuerySpy).toBeCalledWith(expected);
storeQuerySpy.mockRestore();
});
it('calls storeQuery() with unsaved changes', async () => {
await act(async () => {
render(<ShareSqlLabQuery {...defaultProps} />, {
wrapper: standardProviderWithUnsaved,
});
});
const button = screen.getByRole('button');
const { id, ...expected } = unsavedQueryEditor;
const storeQuerySpy = jest.spyOn(utils, 'storeQuery');
userEvent.click(button);
expect(storeQuerySpy.mock.calls).toHaveLength(1);
expect(storeQuerySpy).toBeCalledWith(expected);
storeQuerySpy.mockRestore();
});
});
describe('via saved query', () => {
beforeAll(() => {
isFeatureEnabledMock = jest
.spyOn(uiCore, 'isFeatureEnabled')
.mockImplementation(() => false);
});
afterAll(() => {
isFeatureEnabledMock.mockReset();
});
it('does not call storeQuery() with the query when getCopyUrl() is called and feature is not enabled', async () => {
await act(async () => {
render(<ShareSqlLabQuery {...defaultProps} />, {
wrapper: standardProvider,
});
});
const storeQuerySpy = jest.spyOn(utils, 'storeQuery');
const button = screen.getByRole('button');
userEvent.click(button);
expect(storeQuerySpy.mock.calls).toHaveLength(0);
storeQuerySpy.mockRestore();
});
it('button is disabled and there is a request to save the query', async () => {
const updatedProps = {
queryEditorId: disabled.id,
};
render(<ShareSqlLabQuery {...updatedProps} />, {
wrapper: standardProvider,
});
const button = await screen.findByRole('button', { name: /copy link/i });
expect(button).toBeDisabled();
});
});
});
|
6,498 | 0 | petrpan-code/apache/superset/superset-frontend/src/SqlLab/components | petrpan-code/apache/superset/superset-frontend/src/SqlLab/components/SouthPane/SouthPane.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 configureStore from 'redux-mock-store';
import thunk from 'redux-thunk';
import { render, screen, waitFor } from 'spec/helpers/testing-library';
import SouthPane, { SouthPaneProps } from 'src/SqlLab/components/SouthPane';
import '@testing-library/jest-dom/extend-expect';
import { STATUS_OPTIONS } from 'src/SqlLab/constants';
import { initialState, table, defaultQueryEditor } from 'src/SqlLab/fixtures';
import { denormalizeTimestamp } from '@superset-ui/core';
import { Store } from 'redux';
const mockedProps = {
queryEditorId: defaultQueryEditor.id,
latestQueryId: 'LCly_kkIN',
height: 1,
displayLimit: 1,
defaultQueryLimit: 100,
};
const mockedEmptyProps = {
queryEditorId: 'random_id',
latestQueryId: '',
height: 100,
displayLimit: 100,
defaultQueryLimit: 100,
};
jest.mock('src/SqlLab/components/SqlEditorLeftBar', () => jest.fn());
const latestQueryProgressMsg = 'LATEST QUERY MESSAGE - LCly_kkIN';
const middlewares = [thunk];
const mockStore = configureStore(middlewares);
const store = mockStore({
...initialState,
sqlLab: {
...initialState,
offline: false,
tables: [
{
...table,
dataPreviewQueryId: '2g2_iRFMl',
queryEditorId: defaultQueryEditor.id,
},
],
databases: {},
queries: {
LCly_kkIN: {
cached: false,
changed_on: denormalizeTimestamp(new Date().toISOString()),
db: 'main',
dbId: 1,
id: 'LCly_kkIN',
startDttm: Date.now(),
sqlEditorId: defaultQueryEditor.id,
extra: { progress: latestQueryProgressMsg },
},
lXJa7F9_r: {
cached: false,
changed_on: denormalizeTimestamp(new Date(1559238500401).toISOString()),
db: 'main',
dbId: 1,
id: 'lXJa7F9_r',
startDttm: 1559238500401,
sqlEditorId: defaultQueryEditor.id,
},
'2g2_iRFMl': {
cached: false,
changed_on: denormalizeTimestamp(new Date(1559238506925).toISOString()),
db: 'main',
dbId: 1,
id: '2g2_iRFMl',
startDttm: 1559238506925,
sqlEditorId: defaultQueryEditor.id,
},
erWdqEWPm: {
cached: false,
changed_on: denormalizeTimestamp(new Date(1559238516395).toISOString()),
db: 'main',
dbId: 1,
id: 'erWdqEWPm',
startDttm: 1559238516395,
sqlEditorId: defaultQueryEditor.id,
},
},
},
});
const setup = (props: SouthPaneProps, store: Store) =>
render(<SouthPane {...props} />, {
useRedux: true,
...(store && { store }),
});
describe('SouthPane', () => {
const renderAndWait = (props: SouthPaneProps, store: Store) =>
waitFor(async () => setup(props, store));
it('Renders an empty state for results', async () => {
await renderAndWait(mockedEmptyProps, store);
const emptyStateText = screen.getByText(/run a query to display results/i);
expect(emptyStateText).toBeVisible();
});
it('should render offline when the state is offline', async () => {
await renderAndWait(
mockedEmptyProps,
mockStore({
...initialState,
sqlLab: {
...initialState.sqlLab,
offline: true,
},
}),
);
expect(screen.getByText(STATUS_OPTIONS.offline)).toBeVisible();
});
it('should pass latest query down to ResultSet component', async () => {
await renderAndWait(mockedProps, store);
expect(screen.getByText(latestQueryProgressMsg)).toBeVisible();
});
});
|
6,500 | 0 | petrpan-code/apache/superset/superset-frontend/src/SqlLab/components | petrpan-code/apache/superset/superset-frontend/src/SqlLab/components/SqlEditor/SqlEditor.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 { act } from 'react-dom/test-utils';
import { fireEvent, render, waitFor } from 'spec/helpers/testing-library';
import fetchMock from 'fetch-mock';
import reducers from 'spec/helpers/reducerIndex';
import { setupStore } from 'src/views/store';
import {
initialState,
queries,
table,
defaultQueryEditor,
} from 'src/SqlLab/fixtures';
import SqlEditorLeftBar from 'src/SqlLab/components/SqlEditorLeftBar';
import ResultSet from 'src/SqlLab/components/ResultSet';
import { api } from 'src/hooks/apiResources/queryApi';
import { getExtensionsRegistry } from '@superset-ui/core';
import setupExtensions from 'src/setup/setupExtensions';
import type { Action, Middleware, Store } from 'redux';
import SqlEditor, { Props } from '.';
jest.mock('src/components/AsyncAceEditor', () => ({
...jest.requireActual('src/components/AsyncAceEditor'),
FullSQLEditor: ({
onChange,
onBlur,
value,
}: {
onChange: (value: string) => void;
onBlur: React.FocusEventHandler<HTMLTextAreaElement>;
value: string;
}) => (
<textarea
data-test="react-ace"
onChange={evt => onChange(evt.target.value)}
onBlur={onBlur}
value={value}
/>
),
}));
jest.mock('src/SqlLab/components/SqlEditorLeftBar', () => jest.fn());
jest.mock('src/SqlLab/components/ResultSet', () => jest.fn());
fetchMock.get('glob:*/api/v1/database/*/function_names/', {
function_names: [],
});
fetchMock.get('glob:*/api/v1/database/*', { result: [] });
fetchMock.get('glob:*/api/v1/database/*/tables/*', { options: [] });
fetchMock.post('glob:*/sqllab/execute/*', { result: [] });
let store: Store;
let actions: Action[];
const latestQuery = {
...queries[0],
sqlEditorId: defaultQueryEditor.id,
};
const mockInitialState = {
...initialState,
sqlLab: {
...initialState.sqlLab,
queries: {
[latestQuery.id]: { ...latestQuery, startDttm: new Date().getTime() },
},
databases: {
1991: {
allow_ctas: false,
allow_cvas: false,
allow_dml: false,
allow_file_upload: false,
allow_run_async: false,
backend: 'postgresql',
database_name: 'examples',
expose_in_sqllab: true,
force_ctas_schema: null,
id: 1,
},
},
unsavedQueryEditor: {
id: defaultQueryEditor.id,
dbId: 1991,
latestQueryId: latestQuery.id,
},
},
};
const setup = (props: Props, store: Store) =>
render(<SqlEditor {...props} />, {
useRedux: true,
...(store && { store }),
});
const logAction: Middleware = () => next => action => {
if (typeof action === 'function') {
return next(action);
}
actions.push(action);
return next(action);
};
const createStore = (initState: object) =>
setupStore({
disableDebugger: true,
initialState: initState,
rootReducers: reducers,
middleware: getDefaultMiddleware =>
getDefaultMiddleware().concat(api.middleware, logAction),
});
describe('SqlEditor', () => {
const mockedProps = {
queryEditor: initialState.sqlLab.queryEditors[0],
tables: [table],
getHeight: () => '100px',
editorQueries: [],
dataPreviewQueries: [],
defaultQueryLimit: 1000,
maxRow: 100000,
displayLimit: 100,
saveQueryWarning: '',
scheduleQueryWarning: '',
};
beforeEach(() => {
store = createStore(mockInitialState);
actions = [];
(SqlEditorLeftBar as jest.Mock).mockClear();
(SqlEditorLeftBar as jest.Mock).mockImplementation(() => (
<div data-test="mock-sql-editor-left-bar" />
));
(ResultSet as jest.Mock).mockClear();
(ResultSet as jest.Mock).mockImplementation(() => (
<div data-test="mock-result-set" />
));
});
afterEach(() => {
act(() => {
store.dispatch(api.util.resetApiState());
});
});
it('does not render SqlEditor if no db selected', async () => {
const queryEditor = initialState.sqlLab.queryEditors[1];
const { findByText } = setup({ ...mockedProps, queryEditor }, store);
expect(
await findByText('Select a database to write a query'),
).toBeInTheDocument();
});
it('render a SqlEditorLeftBar', async () => {
const { getByTestId } = setup(mockedProps, store);
await waitFor(() =>
expect(getByTestId('mock-sql-editor-left-bar')).toBeInTheDocument(),
);
});
it('render an AceEditorWrapper', async () => {
const { findByTestId } = setup(mockedProps, store);
expect(await findByTestId('react-ace')).toBeInTheDocument();
});
it('avoids rerendering EditorLeftBar and ResultSet while typing', async () => {
const { findByTestId } = setup(mockedProps, store);
const editor = await findByTestId('react-ace');
const sql = 'select *';
const renderCount = (SqlEditorLeftBar as jest.Mock).mock.calls.length;
const renderCountForSouthPane = (ResultSet as jest.Mock).mock.calls.length;
expect(SqlEditorLeftBar).toHaveBeenCalledTimes(renderCount);
expect(ResultSet).toHaveBeenCalledTimes(renderCountForSouthPane);
fireEvent.change(editor, { target: { value: sql } });
// Verify the rendering regression
expect(SqlEditorLeftBar).toHaveBeenCalledTimes(renderCount);
expect(ResultSet).toHaveBeenCalledTimes(renderCountForSouthPane);
});
it('renders sql from unsaved change', async () => {
const expectedSql = 'SELECT updated_column\nFROM updated_table\nWHERE';
store = createStore({
...initialState,
sqlLab: {
...initialState.sqlLab,
databases: {
2023: {
allow_ctas: false,
allow_cvas: false,
allow_dml: false,
allow_file_upload: false,
allow_run_async: false,
backend: 'postgresql',
database_name: 'examples',
expose_in_sqllab: true,
force_ctas_schema: null,
id: 1,
},
},
unsavedQueryEditor: {
id: defaultQueryEditor.id,
dbId: 2023,
sql: expectedSql,
},
},
});
const { findByTestId } = setup(mockedProps, store);
const editor = await findByTestId('react-ace');
expect(editor).toHaveValue(expectedSql);
});
it('render a SouthPane', async () => {
const { findByTestId } = setup(mockedProps, store);
expect(await findByTestId('mock-result-set')).toBeInTheDocument();
});
it('runs query action with ctas false', async () => {
store = createStore({
...initialState,
sqlLab: {
...initialState.sqlLab,
databases: {
5667: {
allow_ctas: false,
allow_cvas: false,
allow_dml: false,
allow_file_upload: false,
allow_run_async: true,
backend: 'postgresql',
database_name: 'examples',
expose_in_sqllab: true,
force_ctas_schema: null,
id: 1,
},
},
unsavedQueryEditor: {
id: defaultQueryEditor.id,
dbId: 5667,
sql: 'expectedSql',
},
},
});
const { findByTestId } = setup(mockedProps, store);
const runButton = await findByTestId('run-query-action');
fireEvent.click(runButton);
await waitFor(() =>
expect(actions).toContainEqual({
type: 'START_QUERY',
query: expect.objectContaining({
ctas: false,
sqlEditorId: defaultQueryEditor.id,
}),
}),
);
});
it('render a Limit Dropdown', async () => {
const defaultQueryLimit = 101;
const updatedProps = { ...mockedProps, defaultQueryLimit };
const { findByText } = setup(updatedProps, store);
fireEvent.click(await findByText('LIMIT:'));
expect(await findByText('10 000')).toBeInTheDocument();
});
it('renders an Extension if provided', async () => {
const extensionsRegistry = getExtensionsRegistry();
extensionsRegistry.set('sqleditor.extension.form', () => (
<>sqleditor.extension.form extension component</>
));
setupExtensions();
const { findByText } = setup(mockedProps, store);
expect(
await findByText('sqleditor.extension.form extension component'),
).toBeInTheDocument();
});
});
|
6,504 | 0 | petrpan-code/apache/superset/superset-frontend/src/SqlLab/components | petrpan-code/apache/superset/superset-frontend/src/SqlLab/components/SqlEditorTabHeader/SqlEditorTabHeader.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 configureStore from 'redux-mock-store';
import thunk from 'redux-thunk';
import {
fireEvent,
screen,
render,
waitFor,
} from 'spec/helpers/testing-library';
import userEvent from '@testing-library/user-event';
import { QueryEditor } from 'src/SqlLab/types';
import {
initialState,
defaultQueryEditor,
extraQueryEditor1,
extraQueryEditor2,
} from 'src/SqlLab/fixtures';
import { Store } from 'redux';
import {
REMOVE_QUERY_EDITOR,
QUERY_EDITOR_SET_TITLE,
ADD_QUERY_EDITOR,
QUERY_EDITOR_TOGGLE_LEFT_BAR,
} from 'src/SqlLab/actions/sqlLab';
import SqlEditorTabHeader from 'src/SqlLab/components/SqlEditorTabHeader';
jest.mock('src/components/DeprecatedSelect', () => () => (
<div data-test="mock-deprecated-select" />
));
jest.mock('src/components/Select/Select', () => () => (
<div data-test="mock-deprecated-select-select" />
));
jest.mock('src/components/Select/AsyncSelect', () => () => (
<div data-test="mock-async-select" />
));
const middlewares = [thunk];
const mockStore = configureStore(middlewares);
const setup = (queryEditor: QueryEditor, store?: Store) =>
render(<SqlEditorTabHeader queryEditor={queryEditor} />, {
useRedux: true,
...(store && { store }),
});
describe('SqlEditorTabHeader', () => {
it('renders name', () => {
const { queryByText } = setup(defaultQueryEditor, mockStore(initialState));
expect(queryByText(defaultQueryEditor.name)).toBeTruthy();
expect(queryByText(extraQueryEditor1.name)).toBeFalsy();
expect(queryByText(extraQueryEditor2.name)).toBeFalsy();
});
it('renders name from unsaved changes', () => {
const expectedTitle = 'updated title';
const { queryByText } = setup(
defaultQueryEditor,
mockStore({
...initialState,
sqlLab: {
...initialState.sqlLab,
unsavedQueryEditor: {
id: defaultQueryEditor.id,
name: expectedTitle,
},
},
}),
);
expect(queryByText(expectedTitle)).toBeTruthy();
expect(queryByText(defaultQueryEditor.name)).toBeFalsy();
expect(queryByText(extraQueryEditor1.name)).toBeFalsy();
expect(queryByText(extraQueryEditor2.name)).toBeFalsy();
});
it('renders current name for unrelated unsaved changes', () => {
const unrelatedTitle = 'updated title';
const { queryByText } = setup(
defaultQueryEditor,
mockStore({
...initialState,
sqlLab: {
...initialState.sqlLab,
unsavedQueryEditor: {
id: `${defaultQueryEditor.id}-other`,
name: unrelatedTitle,
},
},
}),
);
expect(queryByText(defaultQueryEditor.name)).toBeTruthy();
expect(queryByText(unrelatedTitle)).toBeFalsy();
expect(queryByText(extraQueryEditor1.name)).toBeFalsy();
expect(queryByText(extraQueryEditor2.name)).toBeFalsy();
});
describe('with dropdown menus', () => {
let store = mockStore();
beforeEach(async () => {
store = mockStore(initialState);
const { getByTestId } = setup(defaultQueryEditor, store);
const dropdown = getByTestId('dropdown-trigger');
userEvent.click(dropdown);
});
it('should dispatch removeQueryEditor action', async () => {
await waitFor(() =>
expect(screen.getByTestId('close-tab-menu-option')).toBeInTheDocument(),
);
fireEvent.click(screen.getByTestId('close-tab-menu-option'));
const actions = store.getActions();
await waitFor(() =>
expect(actions[0]).toEqual({
type: REMOVE_QUERY_EDITOR,
queryEditor: defaultQueryEditor,
}),
);
});
it('should dispatch queryEditorSetTitle action', async () => {
await waitFor(() =>
expect(screen.getByTestId('close-tab-menu-option')).toBeInTheDocument(),
);
const expectedTitle = 'typed text';
const mockPrompt = jest
.spyOn(window, 'prompt')
.mockImplementation(() => expectedTitle);
fireEvent.click(screen.getByTestId('rename-tab-menu-option'));
const actions = store.getActions();
await waitFor(() =>
expect(actions[0]).toEqual({
type: QUERY_EDITOR_SET_TITLE,
name: expectedTitle,
queryEditor: expect.objectContaining({
id: defaultQueryEditor.id,
}),
}),
);
mockPrompt.mockClear();
});
it('should dispatch toggleLeftBar action', async () => {
await waitFor(() =>
expect(screen.getByTestId('close-tab-menu-option')).toBeInTheDocument(),
);
fireEvent.click(screen.getByTestId('toggle-menu-option'));
const actions = store.getActions();
await waitFor(() =>
expect(actions[0]).toEqual({
type: QUERY_EDITOR_TOGGLE_LEFT_BAR,
hideLeftBar: !defaultQueryEditor.hideLeftBar,
queryEditor: expect.objectContaining({
id: defaultQueryEditor.id,
}),
}),
);
});
it('should dispatch removeAllOtherQueryEditors action', async () => {
await waitFor(() =>
expect(screen.getByTestId('close-tab-menu-option')).toBeInTheDocument(),
);
fireEvent.click(screen.getByTestId('close-all-other-menu-option'));
const actions = store.getActions();
await waitFor(() =>
expect(actions).toEqual([
{
type: REMOVE_QUERY_EDITOR,
queryEditor: initialState.sqlLab.queryEditors[1],
},
{
type: REMOVE_QUERY_EDITOR,
queryEditor: initialState.sqlLab.queryEditors[2],
},
]),
);
});
it('should dispatch cloneQueryToNewTab action', async () => {
await waitFor(() =>
expect(screen.getByTestId('close-tab-menu-option')).toBeInTheDocument(),
);
fireEvent.click(screen.getByTestId('clone-tab-menu-option'));
const actions = store.getActions();
await waitFor(() =>
expect(actions[0]).toEqual({
type: ADD_QUERY_EDITOR,
queryEditor: expect.objectContaining({
name: `Copy of ${defaultQueryEditor.name}`,
sql: defaultQueryEditor.sql,
autorun: false,
}),
}),
);
});
});
});
|
6,506 | 0 | petrpan-code/apache/superset/superset-frontend/src/SqlLab/components | petrpan-code/apache/superset/superset-frontend/src/SqlLab/components/TabStatusIcon/TabStatusIcon.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 { QueryState } from '@superset-ui/core';
import React from 'react';
import { render } from 'spec/helpers/testing-library';
import TabStatusIcon from 'src/SqlLab/components/TabStatusIcon';
function setup() {
return render(<TabStatusIcon tabState={'running' as QueryState} />);
}
describe('TabStatusIcon', () => {
it('renders a circle without an x when hovered', () => {
const { container } = setup();
expect(container.getElementsByClassName('circle')[0]).toBeInTheDocument();
expect(
container.getElementsByClassName('circle')[0]?.textContent ?? 'undefined',
).toBe('');
});
});
|
6,510 | 0 | petrpan-code/apache/superset/superset-frontend/src/SqlLab/components | petrpan-code/apache/superset/superset-frontend/src/SqlLab/components/TableElement/TableElement.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 * as uiCore from '@superset-ui/core';
import { FeatureFlag } from '@superset-ui/core';
import TableElement, { Column } from 'src/SqlLab/components/TableElement';
import { table, initialState } from 'src/SqlLab/fixtures';
import { render, waitFor, fireEvent } from 'spec/helpers/testing-library';
jest.mock('src/components/Loading', () => () => (
<div data-test="mock-loading" />
));
jest.mock('src/components/IconTooltip', () => ({
IconTooltip: ({
onClick,
tooltip,
}: {
onClick: () => void;
tooltip: string;
}) => (
<button type="button" data-test="mock-icon-tooltip" onClick={onClick}>
{tooltip}
</button>
),
}));
jest.mock(
'src/SqlLab/components/ColumnElement',
() =>
({ column }: { column: Column }) =>
<div data-test="mock-column-element">{column.name}</div>,
);
const getTableMetadataEndpoint = 'glob:**/api/v1/database/*/table/*/*/';
const getExtraTableMetadataEndpoint =
'glob:**/api/v1/database/*/table_extra/*/*/';
const updateTableSchemaEndpoint = 'glob:*/tableschemaview/*/expanded';
beforeEach(() => {
fetchMock.get(getTableMetadataEndpoint, table);
fetchMock.get(getExtraTableMetadataEndpoint, {});
fetchMock.post(updateTableSchemaEndpoint, {});
});
afterEach(() => {
fetchMock.reset();
});
const mockedProps = {
table: {
...table,
initialized: true,
},
};
test('renders', () => {
expect(React.isValidElement(<TableElement table={table} />)).toBe(true);
});
test('renders with props', () => {
expect(React.isValidElement(<TableElement {...mockedProps} />)).toBe(true);
});
test('has 4 IconTooltip elements', async () => {
const { getAllByTestId } = render(<TableElement {...mockedProps} />, {
useRedux: true,
initialState,
});
await waitFor(() =>
expect(getAllByTestId('mock-icon-tooltip')).toHaveLength(4),
);
});
test('has 14 columns', async () => {
const { getAllByTestId } = render(<TableElement {...mockedProps} />, {
useRedux: true,
initialState,
});
await waitFor(() =>
expect(getAllByTestId('mock-column-element')).toHaveLength(14),
);
});
test('fades table', async () => {
const { getAllByTestId } = render(<TableElement {...mockedProps} />, {
useRedux: true,
initialState,
});
await waitFor(() =>
expect(getAllByTestId('mock-icon-tooltip')).toHaveLength(4),
);
const style = window.getComputedStyle(getAllByTestId('fade')[0]);
expect(style.opacity).toBe('0');
fireEvent.mouseEnter(getAllByTestId('table-element-header-container')[0]);
await waitFor(() =>
expect(window.getComputedStyle(getAllByTestId('fade')[0]).opacity).toBe(
'1',
),
);
});
test('sorts columns', async () => {
const { getAllByTestId, getByText } = render(
<TableElement {...mockedProps} />,
{
useRedux: true,
initialState,
},
);
await waitFor(() =>
expect(getAllByTestId('mock-icon-tooltip')).toHaveLength(4),
);
expect(
getAllByTestId('mock-column-element').map(el => el.textContent),
).toEqual(table.columns.map(col => col.name));
fireEvent.click(getByText('Sort columns alphabetically'));
const sorted = [...table.columns.map(col => col.name)].sort();
expect(
getAllByTestId('mock-column-element').map(el => el.textContent),
).toEqual(sorted);
expect(getAllByTestId('mock-column-element')[0]).toHaveTextContent('active');
});
test('removes the table', async () => {
const updateTableSchemaEndpoint = 'glob:*/tableschemaview/*';
fetchMock.delete(updateTableSchemaEndpoint, {});
const isFeatureEnabledMock = jest
.spyOn(uiCore, 'isFeatureEnabled')
.mockImplementation(
featureFlag => featureFlag === FeatureFlag.SQLLAB_BACKEND_PERSISTENCE,
);
const { getAllByTestId, getByText } = render(
<TableElement {...mockedProps} />,
{
useRedux: true,
initialState,
},
);
await waitFor(() =>
expect(getAllByTestId('mock-icon-tooltip')).toHaveLength(4),
);
expect(fetchMock.calls(updateTableSchemaEndpoint)).toHaveLength(0);
fireEvent.click(getByText('Remove table preview'));
await waitFor(() =>
expect(fetchMock.calls(updateTableSchemaEndpoint)).toHaveLength(1),
);
isFeatureEnabledMock.mockClear();
});
test('fetches table metadata when expanded', async () => {
render(<TableElement {...mockedProps} />, {
useRedux: true,
initialState,
});
expect(fetchMock.calls(getTableMetadataEndpoint)).toHaveLength(0);
expect(fetchMock.calls(getExtraTableMetadataEndpoint)).toHaveLength(0);
await waitFor(() =>
expect(fetchMock.calls(getTableMetadataEndpoint)).toHaveLength(1),
);
expect(fetchMock.calls(updateTableSchemaEndpoint)).toHaveLength(0);
expect(fetchMock.calls(getExtraTableMetadataEndpoint)).toHaveLength(1);
});
|
6,512 | 0 | petrpan-code/apache/superset/superset-frontend/src/SqlLab/components | petrpan-code/apache/superset/superset-frontend/src/SqlLab/components/TemplateParamsEditor/TemplateParamsEditor.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 configureStore from 'redux-mock-store';
import thunk from 'redux-thunk';
import { Store } from 'redux';
import {
render,
fireEvent,
getByText,
waitFor,
} from 'spec/helpers/testing-library';
import { initialState, defaultQueryEditor } from 'src/SqlLab/fixtures';
import TemplateParamsEditor, {
TemplateParamsEditorProps,
} from 'src/SqlLab/components/TemplateParamsEditor';
jest.mock('src/components/DeprecatedSelect', () => () => (
<div data-test="mock-deprecated-select" />
));
jest.mock('src/components/Select/Select', () => () => (
<div data-test="mock-deprecated-select-select" />
));
jest.mock('src/components/Select/AsyncSelect', () => () => (
<div data-test="mock-async-select" />
));
jest.mock('src/components/AsyncAceEditor', () => ({
ConfigEditor: ({ value }: { value: string }) => (
<div data-test="mock-async-ace-editor">{value}</div>
),
}));
const middlewares = [thunk];
const mockStore = configureStore(middlewares);
const setup = (
otherProps: Partial<TemplateParamsEditorProps> = {},
store?: Store,
) =>
render(
<TemplateParamsEditor
language="json"
onChange={() => {}}
queryEditorId={defaultQueryEditor.id}
{...otherProps}
/>,
{
useRedux: true,
store: mockStore(initialState),
...(store && { store }),
},
);
describe('TemplateParamsEditor', () => {
it('should render with a title', () => {
const { container } = setup();
expect(container.querySelector('div[role="button"]')).toBeInTheDocument();
});
it('should open a modal with the ace editor', async () => {
const { container, getByTestId } = setup();
fireEvent.click(getByText(container, 'Parameters'));
await waitFor(() => {
expect(getByTestId('mock-async-ace-editor')).toBeInTheDocument();
});
});
it('renders templateParams', async () => {
const { container, getByTestId } = setup();
fireEvent.click(getByText(container, 'Parameters'));
await waitFor(() => {
expect(getByTestId('mock-async-ace-editor')).toBeInTheDocument();
});
expect(getByTestId('mock-async-ace-editor')).toHaveTextContent(
defaultQueryEditor.templateParams,
);
});
it('renders code from unsaved changes', async () => {
const expectedCode = 'custom code value';
const { container, getByTestId } = setup(
{},
mockStore({
...initialState,
sqlLab: {
...initialState.sqlLab,
unsavedQueryEditor: {
id: defaultQueryEditor.id,
templateParams: expectedCode,
},
},
}),
);
fireEvent.click(getByText(container, 'Parameters'));
await waitFor(() => {
expect(getByTestId('mock-async-ace-editor')).toBeInTheDocument();
});
expect(getByTestId('mock-async-ace-editor')).toHaveTextContent(
expectedCode,
);
});
});
|
6,515 | 0 | petrpan-code/apache/superset/superset-frontend/src/SqlLab/hooks | petrpan-code/apache/superset/superset-frontend/src/SqlLab/hooks/useQueryEditor/useQueryEditor.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 configureStore from 'redux-mock-store';
import thunk from 'redux-thunk';
import { initialState, defaultQueryEditor } from 'src/SqlLab/fixtures';
import { renderHook } from '@testing-library/react-hooks';
import { createWrapper } from 'spec/helpers/testing-library';
import useQueryEditor from '.';
const middlewares = [thunk];
const mockStore = configureStore(middlewares);
test('returns selected queryEditor values', () => {
const { result } = renderHook(
() =>
useQueryEditor(defaultQueryEditor.id, ['id', 'name', 'dbId', 'schema']),
{
wrapper: createWrapper({
useRedux: true,
store: mockStore(initialState),
}),
},
);
expect(result.current).toEqual({
id: defaultQueryEditor.id,
name: defaultQueryEditor.name,
dbId: defaultQueryEditor.dbId,
schema: defaultQueryEditor.schema,
});
});
test('includes id implicitly', () => {
const { result } = renderHook(
() => useQueryEditor(defaultQueryEditor.id, ['name']),
{
wrapper: createWrapper({
useRedux: true,
store: mockStore(initialState),
}),
},
);
expect(result.current).toEqual({
id: defaultQueryEditor.id,
name: defaultQueryEditor.name,
});
});
test('returns updated values from unsaved change', () => {
const expectedSql = 'SELECT updated_column\nFROM updated_table\nWHERE';
const { result } = renderHook(
() => useQueryEditor(defaultQueryEditor.id, ['id', 'sql']),
{
wrapper: createWrapper({
useRedux: true,
store: mockStore({
...initialState,
sqlLab: {
...initialState.sqlLab,
unsavedQueryEditor: {
id: defaultQueryEditor.id,
sql: expectedSql,
},
},
}),
}),
},
);
expect(result.current.id).toEqual(defaultQueryEditor.id);
expect(result.current.sql).toEqual(expectedSql);
});
|
6,517 | 0 | petrpan-code/apache/superset/superset-frontend/src/SqlLab | petrpan-code/apache/superset/superset-frontend/src/SqlLab/reducers/getInitialState.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 { DEFAULT_COMMON_BOOTSTRAP_DATA } from 'src/constants';
import { runningQuery, successfulQuery } from 'src/SqlLab/fixtures';
import getInitialState, { dedupeTabHistory } from './getInitialState';
const apiData = {
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 apiDataWithTabState = {
...apiData,
tab_state_ids: [{ id: 1, label: 'test' }],
active_tab: {
id: 1,
user_id: 1,
label: 'editor1',
active: true,
database_id: 1,
sql: '',
table_schemas: [],
saved_query: null,
template_params: null,
latest_query: null,
},
};
describe('getInitialState', () => {
afterEach(() => {
localStorage.clear();
});
it('should output the user that is passed in', () => {
expect(getInitialState(apiData).user?.userId).toEqual(1);
});
it('should return undefined instead of null for templateParams', () => {
expect(
getInitialState(apiDataWithTabState).sqlLab?.queryEditors?.[0]
?.templateParams,
).toBeUndefined();
});
describe('dedupeTabHistory', () => {
it('should dedupe the tab history', () => {
[
{ value: [], expected: [] },
{
value: ['12', '3', '4', '5', '6'],
expected: ['12', '3', '4', '5', '6'],
},
{
value: [
'1',
'2',
'2',
'2',
'2',
'2',
'2',
'2',
'2',
'2',
'2',
'2',
'2',
],
expected: ['1', '2'],
},
{
value: [
'1',
'2',
'2',
'2',
'2',
'2',
'2',
'2',
'2',
'2',
'2',
'2',
'2',
'3',
],
expected: ['1', '2', '3'],
},
{
value: [
'2',
'2',
'2',
'2',
'2',
'2',
'2',
'2',
'2',
'2',
'2',
'2',
'3',
],
expected: ['2', '3'],
},
].forEach(({ value, expected }) => {
expect(dedupeTabHistory(value)).toEqual(expected);
});
});
});
describe('dedupe tables schema', () => {
it('should dedupe the table schema', () => {
localStorage.setItem(
'redux',
JSON.stringify({
sqlLab: {
tables: [
{ id: 1, name: 'test1' },
{ id: 6, name: 'test6' },
],
queryEditors: [{ id: 1, title: 'editor1' }],
queries: {},
tabHistory: [],
},
}),
);
const initializedTables = getInitialState({
...apiData,
active_tab: {
id: 1,
user_id: 1,
label: 'editor1',
active: true,
database_id: 1,
sql: '',
table_schemas: [
{
id: 1,
table: 'table1',
tab_state_id: 1,
description: {
columns: [
{ name: 'id', type: 'INT' },
{ name: 'column2', type: 'STRING' },
],
},
},
{
id: 2,
table: 'table2',
tab_state_id: 1,
description: {
columns: [
{ name: 'id', type: 'INT' },
{ name: 'column2', type: 'STRING' },
],
},
},
],
saved_query: null,
template_params: null,
latest_query: null,
},
}).sqlLab.tables;
expect(initializedTables.map(({ id }) => id)).toEqual([1, 2, 6]);
});
it('should parse the float dttm value', () => {
const startDttmInStr = '1693433503447.166992';
const endDttmInStr = '1693433503500.23132';
localStorage.setItem(
'redux',
JSON.stringify({
sqlLab: {
tables: [
{ id: 1, name: 'test1' },
{ id: 6, name: 'test6' },
],
queryEditors: [{ id: 1, title: 'editor1' }],
queries: {
localStoragePersisted: {
...successfulQuery,
id: 'localStoragePersisted',
startDttm: startDttmInStr,
endDttm: endDttmInStr,
},
},
tabHistory: [],
},
}),
);
const initializedQueries = getInitialState({
...apiData,
queries: {
backendPersisted: {
...runningQuery,
id: 'backendPersisted',
startDttm: startDttmInStr,
endDttm: endDttmInStr,
},
},
}).sqlLab.queries;
expect(initializedQueries.backendPersisted).toEqual(
expect.objectContaining({
startDttm: Number(startDttmInStr),
endDttm: Number(endDttmInStr),
}),
);
expect(initializedQueries.localStoragePersisted).toEqual(
expect.objectContaining({
startDttm: Number(startDttmInStr),
endDttm: Number(endDttmInStr),
}),
);
});
});
describe('restore unsaved changes for PERSISTENCE mode', () => {
const lastUpdatedTime = Date.now();
const expectedValue = 'updated editor value';
beforeEach(() => {
localStorage.setItem(
'redux',
JSON.stringify({
sqlLab: {
queryEditors: [
{
// restore cached value since updates are after server update time
id: '1',
name: expectedValue,
updatedAt: lastUpdatedTime + 100,
},
{
// no update required given that last updated time comes before server update time
id: '2',
name: expectedValue,
updatedAt: lastUpdatedTime - 100,
},
{
// no update required given that there's no updatedAt
id: '3',
name: expectedValue,
},
],
},
}),
);
});
it('restore unsaved changes for PERSISTENCE mode', () => {
const apiDataWithLocalStorage = {
...apiData,
active_tab: {
...apiDataWithTabState.active_tab,
id: 1,
label: 'persisted tab',
table_schemas: [],
extra_json: {
updatedAt: lastUpdatedTime,
},
},
tab_state_ids: [{ id: 1, label: '' }],
};
expect(
getInitialState(apiDataWithLocalStorage).sqlLab.queryEditors[0],
).toEqual(
expect.objectContaining({
id: '1',
name: expectedValue,
}),
);
});
it('skip unsaved changes for expired data', () => {
const apiDataWithLocalStorage = {
...apiData,
active_tab: {
...apiDataWithTabState.active_tab,
id: 2,
label: 'persisted tab',
table_schemas: [],
extra_json: {
updatedAt: lastUpdatedTime,
},
},
tab_state_ids: [{ id: 2, label: '' }],
};
expect(
getInitialState(apiDataWithLocalStorage).sqlLab.queryEditors[1],
).toEqual(
expect.objectContaining({
id: '2',
name: apiDataWithLocalStorage.active_tab.label,
}),
);
});
it('skip unsaved changes for legacy cache data', () => {
const apiDataWithLocalStorage = {
...apiData,
active_tab: {
...apiDataWithTabState.active_tab,
id: 3,
label: 'persisted tab',
table_schemas: [],
extra_json: {
updatedAt: lastUpdatedTime,
},
},
tab_state_ids: [{ id: 3, label: '' }],
};
expect(
getInitialState(apiDataWithLocalStorage).sqlLab.queryEditors[2],
).toEqual(
expect.objectContaining({
id: '3',
name: apiDataWithLocalStorage.active_tab.label,
}),
);
});
});
});
|
6,522 | 0 | petrpan-code/apache/superset/superset-frontend/src/SqlLab | petrpan-code/apache/superset/superset-frontend/src/SqlLab/utils/newQueryTabName.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 { defaultQueryEditor } from 'src/SqlLab/fixtures';
import { newQueryTabName } from './newQueryTabName';
const emptyEditor = {
...defaultQueryEditor,
title: '',
schema: '',
autorun: false,
sql: '',
remoteId: null,
};
describe('newQueryTabName', () => {
it("should return default title if queryEditor's length is 0", () => {
const defaultTitle = 'default title';
const title = newQueryTabName([], defaultTitle);
expect(title).toEqual(defaultTitle);
});
it('should return next available number if there are unsaved editors', () => {
const untitledQueryText = 'Untitled Query';
const unsavedEditors = [
{ ...emptyEditor, name: `${untitledQueryText} 1` },
{ ...emptyEditor, name: `${untitledQueryText} 2` },
];
const nextTitle = newQueryTabName(unsavedEditors);
expect(nextTitle).toEqual(`${untitledQueryText} 3`);
});
});
|
6,709 | 0 | petrpan-code/apache/superset/superset-frontend/src/components | petrpan-code/apache/superset/superset-frontend/src/components/Alert/Alert.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 Alert, { AlertProps } from 'src/components/Alert';
type AlertType = Pick<AlertProps, 'type'>;
type AlertTypeValue = AlertType[keyof AlertType];
test('renders with default props', async () => {
render(<Alert message="Message" />);
expect(screen.getByRole('alert')).toHaveTextContent('Message');
expect(await screen.findByLabelText(`info icon`)).toBeInTheDocument();
expect(await screen.findByLabelText('close icon')).toBeInTheDocument();
});
test('renders each type', async () => {
const types: AlertTypeValue[] = ['info', 'error', 'warning', 'success'];
for (let i = 0; i < types.length; i += 1) {
const type = types[i];
render(<Alert type={type} message="Message" />);
// eslint-disable-next-line no-await-in-loop
expect(await screen.findByLabelText(`${type} icon`)).toBeInTheDocument();
}
});
test('renders without close button', async () => {
render(<Alert message="Message" closable={false} />);
await waitFor(() => {
expect(screen.queryByLabelText('close icon')).not.toBeInTheDocument();
});
});
test('disappear when closed', () => {
render(<Alert message="Message" />);
userEvent.click(screen.queryByLabelText('close icon')!);
expect(screen.queryByRole('alert')).not.toBeInTheDocument();
});
test('renders without icon', async () => {
const type = 'info';
render(<Alert type={type} message="Message" showIcon={false} />);
await waitFor(() => {
expect(screen.queryByLabelText(`${type} icon`)).not.toBeInTheDocument();
});
});
test('renders message', async () => {
render(<Alert message="Message" />);
expect(await screen.findByRole('alert')).toHaveTextContent('Message');
});
test('renders message and description', async () => {
render(<Alert message="Message" description="Description" />);
const alert = await screen.findByRole('alert');
expect(alert).toHaveTextContent('Message');
expect(alert).toHaveTextContent('Description');
});
|
6,716 | 0 | petrpan-code/apache/superset/superset-frontend/src/components | petrpan-code/apache/superset/superset-frontend/src/components/AsyncAceEditor/AsyncAceEditor.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 AsyncAceEditor, {
SQLEditor,
FullSQLEditor,
MarkdownEditor,
TextAreaEditor,
CssEditor,
JsonEditor,
ConfigEditor,
AceModule,
AsyncAceEditorOptions,
} from 'src/components/AsyncAceEditor';
const selector = '[id="ace-editor"]';
test('renders SQLEditor', async () => {
const { container } = render(<SQLEditor />);
await waitFor(() => {
expect(container.querySelector(selector)).toBeInTheDocument();
});
});
test('renders FullSQLEditor', async () => {
const { container } = render(<FullSQLEditor />);
await waitFor(() => {
expect(container.querySelector(selector)).toBeInTheDocument();
});
});
test('renders MarkdownEditor', async () => {
const { container } = render(<MarkdownEditor />);
await waitFor(() => {
expect(container.querySelector(selector)).toBeInTheDocument();
});
});
test('renders TextAreaEditor', async () => {
const { container } = render(<TextAreaEditor />);
await waitFor(() => {
expect(container.querySelector(selector)).toBeInTheDocument();
});
});
test('renders CssEditor', async () => {
const { container } = render(<CssEditor />);
await waitFor(() => {
expect(container.querySelector(selector)).toBeInTheDocument();
});
});
test('renders JsonEditor', async () => {
const { container } = render(<JsonEditor />);
await waitFor(() => {
expect(container.querySelector(selector)).toBeInTheDocument();
});
});
test('renders ConfigEditor', async () => {
const { container } = render(<ConfigEditor />);
await waitFor(() => {
expect(container.querySelector(selector)).toBeInTheDocument();
});
});
test('renders a custom placeholder', () => {
const aceModules: AceModule[] = ['mode/css', 'theme/github'];
const editorOptions: AsyncAceEditorOptions = {
placeholder: () => <p role="paragraph">Custom placeholder</p>,
};
const Editor = AsyncAceEditor(aceModules, editorOptions);
render(<Editor />);
expect(screen.getByRole('paragraph')).toBeInTheDocument();
});
|
6,719 | 0 | petrpan-code/apache/superset/superset-frontend/src/components | petrpan-code/apache/superset/superset-frontend/src/components/AsyncEsmComponent/AsyncEsmComponent.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 AsyncEsmComponent from 'src/components/AsyncEsmComponent';
const Placeholder = () => <span>Loading...</span>;
const AsyncComponent = ({ bold }: { bold: boolean }) => (
<span style={{ fontWeight: bold ? 700 : 400 }}>AsyncComponent</span>
);
const ComponentPromise = new Promise(resolve =>
setTimeout(() => resolve(AsyncComponent), 500),
);
test('renders without placeholder', async () => {
const Component = AsyncEsmComponent(ComponentPromise);
render(<Component showLoadingForImport={false} />);
expect(screen.queryByRole('status')).not.toBeInTheDocument();
expect(await screen.findByText('AsyncComponent')).toBeInTheDocument();
});
test('renders with default placeholder', async () => {
const Component = AsyncEsmComponent(ComponentPromise);
render(<Component height={30} showLoadingForImport />);
expect(screen.getByRole('status')).toBeInTheDocument();
expect(await screen.findByText('AsyncComponent')).toBeInTheDocument();
});
test('renders with custom placeholder', async () => {
const Component = AsyncEsmComponent(ComponentPromise, Placeholder);
render(<Component showLoadingForImport />);
expect(screen.getByText('Loading...')).toBeInTheDocument();
expect(await screen.findByText('AsyncComponent')).toBeInTheDocument();
});
test('renders with custom props', async () => {
const Component = AsyncEsmComponent(ComponentPromise, Placeholder);
render(<Component showLoadingForImport bold />);
const asyncComponent = await screen.findByText('AsyncComponent');
expect(asyncComponent).toBeInTheDocument();
expect(asyncComponent).toHaveStyle({ fontWeight: 700 });
});
|
6,724 | 0 | petrpan-code/apache/superset/superset-frontend/src/components | petrpan-code/apache/superset/superset-frontend/src/components/Badge/Badge.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 Badge from '.';
const mockedProps = {
count: 9,
text: 'Text',
textColor: 'orange',
};
test('should render', () => {
const { container } = render(<Badge {...mockedProps} />);
expect(container).toBeInTheDocument();
});
test('should render the count', () => {
render(<Badge {...mockedProps} />);
expect(screen.getAllByText('9')[0]).toBeInTheDocument();
});
test('should render the text', () => {
render(<Badge {...mockedProps} />);
expect(screen.getByText('Text')).toBeInTheDocument();
});
test('should render with the chosen textColor', () => {
render(<Badge {...mockedProps} />);
const badge = screen.getAllByText('9')[0];
expect(badge).toHaveStyle(`
color: 'orange';
`);
});
|
6,727 | 0 | petrpan-code/apache/superset/superset-frontend/src/components | petrpan-code/apache/superset/superset-frontend/src/components/Button/Button.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 '.';
import {
ButtonGallery,
SIZES as buttonSizes,
STYLES as buttonStyles,
} from './Button.stories';
describe('Button', () => {
let wrapper: ReactWrapper;
// test the basic component
it('renders the base component', () => {
expect(React.isValidElement(<Button />)).toBe(true);
});
it('works with an onClick handler', () => {
const mockAction = jest.fn();
wrapper = mount(<Button onClick={mockAction} />);
wrapper.find('Button').first().simulate('click');
expect(mockAction).toHaveBeenCalled();
});
it('does not handle onClicks when disabled', () => {
const mockAction = jest.fn();
wrapper = mount(<Button onClick={mockAction} disabled />);
wrapper.find('Button').first().simulate('click');
expect(mockAction).toHaveBeenCalledTimes(0);
});
// test stories from the storybook!
it('All the sorybook gallery variants mount', () => {
wrapper = mount(<ButtonGallery />);
const permutationCount =
Object.values(buttonStyles.options).filter(o => o).length *
Object.values(buttonSizes.options).length;
expect(wrapper.find(Button).length).toEqual(permutationCount);
});
});
|
6,730 | 0 | petrpan-code/apache/superset/superset-frontend/src/components | petrpan-code/apache/superset/superset-frontend/src/components/ButtonGroup/ButtonGroup.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 Button from 'src/components/Button';
import ButtonGroup from '.';
test('renders 1 button', () => {
render(
<ButtonGroup>
<Button>Button</Button>
</ButtonGroup>,
);
expect(screen.getByRole('group')).toBeInTheDocument();
});
test('renders 3 buttons', () => {
render(
<ButtonGroup>
<Button>Button</Button>
<Button>Button</Button>
<Button>Button</Button>
</ButtonGroup>,
);
expect(screen.getByRole('group').children.length).toEqual(3);
});
test('renders with custom class', () => {
const customClass = 'custom-class';
render(
<ButtonGroup className={customClass}>
<Button>Button</Button>
</ButtonGroup>,
);
expect(screen.getByRole('group')).toHaveClass(customClass);
});
|
6,732 | 0 | petrpan-code/apache/superset/superset-frontend/src/components | petrpan-code/apache/superset/superset-frontend/src/components/CachedLabel/CachedLabel.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 CachedLabel, { CacheLabelProps } from '.';
const defaultProps = {
onClick: () => {},
cachedTimestamp: '2017-01-01',
};
const setup = (props: CacheLabelProps) => <CachedLabel {...props} />;
describe('CachedLabel', () => {
it('is valid', () => {
expect(React.isValidElement(<CachedLabel {...defaultProps} />)).toBe(true);
});
it('renders', () => {
render(setup(defaultProps));
const label = screen.getByText(/cached/i);
expect(label).toBeVisible();
});
});
|
6,733 | 0 | petrpan-code/apache/superset/superset-frontend/src/components | petrpan-code/apache/superset/superset-frontend/src/components/CachedLabel/TooltipContent.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 moment from 'moment';
import { TooltipContent } from './TooltipContent';
test('Rendering TooltipContent correctly - no timestep', () => {
render(<TooltipContent />);
expect(screen.getByTestId('tooltip-content')?.textContent).toBe(
'Loaded from cache. Click to force-refresh',
);
});
test('Rendering TooltipContent correctly - with timestep', () => {
render(<TooltipContent cachedTimestamp="01-01-2000" />);
expect(screen.getByTestId('tooltip-content')?.textContent).toBe(
`Loaded data cached ${moment
.utc('01-01-2000')
.fromNow()}. Click to force-refresh`,
);
});
|
6,739 | 0 | petrpan-code/apache/superset/superset-frontend/src/components | petrpan-code/apache/superset/superset-frontend/src/components/CertifiedBadge/CertifiedBadge.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 CertifiedBadge, {
CertifiedBadgeProps,
} from 'src/components/CertifiedBadge';
const asyncRender = (props?: CertifiedBadgeProps) =>
waitFor(() => render(<CertifiedBadge {...props} />));
test('renders with default props', async () => {
await asyncRender();
expect(screen.getByRole('img')).toBeInTheDocument();
});
test('renders a tooltip when hovered', async () => {
await asyncRender();
userEvent.hover(screen.getByRole('img'));
expect(await screen.findByRole('tooltip')).toBeInTheDocument();
});
test('renders with certified by', async () => {
const certifiedBy = 'Trusted Authority';
await asyncRender({ certifiedBy });
userEvent.hover(screen.getByRole('img'));
expect(await screen.findByRole('tooltip')).toHaveTextContent(certifiedBy);
});
test('renders with details', async () => {
const details = 'All requirements have been met.';
await asyncRender({ details });
userEvent.hover(screen.getByRole('img'));
expect(await screen.findByRole('tooltip')).toHaveTextContent(details);
});
|
6,753 | 0 | petrpan-code/apache/superset/superset-frontend/src/components | petrpan-code/apache/superset/superset-frontend/src/components/Chart/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 { getMenuAdjustedY } from './utils';
const originalInnerHeight = window.innerHeight;
beforeEach(() => {
window.innerHeight = 500;
});
afterEach(() => {
window.innerHeight = originalInnerHeight;
});
test('correctly positions at upper edge of screen', () => {
expect(getMenuAdjustedY(75, 1)).toEqual(75); // No adjustment
expect(getMenuAdjustedY(75, 2)).toEqual(75); // No adjustment
expect(getMenuAdjustedY(75, 3)).toEqual(75); // No adjustment
});
test('correctly positions at lower edge of screen', () => {
expect(getMenuAdjustedY(425, 1)).toEqual(425); // No adjustment
expect(getMenuAdjustedY(425, 2)).toEqual(404); // Adjustment
expect(getMenuAdjustedY(425, 3)).toEqual(372); // Adjustment
expect(getMenuAdjustedY(425, 8, 200)).toEqual(268);
expect(getMenuAdjustedY(425, 8, 200, 48)).toEqual(220);
});
|
6,756 | 0 | petrpan-code/apache/superset/superset-frontend/src/components/Chart | petrpan-code/apache/superset/superset-frontend/src/components/Chart/ChartContextMenu/useContextMenu.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 { FeatureFlag } from '@superset-ui/core';
import { render, screen } from 'spec/helpers/testing-library';
import { renderHook } from '@testing-library/react-hooks';
import mockState from 'spec/fixtures/mockState';
import { sliceId } from 'spec/fixtures/mockChartQueries';
import { noOp } from 'src/utils/common';
import { useContextMenu } from './useContextMenu';
import { ContextMenuItem } from './ChartContextMenu';
const CONTEXT_MENU_TEST_ID = 'chart-context-menu';
// @ts-ignore
global.featureFlags = {
[FeatureFlag.DASHBOARD_CROSS_FILTERS]: true,
[FeatureFlag.DRILL_TO_DETAIL]: true,
[FeatureFlag.DRILL_BY]: true,
};
const setup = ({
onSelection = noOp,
displayedItems = ContextMenuItem.All,
additionalConfig = {},
}: {
onSelection?: () => void;
displayedItems?: ContextMenuItem | ContextMenuItem[];
additionalConfig?: Record<string, any>;
} = {}) => {
const { result } = renderHook(() =>
useContextMenu(
sliceId,
{ datasource: '1__table', viz_type: 'pie' },
onSelection,
displayedItems,
additionalConfig,
),
);
render(result.current.contextMenu, {
useRedux: true,
initialState: {
...mockState,
user: {
...mockState.user,
roles: { Admin: [['can_explore', 'Superset']] },
},
},
});
return result;
};
test('Context menu renders', () => {
const result = setup();
expect(screen.queryByTestId(CONTEXT_MENU_TEST_ID)).not.toBeInTheDocument();
result.current.onContextMenu(0, 0, {});
expect(screen.getByTestId(CONTEXT_MENU_TEST_ID)).toBeInTheDocument();
expect(screen.getByText('Add cross-filter')).toBeInTheDocument();
expect(screen.getByText('Drill to detail')).toBeInTheDocument();
expect(screen.getByText('Drill by')).toBeInTheDocument();
});
test('Context menu contains all items only', () => {
const result = setup({
displayedItems: [ContextMenuItem.DrillToDetail, ContextMenuItem.DrillBy],
});
result.current.onContextMenu(0, 0, {});
expect(screen.queryByText('Add cross-filter')).not.toBeInTheDocument();
expect(screen.getByText('Drill to detail')).toBeInTheDocument();
expect(screen.getByText('Drill by')).toBeInTheDocument();
});
|
6,758 | 0 | petrpan-code/apache/superset/superset-frontend/src/components/Chart | petrpan-code/apache/superset/superset-frontend/src/components/Chart/DrillBy/DrillByChart.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 chartQueries, { sliceId } from 'spec/fixtures/mockChartQueries';
import { noOp } from 'src/utils/common';
import DrillByChart from './DrillByChart';
const chart = chartQueries[sliceId];
const dataset = {
changed_on_humanized: '01-01-2001',
created_on_humanized: '01-01-2001',
description: 'desc',
table_name: 'my_dataset',
owners: [
{
first_name: 'Sarah',
last_name: 'Connor',
},
],
columns: [
{
column_name: 'gender',
},
{ column_name: 'name' },
],
};
const setup = (overrides: Record<string, any> = {}, result?: any) =>
render(
<DrillByChart
formData={{ ...chart.form_data, ...overrides }}
onContextMenu={noOp}
inContextMenu={false}
result={result}
dataset={dataset}
/>,
{
useRedux: true,
},
);
const waitForRender = (overrides: Record<string, any> = {}) =>
waitFor(() => setup(overrides));
test('should render', async () => {
const { container } = await waitForRender();
expect(container).toBeInTheDocument();
});
test('should render the "No results" components', async () => {
setup({}, []);
expect(await screen.findByText('No Results')).toBeInTheDocument();
});
|
6,760 | 0 | petrpan-code/apache/superset/superset-frontend/src/components/Chart | petrpan-code/apache/superset/superset-frontend/src/components/Chart/DrillBy/DrillByMenuItems.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 userEvent from '@testing-library/user-event';
import {
Behavior,
ChartMetadata,
getChartMetadataRegistry,
} from '@superset-ui/core';
import fetchMock from 'fetch-mock';
import { render, screen, within, waitFor } from 'spec/helpers/testing-library';
import chartQueries, { sliceId } from 'spec/fixtures/mockChartQueries';
import { Menu } from 'src/components/Menu';
import { supersetGetCache } from 'src/utils/cachedSupersetGet';
import { DrillByMenuItems, DrillByMenuItemsProps } from './DrillByMenuItems';
/* eslint jest/expect-expect: ["warn", { "assertFunctionNames": ["expect*"] }] */
const DATASET_ENDPOINT = 'glob:*/api/v1/dataset/7';
const CHART_DATA_ENDPOINT = 'glob:*/api/v1/chart/data*';
const FORM_DATA_KEY_ENDPOINT = 'glob:*/api/v1/explore/form_data';
const { form_data: defaultFormData } = chartQueries[sliceId];
const defaultColumns = [
{ column_name: 'col1', groupby: true },
{ column_name: 'col2', groupby: true },
{ column_name: 'col3', groupby: true },
{ column_name: 'col4', groupby: true },
{ column_name: 'col5', groupby: true },
{ column_name: 'col6', groupby: true },
{ column_name: 'col7', groupby: true },
{ column_name: 'col8', groupby: true },
{ column_name: 'col9', groupby: true },
{ column_name: 'col10', groupby: true },
{ column_name: 'col11', groupby: true },
];
const defaultFilters = [
{
col: 'filter_col',
op: '==' as const,
val: 'val',
},
];
const renderMenu = ({
formData = defaultFormData,
drillByConfig = { filters: defaultFilters, groupbyFieldName: 'groupby' },
...rest
}: Partial<DrillByMenuItemsProps>) =>
render(
<Menu>
<DrillByMenuItems
formData={formData ?? defaultFormData}
drillByConfig={drillByConfig}
{...rest}
/>
</Menu>,
{ useRouter: true, useRedux: true },
);
const expectDrillByDisabled = async (tooltipContent: string) => {
const drillByMenuItem = screen.getByRole('menuitem', {
name: 'Drill by',
});
expect(drillByMenuItem).toBeVisible();
expect(drillByMenuItem).toHaveAttribute('aria-disabled', 'true');
const tooltipTrigger = within(drillByMenuItem).getByTestId('tooltip-trigger');
userEvent.hover(tooltipTrigger as HTMLElement);
const tooltip = await screen.findByRole('tooltip', { name: tooltipContent });
expect(tooltip).toBeInTheDocument();
};
const expectDrillByEnabled = async () => {
const drillByMenuItem = screen.getByRole('menuitem', {
name: 'Drill by',
});
expect(drillByMenuItem).toBeInTheDocument();
await waitFor(() =>
expect(drillByMenuItem).not.toHaveAttribute('aria-disabled'),
);
const tooltipTrigger =
within(drillByMenuItem).queryByTestId('tooltip-trigger');
expect(tooltipTrigger).not.toBeInTheDocument();
userEvent.hover(
within(drillByMenuItem).getByRole('button', { name: 'Drill by' }),
);
expect(await screen.findByTestId('drill-by-submenu')).toBeInTheDocument();
};
getChartMetadataRegistry().registerValue(
'pie',
new ChartMetadata({
name: 'fake pie',
thumbnail: '.png',
useLegacyApi: false,
behaviors: [Behavior.DRILL_BY],
}),
);
afterEach(() => {
supersetGetCache.clear();
fetchMock.restore();
});
test('render disabled menu item for unsupported chart', async () => {
renderMenu({
formData: { ...defaultFormData, viz_type: 'unsupported_viz' },
});
await expectDrillByDisabled(
'Drill by is not yet supported for this chart type',
);
});
test('render disabled menu item for supported chart, no filters', async () => {
renderMenu({ drillByConfig: { filters: [], groupbyFieldName: 'groupby' } });
await expectDrillByDisabled('Drill by is not available for this data point');
});
test('render disabled menu item for supported chart, no columns', async () => {
fetchMock.get(DATASET_ENDPOINT, { result: { columns: [] } });
renderMenu({});
await waitFor(() => fetchMock.called(DATASET_ENDPOINT));
await expectDrillByEnabled();
screen.getByText('No columns found');
});
test('render menu item with submenu without searchbox', async () => {
const slicedColumns = defaultColumns.slice(0, 9);
fetchMock.get(DATASET_ENDPOINT, {
result: { columns: slicedColumns },
});
renderMenu({});
await waitFor(() => fetchMock.called(DATASET_ENDPOINT));
await expectDrillByEnabled();
slicedColumns.forEach(column => {
expect(screen.getByText(column.column_name)).toBeInTheDocument();
});
expect(screen.queryByRole('textbox')).not.toBeInTheDocument();
});
test('render menu item with submenu and searchbox', async () => {
fetchMock.get(DATASET_ENDPOINT, {
result: { columns: defaultColumns },
});
renderMenu({});
await waitFor(() => fetchMock.called(DATASET_ENDPOINT));
await expectDrillByEnabled();
defaultColumns.forEach(column => {
expect(screen.getByText(column.column_name)).toBeInTheDocument();
});
const searchbox = screen.getByRole('textbox');
expect(searchbox).toBeInTheDocument();
userEvent.type(searchbox, 'col1');
await screen.findByText('col1');
const expectedFilteredColumnNames = ['col1', 'col10', 'col11'];
defaultColumns
.filter(col => !expectedFilteredColumnNames.includes(col.column_name))
.forEach(col => {
expect(screen.queryByText(col.column_name)).not.toBeInTheDocument();
});
expectedFilteredColumnNames.forEach(colName => {
expect(screen.getByText(colName)).toBeInTheDocument();
});
});
test('Do not display excluded column in the menu', async () => {
fetchMock.get(DATASET_ENDPOINT, {
result: { columns: defaultColumns },
});
const excludedColNames = ['col3', 'col5'];
renderMenu({
excludedColumns: excludedColNames.map(colName => ({
column_name: colName,
})),
});
await waitFor(() => fetchMock.called(DATASET_ENDPOINT));
await expectDrillByEnabled();
excludedColNames.forEach(colName => {
expect(screen.queryByText(colName)).not.toBeInTheDocument();
});
defaultColumns
.filter(column => !excludedColNames.includes(column.column_name))
.forEach(column => {
expect(screen.getByText(column.column_name)).toBeInTheDocument();
});
});
test('When menu item is clicked, call onSelection with clicked column and drill by filters', async () => {
fetchMock
.get(DATASET_ENDPOINT, {
result: { columns: defaultColumns },
})
.post(FORM_DATA_KEY_ENDPOINT, {})
.post(CHART_DATA_ENDPOINT, {});
const onSelectionMock = jest.fn();
renderMenu({
onSelection: onSelectionMock,
});
await waitFor(() => fetchMock.called(DATASET_ENDPOINT));
await expectDrillByEnabled();
userEvent.click(screen.getByText('col1'));
expect(onSelectionMock).toHaveBeenCalledWith(
{
column_name: 'col1',
groupby: true,
},
{ filters: defaultFilters, groupbyFieldName: 'groupby' },
);
});
|
6,762 | 0 | petrpan-code/apache/superset/superset-frontend/src/components/Chart | petrpan-code/apache/superset/superset-frontend/src/components/Chart/DrillBy/DrillByModal.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, { useState } from 'react';
import fetchMock from 'fetch-mock';
import { omit, isUndefined, omitBy } from 'lodash';
import userEvent from '@testing-library/user-event';
import { waitFor, within } from '@testing-library/react';
import { render, screen } from 'spec/helpers/testing-library';
import chartQueries, { sliceId } from 'spec/fixtures/mockChartQueries';
import mockState from 'spec/fixtures/mockState';
import { DashboardPageIdContext } from 'src/dashboard/containers/DashboardPage';
import DrillByModal, { DrillByModalProps } from './DrillByModal';
const CHART_DATA_ENDPOINT = 'glob:*/api/v1/chart/data*';
const FORM_DATA_KEY_ENDPOINT = 'glob:*/api/v1/explore/form_data';
const { form_data: formData } = chartQueries[sliceId];
const { slice_name: chartName } = formData;
const drillByModalState = {
...mockState,
dashboardLayout: {
past: [],
present: {
CHART_ID: {
id: 'CHART_ID',
meta: {
chartId: formData.slice_id,
sliceName: chartName,
},
},
},
future: [],
},
};
const dataset = {
changed_on_humanized: '01-01-2001',
created_on_humanized: '01-01-2001',
description: 'desc',
table_name: 'my_dataset',
owners: [
{
first_name: 'Sarah',
last_name: 'Connor',
},
],
columns: [
{
column_name: 'gender',
},
{ column_name: 'name' },
],
};
const renderModal = async (modalProps: Partial<DrillByModalProps> = {}) => {
const DrillByModalWrapper = () => {
const [showModal, setShowModal] = useState(false);
return (
<DashboardPageIdContext.Provider value="1">
<button type="button" onClick={() => setShowModal(true)}>
Show modal
</button>
{showModal && (
<DrillByModal
formData={formData}
onHideModal={() => setShowModal(false)}
dataset={dataset}
drillByConfig={{ groupbyFieldName: 'groupby', filters: [] }}
{...modalProps}
/>
)}
</DashboardPageIdContext.Provider>
);
};
render(<DrillByModalWrapper />, {
useDnd: true,
useRedux: true,
useRouter: true,
initialState: drillByModalState,
});
userEvent.click(screen.getByRole('button', { name: 'Show modal' }));
await screen.findByRole('dialog', { name: `Drill by: ${chartName}` });
};
beforeEach(() => {
fetchMock
.post(CHART_DATA_ENDPOINT, { body: {} }, {})
.post(FORM_DATA_KEY_ENDPOINT, { key: '123' });
});
afterEach(() => fetchMock.restore());
test('should render the title', async () => {
await renderModal();
expect(screen.getByText(`Drill by: ${chartName}`)).toBeInTheDocument();
});
test('should render the button', async () => {
await renderModal();
expect(
screen.getByRole('button', { name: 'Edit chart' }),
).toBeInTheDocument();
expect(screen.getAllByRole('button', { name: 'Close' })).toHaveLength(2);
});
test('should close the modal', async () => {
await renderModal();
expect(screen.getByRole('dialog')).toBeInTheDocument();
userEvent.click(screen.getAllByRole('button', { name: 'Close' })[1]);
expect(screen.queryByRole('dialog')).not.toBeInTheDocument();
});
test('should render loading indicator', async () => {
fetchMock.post(
CHART_DATA_ENDPOINT,
{ body: {} },
// delay is missing in fetch-mock types
// @ts-ignore
{ overwriteRoutes: true, delay: 1000 },
);
await renderModal();
expect(screen.getByLabelText('Loading')).toBeInTheDocument();
});
test('should render alert banner when results fail to load', async () => {
await renderModal();
expect(
await screen.findByText('There was an error loading the chart data'),
).toBeInTheDocument();
});
test('should generate Explore url', async () => {
await renderModal({
column: { column_name: 'name' },
drillByConfig: {
filters: [{ col: 'gender', op: '==', val: 'boy' }],
groupbyFieldName: 'groupby',
},
});
await waitFor(() => fetchMock.called(CHART_DATA_ENDPOINT));
const expectedRequestPayload = {
form_data: {
...omitBy(
omit(formData, ['slice_id', 'slice_name', 'dashboards']),
isUndefined,
),
groupby: ['name'],
adhoc_filters: [
...formData.adhoc_filters,
{
clause: 'WHERE',
comparator: 'boy',
expressionType: 'SIMPLE',
operator: '==',
operatorId: 'EQUALS',
subject: 'gender',
},
],
slice_id: 0,
result_format: 'json',
result_type: 'full',
force: false,
},
datasource_id: Number(formData.datasource.split('__')[0]),
datasource_type: formData.datasource.split('__')[1],
};
const parsedRequestPayload = JSON.parse(
fetchMock.lastCall()?.[1]?.body as string,
);
expect(parsedRequestPayload.form_data).toEqual(
expectedRequestPayload.form_data,
);
expect(
await screen.findByRole('link', { name: 'Edit chart' }),
).toHaveAttribute('href', '/explore/?form_data_key=123&dashboard_page_id=1');
});
test('should render radio buttons', async () => {
await renderModal();
const chartRadio = screen.getByRole('radio', { name: /chart/i });
const tableRadio = screen.getByRole('radio', { name: /table/i });
expect(chartRadio).toBeInTheDocument();
expect(tableRadio).toBeInTheDocument();
expect(chartRadio).toBeChecked();
expect(tableRadio).not.toBeChecked();
userEvent.click(tableRadio);
expect(chartRadio).not.toBeChecked();
expect(tableRadio).toBeChecked();
});
test('render breadcrumbs', async () => {
await renderModal({
column: { column_name: 'name' },
drillByConfig: {
filters: [{ col: 'gender', op: '==', val: 'boy' }],
groupbyFieldName: 'groupby',
},
});
const breadcrumbItems = screen.getAllByTestId('drill-by-breadcrumb-item');
expect(breadcrumbItems).toHaveLength(2);
expect(
within(breadcrumbItems[0]).getByText('gender (boy)'),
).toBeInTheDocument();
expect(within(breadcrumbItems[1]).getByText('name')).toBeInTheDocument();
userEvent.click(screen.getByText('gender (boy)'));
const newBreadcrumbItems = screen.getAllByTestId('drill-by-breadcrumb-item');
// we need to assert that there is only 1 element now
// eslint-disable-next-line jest-dom/prefer-in-document
expect(newBreadcrumbItems).toHaveLength(1);
expect(within(breadcrumbItems[0]).getByText('gender')).toBeInTheDocument();
});
|
6,765 | 0 | petrpan-code/apache/superset/superset-frontend/src/components/Chart | petrpan-code/apache/superset/superset-frontend/src/components/Chart/DrillBy/useDrillByBreadcrumbs.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 { renderHook } from '@testing-library/react-hooks';
import userEvent from '@testing-library/user-event';
import { render, screen } from 'spec/helpers/testing-library';
import {
DrillByBreadcrumb,
useDrillByBreadcrumbs,
} from './useDrillByBreadcrumbs';
const BREADCRUMBS_DATA: DrillByBreadcrumb[] = [
{
groupby: [{ column_name: 'col1' }, { column_name: 'col2' }],
filters: [
{ col: 'col1', op: '==', val: 'col1 filter' },
{ col: 'col2', op: '==', val: 'col2 filter' },
],
},
{
groupby: [{ column_name: 'col3', verbose_name: 'Column 3' }],
filters: [{ col: 'col3', op: '==', val: 'col3 filter' }],
},
{ groupby: [{ column_name: 'col4' }] },
];
test('Render breadcrumbs', () => {
const { result } = renderHook(() => useDrillByBreadcrumbs(BREADCRUMBS_DATA));
render(result.current);
expect(screen.getAllByTestId('drill-by-breadcrumb-item')).toHaveLength(3);
expect(
screen.getByText('col1, col2 (col1 filter, col2 filter)'),
).toBeInTheDocument();
expect(screen.getByText('Column 3 (col3 filter)')).toBeInTheDocument();
expect(screen.getByText('col4')).toBeInTheDocument();
});
test('Call click handler with correct arguments when breadcrumb is clicked', () => {
const onClick = jest.fn();
const { result } = renderHook(() =>
useDrillByBreadcrumbs(BREADCRUMBS_DATA, onClick),
);
render(result.current);
userEvent.click(screen.getByText('col1, col2 (col1 filter, col2 filter)'));
expect(onClick).toHaveBeenCalledWith(BREADCRUMBS_DATA[0], 0);
onClick.mockClear();
userEvent.click(screen.getByText('Column 3 (col3 filter)'));
expect(onClick).toHaveBeenCalledWith(BREADCRUMBS_DATA[1], 1);
onClick.mockClear();
userEvent.click(screen.getByText('col4'));
expect(onClick).not.toHaveBeenCalled();
onClick.mockClear();
});
|
6,767 | 0 | petrpan-code/apache/superset/superset-frontend/src/components/Chart | petrpan-code/apache/superset/superset-frontend/src/components/Chart/DrillBy/useResultsTableView.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 { renderHook } from '@testing-library/react-hooks';
import userEvent from '@testing-library/user-event';
import { render, screen, within, waitFor } from 'spec/helpers/testing-library';
import { useResultsTableView } from './useResultsTableView';
const MOCK_CHART_DATA_RESULT = [
{
colnames: ['name', 'sum__num'],
coltypes: [1, 0],
data: [
{
name: 'Michael',
sum__num: 2467063,
},
{
name: 'Christopher',
sum__num: 1725265,
},
{
name: 'David',
sum__num: 1570516,
},
{
name: 'James',
sum__num: 1506025,
},
],
},
{
colnames: ['gender', 'year', 'count'],
coltypes: [1, 0, 0],
data: [
{
gender: 'boy',
year: 2000,
count: 1000,
},
{
gender: 'girl',
year: 2000,
count: 2000,
},
],
},
];
test('Displays results table for 1 query', () => {
const { result } = renderHook(() =>
useResultsTableView(MOCK_CHART_DATA_RESULT.slice(0, 1), '1__table'),
);
render(result.current, { useRedux: true });
expect(screen.queryByRole('tablist')).not.toBeInTheDocument();
expect(screen.getByRole('table')).toBeInTheDocument();
expect(screen.getAllByRole('columnheader')).toHaveLength(2);
expect(screen.getAllByTestId('table-row')).toHaveLength(4);
});
test('Displays results for 2 queries', async () => {
const { result } = renderHook(() =>
useResultsTableView(MOCK_CHART_DATA_RESULT, '1__table'),
);
render(result.current, { useRedux: true });
const getActiveTabElement = () =>
document.querySelector('.ant-tabs-tabpane-active') as HTMLElement;
const tablistElement = screen.getByRole('tablist');
expect(tablistElement).toBeInTheDocument();
expect(within(tablistElement).getByText('Results 1')).toBeInTheDocument();
expect(within(tablistElement).getByText('Results 2')).toBeInTheDocument();
expect(within(getActiveTabElement()).getByRole('table')).toBeInTheDocument();
expect(
within(getActiveTabElement()).getAllByRole('columnheader'),
).toHaveLength(2);
expect(
within(getActiveTabElement()).getAllByTestId('table-row'),
).toHaveLength(4);
userEvent.click(screen.getByText('Results 2'));
await waitFor(() => {
expect(
within(getActiveTabElement()).getAllByRole('columnheader'),
).toHaveLength(3);
});
expect(
within(getActiveTabElement()).getAllByTestId('table-row'),
).toHaveLength(2);
});
|
6,769 | 0 | petrpan-code/apache/superset/superset-frontend/src/components/Chart | petrpan-code/apache/superset/superset-frontend/src/components/Chart/DrillDetail/DrillDetailMenuItems.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 userEvent from '@testing-library/user-event';
import { render, screen, within } from 'spec/helpers/testing-library';
import { getMockStoreWithNativeFilters } from 'spec/fixtures/mockStore';
import chartQueries, { sliceId } from 'spec/fixtures/mockChartQueries';
import { BinaryQueryObjectFilterClause } from '@superset-ui/core';
import { Menu } from 'src/components/Menu';
import DrillDetailMenuItems, {
DrillDetailMenuItemsProps,
} from './DrillDetailMenuItems';
/* eslint jest/expect-expect: ["warn", { "assertFunctionNames": ["expect*"] }] */
jest.mock(
'./DrillDetailPane',
() =>
({ initialFilters }: { initialFilters: BinaryQueryObjectFilterClause[] }) =>
<pre data-test="modal-filters">{JSON.stringify(initialFilters)}</pre>,
);
const { id: defaultChartId, form_data: defaultFormData } =
chartQueries[sliceId];
const { slice_name: chartName } = defaultFormData;
const unsupportedChartFormData = {
...defaultFormData,
viz_type: 'dist_bar',
};
const noDimensionsFormData = {
...defaultFormData,
viz_type: 'table',
query_mode: 'raw',
};
const filterA: BinaryQueryObjectFilterClause = {
col: 'sample_column',
op: '==',
val: 1234567890,
formattedVal: 'Yesterday',
};
const filterB: BinaryQueryObjectFilterClause = {
col: 'sample_column_2',
op: '==',
val: 987654321,
formattedVal: 'Two days ago',
};
const renderMenu = ({
chartId,
formData,
isContextMenu,
filters,
}: Partial<DrillDetailMenuItemsProps>) => {
const store = getMockStoreWithNativeFilters();
return render(
<Menu>
<DrillDetailMenuItems
chartId={chartId ?? defaultChartId}
formData={formData ?? defaultFormData}
filters={filters}
isContextMenu={isContextMenu}
/>
</Menu>,
{ useRouter: true, useRedux: true, store },
);
};
/**
* Drill to Detail modal should appear with correct initial filters
*/
const expectDrillToDetailModal = async (
buttonName: string,
filters: BinaryQueryObjectFilterClause[] = [],
) => {
const button = screen.getByRole('menuitem', { name: buttonName });
userEvent.click(button);
const modal = await screen.findByRole('dialog', {
name: `Drill to detail: ${chartName}`,
});
expect(modal).toBeVisible();
expect(screen.getByTestId('modal-filters')).toHaveTextContent(
JSON.stringify(filters),
);
};
/**
* Menu item should be enabled without explanatory tooltip
*/
const expectMenuItemEnabled = async (menuItem: HTMLElement) => {
expect(menuItem).toBeInTheDocument();
expect(menuItem).not.toHaveAttribute('aria-disabled');
const tooltipTrigger = within(menuItem).queryByTestId('tooltip-trigger');
expect(tooltipTrigger).not.toBeInTheDocument();
};
/**
* Menu item should be disabled, optionally with an explanatory tooltip
*/
const expectMenuItemDisabled = async (
menuItem: HTMLElement,
tooltipContent?: string,
) => {
expect(menuItem).toBeVisible();
expect(menuItem).toHaveAttribute('aria-disabled', 'true');
const tooltipTrigger = within(menuItem).queryByTestId('tooltip-trigger');
if (tooltipContent) {
userEvent.hover(tooltipTrigger as HTMLElement);
const tooltip = await screen.findByRole('tooltip', {
name: tooltipContent,
});
expect(tooltip).toBeInTheDocument();
} else {
expect(tooltipTrigger).not.toBeInTheDocument();
}
};
/**
* "Drill to detail" item should be enabled and open the correct modal
*/
const expectDrillToDetailEnabled = async () => {
const drillToDetailMenuItem = screen.getByRole('menuitem', {
name: 'Drill to detail',
});
await expectMenuItemEnabled(drillToDetailMenuItem);
await expectDrillToDetailModal('Drill to detail');
};
/**
* "Drill to detail" item should be present and disabled
*/
const expectDrillToDetailDisabled = async (tooltipContent?: string) => {
const drillToDetailMenuItem = screen.getByRole('menuitem', {
name: 'Drill to detail',
});
await expectMenuItemDisabled(drillToDetailMenuItem, tooltipContent);
};
/**
* "Drill to detail by" item should not be present
*/
const expectNoDrillToDetailBy = async () => {
const drillToDetailBy = screen.queryByRole('menuitem', {
name: 'Drill to detail by',
});
expect(drillToDetailBy).not.toBeInTheDocument();
};
/**
* "Drill to detail by" submenu should be present and enabled
*/
const expectDrillToDetailByEnabled = async () => {
const drillToDetailBy = screen.getByRole('menuitem', {
name: 'Drill to detail by',
});
await expectMenuItemEnabled(drillToDetailBy);
userEvent.hover(
within(drillToDetailBy).getByRole('button', { name: 'Drill to detail by' }),
);
expect(
await screen.findByTestId('drill-to-detail-by-submenu'),
).toBeInTheDocument();
};
/**
* "Drill to detail by" submenu should be present and disabled
*/
const expectDrillToDetailByDisabled = async (tooltipContent?: string) => {
const drillToDetailBySubmenuItem = screen.getByRole('menuitem', {
name: 'Drill to detail by',
});
await expectMenuItemDisabled(drillToDetailBySubmenuItem, tooltipContent);
};
/**
* "Drill to detail by {dimension}" submenu item should exist and open the correct modal
*/
const expectDrillToDetailByDimension = async (
filter: BinaryQueryObjectFilterClause,
) => {
userEvent.hover(screen.getByRole('button', { name: 'Drill to detail by' }));
const drillToDetailBySubMenu = await screen.findByTestId(
'drill-to-detail-by-submenu',
);
const menuItemName = `Drill to detail by ${filter.formattedVal}`;
const drillToDetailBySubmenuItem = within(drillToDetailBySubMenu).getByRole(
'menuitem',
{ name: menuItemName },
);
await expectMenuItemEnabled(drillToDetailBySubmenuItem);
await expectDrillToDetailModal(menuItemName, [filter]);
};
/**
* "Drill to detail by all" submenu item should exist and open the correct modal
*/
const expectDrillToDetailByAll = async (
filters: BinaryQueryObjectFilterClause[],
) => {
userEvent.hover(screen.getByRole('button', { name: 'Drill to detail by' }));
const drillToDetailBySubMenu = await screen.findByTestId(
'drill-to-detail-by-submenu',
);
const menuItemName = 'Drill to detail by all';
const drillToDetailBySubmenuItem = within(drillToDetailBySubMenu).getByRole(
'menuitem',
{ name: menuItemName },
);
await expectMenuItemEnabled(drillToDetailBySubmenuItem);
await expectDrillToDetailModal(menuItemName, filters);
};
test('dropdown menu for unsupported chart', async () => {
renderMenu({ formData: unsupportedChartFormData });
await expectDrillToDetailEnabled();
await expectNoDrillToDetailBy();
});
test('context menu for unsupported chart', async () => {
renderMenu({
formData: unsupportedChartFormData,
isContextMenu: true,
});
await expectDrillToDetailEnabled();
await expectDrillToDetailByDisabled(
'Drill to detail by value is not yet supported for this chart type.',
);
});
test('dropdown menu for supported chart, no dimensions', async () => {
renderMenu({
formData: noDimensionsFormData,
});
await expectDrillToDetailDisabled(
'Drill to detail is disabled because this chart does not group data by dimension value.',
);
await expectNoDrillToDetailBy();
});
test('context menu for supported chart, no dimensions, no filters', async () => {
renderMenu({
formData: noDimensionsFormData,
isContextMenu: true,
});
await expectDrillToDetailDisabled(
'Drill to detail is disabled because this chart does not group data by dimension value.',
);
await expectDrillToDetailByDisabled();
});
test('context menu for supported chart, no dimensions, 1 filter', async () => {
renderMenu({
formData: noDimensionsFormData,
isContextMenu: true,
filters: [filterA],
});
await expectDrillToDetailDisabled(
'Drill to detail is disabled because this chart does not group data by dimension value.',
);
await expectDrillToDetailByDisabled();
});
test('dropdown menu for supported chart, dimensions', async () => {
renderMenu({ formData: defaultFormData });
await expectDrillToDetailEnabled();
await expectNoDrillToDetailBy();
});
test('context menu for supported chart, dimensions, no filters', async () => {
renderMenu({
formData: defaultFormData,
isContextMenu: true,
});
await expectDrillToDetailEnabled();
await expectDrillToDetailByDisabled(
'Right-click on a dimension value to drill to detail by that value.',
);
});
test('context menu for supported chart, dimensions, 1 filter', async () => {
const filters = [filterA];
renderMenu({
formData: defaultFormData,
isContextMenu: true,
filters,
});
await expectDrillToDetailEnabled();
await expectDrillToDetailByEnabled();
await expectDrillToDetailByDimension(filterA);
});
test('context menu for supported chart, dimensions, 2 filters', async () => {
const filters = [filterA, filterB];
renderMenu({
formData: defaultFormData,
isContextMenu: true,
filters,
});
await expectDrillToDetailEnabled();
await expectDrillToDetailByEnabled();
await expectDrillToDetailByDimension(filterA);
await expectDrillToDetailByDimension(filterB);
await expectDrillToDetailByAll(filters);
});
|
6,771 | 0 | petrpan-code/apache/superset/superset-frontend/src/components/Chart | petrpan-code/apache/superset/superset-frontend/src/components/Chart/DrillDetail/DrillDetailModal.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, { useState } from 'react';
import userEvent from '@testing-library/user-event';
import { render, screen } from 'spec/helpers/testing-library';
import { getMockStoreWithNativeFilters } from 'spec/fixtures/mockStore';
import chartQueries, { sliceId } from 'spec/fixtures/mockChartQueries';
import DrillDetailModal from './DrillDetailModal';
jest.mock('./DrillDetailPane', () => () => null);
const mockHistoryPush = jest.fn();
jest.mock('react-router-dom', () => ({
...jest.requireActual('react-router-dom'),
useHistory: () => ({
push: mockHistoryPush,
}),
}));
const { id: chartId, form_data: formData } = chartQueries[sliceId];
const { slice_name: chartName } = formData;
const renderModal = async () => {
const store = getMockStoreWithNativeFilters();
const DrillDetailModalWrapper = () => {
const [showModal, setShowModal] = useState(false);
return (
<>
<button type="button" onClick={() => setShowModal(true)}>
Show modal
</button>
<DrillDetailModal
chartId={chartId}
formData={formData}
initialFilters={[]}
showModal={showModal}
onHideModal={() => setShowModal(false)}
/>
</>
);
};
render(<DrillDetailModalWrapper />, {
useRouter: true,
useRedux: true,
store,
});
userEvent.click(screen.getByRole('button', { name: 'Show modal' }));
await screen.findByRole('dialog', { name: `Drill to detail: ${chartName}` });
};
test('should render the title', async () => {
await renderModal();
expect(screen.getByText(`Drill to detail: ${chartName}`)).toBeInTheDocument();
});
test('should render the button', async () => {
await renderModal();
expect(
screen.getByRole('button', { name: 'Edit chart' }),
).toBeInTheDocument();
expect(screen.getAllByRole('button', { name: 'Close' })).toHaveLength(2);
});
test('should close the modal', async () => {
await renderModal();
expect(screen.getByRole('dialog')).toBeInTheDocument();
userEvent.click(screen.getAllByRole('button', { name: 'Close' })[1]);
expect(screen.queryByRole('dialog')).not.toBeInTheDocument();
});
test('should forward to Explore', async () => {
await renderModal();
userEvent.click(screen.getByRole('button', { name: 'Edit chart' }));
expect(mockHistoryPush).toHaveBeenCalledWith(
`/explore/?dashboard_page_id=&slice_id=${sliceId}`,
);
});
|
6,773 | 0 | petrpan-code/apache/superset/superset-frontend/src/components/Chart | petrpan-code/apache/superset/superset-frontend/src/components/Chart/DrillDetail/DrillDetailPane.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 { QueryFormData, SupersetClient } from '@superset-ui/core';
import { render, screen, waitFor } from 'spec/helpers/testing-library';
import { getMockStoreWithNativeFilters } from 'spec/fixtures/mockStore';
import chartQueries, { sliceId } from 'spec/fixtures/mockChartQueries';
import { supersetGetCache } from 'src/utils/cachedSupersetGet';
import DrillDetailPane from './DrillDetailPane';
const chart = chartQueries[sliceId];
const setup = (overrides: Record<string, any> = {}) => {
const store = getMockStoreWithNativeFilters();
const props = {
initialFilters: [],
formData: chart.form_data as unknown as QueryFormData,
...overrides,
};
return render(<DrillDetailPane {...props} />, {
useRedux: true,
store,
});
};
const waitForRender = (overrides: Record<string, any> = {}) =>
waitFor(() => setup(overrides));
const SAMPLES_ENDPOINT =
'end:/datasource/samples?force=false&datasource_type=table&datasource_id=7&per_page=50&page=1';
const DATASET_ENDPOINT = 'glob:*/api/v1/dataset/*';
const MOCKED_DATASET = {
changed_on_humanized: '2 days ago',
created_on_humanized: 'a week ago',
description: 'Simple description',
table_name: 'test_table',
changed_by: {
first_name: 'John',
last_name: 'Doe',
},
created_by: {
first_name: 'John',
last_name: 'Doe',
},
owners: [
{
first_name: 'John',
last_name: 'Doe',
},
],
};
const setupDatasetEndpoint = () => {
fetchMock.get(DATASET_ENDPOINT, {
status: 'complete',
result: MOCKED_DATASET,
});
};
const fetchWithNoData = () => {
setupDatasetEndpoint();
fetchMock.post(SAMPLES_ENDPOINT, {
result: {
total_count: 0,
data: [],
colnames: [],
coltypes: [],
},
});
};
const fetchWithData = () => {
setupDatasetEndpoint();
fetchMock.post(SAMPLES_ENDPOINT, {
result: {
total_count: 3,
data: [
{
year: 1996,
na_sales: 11.27,
eu_sales: 8.89,
},
{
year: 1989,
na_sales: 23.2,
eu_sales: 2.26,
},
{
year: 1999,
na_sales: 9,
eu_sales: 6.18,
},
],
colnames: ['year', 'na_sales', 'eu_sales'],
coltypes: [0, 0, 0],
},
});
};
afterEach(() => {
fetchMock.restore();
supersetGetCache.clear();
});
test('should render', async () => {
fetchWithNoData();
const { container } = await waitForRender();
expect(container).toBeInTheDocument();
});
test('should render loading indicator', async () => {
fetchWithData();
setup();
await waitFor(() =>
expect(screen.getByLabelText('Loading')).toBeInTheDocument(),
);
});
test('should render the table with results', async () => {
fetchWithData();
await waitForRender();
expect(screen.getByRole('table')).toBeInTheDocument();
expect(screen.getByText('1996')).toBeInTheDocument();
expect(screen.getByText('11.27')).toBeInTheDocument();
expect(screen.getByText('1989')).toBeInTheDocument();
expect(screen.getByText('23.2')).toBeInTheDocument();
expect(screen.getByText('1999')).toBeInTheDocument();
expect(screen.getByText('9')).toBeInTheDocument();
expect(
screen.getByRole('columnheader', { name: 'year' }),
).toBeInTheDocument();
expect(
screen.getByRole('columnheader', { name: 'na_sales' }),
).toBeInTheDocument();
expect(
screen.getByRole('columnheader', { name: 'eu_sales' }),
).toBeInTheDocument();
});
test('should render the "No results" components', async () => {
fetchWithNoData();
setup();
expect(
await screen.findByText('No rows were returned for this dataset'),
).toBeInTheDocument();
});
test('should render the metadata bar', async () => {
fetchWithNoData();
setup();
expect(
await screen.findByText(MOCKED_DATASET.table_name),
).toBeInTheDocument();
expect(
await screen.findByText(MOCKED_DATASET.description),
).toBeInTheDocument();
expect(
await screen.findByText(
`${MOCKED_DATASET.created_by.first_name} ${MOCKED_DATASET.created_by.last_name}`,
),
).toBeInTheDocument();
expect(
await screen.findByText(MOCKED_DATASET.changed_on_humanized),
).toBeInTheDocument();
});
test('should render an error message when fails to load the metadata', async () => {
fetchWithNoData();
fetchMock.get(DATASET_ENDPOINT, { status: 400 }, { overwriteRoutes: true });
setup();
expect(
await screen.findByText('There was an error loading the dataset metadata'),
).toBeInTheDocument();
});
test('should render the error', async () => {
jest
.spyOn(SupersetClient, 'post')
.mockRejectedValue(new Error('Something went wrong'));
await waitForRender();
expect(screen.getByText('Error: Something went wrong')).toBeInTheDocument();
});
|
6,775 | 0 | petrpan-code/apache/superset/superset-frontend/src/components/Chart | petrpan-code/apache/superset/superset-frontend/src/components/Chart/DrillDetail/DrillDetailTableControls.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 TableControls from './DrillDetailTableControls';
const setFilters = jest.fn();
const onReload = jest.fn();
const setup = (overrides: Record<string, any> = {}) => {
const props = {
filters: [],
setFilters,
onReload,
loading: false,
totalCount: 0,
...overrides,
};
return render(<TableControls {...props} />);
};
test('should render', () => {
const { container } = setup();
expect(container).toBeInTheDocument();
});
test('should show 0 rows', () => {
setup();
expect(screen.getByText('0 rows')).toBeInTheDocument();
});
test('should show the correct amount of rows', () => {
setup({
totalCount: 10,
});
expect(screen.getByText('10 rows')).toBeInTheDocument();
});
test('should render the reload button', () => {
setup();
expect(screen.getByRole('button', { name: 'Reload' })).toBeInTheDocument();
});
test('should show the loading indicator', () => {
setup({
loading: true,
});
expect(screen.getByText('Loading...')).toBeInTheDocument();
});
test('should call onreload', () => {
setup();
userEvent.click(screen.getByRole('button', { name: 'Reload' }));
expect(onReload).toHaveBeenCalledTimes(1);
});
test('should render with filters', () => {
setup({
filters: [
{
col: 'platform',
op: '==',
val: 'GB',
},
{
col: 'lang',
op: '==',
val: 'IT',
},
],
});
expect(screen.getByText('platform')).toBeInTheDocument();
expect(screen.getByText('GB')).toBeInTheDocument();
expect(screen.getByText('lang')).toBeInTheDocument();
expect(screen.getByText('IT')).toBeInTheDocument();
});
test('should remove the filters on close', () => {
setup({
filters: [
{
col: 'platform',
op: '==',
val: 'GB',
},
],
});
expect(screen.getByText('platform')).toBeInTheDocument();
expect(screen.getByText('GB')).toBeInTheDocument();
userEvent.click(screen.getByRole('img', { name: 'close' }));
expect(setFilters).toHaveBeenCalledWith([]);
});
|
6,781 | 0 | petrpan-code/apache/superset/superset-frontend/src/components | petrpan-code/apache/superset/superset-frontend/src/components/Checkbox/Checkbox.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,
styledShallow as shallow,
} from 'spec/helpers/theming';
import Checkbox, {
CheckboxChecked,
CheckboxUnchecked,
} from 'src/components/Checkbox';
describe('Checkbox', () => {
let wrapper: ReactWrapper;
it('renders the base component', () => {
expect(
React.isValidElement(
<Checkbox style={{}} checked={false} onChange={() => true} />,
),
).toBe(true);
});
describe('when unchecked', () => {
it('renders the unchecked component', () => {
const shallowWrapper = shallow(
<Checkbox style={{}} checked={false} onChange={() => true} />,
);
expect(shallowWrapper.dive().find(CheckboxUnchecked)).toExist();
});
});
describe('when checked', () => {
it('renders the checked component', () => {
const shallowWrapper = shallow(
<Checkbox style={{}} checked onChange={() => true} />,
);
expect(shallowWrapper.dive().find(CheckboxChecked)).toExist();
});
});
it('works with an onChange handler', () => {
const mockAction = jest.fn();
wrapper = mount(
<Checkbox style={{}} checked={false} onChange={mockAction} />,
);
wrapper.find('Checkbox').first().simulate('click');
expect(mockAction).toHaveBeenCalled();
});
it('renders custom Checkbox styles without melting', () => {
wrapper = mount(
<Checkbox onChange={() => true} checked={false} style={{ opacity: 1 }} />,
);
expect(wrapper.find('Checkbox')).toExist();
expect(wrapper.find('Checkbox')).toHaveStyle({ opacity: 1 });
});
});
|
6,786 | 0 | petrpan-code/apache/superset/superset-frontend/src/components | petrpan-code/apache/superset/superset-frontend/src/components/Collapse/Collapse.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 { supersetTheme, hexToRgb } from '@superset-ui/core';
import Collapse, { CollapseProps } from '.';
function renderCollapse(props?: CollapseProps) {
return render(
<Collapse {...props}>
<Collapse.Panel header="Header 1" key="1">
Content 1
</Collapse.Panel>
<Collapse.Panel header="Header 2" key="2">
Content 2
</Collapse.Panel>
</Collapse>,
);
}
test('renders collapsed with default props', () => {
renderCollapse();
const headers = screen.getAllByRole('button');
expect(headers[0]).toHaveTextContent('Header 1');
expect(headers[1]).toHaveTextContent('Header 2');
expect(screen.queryByText('Content 1')).not.toBeInTheDocument();
expect(screen.queryByText('Content 2')).not.toBeInTheDocument();
});
test('renders with one item expanded by default', () => {
renderCollapse({ defaultActiveKey: ['1'] });
const headers = screen.getAllByRole('button');
expect(headers[0]).toHaveTextContent('Header 1');
expect(headers[1]).toHaveTextContent('Header 2');
expect(screen.getByText('Content 1')).toBeInTheDocument();
expect(screen.queryByText('Content 2')).not.toBeInTheDocument();
});
test('expands on click', () => {
renderCollapse();
expect(screen.queryByText('Content 1')).not.toBeInTheDocument();
expect(screen.queryByText('Content 2')).not.toBeInTheDocument();
userEvent.click(screen.getAllByRole('button')[0]);
expect(screen.getByText('Content 1')).toBeInTheDocument();
expect(screen.queryByText('Content 2')).not.toBeInTheDocument();
});
test('collapses on click', () => {
renderCollapse({ defaultActiveKey: ['1'] });
expect(screen.getByText('Content 1')).toBeInTheDocument();
expect(screen.queryByText('Content 2')).not.toBeInTheDocument();
userEvent.click(screen.getAllByRole('button')[0]);
expect(screen.getByText('Content 1').parentNode).toHaveClass(
'ant-collapse-content-hidden',
);
expect(screen.queryByText('Content 2')).not.toBeInTheDocument();
});
test('renders with custom properties', () => {
renderCollapse({
light: true,
bigger: true,
bold: true,
animateArrows: true,
});
const header = document.getElementsByClassName('ant-collapse-header')[0];
const arrow =
document.getElementsByClassName('ant-collapse-arrow')[0].children[0];
const headerStyle = window.getComputedStyle(header);
const arrowStyle = window.getComputedStyle(arrow);
expect(headerStyle.fontWeight).toBe(
supersetTheme.typography.weights.bold.toString(),
);
expect(headerStyle.fontSize).toBe(`${supersetTheme.gridUnit * 4}px`);
expect(headerStyle.color).toBe(
hexToRgb(supersetTheme.colors.grayscale.light4),
);
expect(arrowStyle.transition).toBe('transform 0.24s');
});
|
6,792 | 0 | petrpan-code/apache/superset/superset-frontend/src/components | petrpan-code/apache/superset/superset-frontend/src/components/CopyToClipboard/CopyToClipboard.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 CopyToClipboard from '.';
test('renders with default props', () => {
const text = 'Text';
render(<CopyToClipboard text={text} />, { useRedux: true });
expect(screen.getByText(text)).toBeInTheDocument();
expect(screen.getByText('Copy')).toBeInTheDocument();
});
test('renders with custom copy node', () => {
const copyNode = <a href="/">Custom node</a>;
render(<CopyToClipboard copyNode={copyNode} />, { useRedux: true });
expect(screen.getByRole('link')).toBeInTheDocument();
});
test('renders without text showing', () => {
const text = 'Text';
render(<CopyToClipboard text={text} shouldShowText={false} />, {
useRedux: true,
});
expect(screen.queryByText(text)).not.toBeInTheDocument();
});
test('getText on copy', async () => {
const getText = jest.fn(() => 'Text');
render(<CopyToClipboard getText={getText} />, { useRedux: true });
userEvent.click(screen.getByText('Copy'));
await waitFor(() => expect(getText).toHaveBeenCalled());
});
test('renders tooltip on hover', async () => {
const tooltipText = 'Tooltip';
render(<CopyToClipboard tooltipText={tooltipText} />, { useRedux: true });
userEvent.hover(screen.getByText('Copy'));
const tooltip = await screen.findByRole('tooltip');
expect(tooltip).toBeInTheDocument();
expect(tooltip).toHaveTextContent(tooltipText);
});
test('not renders tooltip on hover with hideTooltip props', async () => {
const tooltipText = 'Tooltip';
render(<CopyToClipboard tooltipText={tooltipText} hideTooltip />, {
useRedux: true,
});
userEvent.hover(screen.getByText('Copy'));
const tooltip = screen.queryByRole('tooltip');
expect(tooltip).toBe(null);
});
test('triggers onCopyEnd', async () => {
const onCopyEnd = jest.fn();
render(<CopyToClipboard onCopyEnd={onCopyEnd} />, {
useRedux: true,
});
userEvent.click(screen.getByText('Copy'));
await waitFor(() => expect(onCopyEnd).toHaveBeenCalled());
});
test('renders unwrapped', () => {
const text = 'Text';
render(<CopyToClipboard text={text} wrapped={false} />, {
useRedux: true,
});
expect(screen.queryByText(text)).not.toBeInTheDocument();
});
|
6,795 | 0 | petrpan-code/apache/superset/superset-frontend/src/components | petrpan-code/apache/superset/superset-frontend/src/components/CronPicker/CronPicker.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 } from 'spec/helpers/testing-library';
import * as ReactCronPicker from 'react-js-cron';
import { CronPicker } from './CronPicker';
const spy = jest.spyOn(ReactCronPicker, 'default');
test('Should send correct props to ReactCronPicker', () => {
const props = {
myCustomProp: 'myCustomProp',
};
render(<CronPicker {...(props as any)} />);
expect(spy).toBeCalledWith(
expect.objectContaining({
className: expect.any(String),
locale: expect.anything(),
myCustomProp: 'myCustomProp',
}),
expect.anything(),
);
});
|
6,798 | 0 | petrpan-code/apache/superset/superset-frontend/src/components | petrpan-code/apache/superset/superset-frontend/src/components/DatabaseSelector/DatabaseSelector.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 { act } from 'react-dom/test-utils';
import fetchMock from 'fetch-mock';
import {
render,
screen,
waitFor,
defaultStore as store,
} from 'spec/helpers/testing-library';
import userEvent from '@testing-library/user-event';
import { api } from 'src/hooks/apiResources/queryApi';
import DatabaseSelector, { DatabaseSelectorProps } from '.';
import { EmptyStateSmall } from '../EmptyState';
const createProps = (): DatabaseSelectorProps => ({
db: {
id: 1,
database_name: 'test',
backend: 'test-postgresql',
},
formMode: false,
isDatabaseSelectEnabled: true,
readOnly: false,
schema: 'public',
sqlLabMode: true,
getDbList: jest.fn(),
handleError: jest.fn(),
onDbChange: jest.fn(),
onSchemaChange: jest.fn(),
});
const fakeDatabaseApiResult = {
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_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_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_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_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,
},
],
};
const fakeSchemaApiResult = {
count: 2,
result: ['information_schema', 'public'],
};
const fakeFunctionNamesApiResult = {
function_names: [],
};
const databaseApiRoute = 'glob:*/api/v1/database/?*';
const schemaApiRoute = 'glob:*/api/v1/database/*/schemas/?*';
const tablesApiRoute = 'glob:*/api/v1/database/*/tables/*';
function setupFetchMock() {
fetchMock.get(databaseApiRoute, fakeDatabaseApiResult);
fetchMock.get(schemaApiRoute, fakeSchemaApiResult);
fetchMock.get(tablesApiRoute, fakeFunctionNamesApiResult);
}
beforeEach(() => {
setupFetchMock();
});
afterEach(() => {
fetchMock.reset();
act(() => {
store.dispatch(api.util.resetApiState());
});
});
test('Should render', async () => {
const props = createProps();
render(<DatabaseSelector {...props} />, { useRedux: true, store });
expect(await screen.findByTestId('DatabaseSelector')).toBeInTheDocument();
});
test('Refresh should work', async () => {
const props = createProps();
render(<DatabaseSelector {...props} />, { useRedux: true, store });
expect(fetchMock.calls(schemaApiRoute).length).toBe(0);
const select = screen.getByRole('combobox', {
name: 'Select schema or type to search schemas',
});
userEvent.click(select);
await waitFor(() => {
expect(fetchMock.calls(databaseApiRoute).length).toBe(1);
expect(fetchMock.calls(schemaApiRoute).length).toBe(1);
expect(props.handleError).toBeCalledTimes(0);
expect(props.onDbChange).toBeCalledTimes(0);
expect(props.onSchemaChange).toBeCalledTimes(0);
});
// click schema reload
userEvent.click(screen.getByRole('button', { name: 'refresh' }));
await waitFor(() => {
expect(fetchMock.calls(databaseApiRoute).length).toBe(1);
expect(fetchMock.calls(schemaApiRoute).length).toBe(2);
expect(props.handleError).toBeCalledTimes(0);
expect(props.onDbChange).toBeCalledTimes(0);
expect(props.onSchemaChange).toBeCalledTimes(0);
});
});
test('Should database select display options', async () => {
const props = createProps();
render(<DatabaseSelector {...props} />, { useRedux: true, store });
const select = screen.getByRole('combobox', {
name: 'Select database or type to search databases',
});
expect(select).toBeInTheDocument();
userEvent.click(select);
expect(await screen.findByText('test-mysql')).toBeInTheDocument();
});
test('should show empty state if there are no options', async () => {
fetchMock.reset();
fetchMock.get(databaseApiRoute, { result: [] });
fetchMock.get(schemaApiRoute, { result: [] });
fetchMock.get(tablesApiRoute, { result: [] });
const props = createProps();
render(
<DatabaseSelector
{...props}
db={undefined}
emptyState={<EmptyStateSmall title="empty" image="" />}
/>,
{ useRedux: true, store },
);
const select = screen.getByRole('combobox', {
name: 'Select database or type to search databases',
});
userEvent.click(select);
const emptystate = await screen.findByText('empty');
expect(emptystate).toBeInTheDocument();
expect(screen.queryByText('test-mysql')).not.toBeInTheDocument();
});
test('Should schema select display options', async () => {
const props = createProps();
render(<DatabaseSelector {...props} />, { useRedux: true, store });
const select = screen.getByRole('combobox', {
name: 'Select schema or type to search schemas',
});
expect(select).toBeInTheDocument();
userEvent.click(select);
expect(
await screen.findByRole('option', { name: 'public' }),
).toBeInTheDocument();
expect(
await screen.findByRole('option', { name: 'information_schema' }),
).toBeInTheDocument();
});
test('Sends the correct db when changing the database', async () => {
const props = createProps();
render(<DatabaseSelector {...props} />, { useRedux: true, store });
const select = screen.getByRole('combobox', {
name: 'Select database or type to search databases',
});
expect(select).toBeInTheDocument();
userEvent.click(select);
userEvent.click(await screen.findByText('test-mysql'));
await waitFor(() =>
expect(props.onDbChange).toHaveBeenCalledWith(
expect.objectContaining({
id: 2,
database_name: 'test-mysql',
backend: 'mysql',
}),
),
);
});
test('Sends the correct schema when changing the schema', async () => {
const props = createProps();
render(<DatabaseSelector {...props} />, { useRedux: true, store });
const select = screen.getByRole('combobox', {
name: 'Select schema or type to search schemas',
});
expect(select).toBeInTheDocument();
userEvent.click(select);
const schemaOption = await screen.findAllByText('information_schema');
userEvent.click(schemaOption[1]);
await waitFor(() =>
expect(props.onSchemaChange).toHaveBeenCalledWith('information_schema'),
);
});
|
6,808 | 0 | petrpan-code/apache/superset/superset-frontend/src/components | petrpan-code/apache/superset/superset-frontend/src/components/Datasource/Field.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 { shallow } from 'enzyme';
import TextAreaControl from 'src/explore/components/controls/TextAreaControl';
import Field from './Field';
describe('Field', () => {
const defaultProps = {
fieldKey: 'mock',
value: '',
label: 'mock',
description: 'description',
control: <TextAreaControl />,
onChange: jest.fn(),
compact: false,
inline: false,
};
it('should render', () => {
const { container } = render(<Field {...defaultProps} />);
expect(container).toBeInTheDocument();
});
it('should call onChange', () => {
const wrapper = shallow(<Field {...defaultProps} />);
const textArea = wrapper.find(TextAreaControl);
textArea.simulate('change', { target: { value: 'x' } });
expect(defaultProps.onChange).toHaveBeenCalled();
});
it('should render compact', () => {
render(<Field {...defaultProps} compact />);
expect(
screen.queryByText(defaultProps.description),
).not.toBeInTheDocument();
});
});
|
6,815 | 0 | petrpan-code/apache/superset/superset-frontend/src/components | petrpan-code/apache/superset/superset-frontend/src/components/DeleteModal/DeleteModal.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 DeleteModal from '.';
test('Must display title and content', () => {
const props = {
title: <div data-test="test-title">Title</div>,
description: <div data-test="test-description">Description</div>,
onConfirm: jest.fn(),
onHide: jest.fn(),
open: true,
};
render(<DeleteModal {...props} />);
expect(screen.getByTestId('test-title')).toBeInTheDocument();
expect(screen.getByTestId('test-title')).toBeVisible();
expect(screen.getByTestId('test-description')).toBeInTheDocument();
expect(screen.getByTestId('test-description')).toBeVisible();
});
test('Calling "onHide"', () => {
const props = {
title: <div data-test="test-title">Title</div>,
description: <div data-test="test-description">Description</div>,
onConfirm: jest.fn(),
onHide: jest.fn(),
open: true,
};
const modal = <DeleteModal {...props} />;
render(modal);
expect(props.onHide).toBeCalledTimes(0);
expect(props.onConfirm).toBeCalledTimes(0);
// type "del" in the input
userEvent.type(screen.getByTestId('delete-modal-input'), 'del');
expect(screen.getByTestId('delete-modal-input')).toHaveValue('del');
// close the modal
expect(screen.getByText('×')).toBeVisible();
userEvent.click(screen.getByText('×'));
expect(props.onHide).toBeCalledTimes(1);
expect(props.onConfirm).toBeCalledTimes(0);
// confirm input has been cleared
expect(screen.getByTestId('delete-modal-input')).toHaveValue('');
});
test('Calling "onConfirm" only after typing "delete" in the input', () => {
const props = {
title: <div data-test="test-title">Title</div>,
description: <div data-test="test-description">Description</div>,
onConfirm: jest.fn(),
onHide: jest.fn(),
open: true,
};
render(<DeleteModal {...props} />);
expect(props.onHide).toBeCalledTimes(0);
expect(props.onConfirm).toBeCalledTimes(0);
expect(screen.getByTestId('delete-modal-input')).toBeVisible();
expect(props.onConfirm).toBeCalledTimes(0);
// do not execute "onConfirm" if you have not typed "delete"
userEvent.click(screen.getByText('delete'));
expect(props.onConfirm).toBeCalledTimes(0);
// execute "onConfirm" if you have typed "delete"
userEvent.type(screen.getByTestId('delete-modal-input'), 'delete');
userEvent.click(screen.getByText('delete'));
expect(props.onConfirm).toBeCalledTimes(1);
// confirm input has been cleared
expect(screen.getByTestId('delete-modal-input')).toHaveValue('');
});
|
6,833 | 0 | petrpan-code/apache/superset/superset-frontend/src/components | petrpan-code/apache/superset/superset-frontend/src/components/DropdownContainer/DropdownContainer.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 userEvent from '@testing-library/user-event';
import { screen, render } from 'spec/helpers/testing-library';
import Button from '../Button';
import Icons from '../Icons';
import DropdownContainer from '.';
const generateItems = (n: number) =>
Array.from({ length: n }).map((_, i) => ({
id: `el-${i + 1}`,
element: <Button>{`Element ${i + 1}`}</Button>,
}));
const ITEMS = generateItems(10);
const mockOverflowingIndex = async (
overflowingIndex: number,
func: Function,
) => {
const spy = jest.spyOn(React, 'useState');
spy.mockImplementation(() => [overflowingIndex, jest.fn()]);
await func();
spy.mockRestore();
};
test('renders children', () => {
render(<DropdownContainer items={generateItems(3)} />);
expect(screen.getByText('Element 1')).toBeInTheDocument();
expect(screen.getByText('Element 2')).toBeInTheDocument();
expect(screen.getByText('Element 3')).toBeInTheDocument();
});
test('renders children with custom horizontal spacing', () => {
render(<DropdownContainer items={ITEMS} style={{ gap: 20 }} />);
expect(screen.getByTestId('container')).toHaveStyle('gap: 20px');
});
test('renders a dropdown trigger when overflowing', async () => {
await mockOverflowingIndex(3, () => {
render(<DropdownContainer items={ITEMS} />);
expect(screen.getByText('More')).toBeInTheDocument();
});
});
test('renders a dropdown trigger with custom icon', async () => {
await mockOverflowingIndex(3, async () => {
render(
<DropdownContainer items={ITEMS} dropdownTriggerIcon={<Icons.Link />} />,
);
expect(
await screen.findByRole('img', { name: 'link' }),
).toBeInTheDocument();
});
});
test('renders a dropdown trigger with custom text', async () => {
await mockOverflowingIndex(3, () => {
const customText = 'Custom text';
render(
<DropdownContainer items={ITEMS} dropdownTriggerText={customText} />,
);
expect(screen.getByText(customText)).toBeInTheDocument();
});
});
test('renders a dropdown trigger with custom count', async () => {
await mockOverflowingIndex(3, () => {
const customCount = 99;
render(
<DropdownContainer items={ITEMS} dropdownTriggerCount={customCount} />,
);
expect(screen.getByTitle(customCount)).toBeInTheDocument();
});
});
test('does not render a dropdown button when not overflowing', () => {
render(<DropdownContainer items={generateItems(3)} />);
expect(screen.queryByText('More')).not.toBeInTheDocument();
});
test('renders a dropdown when overflowing', async () => {
await mockOverflowingIndex(3, () => {
render(<DropdownContainer items={ITEMS} />);
userEvent.click(screen.getByText('More'));
expect(screen.getByTestId('dropdown-content')).toBeInTheDocument();
});
});
test('renders children with custom vertical spacing', async () => {
await mockOverflowingIndex(3, () => {
render(<DropdownContainer items={ITEMS} dropdownStyle={{ gap: 20 }} />);
userEvent.click(screen.getByText('More'));
expect(screen.getByTestId('dropdown-content')).toHaveStyle('gap: 20px');
});
});
test('fires event when overflowing state changes', async () => {
await mockOverflowingIndex(3, () => {
const onOverflowingStateChange = jest.fn();
render(
<DropdownContainer
items={generateItems(5)}
onOverflowingStateChange={onOverflowingStateChange}
/>,
);
expect(onOverflowingStateChange).toHaveBeenCalledWith({
notOverflowed: ['el-1', 'el-2', 'el-3'],
overflowed: ['el-4', 'el-5'],
});
});
});
test('renders a dropdown with custom content', async () => {
await mockOverflowingIndex(3, () => {
const customDropdownContent = <div>Custom content</div>;
render(
<DropdownContainer
items={ITEMS}
dropdownContent={() => customDropdownContent}
/>,
);
userEvent.click(screen.getByText('More'));
expect(screen.getByText('Custom content')).toBeInTheDocument();
});
});
test('Shows tooltip on dropdown trigger hover', async () => {
await mockOverflowingIndex(3, async () => {
render(
<DropdownContainer
items={generateItems(5)}
dropdownTriggerTooltip="Test tooltip"
/>,
);
userEvent.hover(screen.getByText('More'));
expect(await screen.findByText('Test tooltip')).toBeInTheDocument();
});
});
|
6,837 | 0 | petrpan-code/apache/superset/superset-frontend/src/components | petrpan-code/apache/superset/superset-frontend/src/components/DropdownSelectableIcon/DropdownSelectableIcon.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 Icons from 'src/components/Icons';
import userEvent from '@testing-library/user-event';
import DropdownSelectableIcon, { DropDownSelectableProps } from '.';
const mockedProps = {
menuItems: [
{
key: 'vertical',
label: 'vertical',
},
{
key: 'horizontal',
label: 'horizontal',
},
],
selectedKeys: [],
icon: <Icons.Gear name="gear" />,
};
const asyncRender = (props: DropDownSelectableProps) =>
waitFor(() => render(<DropdownSelectableIcon {...props} />));
const openMenu = () => {
userEvent.click(screen.getByRole('img', { name: 'gear' }));
};
test('should render', async () => {
const { container } = await asyncRender(mockedProps);
expect(container).toBeInTheDocument();
});
test('should render the icon', async () => {
await asyncRender(mockedProps);
expect(screen.getByRole('img', { name: 'gear' })).toBeInTheDocument();
});
test('should not render the info', async () => {
await asyncRender(mockedProps);
openMenu();
expect(
screen.queryByTestId('dropdown-selectable-info'),
).not.toBeInTheDocument();
});
test('should render the info', async () => {
const infoProps = {
...mockedProps,
info: 'Test',
};
await asyncRender(infoProps);
openMenu();
expect(screen.getByTestId('dropdown-selectable-info')).toBeInTheDocument();
expect(screen.getByText('Test')).toBeInTheDocument();
});
test('should render the menu items', async () => {
await asyncRender(mockedProps);
openMenu();
expect(screen.getAllByRole('menuitem')).toHaveLength(2);
expect(screen.getByText('vertical')).toBeInTheDocument();
expect(screen.getByText('horizontal')).toBeInTheDocument();
});
test('should not render any selected menu item', async () => {
await asyncRender(mockedProps);
openMenu();
expect(screen.getAllByRole('menuitem')).toHaveLength(2);
expect(screen.queryByRole('img', { name: 'check' })).not.toBeInTheDocument();
});
test('should render the selected menu items', async () => {
const selectedProps = {
...mockedProps,
selectedKeys: ['vertical'],
};
await asyncRender(selectedProps);
openMenu();
expect(screen.getByRole('img', { name: 'check' })).toBeInTheDocument();
});
|
6,839 | 0 | petrpan-code/apache/superset/superset-frontend/src/components | petrpan-code/apache/superset/superset-frontend/src/components/DynamicEditableTitle/DynamicEditableTitle.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 userEvent from '@testing-library/user-event';
import { render, screen } from 'spec/helpers/testing-library';
import { DynamicEditableTitle } from '.';
const createProps = (overrides: Record<string, any> = {}) => ({
title: 'Chart title',
placeholder: 'Add the name of the chart',
canEdit: true,
onSave: jest.fn(),
label: 'Chart title',
...overrides,
});
describe('Chart editable title', () => {
it('renders chart title', () => {
const props = createProps();
render(<DynamicEditableTitle {...props} />);
expect(screen.getByText('Chart title')).toBeVisible();
});
it('renders placeholder', () => {
const props = createProps({
title: '',
});
render(<DynamicEditableTitle {...props} />);
expect(screen.getByText('Add the name of the chart')).toBeVisible();
});
it('click, edit and save title', () => {
const props = createProps();
render(<DynamicEditableTitle {...props} />);
const textboxElement = screen.getByRole('textbox');
userEvent.click(textboxElement);
userEvent.type(textboxElement, ' edited');
expect(screen.getByText('Chart title edited')).toBeVisible();
userEvent.type(textboxElement, '{enter}');
expect(props.onSave).toHaveBeenCalled();
});
it('renders in non-editable mode', () => {
const props = createProps({ canEdit: false });
render(<DynamicEditableTitle {...props} />);
const titleElement = screen.getByLabelText('Chart title');
expect(screen.queryByRole('textbox')).not.toBeInTheDocument();
expect(titleElement).toBeVisible();
userEvent.click(titleElement);
userEvent.type(titleElement, ' edited{enter}');
expect(props.onSave).not.toHaveBeenCalled();
});
});
|
6,843 | 0 | petrpan-code/apache/superset/superset-frontend/src/components | petrpan-code/apache/superset/superset-frontend/src/components/EditableTitle/EditableTitle.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 sinon from 'sinon';
import EditableTable from 'src/components/EditableTitle';
describe('EditableTitle', () => {
const callback = sinon.spy();
const mockProps = {
title: 'my title',
canEdit: true,
onSaveTitle: callback,
};
const mockEvent = {
target: {
value: 'new title',
},
};
let editableWrapper = shallow(<EditableTable {...mockProps} />);
const notEditableWrapper = shallow(
<EditableTable title="my title" onSaveTitle={callback} />,
);
it('is valid', () => {
expect(React.isValidElement(<EditableTable {...mockProps} />)).toBe(true);
});
it('should render title', () => {
const titleElement = editableWrapper.find('input');
expect(titleElement.props().value).toBe('my title');
expect(titleElement.props().type).toBe('button');
});
it('should not render an input if it is not editable', () => {
expect(notEditableWrapper.find('input')).not.toExist();
});
describe('should handle click', () => {
it('should change title', () => {
editableWrapper.find('input').simulate('click');
expect(editableWrapper.find('input').props().type).toBe('text');
});
});
describe('should handle change', () => {
afterEach(() => {
editableWrapper = shallow(<EditableTable {...mockProps} />);
});
it('should change title', () => {
editableWrapper.find('input').simulate('change', mockEvent);
expect(editableWrapper.find('input').props().value).toBe('new title');
});
});
describe('should handle blur', () => {
beforeEach(() => {
editableWrapper.find('input').simulate('click');
});
afterEach(() => {
callback.resetHistory();
editableWrapper = shallow(<EditableTable {...mockProps} />);
});
it('default input type should be text', () => {
expect(editableWrapper.find('input').props().type).toBe('text');
});
it('should trigger callback', () => {
editableWrapper.find('input').simulate('change', mockEvent);
editableWrapper.find('input').simulate('blur');
expect(editableWrapper.find('input').props().type).toBe('button');
expect(callback.callCount).toBe(1);
expect(callback.getCall(0).args[0]).toBe('new title');
});
it('should not trigger callback', () => {
editableWrapper.find('input').simulate('blur');
expect(editableWrapper.find('input').props().type).toBe('button');
// no change
expect(callback.callCount).toBe(0);
});
it('should not save empty title', () => {
editableWrapper.find('input').simulate('blur');
expect(editableWrapper.find('input').props().type).toBe('button');
expect(editableWrapper.find('input').props().value).toBe('my title');
expect(callback.callCount).toBe(0);
});
});
});
|
6,847 | 0 | petrpan-code/apache/superset/superset-frontend/src/components | petrpan-code/apache/superset/superset-frontend/src/components/ErrorBoundary/ErrorBoundary.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 ErrorBoundary from '.';
const mockedProps = {
children: <span>Error children</span>,
onError: () => null,
showMessage: false,
};
const Child = () => {
throw new Error('Thrown error');
};
test('should render', () => {
const { container } = render(
<ErrorBoundary {...mockedProps}>
<Child />
</ErrorBoundary>,
);
expect(container).toBeInTheDocument();
});
test('should not render an error message', () => {
render(
<ErrorBoundary {...mockedProps}>
<Child />
</ErrorBoundary>,
);
expect(screen.queryByText('Unexpected error')).not.toBeInTheDocument();
});
test('should render an error message', () => {
const messageProps = {
...mockedProps,
showMessage: true,
};
render(
<ErrorBoundary {...messageProps}>
<Child />
</ErrorBoundary>,
);
expect(screen.getByText('Unexpected error')).toBeInTheDocument();
});
|
6,849 | 0 | petrpan-code/apache/superset/superset-frontend/src/components | petrpan-code/apache/superset/superset-frontend/src/components/ErrorMessage/BasicErrorAlert.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 { supersetTheme } from '@superset-ui/core';
import BasicErrorAlert from './BasicErrorAlert';
import { ErrorLevel } from './types';
jest.mock(
'src/components/Icons/Icon',
() =>
({ fileName }: { fileName: string }) =>
<span role="img" aria-label={fileName.replace('_', '-')} />,
);
const mockedProps = {
body: 'Error body',
level: 'warning' as ErrorLevel,
title: 'Error title',
};
test('should render', () => {
const { container } = render(<BasicErrorAlert {...mockedProps} />);
expect(container).toBeInTheDocument();
});
test('should render warning icon', () => {
render(<BasicErrorAlert {...mockedProps} />);
expect(
screen.getByRole('img', { name: 'warning-solid' }),
).toBeInTheDocument();
});
test('should render error icon', () => {
const errorProps = {
...mockedProps,
level: 'error' as ErrorLevel,
};
render(<BasicErrorAlert {...errorProps} />);
expect(screen.getByRole('img', { name: 'error-solid' })).toBeInTheDocument();
});
test('should render the error title', () => {
render(<BasicErrorAlert {...mockedProps} />);
expect(screen.getByText('Error title')).toBeInTheDocument();
});
test('should render the error body', () => {
render(<BasicErrorAlert {...mockedProps} />);
expect(screen.getByText('Error body')).toBeInTheDocument();
});
test('should render with warning theme', () => {
render(<BasicErrorAlert {...mockedProps} />);
expect(screen.getByRole('alert')).toHaveStyle(
`
backgroundColor: ${supersetTheme.colors.warning.light2};
`,
);
});
test('should render with error theme', () => {
const errorProps = {
...mockedProps,
level: 'error' as ErrorLevel,
};
render(<BasicErrorAlert {...errorProps} />);
expect(screen.getByRole('alert')).toHaveStyle(
`
backgroundColor: ${supersetTheme.colors.error.light2};
`,
);
});
|
Subsets and Splits