level_0
int64
0
10k
index
int64
0
0
repo_id
stringlengths
22
152
file_path
stringlengths
41
203
content
stringlengths
11
11.5M
5,521
0
petrpan-code/apache/superset/superset-frontend/packages/superset-ui-core/test
petrpan-code/apache/superset/superset-frontend/packages/superset-ui-core/test/dimension/getMultipleTextDimensions.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 { getMultipleTextDimensions, promiseTimeout } from '@superset-ui/core'; import { addDummyFill, removeDummyFill, SAMPLE_TEXT } from './getBBoxDummyFill'; describe('getMultipleTextDimension(input)', () => { describe('returns dimension of the given text', () => { beforeEach(addDummyFill); afterEach(removeDummyFill); it('takes an array of text as argument', () => { expect( getMultipleTextDimensions({ texts: [SAMPLE_TEXT[0], SAMPLE_TEXT[1], ''], }), ).toEqual([ { height: 20, width: 200, }, { height: 20, width: 300, }, { height: 0, width: 0, }, ]); }); it('handles empty text', () => { expect( getMultipleTextDimensions({ texts: ['', ''], }), ).toEqual([ { height: 0, width: 0, }, { height: 0, width: 0, }, ]); }); it('handles duplicate text', () => { expect( getMultipleTextDimensions({ texts: [SAMPLE_TEXT[0], SAMPLE_TEXT[0]], }), ).toEqual([ { height: 20, width: 200, }, { height: 20, width: 200, }, ]); }); it('accepts provided class via className', () => { expect( getMultipleTextDimensions({ texts: [SAMPLE_TEXT[0], SAMPLE_TEXT[1]], className: 'test-class', }), ).toEqual([ { height: 20, width: 100, }, { height: 20, width: 150, }, ]); }); it('accepts provided style.font', () => { expect( getMultipleTextDimensions({ texts: [SAMPLE_TEXT[0], SAMPLE_TEXT[1]], style: { font: 'italic 700 30px Lobster', }, }), ).toEqual([ { height: 30, // 20 * (30/20) [fontSize=30] width: 1125, // 200 * 1.25 [fontFamily=Lobster] * (30/20) [fontSize=30] * 1.5 [fontStyle=italic] * 2 [fontWeight=700] }, { height: 30, width: 1688, // 300 * 1.25 [fontFamily=Lobster] * (30/20) [fontSize=30] * 1.5 [fontStyle=italic] * 2 [fontWeight=700] }, ]); }); it('accepts provided style.fontFamily', () => { expect( getMultipleTextDimensions({ texts: [SAMPLE_TEXT[0], SAMPLE_TEXT[1]], style: { fontFamily: 'Lobster', }, }), ).toEqual([ { height: 20, width: 250, // 200 * 1.25 [fontFamily=Lobster] }, { height: 20, width: 375, // 300 * 1.25 [fontFamily=Lobster] }, ]); }); it('accepts provided style.fontSize', () => { expect( getMultipleTextDimensions({ texts: [SAMPLE_TEXT[0], SAMPLE_TEXT[1]], style: { fontSize: '40px', }, }), ).toEqual([ { height: 40, // 20 [baseHeight] * (40/20) [fontSize=40] width: 400, // 200 [baseWidth] * (40/20) [fontSize=40] }, { height: 40, width: 600, // 300 [baseWidth] * (40/20) [fontSize=40] }, ]); }); it('accepts provided style.fontStyle', () => { expect( getMultipleTextDimensions({ texts: [SAMPLE_TEXT[0], SAMPLE_TEXT[1]], style: { fontStyle: 'italic', }, }), ).toEqual([ { height: 20, width: 300, // 200 [baseWidth] * 1.5 [fontStyle=italic] }, { height: 20, width: 450, // 300 [baseWidth] * 1.5 [fontStyle=italic] }, ]); }); it('accepts provided style.fontWeight', () => { expect( getMultipleTextDimensions({ texts: [SAMPLE_TEXT[0], SAMPLE_TEXT[1]], style: { fontWeight: 700, }, }), ).toEqual([ { height: 20, width: 400, // 200 [baseWidth] * 2 [fontWeight=700] }, { height: 20, width: 600, // 300 [baseWidth] * 2 [fontWeight=700] }, ]); }); it('accepts provided style.letterSpacing', () => { expect( getMultipleTextDimensions({ texts: [SAMPLE_TEXT[0], SAMPLE_TEXT[1]], style: { letterSpacing: '1.1', }, }), ).toEqual([ { height: 20, width: 221, // Ceiling(200 [baseWidth] * 1.1 [letterSpacing=1.1]) }, { height: 20, width: 330, // Ceiling(300 [baseWidth] * 1.1 [letterSpacing=1.1]) }, ]); }); }); it('cleans up DOM', async () => { getMultipleTextDimensions({ texts: [SAMPLE_TEXT[0], SAMPLE_TEXT[1]], }); expect(document.querySelectorAll('svg')).toHaveLength(1); await promiseTimeout(() => {}, 501); expect(document.querySelector('svg')).toBeNull(); }); });
5,522
0
petrpan-code/apache/superset/superset-frontend/packages/superset-ui-core/test
petrpan-code/apache/superset/superset-frontend/packages/superset-ui-core/test/dimension/getTextDimension.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 { promiseTimeout, getTextDimension } from '@superset-ui/core'; import { addDummyFill, removeDummyFill, SAMPLE_TEXT } from './getBBoxDummyFill'; describe('getTextDimension(input)', () => { describe('returns default dimension if getBBox() is not available', () => { it('returns default value for default dimension', () => { expect( getTextDimension({ text: SAMPLE_TEXT[0], }), ).toEqual({ height: 20, width: 100, }); }); it('return specified value if specified', () => { expect( getTextDimension( { text: SAMPLE_TEXT[0], }, { height: 30, width: 400, }, ), ).toEqual({ height: 30, width: 400, }); }); }); describe('returns dimension of the given text', () => { beforeEach(addDummyFill); afterEach(removeDummyFill); it('takes text as argument', () => { expect( getTextDimension({ text: SAMPLE_TEXT[0], }), ).toEqual({ height: 20, width: 200, }); }); it('accepts provided class via className', () => { expect( getTextDimension({ text: SAMPLE_TEXT[0], className: 'test-class', }), ).toEqual({ height: 20, width: 100, // width is 100 after adding class }); }); it('accepts provided style.font', () => { expect( getTextDimension({ text: SAMPLE_TEXT[0], style: { font: 'italic 700 30px Lobster', }, }), ).toEqual({ height: 30, // 20 * (30/20) [fontSize=30] width: 1125, // 250 [fontFamily=Lobster] * (30/20) [fontSize=30] * 1.5 [fontStyle=italic] * 2 [fontWeight=700] }); }); it('accepts provided style.fontFamily', () => { expect( getTextDimension({ text: SAMPLE_TEXT[0], style: { fontFamily: 'Lobster', }, }), ).toEqual({ height: 20, width: 250, // (250 [fontFamily=Lobster] }); }); it('accepts provided style.fontSize', () => { expect( getTextDimension({ text: SAMPLE_TEXT[0], style: { fontSize: '40px', }, }), ).toEqual({ height: 40, // 20 [baseHeight] * (40/20) [fontSize=40] width: 400, // 200 [baseWidth] * (40/20) [fontSize=40] }); }); it('accepts provided style.fontStyle', () => { expect( getTextDimension({ text: SAMPLE_TEXT[0], style: { fontStyle: 'italic', }, }), ).toEqual({ height: 20, width: 300, // 200 [baseWidth] * 1.5 [fontStyle=italic] }); }); it('accepts provided style.fontWeight', () => { expect( getTextDimension({ text: SAMPLE_TEXT[0], style: { fontWeight: 700, }, }), ).toEqual({ height: 20, width: 400, // 200 [baseWidth] * 2 [fontWeight=700] }); }); it('accepts provided style.letterSpacing', () => { expect( getTextDimension({ text: SAMPLE_TEXT[0], style: { letterSpacing: '1.1', }, }), ).toEqual({ height: 20, width: 221, // Ceiling(200 [baseWidth] * 1.1 [letterSpacing=1.1]) }); }); it('handle empty text', () => { expect( getTextDimension({ text: '', }), ).toEqual({ height: 0, width: 0, }); }); }); it('cleans up DOM', async () => { getTextDimension({ text: SAMPLE_TEXT[0], }); expect(document.querySelectorAll('svg')).toHaveLength(1); await promiseTimeout(() => {}, 501); expect(document.querySelector('svg')).toBeNull(); }); });
5,523
0
petrpan-code/apache/superset/superset-frontend/packages/superset-ui-core/test
petrpan-code/apache/superset/superset-frontend/packages/superset-ui-core/test/dimension/mergeMargin.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 { mergeMargin } from '@superset-ui/core'; describe('mergeMargin(margin1, margin2, mode?)', () => { it('combines two given margin', () => { expect( mergeMargin( { top: 1, left: 1, bottom: 2, right: 2, }, { top: 2, left: 2, bottom: 1, right: 1, }, ), ).toEqual({ top: 2, left: 2, bottom: 2, right: 2, }); }); describe('default values', () => { it('works if margin1 is not defined', () => { expect( mergeMargin(undefined, { top: 2, left: 2, bottom: 1, right: 1, }), ).toEqual({ top: 2, left: 2, bottom: 1, right: 1, }); }); it('works if margin2 is not defined', () => { expect( mergeMargin( { top: 1, left: 1, bottom: 2, right: 2, }, undefined, ), ).toEqual({ top: 1, left: 1, bottom: 2, right: 2, }); }); it('use 0 for the side that is not specified', () => { expect(mergeMargin({}, {})).toEqual({ top: 0, left: 0, bottom: 0, right: 0, }); }); }); describe('mode', () => { it('if mode=expand, returns the larger margin for each side', () => { expect( mergeMargin( { top: 1, left: 1, bottom: 2, right: 2, }, { top: 2, left: 2, bottom: 1, right: 1, }, 'expand', ), ).toEqual({ top: 2, left: 2, bottom: 2, right: 2, }); }); it('if mode=shrink, returns the smaller margin for each side', () => { expect( mergeMargin( { top: 1, left: 1, bottom: 2, right: 2, }, { top: 2, left: 2, bottom: 1, right: 1, }, 'shrink', ), ).toEqual({ top: 1, left: 1, bottom: 1, right: 1, }); }); it('expand by default', () => { expect( mergeMargin( { top: 1, left: 1, bottom: 2, right: 2, }, { top: 2, left: 2, bottom: 1, right: 1, }, ), ).toEqual({ top: 2, left: 2, bottom: 2, right: 2, }); }); }); it('works correctly for negative margins', () => { expect( mergeMargin( { top: -3, left: -3, bottom: -2, right: -2, }, { top: -2, left: -2, bottom: 0, right: -1, }, ), ).toEqual({ top: -2, left: -2, bottom: 0, right: -1, }); }); it('if there are NaN or null, use another value', () => { expect( mergeMargin( { top: 10, // @ts-ignore to let us pass `null` for testing left: null, bottom: 20, right: NaN, }, { top: NaN, left: 30, bottom: null, right: 40, }, ), ).toEqual({ top: 10, left: 30, bottom: 20, right: 40, }); }); });
5,524
0
petrpan-code/apache/superset/superset-frontend/packages/superset-ui-core/test
petrpan-code/apache/superset/superset-frontend/packages/superset-ui-core/test/dimension/parseLength.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 { parseLength } from '@superset-ui/core'; describe('parseLength(input)', () => { it('handles string "auto"', () => { expect(parseLength('auto')).toEqual({ isDynamic: true, multiplier: 1 }); }); it('handles strings with % at the end', () => { expect(parseLength('100%')).toEqual({ isDynamic: true, multiplier: 1 }); expect(parseLength('50%')).toEqual({ isDynamic: true, multiplier: 0.5 }); expect(parseLength('0%')).toEqual({ isDynamic: true, multiplier: 0 }); }); it('handles strings that are numbers with px at the end', () => { expect(parseLength('100px')).toEqual({ isDynamic: false, value: 100 }); expect(parseLength('20.5px')).toEqual({ isDynamic: false, value: 20.5 }); }); it('handles strings that are numbers', () => { expect(parseLength('100')).toEqual({ isDynamic: false, value: 100 }); expect(parseLength('40.5')).toEqual({ isDynamic: false, value: 40.5 }); expect(parseLength('20.0')).toEqual({ isDynamic: false, value: 20 }); }); it('handles numbers', () => { expect(parseLength(100)).toEqual({ isDynamic: false, value: 100 }); expect(parseLength(0)).toEqual({ isDynamic: false, value: 0 }); }); });
5,525
0
petrpan-code/apache/superset/superset-frontend/packages/superset-ui-core/test/dimension
petrpan-code/apache/superset/superset-frontend/packages/superset-ui-core/test/dimension/svg/LazyFactory.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 LazyFactory from '../../../src/dimension/svg/LazyFactory'; describe('LazyFactory', () => { describe('createInContainer()', () => { it('creates node in the specified container', () => { const factory = new LazyFactory(() => document.createElement('div')); const div = factory.createInContainer(); const innerDiv = factory.createInContainer(div); expect(div.parentNode).toEqual(document.body); expect(innerDiv.parentNode).toEqual(div); }); it('reuses existing', () => { const factoryFn = jest.fn(() => document.createElement('div')); const factory = new LazyFactory(factoryFn); const div1 = factory.createInContainer(); const div2 = factory.createInContainer(); expect(div1).toBe(div2); expect(factoryFn).toHaveBeenCalledTimes(1); }); }); describe('removeFromContainer', () => { it('removes node from container', () => { const factory = new LazyFactory(() => document.createElement('div')); const div = factory.createInContainer(); const innerDiv = factory.createInContainer(div); expect(div.parentNode).toEqual(document.body); expect(innerDiv.parentNode).toEqual(div); factory.removeFromContainer(); factory.removeFromContainer(div); expect(div.parentNode).toBeNull(); expect(innerDiv.parentNode).toBeNull(); }); it('does not remove if others are using', () => { const factory = new LazyFactory(() => document.createElement('div')); const div1 = factory.createInContainer(); factory.createInContainer(); factory.removeFromContainer(); expect(div1.parentNode).toEqual(document.body); factory.removeFromContainer(); expect(div1.parentNode).toBeNull(); }); it('does not crash if try to remove already removed node', () => { const factory = new LazyFactory(() => document.createElement('div')); factory.createInContainer(); factory.removeFromContainer(); expect(() => factory.removeFromContainer()).not.toThrow(); }); }); });
5,526
0
petrpan-code/apache/superset/superset-frontend/packages/superset-ui-core/test/dimension
petrpan-code/apache/superset/superset-frontend/packages/superset-ui-core/test/dimension/svg/getBBoxCeil.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 getBBoxCeil from '../../../src/dimension/svg/getBBoxCeil'; import createTextNode from '../../../src/dimension/svg/createTextNode'; describe('getBBoxCeil(node, defaultDimension)', () => { describe('returns default dimension if getBBox() is not available', () => { it('returns default value for default dimension', () => { expect(getBBoxCeil(createTextNode())).toEqual({ height: 20, width: 100, }); }); it('return specified value if specified', () => { expect( getBBoxCeil(createTextNode(), { height: 30, width: 400, }), ).toEqual({ height: 30, width: 400, }); }); }); describe('returns ceiling of the svg element', () => { it('converts to ceiling if value is not integer', () => { expect( getBBoxCeil(createTextNode(), { height: 10.6, width: 11.1 }), ).toEqual({ height: 11, width: 12, }); }); it('does nothing if value is integer', () => { expect(getBBoxCeil(createTextNode())).toEqual({ height: 20, width: 100, }); }); }); });
5,527
0
petrpan-code/apache/superset/superset-frontend/packages/superset-ui-core/test/dimension
petrpan-code/apache/superset/superset-frontend/packages/superset-ui-core/test/dimension/svg/updateTextNode.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. */ // do not use react-testing-library in plugins /* eslint-disable jest-dom/prefer-to-have-attribute */ /* eslint-disable jest-dom/prefer-to-have-text-content */ /* eslint-disable jest-dom/prefer-to-have-style */ import updateTextNode from '../../../src/dimension/svg/updateTextNode'; import createTextNode from '../../../src/dimension/svg/createTextNode'; describe('updateTextNode(node, options)', () => { it('handles empty options', () => { const node = updateTextNode(createTextNode()); expect(node.getAttribute('class')).toEqual(''); expect(node.style.font).toEqual(''); expect(node.style.fontWeight).toEqual(''); expect(node.style.fontSize).toEqual(''); expect(node.style.fontStyle).toEqual(''); expect(node.style.fontFamily).toEqual(''); expect(node.style.letterSpacing).toEqual(''); expect(node.textContent).toEqual(''); }); it('handles setting class', () => { const node = updateTextNode(createTextNode(), { className: 'abc' }); expect(node.getAttribute('class')).toEqual('abc'); expect(node.style.font).toEqual(''); expect(node.style.fontWeight).toEqual(''); expect(node.style.fontSize).toEqual(''); expect(node.style.fontStyle).toEqual(''); expect(node.style.fontFamily).toEqual(''); expect(node.style.letterSpacing).toEqual(''); expect(node.textContent).toEqual(''); }); it('handles setting text', () => { const node = updateTextNode(createTextNode(), { text: 'abc' }); expect(node.getAttribute('class')).toEqual(''); expect(node.style.font).toEqual(''); expect(node.style.fontWeight).toEqual(''); expect(node.style.fontSize).toEqual(''); expect(node.style.fontStyle).toEqual(''); expect(node.style.fontFamily).toEqual(''); expect(node.style.letterSpacing).toEqual(''); expect(node.textContent).toEqual('abc'); }); it('handles setting font', () => { const node = updateTextNode(createTextNode(), { style: { font: 'italic 30px Lobster 700', }, }); expect(node.getAttribute('class')).toEqual(''); expect(node.style.fontWeight).toEqual('700'); expect(node.style.fontSize).toEqual('30px'); expect(node.style.fontStyle).toEqual('italic'); expect(node.style.fontFamily).toEqual('Lobster'); expect(node.style.letterSpacing).toEqual(''); expect(node.textContent).toEqual(''); }); it('handles setting specific font style', () => { const node = updateTextNode(createTextNode(), { style: { fontFamily: 'Lobster', fontStyle: 'italic', fontWeight: '700', fontSize: '30px', letterSpacing: 1.1, }, }); expect(node.getAttribute('class')).toEqual(''); expect(node.style.fontWeight).toEqual('700'); expect(node.style.fontSize).toEqual('30px'); expect(node.style.fontStyle).toEqual('italic'); expect(node.style.fontFamily).toEqual('Lobster'); expect(node.style.letterSpacing).toEqual('1.1'); expect(node.textContent).toEqual(''); }); }); /* eslint-enable jest-dom/prefer-to-have-attribute */ /* eslint-enable jest-dom/prefer-to-have-text-content */ /* eslint-enable jest-dom/prefer-to-have-style */
5,528
0
petrpan-code/apache/superset/superset-frontend/packages/superset-ui-core/test
petrpan-code/apache/superset/superset-frontend/packages/superset-ui-core/test/dynamic-plugins/shared-modules.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 { defineSharedModule, defineSharedModules, reset } from '../../src'; describe('shared modules', () => { afterEach(() => { reset(); }); it('assigns to window', async () => { const fakeModule = { foo: 'bar' }; const fetchModule = jest.fn().mockResolvedValue(fakeModule); await defineSharedModule('test-module', fetchModule); expect((window as any)['__superset__/test-module']).toStrictEqual( fakeModule, ); }); it('resolves to the same reference every time', async () => { const fakeModule = { foo: 'bar' }; const fetchModule = jest.fn().mockResolvedValue(fakeModule); const result1 = await defineSharedModule('test-module', fetchModule); const result2 = await defineSharedModule('test-module', fetchModule); expect(result1).toStrictEqual(fakeModule); expect(result2).toStrictEqual(fakeModule); }); it('does not redefine unnecessarily', async () => { const fakeModule = { foo: 'bar' }; const fetchModule = jest.fn().mockResolvedValue(fakeModule); const duplicateFetchModule = jest.fn().mockResolvedValue(fakeModule); const result1 = await defineSharedModule('test-module', fetchModule); const result2 = await defineSharedModule( 'test-module', duplicateFetchModule, ); expect(result1).toStrictEqual(fakeModule); expect(result2).toStrictEqual(fakeModule); expect(duplicateFetchModule).not.toHaveBeenCalled(); }); it('deduplicates in-progress definitions', async () => { const fakeModule = { foo: 'bar' }; // get a promise that actually takes a moment; const fetchModule = jest .fn() .mockImplementation(() => Promise.resolve(setImmediate).then(() => fakeModule), ); const promise1 = defineSharedModule('test-module', fetchModule); const promise2 = defineSharedModule('test-module', fetchModule); const [result1, result2] = await Promise.all([promise1, promise2]); expect(fetchModule).toHaveBeenCalledTimes(1); expect(result1).toStrictEqual(result2); }); it('shares a map of modules', async () => { const foo = { foo: 'bar' }; const fizz = { fizz: 'buzz' }; await defineSharedModules({ 'module-foo': async () => foo, 'module-fizz': async () => fizz, }); expect((window as any)['__superset__/module-foo']).toEqual(foo); expect((window as any)['__superset__/module-fizz']).toEqual(fizz); }); });
5,529
0
petrpan-code/apache/superset/superset-frontend/packages/superset-ui-core/test
petrpan-code/apache/superset/superset-frontend/packages/superset-ui-core/test/math-expression/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 { evalExpression, isValidExpression } from '@superset-ui/core'; test('evalExpression evaluates constants correctly', () => { expect(evalExpression('0', 10)).toEqual(0); expect(evalExpression('0.123456', 0)).toEqual(0.123456); expect(evalExpression('789', 100)).toEqual(789); }); test('evalExpression evaluates infinities correctly', () => { const formula = 'x/0'; expect(evalExpression(formula, 1)).toEqual(Infinity); expect(evalExpression(formula, -1)).toEqual(-Infinity); }); test('evalExpression evaluates powers correctly', () => { const formula = '2^(x/2)*100'; expect(evalExpression(formula, 0)).toEqual(100); expect(evalExpression(formula, 1)).toEqual(141.4213562373095); expect(evalExpression(formula, 2)).toEqual(200); }); test('evalExpression ignores whitespace and variables on left hand side of equals sign', () => { expect(evalExpression('y=x+1', 1)).toEqual(2); expect(evalExpression('y = x - 1', 1)).toEqual(0); }); test('evalExpression evaluates custom operators correctly', () => { const equalsExpression = 'x == 10'; expect(evalExpression(equalsExpression, 5)).toEqual(0); expect(evalExpression(equalsExpression, 10)).toEqual(1); expect(evalExpression(equalsExpression, 10.1)).toEqual(0); const closedRange = '(x > 0) and (x < 10)'; expect(evalExpression(closedRange, 0)).toEqual(0); expect(evalExpression(closedRange, 5)).toEqual(1); expect(evalExpression(closedRange, 10)).toEqual(0); const openRange = '(x >= 0) and (x <= 10)'; expect(evalExpression(openRange, -0.1)).toEqual(0); expect(evalExpression(openRange, 0)).toEqual(1); expect(evalExpression(openRange, 5)).toEqual(1); expect(evalExpression(openRange, 10)).toEqual(1); expect(evalExpression(openRange, 10.1)).toEqual(0); const orRange = '(x < 0) or (x > 10)'; expect(evalExpression(orRange, -0.1)).toEqual(1); expect(evalExpression(orRange, 0)).toEqual(0); expect(evalExpression(orRange, 5)).toEqual(0); expect(evalExpression(orRange, 10)).toEqual(0); expect(evalExpression(orRange, 10.1)).toEqual(1); // other less used operators expect(evalExpression('5 & x', 3)).toEqual(1); expect(evalExpression('5 | x', 3)).toEqual(7); expect(evalExpression('5 xor x', 2)).toEqual(7); // complex combinations const complexExpression = '20.51*(x<1577836800000)+20.2((x<15805152000000)&(x>=1577836800000))'; expect(evalExpression(complexExpression, 0)).toEqual(20.51); expect(evalExpression(complexExpression, 1000)).toEqual(20.51); expect(evalExpression(complexExpression, 1577836800000)).toEqual(20.2); expect(evalExpression(complexExpression, 15805151999999)).toEqual(20.2); expect(evalExpression(complexExpression, 15805152000000)).toEqual(0); expect(evalExpression(complexExpression, 15805159000000)).toEqual(0); }); test('isValidExpression correctly identifies invalid formulas', () => { expect(isValidExpression('foobar')).toEqual(false); expect(isValidExpression('x+')).toEqual(false); expect(isValidExpression('z+1')).toEqual(false); }); test('isValidExpression correctly identifies valid formulas', () => { expect(isValidExpression('x')).toEqual(true); expect(isValidExpression('x+1')).toEqual(true); expect(isValidExpression('y=x-1')).toEqual(true); expect(isValidExpression('y = x - 1')).toEqual(true); expect(isValidExpression('y = (x < 100 and x > 0) * 100')).toEqual(true); });
5,530
0
petrpan-code/apache/superset/superset-frontend/packages/superset-ui-core/test
petrpan-code/apache/superset/superset-frontend/packages/superset-ui-core/test/models/ExtensibleFunction.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 { ExtensibleFunction } from '@superset-ui/core'; describe('ExtensibleFunction', () => { interface Func1 { (): number; } class Func1 extends ExtensibleFunction { constructor(x: unknown) { super(() => x); // closure } } interface Func2 { (): number; } class Func2 extends ExtensibleFunction { x: unknown; constructor(x: unknown) { super(() => this.x); // arrow function, refer to its own field this.x = x; } // eslint-disable-next-line class-methods-use-this hi() { return 'hi'; } } class Func3 extends ExtensibleFunction { x: unknown; constructor(x: unknown) { // @ts-ignore super(function customName() { // @ts-ignore return customName.x; }); // named function this.x = x; } } it('its subclass is an instance of Function', () => { expect(Func1).toBeInstanceOf(Function); expect(Func2).toBeInstanceOf(Function); expect(Func3).toBeInstanceOf(Function); }); const func1 = new Func1(100); const func2 = new Func2(100); const func3 = new Func3(100); it('an instance of its subclass is executable like regular function', () => { expect(func1()).toEqual(100); expect(func2()).toEqual(100); }); it('its subclass behaves like regular class with its own fields and functions', () => { expect(func2.x).toEqual(100); expect(func2.hi()).toEqual('hi'); }); it('its subclass can set name by passing named function to its constructor', () => { expect(func3.name).toEqual('customName'); }); });
5,531
0
petrpan-code/apache/superset/superset-frontend/packages/superset-ui-core/test
petrpan-code/apache/superset/superset-frontend/packages/superset-ui-core/test/models/Plugin.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 { Plugin } from '@superset-ui/core'; describe('Plugin', () => { it('exists', () => { expect(Plugin).toBeDefined(); }); describe('new Plugin()', () => { it('creates a new plugin', () => { const plugin = new Plugin(); expect(plugin).toBeInstanceOf(Plugin); }); }); describe('.configure(config, replace)', () => { it('extends the default config with given config when replace is not set or false', () => { const plugin = new Plugin(); plugin.configure({ key: 'abc', foo: 'bar' }); plugin.configure({ key: 'def' }); expect(plugin.config).toEqual({ key: 'def', foo: 'bar' }); }); it('replaces the default config with given config when replace is true', () => { const plugin = new Plugin(); plugin.configure({ key: 'abc', foo: 'bar' }); plugin.configure({ key: 'def' }, true); expect(plugin.config).toEqual({ key: 'def' }); }); it('returns the plugin itself', () => { const plugin = new Plugin(); expect(plugin.configure({ key: 'abc' })).toBe(plugin); }); }); describe('.resetConfig()', () => { it('resets config back to default', () => { const plugin = new Plugin(); plugin.configure({ key: 'abc', foo: 'bar' }); plugin.resetConfig(); expect(plugin.config).toEqual({}); }); it('returns the plugin itself', () => { const plugin = new Plugin(); expect(plugin.resetConfig()).toBe(plugin); }); }); describe('.register()', () => { it('returns the plugin itself', () => { const plugin = new Plugin(); expect(plugin.register()).toBe(plugin); }); }); describe('.unregister()', () => { it('returns the plugin itself', () => { const plugin = new Plugin(); expect(plugin.unregister()).toBe(plugin); }); }); });
5,532
0
petrpan-code/apache/superset/superset-frontend/packages/superset-ui-core/test
petrpan-code/apache/superset/superset-frontend/packages/superset-ui-core/test/models/Preset.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 { Plugin, Preset } from '@superset-ui/core'; describe('Preset', () => { it('exists', () => { expect(Preset).toBeDefined(); }); describe('new Preset()', () => { it('creates new preset', () => { const preset = new Preset(); expect(preset).toBeInstanceOf(Preset); }); }); describe('.register()', () => { it('register all listed presets then plugins', () => { const values: number[] = []; class Plugin1 extends Plugin { register() { values.push(1); return this; } } class Plugin2 extends Plugin { register() { values.push(2); return this; } } class Plugin3 extends Plugin { register() { values.push(3); return this; } } class Plugin4 extends Plugin { register() { const { key } = this.config; values.push(key as number); return this; } } const preset1 = new Preset({ plugins: [new Plugin1()], }); const preset2 = new Preset({ plugins: [new Plugin2()], }); const preset3 = new Preset({ presets: [preset1, preset2], plugins: [new Plugin3(), new Plugin4().configure({ key: 9 })], }); preset3.register(); expect(values).toEqual([1, 2, 3, 9]); }); it('returns itself', () => { const preset = new Preset(); expect(preset.register()).toBe(preset); }); }); });
5,533
0
petrpan-code/apache/superset/superset-frontend/packages/superset-ui-core/test
petrpan-code/apache/superset/superset-frontend/packages/superset-ui-core/test/models/Registry.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. */ /* eslint no-console: 0 */ import mockConsole from 'jest-mock-console'; import { Registry, OverwritePolicy } from '@superset-ui/core'; const loader = () => 'testValue'; describe('Registry', () => { it('exists', () => { expect(Registry !== undefined).toBe(true); }); describe('new Registry(config)', () => { it('can create a new registry when config.name is not given', () => { const registry = new Registry(); expect(registry).toBeInstanceOf(Registry); }); it('can create a new registry when config.name is given', () => { const registry = new Registry({ name: 'abc' }); expect(registry).toBeInstanceOf(Registry); expect(registry.name).toBe('abc'); }); }); describe('.clear()', () => { it('clears all registered items', () => { const registry = new Registry(); registry.registerValue('a', 'testValue'); registry.clear(); expect(Object.keys(registry.items)).toHaveLength(0); expect(Object.keys(registry.promises)).toHaveLength(0); }); it('returns the registry itself', () => { const registry = new Registry(); expect(registry.clear()).toBe(registry); }); }); describe('.has(key)', () => { it('returns true if an item with the given key exists', () => { const registry = new Registry(); registry.registerValue('a', 'testValue'); expect(registry.has('a')).toBe(true); registry.registerLoader('b', () => 'testValue2'); expect(registry.has('b')).toBe(true); }); it('returns false if an item with the given key does not exist', () => { const registry = new Registry(); expect(registry.has('a')).toBe(false); }); }); describe('.registerValue(key, value)', () => { it('registers the given value with the given key', () => { const registry = new Registry(); registry.registerValue('a', 'testValue'); expect(registry.has('a')).toBe(true); expect(registry.get('a')).toBe('testValue'); }); it('does not overwrite if value is exactly the same', () => { const registry = new Registry(); const value = { a: 1 }; registry.registerValue('a', value); const promise1 = registry.getAsPromise('a'); registry.registerValue('a', value); const promise2 = registry.getAsPromise('a'); expect(promise1).toBe(promise2); registry.registerValue('a', { a: 1 }); const promise3 = registry.getAsPromise('a'); expect(promise1).not.toBe(promise3); }); it('overwrites item with loader', () => { const registry = new Registry(); registry.registerLoader('a', () => 'ironman'); expect(registry.get('a')).toBe('ironman'); registry.registerValue('a', 'hulk'); expect(registry.get('a')).toBe('hulk'); }); it('returns the registry itself', () => { const registry = new Registry(); expect(registry.registerValue('a', 'testValue')).toBe(registry); }); }); describe('.registerLoader(key, loader)', () => { it('registers the given loader with the given key', () => { const registry = new Registry(); registry.registerLoader('a', () => 'testValue'); expect(registry.has('a')).toBe(true); expect(registry.get('a')).toBe('testValue'); }); it('does not overwrite if loader is exactly the same', () => { const registry = new Registry(); registry.registerLoader('a', loader); const promise1 = registry.getAsPromise('a'); registry.registerLoader('a', loader); const promise2 = registry.getAsPromise('a'); expect(promise1).toBe(promise2); registry.registerLoader('a', () => 'testValue'); const promise3 = registry.getAsPromise('a'); expect(promise1).not.toBe(promise3); }); it('overwrites item with value', () => { const registry = new Registry(); registry.registerValue('a', 'hulk'); expect(registry.get('a')).toBe('hulk'); registry.registerLoader('a', () => 'ironman'); expect(registry.get('a')).toBe('ironman'); }); it('returns the registry itself', () => { const registry = new Registry(); expect(registry.registerLoader('a', () => 'testValue')).toBe(registry); }); }); describe('.get(key)', () => { it('given the key, returns the value if the item is a value', () => { const registry = new Registry(); registry.registerValue('a', 'testValue'); expect(registry.get('a')).toBe('testValue'); }); it('given the key, returns the result of the loader function if the item is a loader', () => { const registry = new Registry(); registry.registerLoader('b', () => 'testValue2'); expect(registry.get('b')).toBe('testValue2'); }); it('returns undefined if the item with specified key does not exist', () => { const registry = new Registry(); expect(registry.get('a')).toBeUndefined(); }); it('If the key was registered multiple times, returns the most recent item.', () => { const registry = new Registry(); registry.registerValue('a', 'testValue'); expect(registry.get('a')).toBe('testValue'); registry.registerLoader('a', () => 'newValue'); expect(registry.get('a')).toBe('newValue'); }); }); describe('.getAsPromise(key)', () => { it('given the key, returns a promise of item value if the item is a value', () => { const registry = new Registry(); registry.registerValue('a', 'testValue'); return registry .getAsPromise('a') .then(value => expect(value).toBe('testValue')); }); it('given the key, returns a promise of result of the loader function if the item is a loader', () => { const registry = new Registry(); registry.registerLoader('a', () => 'testValue'); return registry .getAsPromise('a') .then(value => expect(value).toBe('testValue')); }); it('returns same promise object for the same key unless user re-registers new value with the key.', () => { const registry = new Registry(); registry.registerLoader('a', () => 'testValue'); const promise1 = registry.getAsPromise('a'); const promise2 = registry.getAsPromise('a'); expect(promise1).toBe(promise2); }); it('returns a rejected promise if the item with specified key does not exist', () => { const registry = new Registry(); return registry.getAsPromise('a').then(null, (err: Error) => { expect(err.toString()).toEqual( 'Error: Item with key "a" is not registered.', ); }); }); it('If the key was registered multiple times, returns a promise of the most recent item.', async () => { const registry = new Registry(); registry.registerValue('a', 'testValue'); expect(await registry.getAsPromise('a')).toBe('testValue'); registry.registerLoader('a', () => 'newValue'); expect(await registry.getAsPromise('a')).toBe('newValue'); }); }); describe('.getMap()', () => { it('returns key-value map as plain object', () => { const registry = new Registry(); registry.registerValue('a', 'cat'); registry.registerLoader('b', () => 'dog'); expect(registry.getMap()).toEqual({ a: 'cat', b: 'dog', }); }); }); describe('.getMapAsPromise()', () => { it('returns a promise of key-value map', () => { const registry = new Registry(); registry.registerValue('a', 'test1'); registry.registerLoader('b', () => 'test2'); registry.registerLoader('c', () => Promise.resolve('test3')); return registry.getMapAsPromise().then(map => expect(map).toEqual({ a: 'test1', b: 'test2', c: 'test3', }), ); }); }); describe('.keys()', () => { it('returns an array of keys', () => { const registry = new Registry(); registry.registerValue('a', 'testValue'); registry.registerLoader('b', () => 'test2'); expect(registry.keys()).toEqual(['a', 'b']); }); }); describe('.values()', () => { it('returns an array of values', () => { const registry = new Registry(); registry.registerValue('a', 'test1'); registry.registerLoader('b', () => 'test2'); expect(registry.values()).toEqual(['test1', 'test2']); }); }); describe('.valuesAsPromise()', () => { it('returns a Promise of an array { key, value }', () => { const registry = new Registry(); registry.registerValue('a', 'test1'); registry.registerLoader('b', () => 'test2'); registry.registerLoader('c', () => Promise.resolve('test3')); return registry .valuesAsPromise() .then(entries => expect(entries).toEqual(['test1', 'test2', 'test3'])); }); }); describe('.entries()', () => { it('returns an array of { key, value }', () => { const registry = new Registry(); registry.registerValue('a', 'test1'); registry.registerLoader('b', () => 'test2'); expect(registry.entries()).toEqual([ { key: 'a', value: 'test1' }, { key: 'b', value: 'test2' }, ]); }); }); describe('.entriesAsPromise()', () => { it('returns a Promise of an array { key, value }', () => { const registry = new Registry(); registry.registerValue('a', 'test1'); registry.registerLoader('b', () => 'test2'); registry.registerLoader('c', () => Promise.resolve('test3')); return registry.entriesAsPromise().then(entries => expect(entries).toEqual([ { key: 'a', value: 'test1' }, { key: 'b', value: 'test2' }, { key: 'c', value: 'test3' }, ]), ); }); }); describe('.remove(key)', () => { it('removes the item with given key', () => { const registry = new Registry(); registry.registerValue('a', 'testValue'); registry.remove('a'); expect(registry.get('a')).toBeUndefined(); }); it('does not throw error if the key does not exist', () => { const registry = new Registry(); expect(() => registry.remove('a')).not.toThrow(); }); it('returns itself', () => { const registry = new Registry(); registry.registerValue('a', 'testValue'); expect(registry.remove('a')).toBe(registry); }); }); describe('config.overwritePolicy', () => { describe('=ALLOW', () => { describe('.registerValue(key, value)', () => { it('registers normally', () => { const restoreConsole = mockConsole(); const registry = new Registry(); registry.registerValue('a', 'testValue'); expect(() => registry.registerValue('a', 'testValue2')).not.toThrow(); expect(registry.get('a')).toEqual('testValue2'); expect(console.warn).not.toHaveBeenCalled(); restoreConsole(); }); }); describe('.registerLoader(key, loader)', () => { it('registers normally', () => { const restoreConsole = mockConsole(); const registry = new Registry(); registry.registerLoader('a', () => 'testValue'); expect(() => registry.registerLoader('a', () => 'testValue2'), ).not.toThrow(); expect(registry.get('a')).toEqual('testValue2'); expect(console.warn).not.toHaveBeenCalled(); restoreConsole(); }); }); }); describe('=WARN', () => { describe('.registerValue(key, value)', () => { it('warns when overwrite', () => { const restoreConsole = mockConsole(); const registry = new Registry({ overwritePolicy: OverwritePolicy.WARN, }); registry.registerValue('a', 'testValue'); expect(() => registry.registerValue('a', 'testValue2')).not.toThrow(); expect(registry.get('a')).toEqual('testValue2'); expect(console.warn).toHaveBeenCalled(); restoreConsole(); }); }); describe('.registerLoader(key, loader)', () => { it('warns when overwrite', () => { const restoreConsole = mockConsole(); const registry = new Registry({ overwritePolicy: OverwritePolicy.WARN, }); registry.registerLoader('a', () => 'testValue'); expect(() => registry.registerLoader('a', () => 'testValue2'), ).not.toThrow(); expect(registry.get('a')).toEqual('testValue2'); expect(console.warn).toHaveBeenCalled(); restoreConsole(); }); }); }); describe('=PROHIBIT', () => { describe('.registerValue(key, value)', () => { it('throws error when overwrite', () => { const registry = new Registry({ overwritePolicy: OverwritePolicy.PROHIBIT, }); registry.registerValue('a', 'testValue'); expect(() => registry.registerValue('a', 'testValue2')).toThrow(); }); }); describe('.registerLoader(key, loader)', () => { it('warns when overwrite', () => { const registry = new Registry({ overwritePolicy: OverwritePolicy.PROHIBIT, }); registry.registerLoader('a', () => 'testValue'); expect(() => registry.registerLoader('a', () => 'testValue2'), ).toThrow(); }); }); }); }); describe('listeners', () => { let registry = new Registry(); let listener = jest.fn(); beforeEach(() => { registry = new Registry(); listener = jest.fn(); registry.addListener(listener); }); it('calls the listener when a value is registered', () => { registry.registerValue('foo', 'bar'); expect(listener).toBeCalledWith(['foo']); }); it('calls the listener when a loader is registered', () => { registry.registerLoader('foo', () => 'bar'); expect(listener).toBeCalledWith(['foo']); }); it('calls the listener when a value is overridden', () => { registry.registerValue('foo', 'bar'); listener.mockClear(); registry.registerValue('foo', 'baz'); expect(listener).toBeCalledWith(['foo']); }); it('calls the listener when a value is removed', () => { registry.registerValue('foo', 'bar'); listener.mockClear(); registry.remove('foo'); expect(listener).toBeCalledWith(['foo']); }); it('does not call the listener when a value is not actually removed', () => { registry.remove('foo'); expect(listener).not.toBeCalled(); }); it('calls the listener when registry is cleared', () => { registry.registerValue('foo', 'bar'); registry.registerLoader('fluz', () => 'baz'); listener.mockClear(); registry.clear(); expect(listener).toBeCalledWith(['foo', 'fluz']); }); it('removes listeners correctly', () => { registry.removeListener(listener); registry.registerValue('foo', 'bar'); expect(listener).not.toBeCalled(); }); describe('with a broken listener', () => { let restoreConsole: any; beforeEach(() => { restoreConsole = mockConsole(); }); afterEach(() => { restoreConsole(); }); it('keeps working', () => { const errorListener = jest.fn().mockImplementation(() => { throw new Error('test error'); }); const lastListener = jest.fn(); registry.addListener(errorListener); registry.addListener(lastListener); registry.registerValue('foo', 'bar'); expect(listener).toBeCalledWith(['foo']); expect(errorListener).toBeCalledWith(['foo']); expect(lastListener).toBeCalledWith(['foo']); expect(console.error).toBeCalled(); }); }); }); });
5,534
0
petrpan-code/apache/superset/superset-frontend/packages/superset-ui-core/test
petrpan-code/apache/superset/superset-frontend/packages/superset-ui-core/test/models/RegistryWithDefaultKey.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 { Registry, RegistryWithDefaultKey } from '@superset-ui/core'; describe('RegistryWithDefaultKey', () => { let registry: RegistryWithDefaultKey<number>; beforeEach(() => { registry = new RegistryWithDefaultKey(); }); it('exists', () => { expect(RegistryWithDefaultKey).toBeDefined(); }); describe('new RegistryWithDefaultKey(config)', () => { it('returns a class that extends from Registry', () => { expect(registry).toBeInstanceOf(Registry); }); }); describe('.clear()', () => { it('also resets default key', () => { registry.setDefaultKey('abc'); registry.clear(); expect(registry.getDefaultKey()).toBeUndefined(); }); it('returns itself', () => { expect(registry.clear()).toBe(registry); }); }); describe('.get()', () => { beforeEach(() => { registry .registerValue('abc', 100) .registerValue('def', 200) .setDefaultKey('abc'); }); it('.get() returns value from default key', () => { expect(registry.get()).toEqual(100); }); it('.get(key) returns value from specified key', () => { expect(registry.get('def')).toEqual(200); }); it('returns undefined if no key was given and there is no default key', () => { registry.clearDefaultKey(); expect(registry.get()).toBeUndefined(); }); }); describe('.getDefaultKey()', () => { it('returns defaultKey', () => { registry.setDefaultKey('abc'); expect(registry.getDefaultKey()).toEqual('abc'); }); }); describe('.setDefaultKey(key)', () => { it('set the default key', () => { registry.setDefaultKey('abc'); expect(registry.defaultKey).toEqual('abc'); }); it('returns itself', () => { expect(registry.setDefaultKey('ghi')).toBe(registry); }); }); describe('.clearDefaultKey()', () => { it('set the default key to undefined', () => { registry.clearDefaultKey(); expect(registry.defaultKey).toBeUndefined(); }); it('returns itself', () => { expect(registry.clearDefaultKey()).toBe(registry); }); }); describe('config.defaultKey', () => { describe('when not set', () => { it(`After creation, default key is undefined`, () => { expect(registry.defaultKey).toBeUndefined(); }); it('.clear() reset defaultKey to undefined', () => { registry.setDefaultKey('abc'); registry.clear(); expect(registry.getDefaultKey()).toBeUndefined(); }); }); describe('when config.initialDefaultKey is set', () => { const registry2 = new RegistryWithDefaultKey({ initialDefaultKey: 'def', }); it(`After creation, default key is undefined`, () => { expect(registry2.defaultKey).toEqual('def'); }); it('.clear() reset defaultKey to this config.defaultKey', () => { registry2.setDefaultKey('abc'); registry2.clear(); expect(registry2.getDefaultKey()).toEqual('def'); }); }); }); describe('config.setFirstItemAsDefault', () => { describe('when true', () => { const registry2 = new RegistryWithDefaultKey({ setFirstItemAsDefault: true, }); beforeEach(() => { registry2.clear(); }); describe('.registerValue(key, value)', () => { it('sets the default key to this key if default key is not set', () => { registry2.registerValue('abc', 100); expect(registry2.getDefaultKey()).toEqual('abc'); }); it('does not modify the default key if already set', () => { registry2.setDefaultKey('def').registerValue('abc', 100); expect(registry2.getDefaultKey()).toEqual('def'); }); it('returns itself', () => { expect(registry2.registerValue('ghi', 300)).toBe(registry2); }); }); describe('.registerLoader(key, loader)', () => { it('sets the default key to this key if default key is not set', () => { registry2.registerLoader('abc', () => 100); expect(registry2.getDefaultKey()).toEqual('abc'); }); it('does not modify the default key if already set', () => { registry2.setDefaultKey('def').registerLoader('abc', () => 100); expect(registry2.getDefaultKey()).toEqual('def'); }); it('returns itself', () => { expect(registry2.registerLoader('ghi', () => 300)).toBe(registry2); }); }); }); describe('when false', () => { const registry2 = new RegistryWithDefaultKey({ setFirstItemAsDefault: false, }); beforeEach(() => { registry2.clear(); }); describe('.registerValue(key, value)', () => { it('does not modify default key', () => { registry2.registerValue('abc', 100); expect(registry2.defaultKey).toBeUndefined(); registry2.setDefaultKey('def'); registry2.registerValue('ghi', 300); expect(registry2.defaultKey).toEqual('def'); }); it('returns itself', () => { expect(registry2.registerValue('ghi', 300)).toBe(registry2); }); }); describe('.registerLoader(key, loader)', () => { it('does not modify default key', () => { registry2.registerValue('abc', () => 100); expect(registry2.defaultKey).toBeUndefined(); registry2.setDefaultKey('def'); registry2.registerValue('ghi', () => 300); expect(registry2.defaultKey).toEqual('def'); }); it('returns itself', () => { expect(registry2.registerLoader('ghi', () => 300)).toBe(registry2); }); }); }); }); });
5,535
0
petrpan-code/apache/superset/superset-frontend/packages/superset-ui-core/test
petrpan-code/apache/superset/superset-frontend/packages/superset-ui-core/test/models/TypedRegistry.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 { TypedRegistry } from '@superset-ui/core'; describe('TypedRegistry', () => { it('gets a value', () => { const reg = new TypedRegistry({ foo: 'bar' }); expect(reg.get('foo')).toBe('bar'); }); it('sets a value', () => { const reg = new TypedRegistry({ foo: 'bar' }); reg.set('foo', 'blah'); expect(reg.get('foo')).toBe('blah'); }); });
5,536
0
petrpan-code/apache/superset/superset-frontend/packages/superset-ui-core/test
petrpan-code/apache/superset/superset-frontend/packages/superset-ui-core/test/number-format/NumberFormatter.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 { NumberFormatter } from '@superset-ui/core'; describe('NumberFormatter', () => { describe('new NumberFormatter(config)', () => { it('requires config.id', () => { expect( () => // @ts-ignore new NumberFormatter({ formatFunc: () => '', }), ).toThrow(); }); it('requires config.formatFunc', () => { expect( () => // @ts-ignore new NumberFormatter({ id: 'my_format', }), ).toThrow(); }); }); describe('formatter is also a format function itself', () => { const formatter = new NumberFormatter({ id: 'fixed_3', formatFunc: value => value.toFixed(3), }); it('returns formatted value', () => { expect(formatter(12345.67)).toEqual('12345.670'); }); it('formatter(value) is the same with formatter.format(value)', () => { const value = 12345.67; expect(formatter(value)).toEqual(formatter.format(value)); }); }); describe('.format(value)', () => { const formatter = new NumberFormatter({ id: 'fixed_3', formatFunc: value => value.toFixed(3), }); it('handles null', () => { expect(formatter.format(null)).toEqual('null'); }); it('handles undefined', () => { expect(formatter.format(undefined)).toEqual('undefined'); }); it('handles NaN', () => { expect(formatter.format(NaN)).toEqual('NaN'); }); it('handles positive and negative infinity', () => { expect(formatter.format(Number.POSITIVE_INFINITY)).toEqual('∞'); expect(formatter.format(Number.NEGATIVE_INFINITY)).toEqual('-∞'); }); it('otherwise returns formatted value', () => { expect(formatter.format(12345.67)).toEqual('12345.670'); }); }); describe('.preview(value)', () => { const formatter = new NumberFormatter({ id: 'fixed_2', formatFunc: value => value.toFixed(2), }); it('returns string comparing value before and after formatting', () => { expect(formatter.preview(100)).toEqual('100 => 100.00'); }); it('uses the default preview value if not specified', () => { expect(formatter.preview()).toEqual('12345.432 => 12345.43'); }); }); });
5,537
0
petrpan-code/apache/superset/superset-frontend/packages/superset-ui-core/test
petrpan-code/apache/superset/superset-frontend/packages/superset-ui-core/test/number-format/NumberFormatterRegistry.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 { NumberFormats, NumberFormatter, NumberFormatterRegistry, } from '@superset-ui/core'; describe('NumberFormatterRegistry', () => { let registry: NumberFormatterRegistry; beforeEach(() => { registry = new NumberFormatterRegistry(); }); it('has SMART_NUMBER as default formatter out of the box', () => { expect(registry.getDefaultKey()).toBe(NumberFormats.SMART_NUMBER); }); describe('.get(format)', () => { it('creates and returns a new formatter if does not exist', () => { const formatter = registry.get('.2f'); expect(formatter).toBeInstanceOf(NumberFormatter); expect(formatter.format(100)).toEqual('100.00'); }); it('returns an existing formatter if already exists', () => { const formatter = registry.get('.2f'); const formatter2 = registry.get('.2f'); expect(formatter).toBe(formatter2); }); it('falls back to default format if format is not specified', () => { registry.setDefaultKey('.1f'); const formatter = registry.get(); expect(formatter.format(100)).toEqual('100.0'); }); it('falls back to default format if format is null', () => { registry.setDefaultKey('.1f'); // @ts-ignore const formatter = registry.get(null); expect(formatter.format(100)).toEqual('100.0'); }); it('falls back to default format if format is undefined', () => { registry.setDefaultKey('.1f'); const formatter = registry.get(undefined); expect(formatter.format(100)).toEqual('100.0'); }); it('falls back to default format if format is empty string', () => { registry.setDefaultKey('.1f'); const formatter = registry.get(''); expect(formatter.format(100)).toEqual('100.0'); }); it('removes leading and trailing spaces from format', () => { const formatter = registry.get(' .2f'); expect(formatter).toBeInstanceOf(NumberFormatter); expect(formatter.format(100)).toEqual('100.00'); const formatter2 = registry.get('.2f '); expect(formatter2).toBeInstanceOf(NumberFormatter); expect(formatter2.format(100)).toEqual('100.00'); const formatter3 = registry.get(' .2f '); expect(formatter3).toBeInstanceOf(NumberFormatter); expect(formatter3.format(100)).toEqual('100.00'); }); }); describe('.format(format, value)', () => { it('return the value with the specified format', () => { expect(registry.format('.2f', 100)).toEqual('100.00'); expect(registry.format(',d', 100)).toEqual('100'); }); it('falls back to the default formatter if the format is undefined', () => { expect(registry.format(undefined, 1000)).toEqual('1k'); }); }); });
5,538
0
petrpan-code/apache/superset/superset-frontend/packages/superset-ui-core/test
petrpan-code/apache/superset/superset-frontend/packages/superset-ui-core/test/number-format/NumberFormatterRegistrySingleton.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 { NumberFormatterRegistry, getNumberFormatterRegistry, setD3Format, getNumberFormatter, formatNumber, } from '@superset-ui/core'; describe('NumberFormatterRegistrySingleton', () => { describe('getNumberFormatterRegistry()', () => { it('returns a NumberFormatterRegistry', () => { expect(getNumberFormatterRegistry()).toBeInstanceOf( NumberFormatterRegistry, ); }); }); describe('getNumberFormatter(format)', () => { it('returns a format function', () => { const format = getNumberFormatter('.3s'); expect(format(12345)).toEqual('12.3k'); }); it('returns a format function even given invalid format', () => { const format = getNumberFormatter('xkcd'); expect(format(12345)).toEqual('12345 (Invalid format: xkcd)'); }); it('falls back to default format if format is not specified', () => { const formatter = getNumberFormatter(); expect(formatter.format(100)).toEqual('100'); }); }); describe('formatNumber(format, value)', () => { it('format the given number using the specified format', () => { const output = formatNumber('.3s', 12345); expect(output).toEqual('12.3k'); }); it('falls back to the default formatter if the format is undefined', () => { expect(formatNumber(undefined, 1000)).toEqual('1k'); }); }); describe('setD3Format()', () => { it('sets a specific FormatLocaleDefinition', () => { setD3Format({ decimal: ';', thousands: '-', currency: ['€', ''], grouping: [2], }); const formatter = getNumberFormatter('$,.2f'); expect(formatter.format(12345.67)).toEqual('€1-23-45;67'); }); it('falls back to default value for unspecified locale format parameters', () => { setD3Format({ currency: ['€', ''], }); const formatter = getNumberFormatter('$,.1f'); expect(formatter.format(12345.67)).toEqual('€12,345.7'); }); }); });
5,539
0
petrpan-code/apache/superset/superset-frontend/packages/superset-ui-core/test
petrpan-code/apache/superset/superset-frontend/packages/superset-ui-core/test/number-format/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 { createD3NumberFormatter, createDurationFormatter, createSiAtMostNDigitFormatter, formatNumber, getNumberFormatter, getNumberFormatterRegistry, NumberFormats, NumberFormatter, PREVIEW_VALUE, } from '@superset-ui/core'; describe('index', () => { it('exports modules', () => { [ createD3NumberFormatter, createDurationFormatter, createSiAtMostNDigitFormatter, formatNumber, getNumberFormatter, getNumberFormatterRegistry, NumberFormats, NumberFormatter, PREVIEW_VALUE, ].forEach(x => expect(x).toBeDefined()); }); });
5,540
0
petrpan-code/apache/superset/superset-frontend/packages/superset-ui-core/test/number-format
petrpan-code/apache/superset/superset-frontend/packages/superset-ui-core/test/number-format/factories/createD3NumberFormatter.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 { createD3NumberFormatter } from '@superset-ui/core'; describe('createD3NumberFormatter(config)', () => { it('requires config.formatString', () => { // @ts-ignore -- intentionally pass invalid input expect(() => createD3NumberFormatter({})).toThrow(); }); describe('config.formatString', () => { it('creates a NumberFormatter with the formatString as id', () => { const formatter = createD3NumberFormatter({ formatString: '.2f' }); expect(formatter.id).toEqual('.2f'); }); describe('if it is valid d3 formatString', () => { it('uses d3.format(config.formatString) as format function', () => { const formatter = createD3NumberFormatter({ formatString: '.2f' }); expect(formatter.format(100)).toEqual('100.00'); }); }); describe('if it is invalid d3 formatString', () => { it('The format function displays error message', () => { const formatter = createD3NumberFormatter({ formatString: 'i-am-groot', }); expect(formatter.format(12345.67)).toEqual( '12345.67 (Invalid format: i-am-groot)', ); }); it('also set formatter.isInvalid to true', () => { const formatter = createD3NumberFormatter({ formatString: 'i-am-groot', }); expect(formatter.isInvalid).toEqual(true); }); }); }); describe('config.label', () => { it('set label if specified', () => { const formatter = createD3NumberFormatter({ formatString: '.2f', label: 'float formatter', }); expect(formatter.label).toEqual('float formatter'); }); }); describe('config.description', () => { it('set description if specified', () => { const formatter = createD3NumberFormatter({ description: 'lorem ipsum', formatString: '.2f', }); expect(formatter.description).toEqual('lorem ipsum'); }); }); describe('config.locale', () => { it('supports locale customization such as currency', () => { const formatter = createD3NumberFormatter({ description: 'lorem ipsum', formatString: '$.2f', locale: { decimal: '.', thousands: ',', grouping: [3], currency: ['€', ''], }, }); expect(formatter(200)).toEqual('€200.00'); }); }); });
5,541
0
petrpan-code/apache/superset/superset-frontend/packages/superset-ui-core/test/number-format
petrpan-code/apache/superset/superset-frontend/packages/superset-ui-core/test/number-format/factories/createDurationFormatter.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 { NumberFormatter, createDurationFormatter } from '@superset-ui/core'; describe('createDurationFormatter()', () => { it('creates an instance of NumberFormatter', () => { const formatter = createDurationFormatter(); expect(formatter).toBeInstanceOf(NumberFormatter); }); it('format milliseconds in human readable format with default options', () => { const formatter = createDurationFormatter(); expect(formatter(0)).toBe('0ms'); expect(formatter(1000)).toBe('1s'); expect(formatter(1337)).toBe('1.3s'); expect(formatter(10500)).toBe('10.5s'); expect(formatter(60 * 1000)).toBe('1m'); expect(formatter(90 * 1000)).toBe('1m 30s'); }); it('format seconds in human readable format with default options', () => { const formatter = createDurationFormatter({ multiplier: 1000 }); expect(formatter(0.5)).toBe('500ms'); expect(formatter(1)).toBe('1s'); expect(formatter(30)).toBe('30s'); expect(formatter(60)).toBe('1m'); expect(formatter(90)).toBe('1m 30s'); }); it('format milliseconds in human readable format with additional pretty-ms options', () => { const colonNotationFormatter = createDurationFormatter({ colonNotation: true, }); expect(colonNotationFormatter(10500)).toBe('0:10.5'); const zeroDecimalFormatter = createDurationFormatter({ secondsDecimalDigits: 0, }); expect(zeroDecimalFormatter(10500)).toBe('10s'); const subMillisecondFormatter = createDurationFormatter({ formatSubMilliseconds: true, }); expect(subMillisecondFormatter(100.40008)).toBe('100ms 400µs 80ns'); }); });
5,542
0
petrpan-code/apache/superset/superset-frontend/packages/superset-ui-core/test/number-format
petrpan-code/apache/superset/superset-frontend/packages/superset-ui-core/test/number-format/factories/createSiAtMostNDigitFormatter.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 { NumberFormatter, createSiAtMostNDigitFormatter, } from '@superset-ui/core'; describe('createSiAtMostNDigitFormatter({ n })', () => { it('creates an instance of NumberFormatter', () => { const formatter = createSiAtMostNDigitFormatter({ n: 4 }); expect(formatter).toBeInstanceOf(NumberFormatter); }); it('when n is specified, it formats number in SI format with at most n significant digits', () => { const formatter = createSiAtMostNDigitFormatter({ n: 2 }); expect(formatter(10)).toBe('10'); expect(formatter(1)).toBe('1'); expect(formatter(1)).toBe('1'); expect(formatter(10)).toBe('10'); expect(formatter(10001)).toBe('10k'); expect(formatter(10100)).toBe('10k'); expect(formatter(111000000)).toBe('110M'); expect(formatter(0.23)).toBe('230m'); expect(formatter(0)).toBe('0'); expect(formatter(-10)).toBe('-10'); expect(formatter(-1)).toBe('-1'); expect(formatter(-1)).toBe('-1'); expect(formatter(-10)).toBe('-10'); expect(formatter(-10001)).toBe('-10k'); expect(formatter(-10101)).toBe('-10k'); expect(formatter(-111000000)).toBe('-110M'); expect(formatter(-0.23)).toBe('-230m'); }); it('when n is not specified, it defaults to n=3', () => { const formatter = createSiAtMostNDigitFormatter(); expect(formatter(10)).toBe('10'); expect(formatter(1)).toBe('1'); expect(formatter(1)).toBe('1'); expect(formatter(10)).toBe('10'); expect(formatter(10001)).toBe('10.0k'); expect(formatter(10100)).toBe('10.1k'); expect(formatter(111000000)).toBe('111M'); expect(formatter(0.23)).toBe('230m'); expect(formatter(0)).toBe('0'); expect(formatter(-10)).toBe('-10'); expect(formatter(-1)).toBe('-1'); expect(formatter(-1)).toBe('-1'); expect(formatter(-10)).toBe('-10'); expect(formatter(-10001)).toBe('-10.0k'); expect(formatter(-10101)).toBe('-10.1k'); expect(formatter(-111000000)).toBe('-111M'); expect(formatter(-0.23)).toBe('-230m'); }); });
5,543
0
petrpan-code/apache/superset/superset-frontend/packages/superset-ui-core/test/number-format
petrpan-code/apache/superset/superset-frontend/packages/superset-ui-core/test/number-format/factories/createSmartNumberFormatter.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 { NumberFormatter, createSmartNumberFormatter } from '@superset-ui/core'; describe('createSmartNumberFormatter(options)', () => { it('creates an instance of NumberFormatter', () => { const formatter = createSmartNumberFormatter(); expect(formatter).toBeInstanceOf(NumberFormatter); }); describe('using default options', () => { const formatter = createSmartNumberFormatter(); it('formats 0 correctly', () => { expect(formatter(0)).toBe('0'); }); describe('for positive numbers', () => { it('formats billion with B in stead of G', () => { expect(formatter(1000000000)).toBe('1B'); expect(formatter(4560000000)).toBe('4.56B'); }); it('formats numbers that are >= 1,000 & <= 1,000,000,000 as SI format with precision 3', () => { expect(formatter(1000)).toBe('1k'); expect(formatter(10001)).toBe('10k'); expect(formatter(10100)).toBe('10.1k'); expect(formatter(111000000)).toBe('111M'); }); it('formats number that are >= 1 & < 1,000 as integer or float with at most 2 decimal points', () => { expect(formatter(1)).toBe('1'); expect(formatter(1)).toBe('1'); expect(formatter(10)).toBe('10'); expect(formatter(10)).toBe('10'); expect(formatter(10.23432)).toBe('10.23'); expect(formatter(274.2856)).toBe('274.29'); expect(formatter(999)).toBe('999'); }); it('formats numbers that are < 1 & >= 0.001 as float with at most 4 decimal points', () => { expect(formatter(0.1)).toBe('0.1'); expect(formatter(0.23)).toBe('0.23'); expect(formatter(0.699)).toBe('0.699'); expect(formatter(0.0023)).toBe('0.0023'); expect(formatter(0.002300001)).toBe('0.0023'); }); it('formats numbers that are < 0.001 & >= 0.000001 as micron', () => { expect(formatter(0.0002300001)).toBe('230µ'); expect(formatter(0.000023)).toBe('23µ'); expect(formatter(0.000001)).toBe('1µ'); }); it('formats numbers that are less than 0.000001 as SI format with precision 3', () => { expect(formatter(0.0000001)).toBe('100n'); }); }); describe('for negative numbers', () => { it('formats billion with B in stead of G', () => { expect(formatter(-1000000000)).toBe('-1B'); expect(formatter(-4560000000)).toBe('-4.56B'); }); it('formats numbers that are >= 1,000 & <= 1,000,000,000 as SI format with precision 3', () => { expect(formatter(-1000)).toBe('-1k'); expect(formatter(-10001)).toBe('-10k'); expect(formatter(-10100)).toBe('-10.1k'); expect(formatter(-111000000)).toBe('-111M'); }); it('formats number that are >= 1 & < 1,000 as integer or float with at most 2 decimal points', () => { expect(formatter(-1)).toBe('-1'); expect(formatter(-1)).toBe('-1'); expect(formatter(-10)).toBe('-10'); expect(formatter(-10)).toBe('-10'); expect(formatter(-10.23432)).toBe('-10.23'); expect(formatter(-274.2856)).toBe('-274.29'); expect(formatter(-999)).toBe('-999'); }); it('formats numbers that are < 1 & >= 0.001 as float with at most 4 decimal points', () => { expect(formatter(-0.1)).toBe('-0.1'); expect(formatter(-0.23)).toBe('-0.23'); expect(formatter(-0.699)).toBe('-0.699'); expect(formatter(-0.0023)).toBe('-0.0023'); expect(formatter(-0.002300001)).toBe('-0.0023'); }); it('formats numbers that are < 0.001 & >= 0.000001 as micron', () => { expect(formatter(-0.0002300001)).toBe('-230µ'); expect(formatter(-0.000023)).toBe('-23µ'); expect(formatter(-0.000001)).toBe('-1µ'); }); it('formats numbers that are less than 0.000001 as SI format with precision 3', () => { expect(formatter(-0.0000001)).toBe('-100n'); }); }); }); describe('when options.signed is true, it adds + for positive numbers', () => { const formatter = createSmartNumberFormatter({ signed: true }); it('formats 0 correctly', () => { expect(formatter(0)).toBe('0'); }); describe('for positive numbers', () => { it('formats billion with B in stead of G', () => { expect(formatter(1000000000)).toBe('+1B'); expect(formatter(4560000000)).toBe('+4.56B'); }); it('formats numbers that are >= 1,000 & <= 1,000,000,000 as SI format with precision 3', () => { expect(formatter(1000)).toBe('+1k'); expect(formatter(10001)).toBe('+10k'); expect(formatter(10100)).toBe('+10.1k'); expect(formatter(111000000)).toBe('+111M'); }); it('formats number that are >= 1 & < 1,000 as integer or float with at most 2 decimal points', () => { expect(formatter(1)).toBe('+1'); expect(formatter(1)).toBe('+1'); expect(formatter(10)).toBe('+10'); expect(formatter(10)).toBe('+10'); expect(formatter(10.23432)).toBe('+10.23'); expect(formatter(274.2856)).toBe('+274.29'); expect(formatter(999)).toBe('+999'); }); it('formats numbers that are < 1 & >= 0.001 as float with at most 4 decimal points', () => { expect(formatter(0.1)).toBe('+0.1'); expect(formatter(0.23)).toBe('+0.23'); expect(formatter(0.699)).toBe('+0.699'); expect(formatter(0.0023)).toBe('+0.0023'); expect(formatter(0.002300001)).toBe('+0.0023'); }); it('formats numbers that are < 0.001 & >= 0.000001 as micron', () => { expect(formatter(0.0002300001)).toBe('+230µ'); expect(formatter(0.000023)).toBe('+23µ'); expect(formatter(0.000001)).toBe('+1µ'); }); it('formats numbers that are less than 0.000001 as SI format with precision 3', () => { expect(formatter(0.0000001)).toBe('+100n'); }); }); }); });
5,544
0
petrpan-code/apache/superset/superset-frontend/packages/superset-ui-core/test
petrpan-code/apache/superset/superset-frontend/packages/superset-ui-core/test/query/DatasourceKey.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 { DatasourceKey } from '@superset-ui/core'; describe('DatasourceKey', () => { it('should handle table data sources', () => { const datasourceKey = new DatasourceKey('5__table'); expect(datasourceKey.toString()).toBe('5__table'); expect(datasourceKey.toObject()).toEqual({ id: 5, type: 'table' }); }); it('should handle query data sources', () => { const datasourceKey = new DatasourceKey('5__query'); expect(datasourceKey.toString()).toBe('5__query'); expect(datasourceKey.toObject()).toEqual({ id: 5, type: 'query' }); }); });
5,545
0
petrpan-code/apache/superset/superset-frontend/packages/superset-ui-core/test
petrpan-code/apache/superset/superset-frontend/packages/superset-ui-core/test/query/buildQueryContext.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 { buildQueryContext } from '@superset-ui/core'; import * as queryModule from '../../src/query/normalizeTimeColumn'; import * as getXAxisModule from '../../src/query/getXAxis'; describe('buildQueryContext', () => { it('should build datasource for table sources and apply defaults', () => { const queryContext = buildQueryContext({ datasource: '5__table', granularity_sqla: 'ds', viz_type: 'table', }); expect(queryContext.datasource.id).toBe(5); expect(queryContext.datasource.type).toBe('table'); expect(queryContext.force).toBe(false); expect(queryContext.result_format).toBe('json'); expect(queryContext.result_type).toBe('full'); }); it('should build datasource for table sources with columns', () => { const queryContext = buildQueryContext( { datasource: '5__table', granularity_sqla: 'ds', viz_type: 'table', source: 'source_column', source_category: 'source_category_column', target: 'target_column', target_category: 'target_category_column', }, { queryFields: { source: 'columns', source_category: 'columns', target: 'columns', target_category: 'columns', }, }, ); expect(queryContext.datasource.id).toBe(5); expect(queryContext.datasource.type).toBe('table'); expect(queryContext.force).toBe(false); expect(queryContext.result_format).toBe('json'); expect(queryContext.result_type).toBe('full'); expect(queryContext.queries).toEqual( expect.arrayContaining([ expect.objectContaining({ columns: [ 'source_column', 'source_category_column', 'target_column', 'target_category_column', ], }), ]), ); }); it('should build datasource for table sources and process with custom function', () => { const queryContext = buildQueryContext( { datasource: '5__table', granularity_sqla: 'ds', viz_type: 'table', source: 'source_column', source_category: 'source_category_column', target: 'target_column', target_category: 'target_category_column', }, function addExtraColumn(queryObject) { return [{ ...queryObject, columns: ['dummy_column'] }]; }, ); expect(queryContext.datasource.id).toBe(5); expect(queryContext.datasource.type).toBe('table'); expect(queryContext.force).toBe(false); expect(queryContext.result_format).toBe('json'); expect(queryContext.result_type).toBe('full'); expect(queryContext.queries).toEqual( expect.arrayContaining([ expect.objectContaining({ columns: ['dummy_column'], }), ]), ); }); // todo(Yongjie): move these test case into buildQueryObject.test.ts it('should remove undefined value in post_processing', () => { const queryContext = buildQueryContext( { datasource: '5__table', viz_type: 'table', }, () => [ { post_processing: [ undefined, undefined, { operation: 'flatten', }, undefined, ], }, ], ); expect(queryContext.queries[0].post_processing).toEqual([ { operation: 'flatten', }, ]); }); it('should call normalizeTimeColumn if GENERIC_CHART_AXES is enabled and has x_axis', () => { Object.defineProperty(getXAxisModule, 'hasGenericChartAxes', { value: true, }); const spyNormalizeTimeColumn = jest.spyOn( queryModule, 'normalizeTimeColumn', ); buildQueryContext( { datasource: '5__table', viz_type: 'table', x_axis: 'axis', }, () => [{}], ); expect(spyNormalizeTimeColumn).toBeCalled(); spyNormalizeTimeColumn.mockRestore(); }); it("shouldn't call normalizeTimeColumn if GENERIC_CHART_AXES is disabled", () => { Object.defineProperty(getXAxisModule, 'hasGenericChartAxes', { value: false, }); const spyNormalizeTimeColumn = jest.spyOn( queryModule, 'normalizeTimeColumn', ); buildQueryContext( { datasource: '5__table', viz_type: 'table', }, () => [{}], ); expect(spyNormalizeTimeColumn).not.toBeCalled(); spyNormalizeTimeColumn.mockRestore(); }); });
5,546
0
petrpan-code/apache/superset/superset-frontend/packages/superset-ui-core/test
petrpan-code/apache/superset/superset-frontend/packages/superset-ui-core/test/query/buildQueryObject.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 { JsonObject, AnnotationLayer, AnnotationOpacity, AnnotationSourceType, AnnotationStyle, AnnotationType, buildQueryObject, QueryObject, } from '@superset-ui/core'; describe('buildQueryObject', () => { let query: QueryObject; it('should build granularity for sqlalchemy datasources', () => { query = buildQueryObject({ datasource: '5__table', granularity_sqla: 'ds', viz_type: 'table', }); expect(query.granularity).toEqual('ds'); }); it('should build metrics based on default queryFields', () => { query = buildQueryObject({ datasource: '5__table', granularity_sqla: 'ds', viz_type: 'table', metric: 'sum__num', secondary_metric: 'avg__num', }); expect(query.metrics).toEqual(['sum__num', 'avg__num']); }); it('should merge original and append filters', () => { query = buildQueryObject({ datasource: '5__table', granularity_sqla: 'ds', viz_type: 'table', extra_filters: [{ col: 'abc', op: '==', val: 'qwerty' }], adhoc_filters: [ { expressionType: 'SIMPLE', clause: 'WHERE', subject: 'foo', operator: '!=', comparator: 'bar', }, ], where: 'a = b', extra_form_data: { adhoc_filters: [ { expressionType: 'SQL', clause: 'WHERE', sqlExpression: '(1 = 1)', }, ], }, }); expect(query.filters).toEqual([ { col: 'abc', op: '==', val: 'qwerty' }, { col: 'foo', op: '!=', val: 'bar' }, ]); expect(query.extras?.where).toEqual('(a = b) AND ((1 = 1))'); }); it('should group custom metric control', () => { query = buildQueryObject( { datasource: '5__table', granularity_sqla: 'ds', viz_type: 'table', my_custom_metric_control: 'sum__num', }, { my_custom_metric_control: 'metrics' }, ); expect(query.metrics).toEqual(['sum__num']); }); it('should group custom metric control with predefined metrics', () => { query = buildQueryObject( { datasource: '5__table', granularity_sqla: 'ds', viz_type: 'table', metrics: ['sum__num'], my_custom_metric_control: 'avg__num', }, { my_custom_metric_control: 'metrics' }, ); expect(query.metrics).toEqual(['sum__num', 'avg__num']); }); it('should build series_limit from legacy control', () => { const series_limit = 2; query = buildQueryObject({ datasource: '5__table', granularity_sqla: 'ds', viz_type: 'table', limit: series_limit, }); expect(query.series_limit).toEqual(series_limit); }); it('should build series_limit', () => { const series_limit = 2; query = buildQueryObject({ datasource: '5__table', granularity_sqla: 'ds', viz_type: 'table', series_limit, }); expect(query.series_limit).toEqual(series_limit); }); it('should build order_desc', () => { const orderDesc = false; query = buildQueryObject({ datasource: '5__table', granularity_sqla: 'ds', viz_type: 'table', order_desc: orderDesc, }); expect(query.order_desc).toEqual(orderDesc); }); it('should build series_limit_metric from legacy control', () => { const metric = 'country'; query = buildQueryObject({ datasource: '5__table', granularity_sqla: 'ds', viz_type: 'table', timeseries_limit_metric: metric, }); expect(query.series_limit_metric).toEqual(metric); }); it('should build series_limit_metric', () => { const metric = 'country'; query = buildQueryObject({ datasource: '5__table', granularity_sqla: 'ds', viz_type: 'pivot_table_v2', series_limit_metric: metric, }); expect(query.series_limit_metric).toEqual(metric); }); it('should build series_limit_metric as undefined when empty array', () => { const metric: any = []; query = buildQueryObject({ datasource: '5__table', granularity_sqla: 'ds', viz_type: 'pivot_table_v2', series_limit_metric: metric, }); expect(query.series_limit_metric).toEqual(undefined); }); it('should handle null and non-numeric row_limit and row_offset', () => { const baseQuery = { datasource: '5__table', granularity_sqla: 'ds', viz_type: 'table', row_limit: null, }; // undefined query = buildQueryObject({ ...baseQuery }); expect(query.row_limit).toBeUndefined(); expect(query.row_offset).toBeUndefined(); // null value query = buildQueryObject({ ...baseQuery, row_limit: null, row_offset: null, }); expect(query.row_limit).toBeUndefined(); expect(query.row_offset).toBeUndefined(); query = buildQueryObject({ ...baseQuery, row_limit: 1000, row_offset: 50 }); expect(query.row_limit).toStrictEqual(1000); expect(query.row_offset).toStrictEqual(50); // valid string query = buildQueryObject({ ...baseQuery, row_limit: '200', row_offset: '100', }); expect(query.row_limit).toStrictEqual(200); expect(query.row_offset).toStrictEqual(100); // invalid string query = buildQueryObject({ ...baseQuery, row_limit: 'two hundred', row_offset: 'twenty', }); expect(query.row_limit).toBeUndefined(); expect(query.row_offset).toBeUndefined(); }); it('should populate annotation_layers', () => { const annotationLayers: AnnotationLayer[] = [ { annotationType: AnnotationType.Formula, color: '#ff7f44', name: 'My Formula', opacity: AnnotationOpacity.Low, show: true, showLabel: false, style: AnnotationStyle.Solid, value: '10*sin(x)', width: 1, }, { annotationType: AnnotationType.Interval, color: null, show: false, showLabel: false, name: 'My Interval', sourceType: AnnotationSourceType.Native, style: AnnotationStyle.Dashed, value: 1, width: 100, }, { annotationType: AnnotationType.Event, color: null, descriptionColumns: [], name: 'My Interval', overrides: { granularity: null, time_grain_sqla: null, time_range: null, }, sourceType: AnnotationSourceType.Table, show: false, showLabel: false, timeColumn: 'ds', style: AnnotationStyle.Dashed, value: 1, width: 100, }, ]; query = buildQueryObject({ datasource: '5__table', granularity_sqla: 'ds', viz_type: 'table', annotation_layers: annotationLayers, }); expect(query.annotation_layers).toEqual(annotationLayers); }); it('should populate url_params', () => { expect( buildQueryObject({ datasource: '5__table', granularity_sqla: 'ds', viz_type: 'table', url_params: { abc: '123' }, }).url_params, ).toEqual({ abc: '123' }); expect( buildQueryObject({ datasource: '5__table', granularity_sqla: 'ds', viz_type: 'table', // @ts-expect-error url_params: null, }).url_params, ).toBeUndefined(); }); it('should populate granularity', () => { const granularity = 'ds'; query = buildQueryObject({ datasource: '5__table', granularity, viz_type: 'table', }); expect(query.granularity).toEqual(granularity); }); it('should populate granularity from legacy field', () => { const granularity = 'ds'; query = buildQueryObject({ datasource: '5__table', granularity_sqla: granularity, viz_type: 'table', }); expect(query.granularity).toEqual(granularity); }); it('should populate custom_params', () => { const customParams: JsonObject = { customObject: { id: 137, name: 'C-137' }, }; query = buildQueryObject({ datasource: '5__table', granularity_sqla: 'ds', viz_type: 'table', custom_params: customParams, }); expect(query.custom_params).toEqual(customParams); }); });
5,547
0
petrpan-code/apache/superset/superset-frontend/packages/superset-ui-core/test
petrpan-code/apache/superset/superset-frontend/packages/superset-ui-core/test/query/convertFilter.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 { convertFilter } from '@superset-ui/core'; describe('convertFilter', () => { it('should handle unary filter', () => { expect( convertFilter({ expressionType: 'SIMPLE', clause: 'WHERE', subject: 'topping', operator: 'IS NOT NULL', }), ).toEqual({ col: 'topping', op: 'IS NOT NULL', }); }); it('should convert binary filter', () => { expect( convertFilter({ expressionType: 'SIMPLE', clause: 'WHERE', subject: 'topping', operator: '==', comparator: 'grass jelly', }), ).toEqual({ col: 'topping', op: '==', val: 'grass jelly', }); }); it('should convert set filter', () => { expect( convertFilter({ expressionType: 'SIMPLE', clause: 'WHERE', subject: 'toppings', operator: 'IN', comparator: ['boba', 'grass jelly'], }), ).toEqual({ col: 'toppings', op: 'IN', val: ['boba', 'grass jelly'], }); }); });
5,548
0
petrpan-code/apache/superset/superset-frontend/packages/superset-ui-core/test
petrpan-code/apache/superset/superset-frontend/packages/superset-ui-core/test/query/extractExtras.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 extractExtras from '../../src/query/extractExtras'; describe('extractExtras', () => { const baseQueryFormData = { datasource: '1__table', granularity_sqla: 'ds', time_grain_sqla: TimeGranularity.MINUTE, viz_type: 'my_viz', }; it('should populate time range endpoints and override formData with double underscored date options', () => { expect( extractExtras({ ...baseQueryFormData, extra_filters: [ { col: '__time_col', op: '==', val: 'ds2', }, { col: '__time_grain', op: '==', val: 'PT5M', }, { col: '__time_range', op: '==', val: '2009-07-17T00:00:00 : 2020-07-17T00:00:00', }, ], }), ).toEqual({ applied_time_extras: { __time_col: 'ds2', __time_grain: 'PT5M', __time_range: '2009-07-17T00:00:00 : 2020-07-17T00:00:00', }, extras: { time_grain_sqla: 'PT5M', }, filters: [], granularity: 'ds2', time_range: '2009-07-17T00:00:00 : 2020-07-17T00:00:00', }); }); it('should create regular filters from non-reserved columns', () => { expect( extractExtras({ ...baseQueryFormData, extra_filters: [ { col: 'gender', op: '==', val: 'girl', }, { col: 'name', op: 'IN', val: ['Eve', 'Evelyn'], }, ], }), ).toEqual({ applied_time_extras: {}, extras: { time_grain_sqla: 'PT1M', }, filters: [ { col: 'gender', op: '==', val: 'girl', }, { col: 'name', op: 'IN', val: ['Eve', 'Evelyn'], }, ], granularity: 'ds', }); }); it('should create regular filters from reserved and non-reserved columns', () => { expect( extractExtras({ ...baseQueryFormData, extra_filters: [ { col: 'gender', op: '==', val: 'girl', }, { col: '__time_col', op: '==', val: 'ds2', }, { col: '__time_grain', op: '==', val: 'PT5M', }, { col: '__time_range', op: '==', val: '2009-07-17T00:00:00 : 2020-07-17T00:00:00', }, ], }), ).toEqual({ applied_time_extras: { __time_col: 'ds2', __time_grain: 'PT5M', __time_range: '2009-07-17T00:00:00 : 2020-07-17T00:00:00', }, extras: { time_grain_sqla: 'PT5M', }, filters: [ { col: 'gender', op: '==', val: 'girl', }, ], granularity: 'ds2', time_range: '2009-07-17T00:00:00 : 2020-07-17T00:00:00', }); }); });
5,549
0
petrpan-code/apache/superset/superset-frontend/packages/superset-ui-core/test
petrpan-code/apache/superset/superset-frontend/packages/superset-ui-core/test/query/extractQueryFields.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 { configure, QueryMode, DTTM_ALIAS } from '@superset-ui/core'; import extractQueryFields from '../../src/query/extractQueryFields'; import { NUM_METRIC } from '../fixtures'; configure(); describe('extractQueryFields', () => { it('should return default object', () => { expect(extractQueryFields({})).toEqual({ columns: [], metrics: [], orderby: undefined, }); }); it('should group single value to arrays', () => { expect( extractQueryFields({ metric: 'my_metric', columns: 'abc', orderby: '["ccc",true]', }), ).toEqual({ metrics: ['my_metric'], columns: ['abc'], orderby: [['ccc', true]], }); }); it('should combine field aliases', () => { expect( extractQueryFields( { metric: 'metric_1', metric_2: 'metric_2', my_custom_metric: 'my_custom_metric', }, { my_custom_metric: 'metrics' }, ).metrics, ).toEqual(['metric_1', 'metric_2', 'my_custom_metric']); }); it('should extract columns', () => { expect(extractQueryFields({ columns: 'col_1' })).toEqual({ columns: ['col_1'], metrics: [], orderby: undefined, }); }); it('should extract groupby as columns and set empty metrics', () => { expect(extractQueryFields({ groupby: 'col_1' })).toEqual({ columns: ['col_1'], metrics: [], orderby: undefined, }); }); it('should remove duplicate metrics', () => { expect( extractQueryFields({ metrics: ['col_1', { ...NUM_METRIC }, { ...NUM_METRIC }], }), ).toEqual({ columns: [], metrics: ['col_1', NUM_METRIC], orderby: undefined, }); }); it('should extract custom columns fields', () => { expect( extractQueryFields( { series: 'col_1', metric: 'metric_1' }, { series: 'groupby' }, ), ).toEqual({ columns: ['col_1'], metrics: ['metric_1'], orderby: undefined, }); }); it('should merge custom groupby into columns', () => { expect( extractQueryFields( { groupby: 'col_1', series: 'col_2', metric: 'metric_1' }, { series: 'groupby' }, ), ).toEqual({ columns: ['col_1', 'col_2'], metrics: ['metric_1'], orderby: undefined, }); }); it('should include time', () => { expect( extractQueryFields({ groupby: 'col_1', include_time: true }).columns, ).toEqual([DTTM_ALIAS, 'col_1']); expect( extractQueryFields({ groupby: ['col_1', DTTM_ALIAS, ''], include_time: true, }).columns, ).toEqual(['col_1', DTTM_ALIAS]); }); it('should ignore null values', () => { expect( extractQueryFields({ series: ['a'], columns: null }).columns, ).toEqual(['a']); }); it('should ignore groupby and metrics when in raw QueryMode', () => { expect( extractQueryFields({ columns: ['a'], groupby: ['b'], metric: ['m'], query_mode: QueryMode.raw, }), ).toEqual({ columns: ['a'], metrics: undefined, orderby: undefined, }); }); it('should ignore columns when in aggregate QueryMode', () => { expect( extractQueryFields({ columns: ['a'], groupby: [], metric: ['m'], query_mode: QueryMode.aggregate, }), ).toEqual({ metrics: ['m'], columns: [], orderby: undefined, }); expect( extractQueryFields({ columns: ['a'], groupby: ['b'], metric: ['m'], query_mode: QueryMode.aggregate, }), ).toEqual({ metrics: ['m'], columns: ['b'], orderby: undefined, }); }); it('should parse orderby if needed', () => { expect( extractQueryFields({ columns: ['a'], order_by_cols: ['["foo",false]', '["bar",true]'], orderby: [['abc', true]], }), ).toEqual({ columns: ['a'], metrics: [], orderby: [ ['foo', false], ['bar', true], ['abc', true], ], }); }); it('should throw error if parse orderby failed', () => { expect(() => { extractQueryFields({ orderby: ['ccc'], }); }).toThrow('invalid orderby'); }); });
5,550
0
petrpan-code/apache/superset/superset-frontend/packages/superset-ui-core/test
petrpan-code/apache/superset/superset-frontend/packages/superset-ui-core/test/query/extractTimegrain.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 { extractTimegrain, QueryFormData } from '@superset-ui/core'; describe('extractTimegrain', () => { const baseFormData: QueryFormData = { datasource: 'table__1', viz_type: 'my_viz', }; it('should extract regular from form data', () => { expect( extractTimegrain({ ...baseFormData, time_grain_sqla: 'P1D', }), ).toEqual('P1D'); }); it('should extract filter box time grain from form data', () => { expect( extractTimegrain({ ...baseFormData, time_grain_sqla: 'P1D', extra_filters: [ { col: '__time_grain', op: '==', val: 'P1M', }, ], }), ).toEqual('P1M'); }); it('should extract native filter time grain from form data', () => { expect( extractTimegrain({ ...baseFormData, time_grain_sqla: 'P1D', extra_form_data: { time_grain_sqla: 'P1W', }, }), ).toEqual('P1W'); }); it('should give priority to native filters', () => { expect( extractTimegrain({ ...baseFormData, time_grain_sqla: 'P1D', extra_filters: [ { col: '__time_grain', op: '==', val: 'P1M', }, ], extra_form_data: { time_grain_sqla: 'P1W', }, }), ).toEqual('P1W'); }); it('returns undefined if timegrain not defined', () => { expect(extractTimegrain({ ...baseFormData })).toEqual(undefined); }); });
5,551
0
petrpan-code/apache/superset/superset-frontend/packages/superset-ui-core/test
petrpan-code/apache/superset/superset-frontend/packages/superset-ui-core/test/query/getAxis.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 { isXAxisSet } from '@superset-ui/core'; test('isXAxisSet', () => { expect(isXAxisSet({ datasource: '123', viz_type: 'table' })).not.toBeTruthy(); expect( isXAxisSet({ datasource: '123', viz_type: 'table', x_axis: 'axis' }), ).toBeTruthy(); });
5,552
0
petrpan-code/apache/superset/superset-frontend/packages/superset-ui-core/test
petrpan-code/apache/superset/superset-frontend/packages/superset-ui-core/test/query/getColumnLabel.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 { getColumnLabel } from '@superset-ui/core'; describe('getColumnLabel', () => { it('should handle physical column', () => { expect(getColumnLabel('gender')).toEqual('gender'); }); it('should handle adhoc columns with label', () => { expect( getColumnLabel({ sqlExpression: "case when 1 then 'a' else 'b' end", label: 'my col', expressionType: 'SQL', }), ).toEqual('my col'); }); it('should handle adhoc columns without label', () => { expect( getColumnLabel({ sqlExpression: "case when 1 then 'a' else 'b' end", expressionType: 'SQL', }), ).toEqual("case when 1 then 'a' else 'b' end"); }); });
5,553
0
petrpan-code/apache/superset/superset-frontend/packages/superset-ui-core/test
petrpan-code/apache/superset/superset-frontend/packages/superset-ui-core/test/query/getMetricLabel.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 { getMetricLabel } from '@superset-ui/core'; describe('getMetricLabel', () => { it('should handle predefined metric name', () => { expect(getMetricLabel('sum__num')).toEqual('sum__num'); }); it('should handle simple adhoc metrics', () => { expect( getMetricLabel({ expressionType: 'SIMPLE', aggregate: 'AVG', column: { id: 5, type: 'BIGINT', columnName: 'sum_girls', }, }), ).toEqual('AVG(sum_girls)'); }); it('should handle column_name in alternative field', () => { expect( getMetricLabel({ expressionType: 'SIMPLE', aggregate: 'AVG', column: { id: 5, type: 'BIGINT', column_name: 'sum_girls', }, }), ).toEqual('AVG(sum_girls)'); }); it('should handle SQL adhoc metrics', () => { expect( getMetricLabel({ expressionType: 'SQL', sqlExpression: 'COUNT(sum_girls)', }), ).toEqual('COUNT(sum_girls)'); }); it('should handle adhoc metrics with custom labels', () => { expect( getMetricLabel({ expressionType: 'SQL', label: 'foo', sqlExpression: 'COUNT(sum_girls)', }), ).toEqual('foo'); }); });
5,554
0
petrpan-code/apache/superset/superset-frontend/packages/superset-ui-core/test
petrpan-code/apache/superset/superset-frontend/packages/superset-ui-core/test/query/normalizeOrderBy.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 { normalizeOrderBy, QueryObject } from '@superset-ui/core'; describe('normalizeOrderBy', () => { it('should not change original queryObject when orderby populated', () => { const query: QueryObject = { datasource: '5__table', viz_type: 'table', time_range: '1 year ago : 2013', orderby: [['count(*)', true]], }; expect(normalizeOrderBy(query)).toEqual(query); }); it('has series_limit_metric in queryObject', () => { const query: QueryObject = { datasource: '5__table', viz_type: 'table', time_range: '1 year ago : 2013', metrics: ['count(*)'], series_limit_metric: { expressionType: 'SIMPLE', column: { id: 1, column_name: 'sales', }, aggregate: 'SUM', }, order_desc: true, }; const expectedQueryObject = normalizeOrderBy(query); expect(expectedQueryObject).not.toHaveProperty('series_limit_metric'); expect(expectedQueryObject).not.toHaveProperty('order_desc'); expect(expectedQueryObject).toEqual({ datasource: '5__table', viz_type: 'table', time_range: '1 year ago : 2013', metrics: ['count(*)'], orderby: [ [ { expressionType: 'SIMPLE', column: { id: 1, column_name: 'sales', }, aggregate: 'SUM', }, false, ], ], }); }); it('should transform legacy_order_by in queryObject', () => { const query: QueryObject = { datasource: '5__table', viz_type: 'table', time_range: '1 year ago : 2013', metrics: ['count(*)'], legacy_order_by: { expressionType: 'SIMPLE', column: { id: 1, column_name: 'sales', }, aggregate: 'SUM', }, order_desc: true, }; const expectedQueryObject = normalizeOrderBy(query); expect(expectedQueryObject).not.toHaveProperty('legacy_order_by'); expect(expectedQueryObject).not.toHaveProperty('order_desc'); expect(expectedQueryObject).toEqual({ datasource: '5__table', viz_type: 'table', time_range: '1 year ago : 2013', metrics: ['count(*)'], orderby: [ [ { expressionType: 'SIMPLE', column: { id: 1, column_name: 'sales', }, aggregate: 'SUM', }, false, ], ], }); }); it('has metrics in queryObject', () => { const query: QueryObject = { datasource: '5__table', viz_type: 'table', time_range: '1 year ago : 2013', metrics: ['count(*)'], order_desc: true, }; const expectedQueryObject = normalizeOrderBy(query); expect(expectedQueryObject).not.toHaveProperty('series_limit_metric'); expect(expectedQueryObject).not.toHaveProperty('order_desc'); expect(expectedQueryObject).toEqual({ datasource: '5__table', viz_type: 'table', time_range: '1 year ago : 2013', metrics: ['count(*)'], orderby: [['count(*)', false]], }); }); it('should not change', () => { const query: QueryObject = { datasource: '5__table', viz_type: 'table', time_range: '1 year ago : 2013', }; expect(normalizeOrderBy(query)).toEqual(query); }); it('remove empty orderby', () => { const query: QueryObject = { datasource: '5__table', viz_type: 'table', time_range: '1 year ago : 2013', orderby: [], }; expect(normalizeOrderBy(query)).not.toHaveProperty('orderby'); }); it('remove orderby with an empty array', () => { const query: QueryObject = { datasource: '5__table', viz_type: 'table', time_range: '1 year ago : 2013', orderby: [[]], }; expect(normalizeOrderBy(query)).not.toHaveProperty('orderby'); }); it('remove orderby with an empty metric', () => { const query: QueryObject = { datasource: '5__table', viz_type: 'table', time_range: '1 year ago : 2013', orderby: [['', true]], }; expect(normalizeOrderBy(query)).not.toHaveProperty('orderby'); }); it('remove orderby with an empty adhoc metric', () => { const query: QueryObject = { datasource: '5__table', viz_type: 'table', time_range: '1 year ago : 2013', orderby: [[{}, true]], }; expect(normalizeOrderBy(query)).not.toHaveProperty('orderby'); }); it('remove orderby with an non-boolean type', () => { const query: QueryObject = { datasource: '5__table', viz_type: 'table', time_range: '1 year ago : 2013', // @ts-ignore orderby: [['count(*)', 'true']], }; expect(normalizeOrderBy(query)).not.toHaveProperty('orderby'); }); });
5,555
0
petrpan-code/apache/superset/superset-frontend/packages/superset-ui-core/test
petrpan-code/apache/superset/superset-frontend/packages/superset-ui-core/test/query/normalizeTimeColumn.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 { normalizeTimeColumn, QueryObject, SqlaFormData, } from '@superset-ui/core'; 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(); }); it('should return original QueryObject if disabled GENERIC_CHART_AXES', () => { const formData: SqlaFormData = { datasource: '5__table', viz_type: 'table', granularity: 'time_column', time_grain_sqla: 'P1Y', time_range: '1 year ago : 2013', columns: ['col1'], metrics: ['count(*)'], }; const query: QueryObject = { datasource: '5__table', viz_type: 'table', granularity: 'time_column', extras: { time_grain_sqla: 'P1Y', }, time_range: '1 year ago : 2013', orderby: [['count(*)', true]], columns: ['col1'], metrics: ['count(*)'], is_timeseries: true, }; expect(normalizeTimeColumn(formData, query)).toEqual(query); }); it('should return converted QueryObject even though disabled GENERIC_CHART_AXES (x_axis in formData)', () => { const formData: SqlaFormData = { datasource: '5__table', viz_type: 'table', granularity: 'time_column', time_grain_sqla: 'P1Y', time_range: '1 year ago : 2013', columns: ['col1'], metrics: ['count(*)'], x_axis: 'time_column', }; const query: QueryObject = { datasource: '5__table', viz_type: 'table', granularity: 'time_column', extras: { time_grain_sqla: 'P1Y', }, time_range: '1 year ago : 2013', orderby: [['count(*)', true]], columns: ['time_column', 'col1'], metrics: ['count(*)'], is_timeseries: true, }; expect(normalizeTimeColumn(formData, query)).toEqual({ datasource: '5__table', viz_type: 'table', granularity: 'time_column', extras: { time_grain_sqla: 'P1Y', }, time_range: '1 year ago : 2013', orderby: [['count(*)', true]], columns: [ { timeGrain: 'P1Y', columnType: 'BASE_AXIS', sqlExpression: 'time_column', label: 'time_column', expressionType: 'SQL', }, 'col1', ], metrics: ['count(*)'], }); }); }); 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(); }); it('should return original QueryObject if x_axis is empty', () => { const formData: SqlaFormData = { datasource: '5__table', viz_type: 'table', granularity: 'time_column', time_grain_sqla: 'P1Y', time_range: '1 year ago : 2013', columns: ['col1'], metrics: ['count(*)'], }; const query: QueryObject = { datasource: '5__table', viz_type: 'table', granularity: 'time_column', extras: { time_grain_sqla: 'P1Y', }, time_range: '1 year ago : 2013', orderby: [['count(*)', true]], columns: ['col1'], metrics: ['count(*)'], is_timeseries: true, }; expect(normalizeTimeColumn(formData, query)).toEqual(query); }); it('should support different columns for x-axis and granularity', () => { const formData: SqlaFormData = { datasource: '5__table', viz_type: 'table', granularity: 'time_column', time_grain_sqla: 'P1Y', time_range: '1 year ago : 2013', x_axis: 'time_column_in_x_axis', columns: ['col1'], metrics: ['count(*)'], }; const query: QueryObject = { datasource: '5__table', viz_type: 'table', granularity: 'time_column', extras: { time_grain_sqla: 'P1Y', where: '', having: '', }, time_range: '1 year ago : 2013', orderby: [['count(*)', true]], columns: ['time_column_in_x_axis', 'col1'], metrics: ['count(*)'], is_timeseries: true, }; expect(normalizeTimeColumn(formData, query)).toEqual({ datasource: '5__table', viz_type: 'table', granularity: 'time_column', extras: { where: '', having: '', time_grain_sqla: 'P1Y' }, time_range: '1 year ago : 2013', orderby: [['count(*)', true]], columns: [ { timeGrain: 'P1Y', columnType: 'BASE_AXIS', sqlExpression: 'time_column_in_x_axis', label: 'time_column_in_x_axis', expressionType: 'SQL', }, 'col1', ], metrics: ['count(*)'], }); }); it('should support custom SQL in x-axis', () => { const formData: SqlaFormData = { datasource: '5__table', viz_type: 'table', granularity: 'time_column', time_grain_sqla: 'P1Y', time_range: '1 year ago : 2013', x_axis: { expressionType: 'SQL', label: 'Order Data + 1 year', sqlExpression: '"Order Date" + interval \'1 year\'', }, columns: ['col1'], metrics: ['count(*)'], }; const query: QueryObject = { datasource: '5__table', viz_type: 'table', granularity: 'time_column', extras: { time_grain_sqla: 'P1Y', where: '', having: '', }, time_range: '1 year ago : 2013', orderby: [['count(*)', true]], columns: [ { expressionType: 'SQL', label: 'Order Data + 1 year', sqlExpression: '"Order Date" + interval \'1 year\'', }, 'col1', ], metrics: ['count(*)'], is_timeseries: true, }; expect(normalizeTimeColumn(formData, query)).toEqual({ datasource: '5__table', viz_type: 'table', granularity: 'time_column', extras: { where: '', having: '', time_grain_sqla: 'P1Y' }, time_range: '1 year ago : 2013', orderby: [['count(*)', true]], columns: [ { timeGrain: 'P1Y', columnType: 'BASE_AXIS', expressionType: 'SQL', label: 'Order Data + 1 year', sqlExpression: `"Order Date" + interval '1 year'`, }, 'col1', ], metrics: ['count(*)'], }); }); it('fallback and invalid columns value', () => { const formData: SqlaFormData = { datasource: '5__table', viz_type: 'table', granularity: 'time_column', time_grain_sqla: 'P1Y', time_range: '1 year ago : 2013', x_axis: { expressionType: 'SQL', label: 'Order Data + 1 year', sqlExpression: '"Order Date" + interval \'1 year\'', }, columns: ['col1'], metrics: ['count(*)'], }; const query: QueryObject = { datasource: '5__table', viz_type: 'table', granularity: 'time_column', extras: { time_grain_sqla: 'P1Y', where: '', having: '', }, time_range: '1 year ago : 2013', orderby: [['count(*)', true]], metrics: ['count(*)'], is_timeseries: true, }; expect(normalizeTimeColumn(formData, query)).toEqual(query); }); });
5,556
0
petrpan-code/apache/superset/superset-frontend/packages/superset-ui-core/test
petrpan-code/apache/superset/superset-frontend/packages/superset-ui-core/test/query/processExtraFormData.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 { overrideExtraFormData } from '../../src/query/processExtraFormData'; describe('overrideExtraFormData', () => { it('should assign allowed non-existent value', () => { expect( overrideExtraFormData( { granularity: 'something', viz_type: 'custom', datasource: 'table_1', }, { time_range: '100 years ago', }, ), ).toEqual({ granularity: 'something', viz_type: 'custom', datasource: 'table_1', time_range: '100 years ago', }); }); it('should override allowed preexisting value', () => { expect( overrideExtraFormData( { granularity: 'something', viz_type: 'custom', datasource: 'table_1', time_range: '100 years ago', }, { time_range: '50 years ago', }, ), ).toEqual({ granularity: 'something', viz_type: 'custom', datasource: 'table_1', time_range: '50 years ago', }); }); it('should not override non-allowed value', () => { expect( overrideExtraFormData( { granularity: 'something', viz_type: 'custom', datasource: 'table_1', time_range: '100 years ago', }, { // @ts-expect-error viz_type: 'other custom viz', }, ), ).toEqual({ granularity: 'something', viz_type: 'custom', datasource: 'table_1', time_range: '100 years ago', }); }); it('should override pre-existing extra value', () => { expect( overrideExtraFormData( { granularity: 'something', viz_type: 'custom', datasource: 'table_1', time_range: '100 years ago', extras: { time_grain_sqla: 'PT1H', }, }, { time_grain_sqla: 'P1D' }, ), ).toEqual({ granularity: 'something', viz_type: 'custom', datasource: 'table_1', time_range: '100 years ago', extras: { time_grain_sqla: 'P1D', }, }); }); it('should add extra override value', () => { expect( overrideExtraFormData( { granularity: 'something', viz_type: 'custom', datasource: 'table_1', time_range: '100 years ago', }, { time_grain_sqla: 'PT1H', }, ), ).toEqual({ granularity: 'something', viz_type: 'custom', datasource: 'table_1', time_range: '100 years ago', extras: { time_grain_sqla: 'PT1H', }, }); }); });
5,557
0
petrpan-code/apache/superset/superset-frontend/packages/superset-ui-core/test
petrpan-code/apache/superset/superset-frontend/packages/superset-ui-core/test/query/processFilters.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 processFilters from '../../src/query/processFilters'; describe('processFilters', () => { it('should handle non-array adhoc_filters', () => { expect( processFilters({ granularity: 'something', viz_type: 'custom', datasource: 'boba', }), ).toEqual( expect.objectContaining({ extras: { having: '', where: '' }, filters: [], }), ); }); it('should merge simple adhoc_filters and filters', () => { expect( processFilters({ granularity: 'something', viz_type: 'custom', datasource: 'boba', filters: [ { col: 'name', op: '==', val: 'Aaron', }, ], adhoc_filters: [ { expressionType: 'SIMPLE', clause: 'WHERE', subject: 'gender', operator: 'IS NOT NULL', }, // ignore simple having filter { expressionType: 'SIMPLE', clause: 'HAVING', subject: 'sum(sales)', operator: '>', comparator: '100', }, ], }), ).toEqual({ extras: { having: '', where: '', }, filters: [ { col: 'name', op: '==', val: 'Aaron', }, { col: 'gender', op: 'IS NOT NULL', }, ], }); }); it('should handle an empty array', () => { expect( processFilters({ where: '1 = 1', granularity: 'something', viz_type: 'custom', datasource: 'boba', adhoc_filters: [], }), ).toEqual({ filters: [], extras: { having: '', where: '(1 = 1)', }, }); }); it('should put adhoc_filters into the correct group and format accordingly', () => { expect( processFilters({ granularity: 'something', viz_type: 'custom', datasource: 'boba', adhoc_filters: [ { expressionType: 'SIMPLE', clause: 'WHERE', subject: 'milk', operator: 'IS NOT NULL', }, { expressionType: 'SIMPLE', clause: 'WHERE', subject: 'milk', operator: '==', comparator: 'almond', }, { expressionType: 'SQL', clause: 'WHERE', sqlExpression: "tea = 'jasmine'", }, { expressionType: 'SQL', clause: 'WHERE', sqlExpression: "cup = 'large' -- comment", }, { expressionType: 'SQL', clause: 'HAVING', sqlExpression: 'ice = 25 OR ice = 50', }, { expressionType: 'SQL', clause: 'HAVING', sqlExpression: 'waitTime <= 180 -- comment', }, ], }), ).toEqual({ extras: { having: '(ice = 25 OR ice = 50) AND (waitTime <= 180 -- comment\n)', where: "(tea = 'jasmine') AND (cup = 'large' -- comment\n)", }, filters: [ { col: 'milk', op: 'IS NOT NULL', }, { col: 'milk', op: '==', val: 'almond', }, ], }); }); });
5,559
0
petrpan-code/apache/superset/superset-frontend/packages/superset-ui-core/test/query/api
petrpan-code/apache/superset/superset-frontend/packages/superset-ui-core/test/query/api/legacy/getDatasourceMetadata.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 { getDatasourceMetadata } from '../../../../src/query/api/legacy'; import setupClientForTest from '../setupClientForTest'; describe('getFormData()', () => { beforeAll(setupClientForTest); afterEach(fetchMock.restore); it('returns datasource metadata for given datasource key', () => { const mockData = { field1: 'abc', field2: 'def', }; fetchMock.get( 'glob:*/superset/fetch_datasource_metadata?datasourceKey=1__table', mockData, ); return expect( getDatasourceMetadata({ datasourceKey: '1__table', }), ).resolves.toEqual(mockData); }); });
5,560
0
petrpan-code/apache/superset/superset-frontend/packages/superset-ui-core/test/query/api
petrpan-code/apache/superset/superset-frontend/packages/superset-ui-core/test/query/api/legacy/getFormData.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 { getFormData } from '../../../../src/query/api/legacy'; import setupClientForTest from '../setupClientForTest'; describe('getFormData()', () => { beforeAll(setupClientForTest); afterEach(fetchMock.restore); const mockData = { datasource: '1__table', viz_type: 'sankey', slice_id: 1, url_params: {}, granularity_sqla: null, time_grain_sqla: 'P1D', time_range: 'Last week', groupby: ['source', 'target'], metric: 'sum__value', adhoc_filters: [], row_limit: 1000, }; it('returns formData for given slice id', () => { fetchMock.get(`glob:*/api/v1/form_data/?slice_id=1`, mockData); return expect( getFormData({ sliceId: 1, }), ).resolves.toEqual(mockData); }); it('overrides formData when overrideFormData is specified', () => { fetchMock.get(`glob:*/api/v1/form_data/?slice_id=1`, mockData); return expect( getFormData({ sliceId: 1, overrideFormData: { metric: 'avg__value', }, }), ).resolves.toEqual({ ...mockData, metric: 'avg__value', }); }); });
5,561
0
petrpan-code/apache/superset/superset-frontend/packages/superset-ui-core/test/query/api
petrpan-code/apache/superset/superset-frontend/packages/superset-ui-core/test/query/api/v1/getChartData.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 { buildQueryContext, ApiV1 } from '@superset-ui/core'; import setupClientForTest from '../setupClientForTest'; describe('API v1 > getChartData()', () => { beforeAll(setupClientForTest); afterEach(fetchMock.restore); it('returns a promise of ChartDataResponse', async () => { const response = { result: [ { field1: 'abc', field2: 'def', }, ], }; fetchMock.post('glob:*/api/v1/chart/data', response); const result = await ApiV1.getChartData( buildQueryContext({ granularity: 'minute', viz_type: 'word_cloud', datasource: '1__table', }), ); return expect(result).toEqual(response); }); });
5,562
0
petrpan-code/apache/superset/superset-frontend/packages/superset-ui-core/test/query/api
petrpan-code/apache/superset/superset-frontend/packages/superset-ui-core/test/query/api/v1/handleError.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 'whatwg-fetch'; // for adding Response polyfill import { JsonObject, SupersetApiError, SupersetApiErrorType, } from '@superset-ui/core'; import handleError, { ErrorInput, } from '../../../../src/query/api/v1/handleError'; async function testHandleError( inputError: ErrorInput, expected: string | JsonObject, ): Promise<SupersetApiError> { try { await handleError(inputError); } catch (error) { const typedError = error as SupersetApiError; expect(typedError).toBeInstanceOf(SupersetApiError); if (typeof expected === 'string') { expect(typedError.message).toContain(expected); } else { expect(typedError).toEqual(expect.objectContaining(expected)); } return error; } return new SupersetApiError({ message: 'Where is the error?' }); } describe('handleError()', () => { it('should throw error directly', async () => { expect.assertions(3); const input = new SupersetApiError({ message: 'timeout' }); const output = await testHandleError(input, 'timeout'); expect(input).toBe(output); }); it('should handle error string', async () => { expect.assertions(2); await testHandleError('STOP', 'STOP'); }); it('should handle HTTP error', async () => { expect.assertions(2); const mockResponse = new Response('Ha?', { status: 404, statusText: 'NOT FOUND', }); await testHandleError(mockResponse, '404 NOT FOUND'); }); it('should handle HTTP error with status < 400', async () => { expect.assertions(2); const mockResponse = new Response('Ha haha?', { status: 302, statusText: 'Found', }); await testHandleError(mockResponse, '302 Found'); }); it('should use message from HTTP error', async () => { expect.assertions(2); const mockResponse = new Response('{ "message": "BAD BAD" }', { status: 500, statusText: 'Server Error', }); await testHandleError(mockResponse, 'BAD BAD'); }); it('should handle response of single error', async () => { expect.assertions(2); const mockResponse = new Response( '{ "error": "BAD BAD", "link": "https://superset.apache.org" }', { status: 403, statusText: 'Access Denied', }, ); await testHandleError(mockResponse, { message: 'BAD BAD', extra: { link: 'https://superset.apache.org' }, }); }); it('should handle single error object', async () => { expect.assertions(2); const mockError = { error: { message: 'Request timeout', error_type: SupersetApiErrorType.FRONTEND_TIMEOUT_ERROR, }, }; await testHandleError(mockError, { message: 'Request timeout', errorType: 'FRONTEND_TIMEOUT_ERROR', }); }); it('should process multi errors in HTTP json', async () => { expect.assertions(2); const mockResponse = new Response( '{ "errors": [{ "error_type": "NOT OK" }] }', { status: 403, statusText: 'Access Denied', }, ); await testHandleError(mockResponse, 'NOT OK'); }); it('should handle invalid multi errors', async () => { expect.assertions(4); const mockResponse1 = new Response('{ "errors": [] }', { status: 403, statusText: 'Access Denied', }); const mockResponse2 = new Response('{ "errors": null }', { status: 400, statusText: 'Bad Request', }); await testHandleError(mockResponse1, '403 Access Denied'); await testHandleError(mockResponse2, '400 Bad Request'); }); it('should fallback to statusText', async () => { expect.assertions(2); const mockResponse = new Response('{ "failed": "random ramble" }', { status: 403, statusText: 'Access Denied', }); await testHandleError(mockResponse, '403 Access Denied'); }); it('should handle regular JS error', async () => { expect.assertions(4); await testHandleError(new Error('What?'), 'What?'); const emptyError = new Error(); emptyError.stack = undefined; await testHandleError(emptyError, 'Unknown Error'); }); it('should handle { error: ... }', async () => { expect.assertions(2); await testHandleError({ error: 'Hmm' }, 'Hmm'); }); it('should throw unknown error', async () => { expect.assertions(4); await testHandleError( Promise.resolve('Some random things') as never, 'Unknown Error', ); await testHandleError(undefined as never, 'Unknown Error'); }); });
5,563
0
petrpan-code/apache/superset/superset-frontend/packages/superset-ui-core/test/query/api
petrpan-code/apache/superset/superset-frontend/packages/superset-ui-core/test/query/api/v1/makeApi.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 { JsonValue, SupersetClientClass } from '@superset-ui/core'; import { makeApi, SupersetApiError } from '../../../../src/query'; import setupClientForTest from '../setupClientForTest'; describe('makeApi()', () => { beforeAll(setupClientForTest); afterEach(fetchMock.restore); it('should expose method and endpoint', () => { const api = makeApi({ method: 'GET', endpoint: '/test', }); expect(api.method).toEqual('GET'); expect(api.endpoint).toEqual('/test'); expect(api.requestType).toEqual('search'); }); it('should allow custom client', async () => { expect.assertions(2); const api = makeApi({ method: 'GET', endpoint: '/test-custom-client', }); const client = new SupersetClientClass({ baseUrl: 'http://foo/' }); const mockResponse = { yes: 'ok' }; const mockRequest = jest.fn(() => Promise.resolve( new Response(JSON.stringify(mockResponse), { headers: { 'Content-Type': 'application/json' }, }), ), ); Object.assign(client, { request: mockRequest, }); const result = await api(null, { client }); expect(result).toEqual(mockResponse); expect(mockRequest).toHaveBeenCalledTimes(1); }); it('should obtain json response by default', async () => { expect.assertions(1); const api = makeApi({ method: 'GET', endpoint: '/test', }); fetchMock.get('glob:*/test', { yes: 'ok' }); expect(await api({})).toEqual({ yes: 'ok' }); }); it('should allow custom parseResponse', async () => { expect.assertions(2); const responseJson = { items: [1, 2, 3] }; fetchMock.post('glob:*/test', responseJson); const api = makeApi({ method: 'POST', endpoint: '/test', processResponse: (json: typeof responseJson) => json.items.reduce((a: number, b: number) => a + b), }); expect(api.method).toEqual('POST'); expect(await api({})).toBe(6); }); it('should post FormData when requestType=form', async () => { expect.assertions(3); const api = makeApi({ method: 'POST', endpoint: '/test-formdata', requestType: 'form', }); fetchMock.post('glob:*/test-formdata', { test: 'ok' }); expect(await api({ request: 'test' })).toEqual({ test: 'ok' }); const expected = new FormData(); expected.append('request', JSON.stringify('test')); const received = fetchMock.lastOptions()?.body as FormData; expect(received).toBeInstanceOf(FormData); expect(received.get('request')).toEqual(expected.get('request')); }); it('should use searchParams for method=GET (`requestType=search` implied)', async () => { expect.assertions(1); const api = makeApi({ method: 'GET', endpoint: '/test-get-search', }); fetchMock.get('glob:*/test-get-search*', { search: 'get' }); await api({ p1: 1, p2: 2, p3: [1, 2] }); expect(fetchMock.lastUrl()).toContain( '/test-get-search?p1=1&p2=2&p3=1%2C2', ); }); it('should serialize rison for method=GET, requestType=rison', async () => { expect.assertions(1); const api = makeApi({ method: 'GET', endpoint: '/test-post-search', requestType: 'rison', }); fetchMock.get('glob:*/test-post-search*', { rison: 'get' }); await api({ p1: 1, p3: [1, 2] }); expect(fetchMock.lastUrl()).toContain( '/test-post-search?q=(p1:1,p3:!(1,2))', ); }); it('should use searchParams for method=POST, requestType=search', async () => { expect.assertions(1); const api = makeApi({ method: 'POST', endpoint: '/test-post-search', requestType: 'search', }); fetchMock.post('glob:*/test-post-search*', { search: 'post' }); await api({ p1: 1, p3: [1, 2] }); expect(fetchMock.lastUrl()).toContain('/test-post-search?p1=1&p3=1%2C2'); }); it('should throw when requestType is invalid', () => { expect(() => { makeApi({ method: 'POST', endpoint: '/test-formdata', // @ts-ignore requestType: 'text', }); }).toThrow('Invalid request payload type'); }); it('should handle errors', async () => { expect.assertions(1); const api = makeApi({ method: 'POST', endpoint: '/test-formdata', requestType: 'form', }); let error; fetchMock.post('glob:*/test-formdata', { test: 'ok' }); try { await api('<This is an invalid JSON string>'); } catch (err) { error = err; } finally { expect((error as SupersetApiError).message).toContain('Invalid payload'); } }); it('should handle error on 200 response', async () => { expect.assertions(1); const api = makeApi({ method: 'POST', endpoint: '/test-200-error', requestType: 'json', }); fetchMock.post('glob:*/test-200-error', { error: 'not ok' }); let error; try { await api({}); } catch (err) { error = err; } finally { expect((error as SupersetApiError).message).toContain('not ok'); } }); it('should parse text response when responseType=text', async () => { expect.assertions(1); const api = makeApi<JsonValue, string, 'text'>({ method: 'PUT', endpoint: '/test-parse-text', requestType: 'form', responseType: 'text', processResponse: text => `${text}?`, }); fetchMock.put('glob:*/test-parse-text', 'ok'); const result = await api({ field1: 11 }); expect(result).toBe('ok?'); }); it('should return raw response when responseType=raw', async () => { expect.assertions(2); const api = makeApi<JsonValue, number, 'raw'>({ method: 'DELETE', endpoint: '/test-raw-response', responseType: 'raw', processResponse: response => response.status, }); fetchMock.delete('glob:*/test-raw-response?*', 'ok'); const result = await api({ field1: 11 }, {}); expect(result).toEqual(200); expect(fetchMock.lastUrl()).toContain('/test-raw-response?field1=11'); }); });
5,564
0
petrpan-code/apache/superset/superset-frontend/packages/superset-ui-core/test/query
petrpan-code/apache/superset/superset-frontend/packages/superset-ui-core/test/query/types/AnnotationLayer.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, EventAnnotationLayer, FormulaAnnotationLayer, IntervalAnnotationLayer, isEventAnnotationLayer, isFormulaAnnotationLayer, isIntervalAnnotationLayer, isRecordAnnotationResult, isTableAnnotationLayer, isTimeseriesAnnotationLayer, isTimeseriesAnnotationResult, RecordAnnotationResult, TableAnnotationLayer, TimeseriesAnnotationLayer, TimeseriesAnnotationResult, } from '@superset-ui/core'; describe('AnnotationLayer type guards', () => { const formulaAnnotationLayer: FormulaAnnotationLayer = { annotationType: AnnotationType.Formula, name: 'My Formula', value: 'sin(2*x)', style: AnnotationStyle.Solid, show: true, showLabel: false, }; const eventAnnotationLayer: EventAnnotationLayer = { annotationType: AnnotationType.Event, name: 'My Event', value: 1, style: AnnotationStyle.Solid, show: true, showLabel: false, sourceType: AnnotationSourceType.Native, }; const intervalAnnotationLayer: IntervalAnnotationLayer = { annotationType: AnnotationType.Interval, sourceType: AnnotationSourceType.Table, name: 'My Event', value: 1, style: AnnotationStyle.Solid, show: true, showLabel: false, }; const timeseriesAnnotationLayer: TimeseriesAnnotationLayer = { annotationType: AnnotationType.Timeseries, sourceType: AnnotationSourceType.Line, name: 'My Event', value: 1, style: AnnotationStyle.Solid, show: true, showLabel: false, }; const tableAnnotationLayer: TableAnnotationLayer = { annotationType: AnnotationType.Interval, sourceType: AnnotationSourceType.Table, name: 'My Event', value: 1, style: AnnotationStyle.Solid, show: true, showLabel: false, }; const timeseriesAnnotationResult: TimeseriesAnnotationResult = [ { key: 'My Key', values: [ { x: -1000, y: 0 }, { x: 0, y: 1000 }, { x: 1000, y: 2000 }, ], }, ]; const recordAnnotationResult: RecordAnnotationResult = { records: [ { a: 1, b: 2 }, { a: 2, b: 3 }, ], }; describe('isFormulaAnnotationLayer', () => { it('should return true when it is the correct type', () => { expect(isFormulaAnnotationLayer(formulaAnnotationLayer)).toEqual(true); }); it('should return false otherwise', () => { expect(isFormulaAnnotationLayer(eventAnnotationLayer)).toEqual(false); expect(isFormulaAnnotationLayer(intervalAnnotationLayer)).toEqual(false); expect(isFormulaAnnotationLayer(timeseriesAnnotationLayer)).toEqual( false, ); }); }); describe('isEventAnnotationLayer', () => { it('should return true when it is the correct type', () => { expect(isEventAnnotationLayer(eventAnnotationLayer)).toEqual(true); }); it('should return false otherwise', () => { expect(isEventAnnotationLayer(formulaAnnotationLayer)).toEqual(false); expect(isEventAnnotationLayer(intervalAnnotationLayer)).toEqual(false); expect(isEventAnnotationLayer(timeseriesAnnotationLayer)).toEqual(false); }); }); describe('isIntervalAnnotationLayer', () => { it('should return true when it is the correct type', () => { expect(isIntervalAnnotationLayer(intervalAnnotationLayer)).toEqual(true); }); it('should return false otherwise', () => { expect(isIntervalAnnotationLayer(formulaAnnotationLayer)).toEqual(false); expect(isIntervalAnnotationLayer(eventAnnotationLayer)).toEqual(false); expect(isIntervalAnnotationLayer(timeseriesAnnotationLayer)).toEqual( false, ); }); }); describe('isTimeseriesAnnotationLayer', () => { it('should return true when it is the correct type', () => { expect(isTimeseriesAnnotationLayer(timeseriesAnnotationLayer)).toEqual( true, ); }); it('should return false otherwise', () => { expect(isTimeseriesAnnotationLayer(formulaAnnotationLayer)).toEqual( false, ); expect(isTimeseriesAnnotationLayer(eventAnnotationLayer)).toEqual(false); expect(isTimeseriesAnnotationLayer(intervalAnnotationLayer)).toEqual( false, ); }); }); describe('isTableAnnotationLayer', () => { it('should return true when it is the correct type', () => { expect(isTableAnnotationLayer(tableAnnotationLayer)).toEqual(true); }); it('should return false otherwise', () => { expect(isTableAnnotationLayer(formulaAnnotationLayer)).toEqual(false); }); }); describe('isTimeseriesAnnotationResult', () => { it('should return true when it is the correct type', () => { expect(isTimeseriesAnnotationResult(timeseriesAnnotationResult)).toEqual( true, ); }); it('should return false otherwise', () => { expect(isTimeseriesAnnotationResult(recordAnnotationResult)).toEqual( false, ); }); }); describe('isRecordAnnotationResult', () => { it('should return true when it is the correct type', () => { expect(isRecordAnnotationResult(recordAnnotationResult)).toEqual(true); }); it('should return false otherwise', () => { expect(isRecordAnnotationResult(timeseriesAnnotationResult)).toEqual( false, ); }); }); });
5,565
0
petrpan-code/apache/superset/superset-frontend/packages/superset-ui-core/test/query
petrpan-code/apache/superset/superset-frontend/packages/superset-ui-core/test/query/types/Column.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 { isAdhocColumn, isPhysicalColumn, isQueryFormColumn, } from '@superset-ui/core'; const adhocColumn = { expressionType: 'SQL', label: 'country', optionName: 'country', sqlExpression: 'country', }; test('isPhysicalColumn returns true', () => { expect(isPhysicalColumn('gender')).toEqual(true); }); test('isPhysicalColumn returns false', () => { expect(isPhysicalColumn(adhocColumn)).toEqual(false); }); test('isAdhocColumn returns true', () => { expect(isAdhocColumn(adhocColumn)).toEqual(true); }); test('isAdhocColumn returns false', () => { expect(isAdhocColumn('hello')).toEqual(false); expect(isAdhocColumn({})).toEqual(false); expect( isAdhocColumn({ expressionType: 'SQL', label: 'country', optionName: 'country', }), ).toEqual(false); }); test('isQueryFormColumn returns true', () => { expect(isQueryFormColumn('gender')).toEqual(true); expect(isQueryFormColumn(adhocColumn)).toEqual(true); }); test('isQueryFormColumn returns false', () => { expect(isQueryFormColumn({})).toEqual(false); });
5,566
0
petrpan-code/apache/superset/superset-frontend/packages/superset-ui-core/test/query
petrpan-code/apache/superset/superset-frontend/packages/superset-ui-core/test/query/types/Dashboard.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 { isNativeFilter, isFilterDivider, Filter, NativeFilterType, FilterWithDataMask, Divider, isNativeFilterWithDataMask, } from '@superset-ui/core'; const filter: Filter = { cascadeParentIds: [], defaultDataMask: {}, id: 'filter_id', name: 'Filter Name', scope: { rootPath: [], excluded: [] }, filterType: 'filter_type', targets: [{}], controlValues: {}, type: NativeFilterType.NATIVE_FILTER, description: 'Filter description.', }; const filterWithDataMask: FilterWithDataMask = { ...filter, dataMask: { id: 'data_mask_id', filterState: { value: 'Filter value' } }, }; const filterDivider: Divider = { id: 'divider_id', type: NativeFilterType.DIVIDER, title: 'Divider title', description: 'Divider description.', }; test('filter type guard', () => { expect(isNativeFilter(filter)).toBeTruthy(); expect(isNativeFilter(filterWithDataMask)).toBeTruthy(); expect(isNativeFilter(filterDivider)).toBeFalsy(); }); test('filter with dataMask type guard', () => { expect(isNativeFilterWithDataMask(filter)).toBeFalsy(); expect(isNativeFilterWithDataMask(filterWithDataMask)).toBeTruthy(); expect(isNativeFilterWithDataMask(filterDivider)).toBeFalsy(); }); test('filter divider type guard', () => { expect(isFilterDivider(filter)).toBeFalsy(); expect(isFilterDivider(filterWithDataMask)).toBeFalsy(); expect(isFilterDivider(filterDivider)).toBeTruthy(); });
5,567
0
petrpan-code/apache/superset/superset-frontend/packages/superset-ui-core/test/query
petrpan-code/apache/superset/superset-frontend/packages/superset-ui-core/test/query/types/Datasource.test.ts
/** * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ import { DatasourceType, DEFAULT_METRICS } from '@superset-ui/core'; test('DEFAULT_METRICS', () => { expect(DEFAULT_METRICS).toEqual([ { metric_name: 'COUNT(*)', expression: 'COUNT(*)', }, ]); }); test('DatasourceType', () => { expect(Object.keys(DatasourceType).length).toBe(5); expect(DatasourceType.Table).toBe('table'); expect(DatasourceType.Query).toBe('query'); expect(DatasourceType.Dataset).toBe('dataset'); expect(DatasourceType.SlTable).toBe('sl_table'); expect(DatasourceType.SavedQuery).toBe('saved_query'); });
5,568
0
petrpan-code/apache/superset/superset-frontend/packages/superset-ui-core/test/query
petrpan-code/apache/superset/superset-frontend/packages/superset-ui-core/test/query/types/Filter.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 { isUnaryAdhocFilter, isBinaryAdhocFilter, isSetAdhocFilter, isFreeFormAdhocFilter, } from '@superset-ui/core'; describe('Filter type guards', () => { describe('isUnaryAdhocFilter', () => { it('should return true when it is the correct type', () => { expect( isUnaryAdhocFilter({ expressionType: 'SIMPLE', clause: 'WHERE', subject: 'tea', operator: 'IS NOT NULL', }), ).toEqual(true); }); it('should return false otherwise', () => { expect( isUnaryAdhocFilter({ expressionType: 'SIMPLE', clause: 'WHERE', subject: 'tea', operator: '==', comparator: 'matcha', }), ).toEqual(false); }); }); describe('isBinaryAdhocFilter', () => { it('should return true when it is the correct type', () => { expect( isBinaryAdhocFilter({ expressionType: 'SIMPLE', clause: 'WHERE', subject: 'tea', operator: '!=', comparator: 'matcha', }), ).toEqual(true); }); it('should return false otherwise', () => { expect( isBinaryAdhocFilter({ expressionType: 'SIMPLE', clause: 'WHERE', subject: 'tea', operator: 'IS NOT NULL', }), ).toEqual(false); }); }); describe('isSetAdhocFilter', () => { it('should return true when it is the correct type', () => { expect( isSetAdhocFilter({ expressionType: 'SIMPLE', clause: 'WHERE', subject: 'tea', operator: 'IN', comparator: ['hojicha', 'earl grey'], }), ).toEqual(true); }); it('should return false otherwise', () => { expect( isSetAdhocFilter({ expressionType: 'SIMPLE', clause: 'WHERE', subject: 'tea', operator: 'IS NOT NULL', }), ).toEqual(false); }); }); describe('isFreeFormAdhocFilter', () => { it('should return true when it is the correct type', () => { expect( isFreeFormAdhocFilter({ expressionType: 'SQL', clause: 'WHERE', sqlExpression: 'gender = "boy"', }), ).toEqual(true); }); it('should return false otherwise', () => { expect( isFreeFormAdhocFilter({ expressionType: 'SIMPLE', clause: 'WHERE', subject: 'tea', operator: '==', comparator: 'matcha', }), ).toEqual(false); }); }); });
5,569
0
petrpan-code/apache/superset/superset-frontend/packages/superset-ui-core/test/query
petrpan-code/apache/superset/superset-frontend/packages/superset-ui-core/test/query/types/Metric.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 { isSavedMetric, isAdhocMetricSimple, isAdhocMetricSQL, isQueryFormMetric, } from '@superset-ui/core'; const adhocMetricSimple = { expressionType: 'SIMPLE', column: { id: 1, column_name: 'sales', columnName: 'sales', verbose_name: 'sales', }, aggregate: 'SUM', label: 'count', optionName: 'count', }; const adhocMetricSQL = { expressionType: 'SQL', label: 'count', optionName: 'count', sqlExpression: 'count(*)', }; const savedMetric = 'count(*)'; test('isSavedMetric returns true', () => { expect(isSavedMetric(savedMetric)).toEqual(true); }); test('isSavedMetric returns false', () => { expect(isSavedMetric(adhocMetricSQL)).toEqual(false); expect(isSavedMetric(null)).toEqual(false); expect(isSavedMetric(undefined)).toEqual(false); }); test('isAdhocMetricSimple returns true', () => { expect(isAdhocMetricSimple(adhocMetricSimple)).toEqual(true); }); test('isAdhocMetricSimple returns false', () => { expect(isAdhocMetricSimple('hello')).toEqual(false); expect(isAdhocMetricSimple({})).toEqual(false); expect(isAdhocMetricSimple(adhocMetricSQL)).toEqual(false); }); test('isAdhocMetricSQL returns true', () => { expect(isAdhocMetricSQL(adhocMetricSQL)).toEqual(true); }); test('isAdhocMetricSQL returns false', () => { expect(isAdhocMetricSQL('hello')).toEqual(false); expect(isAdhocMetricSQL({})).toEqual(false); expect(isAdhocMetricSQL(adhocMetricSimple)).toEqual(false); }); test('isQueryFormMetric returns true', () => { expect(isQueryFormMetric(adhocMetricSQL)).toEqual(true); expect(isQueryFormMetric(adhocMetricSimple)).toEqual(true); expect(isQueryFormMetric(savedMetric)).toEqual(true); }); test('isQueryFormMetric returns false', () => { expect(isQueryFormMetric({})).toEqual(false); expect(isQueryFormMetric(undefined)).toEqual(false); expect(isQueryFormMetric(null)).toEqual(false); });
5,570
0
petrpan-code/apache/superset/superset-frontend/packages/superset-ui-core/test/query
petrpan-code/apache/superset/superset-frontend/packages/superset-ui-core/test/query/types/PostProcessing.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 { Aggregates, isPostProcessingAggregation, isPostProcessingBoxplot, isPostProcessingCompare, isPostProcessingContribution, isPostProcessingCum, isPostProcessingDiff, isPostProcessingPivot, isPostProcessingProphet, isPostProcessingRolling, isPostProcessingResample, isPostProcessingSort, PandasAxis, PostProcessingAggregation, PostProcessingBoxplot, PostProcessingCompare, PostProcessingContribution, PostProcessingCum, PostProcessingDiff, PostProcessingPivot, PostProcessingProphet, PostProcessingResample, PostProcessingRolling, PostProcessingSort, } from '@superset-ui/core'; import { ComparisonType, RollingType, TimeGranularity } from '../../../src'; const AGGREGATES_OPTION: Aggregates = { bar: { operator: 'max', column: 'bar', options: {}, }, }; const AGGREGATE_RULE: PostProcessingAggregation = { operation: 'aggregation', options: { groupby: ['foo'], aggregates: AGGREGATES_OPTION, }, }; const BOXPLOT_RULE: PostProcessingBoxplot = { operation: 'boxplot', options: { groupby: ['foo'], metrics: ['bar'], whisker_type: 'tukey', }, }; const COMPARE_RULE: PostProcessingCompare = { operation: 'compare', options: { source_columns: ['foo'], compare_columns: ['bar'], compare_type: ComparisonType.Percentage, drop_original_columns: false, }, }; const CONTRIBUTION_RULE: PostProcessingContribution = { operation: 'contribution', options: { orientation: 'row', columns: ['foo'], }, }; const CUM_RULE: PostProcessingCum = { operation: 'cum', options: { columns: ['foo'], operator: 'min', }, }; const DIFF_RULE: PostProcessingDiff = { operation: 'diff', options: { columns: ['foo'], periods: 12, axis: PandasAxis.Column, }, }; const PIVOT_RULE: PostProcessingPivot = { operation: 'pivot', options: { index: ['foo'], columns: ['bar'], aggregates: AGGREGATES_OPTION, }, }; const PROPHET_RULE: PostProcessingProphet = { operation: 'prophet', options: { time_grain: TimeGranularity.DAY, periods: 365, confidence_interval: 0.8, yearly_seasonality: false, weekly_seasonality: false, daily_seasonality: false, }, }; const RESAMPLE_RULE: PostProcessingResample = { operation: 'resample', options: { method: 'method', rule: 'rule', fill_value: null, }, }; const ROLLING_RULE: PostProcessingRolling = { operation: 'rolling', options: { rolling_type: RollingType.Cumsum, window: 12, min_periods: 12, columns: ['foo', 'bar'], }, }; const SORT_RULE: PostProcessingSort = { operation: 'sort', options: { by: 'foo', }, }; test('PostProcessingAggregation type guard', () => { expect(isPostProcessingAggregation(AGGREGATE_RULE)).toEqual(true); expect(isPostProcessingAggregation(BOXPLOT_RULE)).toEqual(false); expect(isPostProcessingAggregation(undefined)).toEqual(false); }); test('PostProcessingBoxplot type guard', () => { expect(isPostProcessingBoxplot(BOXPLOT_RULE)).toEqual(true); expect(isPostProcessingBoxplot(AGGREGATE_RULE)).toEqual(false); expect(isPostProcessingBoxplot(undefined)).toEqual(false); }); test('PostProcessingCompare type guard', () => { expect(isPostProcessingCompare(COMPARE_RULE)).toEqual(true); expect(isPostProcessingCompare(AGGREGATE_RULE)).toEqual(false); expect(isPostProcessingCompare(undefined)).toEqual(false); }); test('PostProcessingContribution type guard', () => { expect(isPostProcessingContribution(CONTRIBUTION_RULE)).toEqual(true); expect(isPostProcessingContribution(AGGREGATE_RULE)).toEqual(false); expect(isPostProcessingContribution(undefined)).toEqual(false); }); test('PostProcessingCum type guard', () => { expect(isPostProcessingCum(CUM_RULE)).toEqual(true); expect(isPostProcessingCum(AGGREGATE_RULE)).toEqual(false); expect(isPostProcessingCum(undefined)).toEqual(false); }); test('PostProcessingDiff type guard', () => { expect(isPostProcessingDiff(DIFF_RULE)).toEqual(true); expect(isPostProcessingDiff(AGGREGATE_RULE)).toEqual(false); expect(isPostProcessingDiff(undefined)).toEqual(false); }); test('PostProcessingPivot type guard', () => { expect(isPostProcessingPivot(PIVOT_RULE)).toEqual(true); expect(isPostProcessingPivot(AGGREGATE_RULE)).toEqual(false); expect(isPostProcessingPivot(undefined)).toEqual(false); }); test('PostProcessingProphet type guard', () => { expect(isPostProcessingProphet(PROPHET_RULE)).toEqual(true); expect(isPostProcessingProphet(AGGREGATE_RULE)).toEqual(false); expect(isPostProcessingProphet(undefined)).toEqual(false); }); test('PostProcessingResample type guard', () => { expect(isPostProcessingResample(RESAMPLE_RULE)).toEqual(true); expect(isPostProcessingResample(AGGREGATE_RULE)).toEqual(false); expect(isPostProcessingResample(undefined)).toEqual(false); }); test('PostProcessingRolling type guard', () => { expect(isPostProcessingRolling(ROLLING_RULE)).toEqual(true); expect(isPostProcessingRolling(AGGREGATE_RULE)).toEqual(false); expect(isPostProcessingRolling(undefined)).toEqual(false); }); test('PostProcessingSort type guard', () => { expect(isPostProcessingSort(SORT_RULE)).toEqual(true); expect(isPostProcessingSort(AGGREGATE_RULE)).toEqual(false); expect(isPostProcessingSort(undefined)).toEqual(false); });
5,571
0
petrpan-code/apache/superset/superset-frontend/packages/superset-ui-core/test
petrpan-code/apache/superset/superset-frontend/packages/superset-ui-core/test/style/index.test.tsx
/* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ import React from 'react'; import { mount } from 'enzyme'; import { styled, supersetTheme, SupersetThemeProps, useTheme, ThemeProvider, EmotionCacheProvider, emotionCache, } from '@superset-ui/core'; describe('@superset-ui/style package', () => { it('exports a theme', () => { expect(typeof supersetTheme).toBe('object'); }); it('exports styled component templater', () => { expect(typeof styled.div).toBe('function'); }); it('exports SupersetThemeProps', () => { const props: SupersetThemeProps = { theme: supersetTheme, }; expect(typeof props).toBe('object'); }); describe('useTheme()', () => { it('returns the theme', () => { function ThemeUser() { expect(useTheme()).toStrictEqual(supersetTheme); return <div>test</div>; } mount(<ThemeUser />, { wrappingComponent: ({ children }) => ( <EmotionCacheProvider value={emotionCache}> <ThemeProvider theme={supersetTheme}>{children}</ThemeProvider> </EmotionCacheProvider> ), }); }); it('throws when a theme is not present', () => { function ThemeUser() { expect(useTheme).toThrow(/could not find a ThemeContext/); return <div>test</div>; } mount(<ThemeUser />, { wrappingComponent: ({ children }) => <div>{children}</div>, }); }); }); });
5,572
0
petrpan-code/apache/superset/superset-frontend/packages/superset-ui-core/test
petrpan-code/apache/superset/superset-frontend/packages/superset-ui-core/test/time-format/TimeFormatter.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 { TimeFormatter, PREVIEW_TIME } from '@superset-ui/core'; describe('TimeFormatter', () => { describe('new TimeFormatter(config)', () => { it('requires config.id', () => { expect( () => // @ts-ignore -- intentionally pass invalid input new TimeFormatter({ formatFunc: () => 'test', }), ).toThrow(); }); it('requires config.formatFunc', () => { expect( () => // @ts-ignore -- intentionally pass invalid input new TimeFormatter({ id: 'my_format', }), ).toThrow(); }); }); describe('formatter is also a format function itself', () => { const formatter = new TimeFormatter({ id: 'year_only', formatFunc: (value: Date) => `${value.getFullYear()}`, }); it('returns formatted value', () => { expect(formatter(PREVIEW_TIME)).toEqual('2017'); }); it('formatter(value) is the same with formatter.format(value)', () => { const value = PREVIEW_TIME; expect(formatter(value)).toEqual(formatter.format(value)); }); }); describe('.format(value)', () => { const formatter = new TimeFormatter({ id: 'year_only', formatFunc: value => `${value.getFullYear()}`, }); it('handles null', () => { expect(formatter.format(null)).toEqual('null'); }); it('handles undefined', () => { expect(formatter.format(undefined)).toEqual('undefined'); }); it('handles number, treating it as a timestamp', () => { expect(formatter.format(PREVIEW_TIME.getTime())).toEqual('2017'); }); it('otherwise returns formatted value', () => { expect(formatter.format(PREVIEW_TIME)).toEqual('2017'); }); }); describe('.preview(value)', () => { const formatter = new TimeFormatter({ id: 'year_only', formatFunc: value => `${value.getFullYear()}`, }); it('returns string comparing value before and after formatting', () => { const time = new Date(Date.UTC(2018, 10, 21, 22, 11, 44)); expect(formatter.preview(time)).toEqual( 'Wed, 21 Nov 2018 22:11:44 GMT => 2018', ); }); it('uses the default preview value if not specified', () => { expect(formatter.preview()).toEqual( 'Tue, 14 Feb 2017 11:22:33 GMT => 2017', ); }); }); });
5,573
0
petrpan-code/apache/superset/superset-frontend/packages/superset-ui-core/test
petrpan-code/apache/superset/superset-frontend/packages/superset-ui-core/test/time-format/TimeFormatterRegistry.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 { TimeFormats, TimeFormatter, PREVIEW_TIME } from '@superset-ui/core'; import TimeFormatterRegistry from '../../src/time-format/TimeFormatterRegistry'; describe('TimeFormatterRegistry', () => { let registry: TimeFormatterRegistry; beforeEach(() => { registry = new TimeFormatterRegistry(); }); describe('.get(format)', () => { it('creates and returns a new formatter if does not exist', () => { const formatter = registry.get(TimeFormats.DATABASE_DATETIME); expect(formatter).toBeInstanceOf(TimeFormatter); expect(formatter.format(PREVIEW_TIME)).toEqual('2017-02-14 11:22:33'); }); it('returns an existing formatter if already exists', () => { const formatter = registry.get(TimeFormats.TIME); const formatter2 = registry.get(TimeFormats.TIME); expect(formatter).toBe(formatter2); }); it('falls back to default format if format is not specified', () => { registry.setDefaultKey(TimeFormats.INTERNATIONAL_DATE); const formatter = registry.get(); expect(formatter.format(PREVIEW_TIME)).toEqual('14/02/2017'); }); it('falls back to default format if format is null', () => { registry.setDefaultKey(TimeFormats.INTERNATIONAL_DATE); // @ts-ignore const formatter = registry.get(null); expect(formatter.format(PREVIEW_TIME)).toEqual('14/02/2017'); }); it('falls back to default format if format is undefined', () => { registry.setDefaultKey(TimeFormats.INTERNATIONAL_DATE); const formatter = registry.get(undefined); expect(formatter.format(PREVIEW_TIME)).toEqual('14/02/2017'); }); it('falls back to default format if format is empty string', () => { registry.setDefaultKey(TimeFormats.INTERNATIONAL_DATE); const formatter = registry.get(''); expect(formatter.format(PREVIEW_TIME)).toEqual('14/02/2017'); }); it('removes leading and trailing spaces from format', () => { const formatter = registry.get(' %Y '); expect(formatter).toBeInstanceOf(TimeFormatter); expect(formatter.format(PREVIEW_TIME)).toEqual('2017'); }); }); describe('.format(format, value)', () => { it('return the value with the specified format', () => { expect(registry.format(TimeFormats.US_DATE, PREVIEW_TIME)).toEqual( '02/14/2017', ); expect(registry.format(TimeFormats.TIME, PREVIEW_TIME)).toEqual( '11:22:33', ); }); it('falls back to the default formatter if the format is undefined', () => { expect(registry.format(undefined, PREVIEW_TIME)).toEqual( '2017-02-14 11:22:33', ); }); }); });
5,574
0
petrpan-code/apache/superset/superset-frontend/packages/superset-ui-core/test
petrpan-code/apache/superset/superset-frontend/packages/superset-ui-core/test/time-format/TimeFormatterRegistrySingleton.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, LOCAL_PREFIX, PREVIEW_TIME, getTimeFormatter, formatTime, getTimeFormatterForGranularity, formatTimeRange, getTimeFormatterRegistry, } from '@superset-ui/core'; import TimeFormatterRegistry from '../../src/time-format/TimeFormatterRegistry'; describe('TimeFormatterRegistrySingleton', () => { describe('getTimeFormatterRegistry()', () => { it('returns a TimeFormatterRegistry', () => { expect(getTimeFormatterRegistry()).toBeInstanceOf(TimeFormatterRegistry); }); }); describe('getTimeFormatter(format)', () => { it('returns a format function', () => { const format = getTimeFormatter('%d/%m/%Y'); expect(format(PREVIEW_TIME)).toEqual('14/02/2017'); }); it('falls back to default format if format is not specified', () => { const format = getTimeFormatter(); expect(format(PREVIEW_TIME)).toEqual('2017-02-14 11:22:33'); }); it(`use local time when format string has LOCAL_PREFIX (${LOCAL_PREFIX})`, () => { const format = getTimeFormatter('local!%m-%d %H:%M'); expect(format(new Date(2019, 5, 18, 11, 23))).toEqual('06-18 11:23'); }); }); describe('getTimeFormatterForGranularity(granularity?)', () => { it('returns the default formatter for that granularity', () => { const date = new Date(Date.UTC(2020, 4, 10)); // May 10, 2020 is Sunday expect( getTimeFormatterForGranularity(TimeGranularity.DATE)(date), ).toEqual('2020-05-10'); }); }); describe('formatTimeRange(format?, values)', () => { it('format the given time range with specified format', () => { expect( formatTimeRange('%m-%d', [ new Date(Date.UTC(2017, 1, 1)), new Date(Date.UTC(2017, 1, 2)), ]), ).toEqual('02-01 — 02-02'); }); it('show only one value if start and end are equal after formatting', () => { expect( formatTimeRange('%m-%d', [ new Date(Date.UTC(2017, 1, 1)), new Date(Date.UTC(2017, 1, 1, 10)), ]), ).toEqual('02-01'); }); it('falls back to default format if format is not specified', () => { expect( formatTimeRange(undefined, [ new Date(Date.UTC(2017, 1, 1)), new Date(Date.UTC(2017, 1, 2)), ]), ).toEqual('2017-02-01 00:00:00 — 2017-02-02 00:00:00'); }); }); describe('formatTime(format?, value, granularity?)', () => { describe('without granularity', () => { it('format the given time using the specified format', () => { const output = formatTime('%Y-%m-%d', PREVIEW_TIME); expect(output).toEqual('2017-02-14'); }); it('falls back to the default formatter if the format is undefined', () => { expect(formatTime(undefined, PREVIEW_TIME)).toEqual( '2017-02-14 11:22:33', ); }); }); describe('with granularity', () => { it('format the given time using specified format', () => { const output = formatTime( '%-m/%d', new Date(Date.UTC(2017, 4, 10)), TimeGranularity.WEEK, ); expect(output).toEqual('5/10 — 5/16'); }); it('format the given time using default format if format is not specified', () => { const date = new Date(Date.UTC(2020, 4, 10)); // May 10, 2020 is Sunday expect(formatTime(undefined, date, TimeGranularity.DATE)).toEqual( '2020-05-10', ); expect(formatTime(undefined, date, TimeGranularity.SECOND)).toEqual( '2020-05-10 00:00:00', ); expect(formatTime(undefined, date, TimeGranularity.MINUTE)).toEqual( '2020-05-10 00:00', ); expect( formatTime(undefined, date, TimeGranularity.FIVE_MINUTES), ).toEqual('2020-05-10 00:00 — 2020-05-10 00:04'); expect( formatTime(undefined, date, TimeGranularity.TEN_MINUTES), ).toEqual('2020-05-10 00:00 — 2020-05-10 00:09'); expect( formatTime(undefined, date, TimeGranularity.FIFTEEN_MINUTES), ).toEqual('2020-05-10 00:00 — 2020-05-10 00:14'); expect( formatTime(undefined, date, TimeGranularity.THIRTY_MINUTES), ).toEqual('2020-05-10 00:00 — 2020-05-10 00:29'); expect(formatTime(undefined, date, TimeGranularity.HOUR)).toEqual( '2020-05-10 00:00', ); expect(formatTime(undefined, date, TimeGranularity.DAY)).toEqual( '2020-05-10', ); expect(formatTime(undefined, date, TimeGranularity.WEEK)).toEqual( '2020-05-10 — 2020-05-16', ); expect( formatTime(undefined, date, TimeGranularity.WEEK_STARTING_SUNDAY), ).toEqual('2020-05-10 — 2020-05-16'); expect( formatTime( undefined, new Date(Date.UTC(2020, 4, 11)), TimeGranularity.WEEK_STARTING_MONDAY, ), ).toEqual('2020-05-11 — 2020-05-17'); expect( formatTime( undefined, new Date(Date.UTC(2020, 4, 10)), TimeGranularity.WEEK_ENDING_SUNDAY, ), ).toEqual('2020-05-04 — 2020-05-10'); expect( formatTime( undefined, new Date(Date.UTC(2020, 4, 9)), TimeGranularity.WEEK_ENDING_SATURDAY, ), ).toEqual('2020-05-03 — 2020-05-09'); expect( formatTime( undefined, new Date(Date.UTC(2020, 3, 1)), TimeGranularity.MONTH, ), ).toEqual('Apr 2020'); expect( formatTime( undefined, new Date(Date.UTC(2020, 3, 1)), TimeGranularity.QUARTER, ), ).toEqual('2020 Q2'); expect( formatTime( undefined, new Date(Date.UTC(2020, 0, 1)), TimeGranularity.YEAR, ), ).toEqual('2020'); }); }); }); });
5,575
0
petrpan-code/apache/superset/superset-frontend/packages/superset-ui-core/test
petrpan-code/apache/superset/superset-frontend/packages/superset-ui-core/test/time-format/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 { createD3TimeFormatter, createMultiFormatter, formatTime, getTimeFormatter, getTimeFormatterRegistry, LOCAL_PREFIX, PREVIEW_TIME, smartDateFormatter, smartDateVerboseFormatter, TimeFormats, TimeFormatter, } from '@superset-ui/core'; describe('index', () => { it('exports modules', () => { [ createD3TimeFormatter, createMultiFormatter, formatTime, getTimeFormatter, getTimeFormatterRegistry, LOCAL_PREFIX, PREVIEW_TIME, smartDateFormatter, smartDateVerboseFormatter, TimeFormats, TimeFormatter, ].forEach(x => expect(x).toBeDefined()); }); });
5,576
0
petrpan-code/apache/superset/superset-frontend/packages/superset-ui-core/test/time-format
petrpan-code/apache/superset/superset-frontend/packages/superset-ui-core/test/time-format/factories/createD3TimeFormatter.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 { TimeLocaleDefinition } from 'd3-time-format'; import { createD3TimeFormatter, PREVIEW_TIME, TimeFormats, } from '@superset-ui/core'; const thLocale: TimeLocaleDefinition = { dateTime: '%a %e %b %Y %X', date: '%d/%m/%Y', time: '%H:%M:%S', periods: ['AM', 'PM'], days: [ 'วันอาทิตย์', 'วันจันทร์', 'วันอังคาร', 'วันพุธ', 'วันพฤหัส', 'วันศุกร์', 'วันเสาร์', ], shortDays: ['อา.', 'จ.', 'อ.', 'พ.', 'พฤ', 'ศ.', 'ส.'], months: [ 'มกราคม', 'กุมภาพันธ์', 'มีนาคม', 'เมษายน', 'พฤษภาคม', 'มิถุนายน', 'กรกฎาคม', 'สิงหาคม', 'กันยายน', 'ตุลาคม', 'พฤศจิกายน', 'ธันวาคม', ], shortMonths: [ 'ม.ค.', 'ก.พ.', 'มี.ค.', 'เม.ย.', 'พ.ค.', 'มิ.ย.', 'ก.ค.', 'ส.ค.', 'ก.ย.', 'ต.ค.', 'พ.ย.', 'ธ.ค.', ], }; describe('createD3TimeFormatter(config)', () => { it('requires config.formatString', () => { // @ts-ignore expect(() => createD3TimeFormatter()).toThrow(); // @ts-ignore expect(() => createD3TimeFormatter({})).toThrow(); }); describe('config.useLocalTime', () => { it('if falsy, formats in UTC time', () => { const formatter = createD3TimeFormatter({ formatString: TimeFormats.DATABASE_DATETIME, }); expect(formatter.format(PREVIEW_TIME)).toEqual('2017-02-14 11:22:33'); }); it('if true, formats in local time', () => { const formatter = createD3TimeFormatter({ formatString: TimeFormats.DATABASE_DATETIME, useLocalTime: true, }); const formatterInUTC = createD3TimeFormatter({ formatString: TimeFormats.DATABASE_DATETIME, }); const offset = new Date(PREVIEW_TIME.valueOf()).getTimezoneOffset(); // in minutes const expected = offset === 0 ? '2017-02-14 11:22:33' : formatterInUTC( new Date(PREVIEW_TIME.valueOf() - 60 * 1000 * offset), ); expect(formatter.format(PREVIEW_TIME)).toEqual(expected); }); }); describe('config.locale', () => { const TEST_TIME = new Date(Date.UTC(2015, 11, 20)); it('supports locale customization (utc time)', () => { const formatter = createD3TimeFormatter({ formatString: '%c', locale: thLocale, }); expect(formatter(TEST_TIME)).toEqual('อา. 20 ธ.ค. 2015 00:00:00'); }); it('supports locale customization (local time)', () => { const formatter = createD3TimeFormatter({ formatString: '%c', locale: thLocale, useLocalTime: true, }); const formatterInUTC = createD3TimeFormatter({ formatString: '%c', locale: thLocale, }); const offset = new Date(PREVIEW_TIME.valueOf()).getTimezoneOffset(); const expected = offset === 0 ? 'อา. 20 ธ.ค. 2015 00:00:00' : formatterInUTC(new Date(TEST_TIME.valueOf() - 60 * 1000 * offset)); expect(formatter(TEST_TIME)).toEqual(expected); }); }); });
5,577
0
petrpan-code/apache/superset/superset-frontend/packages/superset-ui-core/test/time-format
petrpan-code/apache/superset/superset-frontend/packages/superset-ui-core/test/time-format/factories/createMultiFormatter.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 { createMultiFormatter } from '@superset-ui/core'; describe('createMultiFormatter()', () => { describe('creates a multi-step formatter', () => { const formatter = createMultiFormatter({ id: 'my_format', useLocalTime: true, }); it('formats millisecond', () => { expect(formatter(new Date(2018, 10, 20, 11, 22, 33, 100))).toEqual( '.100', ); }); it('formats second', () => { expect(formatter(new Date(2018, 10, 20, 11, 22, 33))).toEqual(':33'); }); it('format minutes', () => { expect(formatter(new Date(2018, 10, 20, 11, 22))).toEqual('11:22'); }); it('format hours', () => { expect(formatter(new Date(2018, 10, 20, 11))).toEqual('11 AM'); }); it('format first day of week', () => { expect(formatter(new Date(2018, 10, 18))).toEqual('Nov 18'); }); it('format other day of week', () => { expect(formatter(new Date(2018, 10, 20))).toEqual('Tue 20'); }); it('format month', () => { expect(formatter(new Date(2018, 10))).toEqual('November'); }); it('format year', () => { expect(formatter(new Date(2018, 0))).toEqual('2018'); }); }); });
5,578
0
petrpan-code/apache/superset/superset-frontend/packages/superset-ui-core/test/time-format
petrpan-code/apache/superset/superset-frontend/packages/superset-ui-core/test/time-format/formatters/smartDate.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 { TimeFormatter, smartDateFormatter } from '@superset-ui/core'; describe('smartDateFormatter', () => { it('is a function', () => { expect(smartDateFormatter).toBeInstanceOf(TimeFormatter); }); it('shows only year when 1st day of the year', () => { expect(smartDateFormatter(new Date('2020-01-01'))).toBe('2020'); }); it('shows only month when 1st of month', () => { expect(smartDateFormatter(new Date('2020-03-01'))).toBe('March'); }); it('does not show day of week when it is Sunday', () => { expect(smartDateFormatter(new Date('2020-03-15'))).toBe('Mar 15'); }); it('shows weekday when it is not Sunday (and no ms/sec/min/hr)', () => { expect(smartDateFormatter(new Date('2020-03-03'))).toBe('Tue 03'); }); });
5,579
0
petrpan-code/apache/superset/superset-frontend/packages/superset-ui-core/test/time-format
petrpan-code/apache/superset/superset-frontend/packages/superset-ui-core/test/time-format/formatters/smartDateDetailed.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 { TimeFormatter, smartDateDetailedFormatter } from '@superset-ui/core'; describe('smartDateDetailedFormatter', () => { const formatter = smartDateDetailedFormatter; it('is a function', () => { expect(formatter).toBeInstanceOf(TimeFormatter); }); it('shows only year when 1st day of the year', () => { expect(formatter(new Date('2020-01-01T00:00:00.000+00:00'))).toBe('2020'); }); it('shows full date when a regular date', () => { expect(formatter(new Date('2020-03-01T00:00:00.000+00:00'))).toBe( '2020-03-01', ); }); it('shows full date including time of day without seconds when hour precision', () => { expect(formatter(new Date('2020-03-01T13:00:00.000+00:00'))).toBe( '2020-03-01 13:00', ); }); it('shows full date including time of day when minute precision', () => { expect(formatter(new Date('2020-03-10T13:10:00.000+00:00'))).toBe( '2020-03-10 13:10', ); }); it('shows full date including time of day when subsecond precision', () => { expect(formatter(new Date('2020-03-10T13:10:00.100+00:00'))).toBe( '2020-03-10 13:10:00.100', ); }); });
5,580
0
petrpan-code/apache/superset/superset-frontend/packages/superset-ui-core/test/time-format
petrpan-code/apache/superset/superset-frontend/packages/superset-ui-core/test/time-format/formatters/smartDateVerbose.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 { TimeFormatter, smartDateVerboseFormatter } from '@superset-ui/core'; describe('smartDateVerboseFormatter', () => { const formatter = smartDateVerboseFormatter; it('is a function', () => { expect(formatter).toBeInstanceOf(TimeFormatter); }); it('shows only year when 1st day of the year', () => { expect(formatter(new Date('2020-01-01'))).toBe('2020'); }); it('shows month and year when 1st of month', () => { expect(formatter(new Date('2020-03-01'))).toBe('Mar 2020'); }); it('shows weekday when any day of the month', () => { expect(formatter(new Date('2020-03-03'))).toBe('Tue Mar 3'); expect(formatter(new Date('2020-03-15'))).toBe('Sun Mar 15'); }); });
5,581
0
petrpan-code/apache/superset/superset-frontend/packages/superset-ui-core/test/time-format
petrpan-code/apache/superset/superset-frontend/packages/superset-ui-core/test/time-format/utils/createTime.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 createTime from '../../../src/time-format/utils/createTime'; describe('createTime(mode, year, month, date, hours, minutes, seconds, milliseconds)', () => { describe('mode', () => { it('creates UTC time when mode==="utc"', () => { const time = createTime('utc', 2020, 5, 15); expect(time.getUTCFullYear()).toEqual(2020); expect(time.getUTCMonth()).toEqual(5); expect(time.getUTCDate()).toEqual(15); }); it('creates local time when mode==="local"', () => { const time = createTime('local', 2020, 5, 15); expect(time.getFullYear()).toEqual(2020); expect(time.getMonth()).toEqual(5); expect(time.getDate()).toEqual(15); }); }); it('sets all the date parts', () => { const time = createTime('local', 2020, 5, 15, 1, 2, 3, 4); expect(time.getFullYear()).toEqual(2020); expect(time.getMonth()).toEqual(5); expect(time.getDate()).toEqual(15); expect(time.getHours()).toEqual(1); expect(time.getMinutes()).toEqual(2); expect(time.getSeconds()).toEqual(3); expect(time.getMilliseconds()).toEqual(4); }); it('sets default values for date parts', () => { const time = createTime('utc', 2020); expect(time.getUTCMonth()).toEqual(0); expect(time.getUTCDate()).toEqual(1); expect(time.getUTCHours()).toEqual(0); expect(time.getUTCMinutes()).toEqual(0); expect(time.getUTCSeconds()).toEqual(0); expect(time.getUTCMilliseconds()).toEqual(0); }); });
5,582
0
petrpan-code/apache/superset/superset-frontend/packages/superset-ui-core/test/time-format
petrpan-code/apache/superset/superset-frontend/packages/superset-ui-core/test/time-format/utils/createTimeRangeFromGranularity.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, getTimeRangeFormatter, LOCAL_PREFIX, } from '@superset-ui/core'; import createTimeRangeFromGranularity from '../../../src/time-format/utils/createTimeRangeFromGranularity'; const formatString = '%Y-%m-%d %H:%M:%S.%L'; const formatUTCTimeRange = getTimeRangeFormatter(formatString); const formatLocalTimeRange = getTimeRangeFormatter( `${LOCAL_PREFIX}${formatString}`, ); function testUTC( granularity: TimeGranularity, year: number, month = 0, date = 1, hours = 0, minutes = 0, seconds = 0, ) { return formatUTCTimeRange( createTimeRangeFromGranularity( new Date(Date.UTC(year, month, date, hours, minutes, seconds)), granularity, ), ); } function testLocal( granularity: TimeGranularity, year: number, month = 0, date = 1, hours = 0, minutes = 0, seconds = 0, ) { return formatLocalTimeRange( createTimeRangeFromGranularity( new Date(year, month, date, hours, minutes, seconds), granularity, true, ), ); } describe('createTimeRangeFromGranularity(time, granularity, useLocalTime)', () => { describe('UTC time', () => { it('creates time range according to specified granularity', () => { expect(testUTC(TimeGranularity.DATE, 2020, 4, 15)).toEqual( '2020-05-15 00:00:00.000 — 2020-05-15 23:59:59.999', ); expect(testUTC(TimeGranularity.SECOND, 2020, 4, 15)).toEqual( '2020-05-15 00:00:00.000 — 2020-05-15 00:00:00.999', ); expect(testUTC(TimeGranularity.MINUTE, 2020, 4, 15)).toEqual( '2020-05-15 00:00:00.000 — 2020-05-15 00:00:59.999', ); expect(testUTC(TimeGranularity.FIVE_MINUTES, 2020, 4, 15)).toEqual( '2020-05-15 00:00:00.000 — 2020-05-15 00:04:59.999', ); expect(testUTC(TimeGranularity.TEN_MINUTES, 2020, 4, 15)).toEqual( '2020-05-15 00:00:00.000 — 2020-05-15 00:09:59.999', ); expect(testUTC(TimeGranularity.FIFTEEN_MINUTES, 2020, 4, 15)).toEqual( '2020-05-15 00:00:00.000 — 2020-05-15 00:14:59.999', ); expect(testUTC(TimeGranularity.THIRTY_MINUTES, 2020, 4, 15)).toEqual( '2020-05-15 00:00:00.000 — 2020-05-15 00:29:59.999', ); expect(testUTC(TimeGranularity.HOUR, 2020, 4, 15)).toEqual( '2020-05-15 00:00:00.000 — 2020-05-15 00:59:59.999', ); expect(testUTC(TimeGranularity.DAY, 2020, 4, 15)).toEqual( '2020-05-15 00:00:00.000 — 2020-05-15 23:59:59.999', ); expect(testUTC(TimeGranularity.WEEK, 2020, 4, 15)).toEqual( '2020-05-15 00:00:00.000 — 2020-05-21 23:59:59.999', ); expect( testUTC(TimeGranularity.WEEK_STARTING_SUNDAY, 2020, 4, 17), ).toEqual('2020-05-17 00:00:00.000 — 2020-05-23 23:59:59.999'); expect( testUTC(TimeGranularity.WEEK_STARTING_MONDAY, 2020, 4, 18), ).toEqual('2020-05-18 00:00:00.000 — 2020-05-24 23:59:59.999'); expect( testUTC(TimeGranularity.WEEK_ENDING_SATURDAY, 2020, 4, 16), ).toEqual('2020-05-10 00:00:00.000 — 2020-05-16 23:59:59.999'); expect(testUTC(TimeGranularity.WEEK_ENDING_SUNDAY, 2020, 4, 17)).toEqual( '2020-05-11 00:00:00.000 — 2020-05-17 23:59:59.999', ); expect(testUTC(TimeGranularity.MONTH, 2020, 4, 1)).toEqual( '2020-05-01 00:00:00.000 — 2020-05-31 23:59:59.999', ); expect(testUTC(TimeGranularity.MONTH, 2020, 11, 1)).toEqual( '2020-12-01 00:00:00.000 — 2020-12-31 23:59:59.999', ); expect(testUTC(TimeGranularity.QUARTER, 2020, 3, 1)).toEqual( '2020-04-01 00:00:00.000 — 2020-06-30 23:59:59.999', ); expect(testUTC(TimeGranularity.QUARTER, 2020, 9, 1)).toEqual( '2020-10-01 00:00:00.000 — 2020-12-31 23:59:59.999', ); expect(testUTC(TimeGranularity.YEAR, 2020, 0, 1)).toEqual( '2020-01-01 00:00:00.000 — 2020-12-31 23:59:59.999', ); }); }); describe('Local time', () => { it('creates time range according to specified granularity', () => { expect(testLocal(TimeGranularity.DATE, 2020, 4, 15)).toEqual( '2020-05-15 00:00:00.000 — 2020-05-15 23:59:59.999', ); expect(testLocal(TimeGranularity.SECOND, 2020, 4, 15)).toEqual( '2020-05-15 00:00:00.000 — 2020-05-15 00:00:00.999', ); expect(testLocal(TimeGranularity.MINUTE, 2020, 4, 15)).toEqual( '2020-05-15 00:00:00.000 — 2020-05-15 00:00:59.999', ); expect(testLocal(TimeGranularity.FIVE_MINUTES, 2020, 4, 15)).toEqual( '2020-05-15 00:00:00.000 — 2020-05-15 00:04:59.999', ); expect(testLocal(TimeGranularity.TEN_MINUTES, 2020, 4, 15)).toEqual( '2020-05-15 00:00:00.000 — 2020-05-15 00:09:59.999', ); expect(testLocal(TimeGranularity.FIFTEEN_MINUTES, 2020, 4, 15)).toEqual( '2020-05-15 00:00:00.000 — 2020-05-15 00:14:59.999', ); expect(testLocal(TimeGranularity.THIRTY_MINUTES, 2020, 4, 15)).toEqual( '2020-05-15 00:00:00.000 — 2020-05-15 00:29:59.999', ); expect(testLocal(TimeGranularity.HOUR, 2020, 4, 15)).toEqual( '2020-05-15 00:00:00.000 — 2020-05-15 00:59:59.999', ); expect(testLocal(TimeGranularity.DAY, 2020, 4, 15)).toEqual( '2020-05-15 00:00:00.000 — 2020-05-15 23:59:59.999', ); expect(testLocal(TimeGranularity.WEEK, 2020, 4, 15)).toEqual( '2020-05-15 00:00:00.000 — 2020-05-21 23:59:59.999', ); expect( testLocal(TimeGranularity.WEEK_STARTING_SUNDAY, 2020, 4, 17), ).toEqual('2020-05-17 00:00:00.000 — 2020-05-23 23:59:59.999'); expect( testLocal(TimeGranularity.WEEK_STARTING_MONDAY, 2020, 4, 18), ).toEqual('2020-05-18 00:00:00.000 — 2020-05-24 23:59:59.999'); expect( testLocal(TimeGranularity.WEEK_ENDING_SATURDAY, 2020, 4, 16), ).toEqual('2020-05-10 00:00:00.000 — 2020-05-16 23:59:59.999'); expect( testLocal(TimeGranularity.WEEK_ENDING_SUNDAY, 2020, 4, 17), ).toEqual('2020-05-11 00:00:00.000 — 2020-05-17 23:59:59.999'); expect(testLocal(TimeGranularity.MONTH, 2020, 4, 1)).toEqual( '2020-05-01 00:00:00.000 — 2020-05-31 23:59:59.999', ); expect(testLocal(TimeGranularity.MONTH, 2020, 11, 1)).toEqual( '2020-12-01 00:00:00.000 — 2020-12-31 23:59:59.999', ); expect(testLocal(TimeGranularity.QUARTER, 2020, 3, 1)).toEqual( '2020-04-01 00:00:00.000 — 2020-06-30 23:59:59.999', ); expect(testLocal(TimeGranularity.QUARTER, 2020, 9, 1)).toEqual( '2020-10-01 00:00:00.000 — 2020-12-31 23:59:59.999', ); expect(testLocal(TimeGranularity.YEAR, 2020, 0, 1)).toEqual( '2020-01-01 00:00:00.000 — 2020-12-31 23:59:59.999', ); }); }); });
5,583
0
petrpan-code/apache/superset/superset-frontend/packages/superset-ui-core/test/time-format
petrpan-code/apache/superset/superset-frontend/packages/superset-ui-core/test/time-format/utils/d3Time.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 { utcUtils, localTimeUtils, } from '../../../src/time-format/utils/d3Time'; describe('utils', () => { describe('utcUtils', () => { it('has isNotFirstDayOfWeekStartOnSunday', () => { const date = new Date(Date.UTC(2018, 10, 19)); expect(utcUtils.isNotFirstDayOfWeekStartOnSunday(date)).toBeTruthy(); const date2 = new Date(Date.UTC(2018, 10, 18)); expect(utcUtils.isNotFirstDayOfWeekStartOnSunday(date2)).toBeFalsy(); }); it('has isNotFirstDayOfWeekStartOnMonday', () => { const date = new Date(Date.UTC(2018, 10, 20)); expect(utcUtils.isNotFirstDayOfWeekStartOnMonday(date)).toBeTruthy(); const date2 = new Date(Date.UTC(2018, 10, 19)); expect(utcUtils.isNotFirstDayOfWeekStartOnMonday(date2)).toBeFalsy(); }); it('has isNotFirstDayOfWeekStartOnTuesday', () => { const date = new Date(Date.UTC(2018, 10, 21)); expect(utcUtils.isNotFirstDayOfWeekStartOnTuesday(date)).toBeTruthy(); const date2 = new Date(Date.UTC(2018, 10, 20)); expect(utcUtils.isNotFirstDayOfWeekStartOnTuesday(date2)).toBeFalsy(); }); it('has isNotFirstDayOfWeekStartOnWednesday', () => { const date = new Date(Date.UTC(2018, 10, 22)); expect(utcUtils.isNotFirstDayOfWeekStartOnWednesday(date)).toBeTruthy(); const date2 = new Date(Date.UTC(2018, 10, 21)); expect(utcUtils.isNotFirstDayOfWeekStartOnWednesday(date2)).toBeFalsy(); }); it('has isNotFirstDayOfWeekStartOnThursday', () => { const date = new Date(Date.UTC(2018, 10, 23)); expect(utcUtils.isNotFirstDayOfWeekStartOnThursday(date)).toBeTruthy(); const date2 = new Date(Date.UTC(2018, 10, 22)); expect(utcUtils.isNotFirstDayOfWeekStartOnThursday(date2)).toBeFalsy(); }); it('has isNotFirstDayOfWeekStartOnFriday', () => { const date = new Date(Date.UTC(2018, 10, 24)); expect(utcUtils.isNotFirstDayOfWeekStartOnFriday(date)).toBeTruthy(); const date2 = new Date(Date.UTC(2018, 10, 23)); expect(utcUtils.isNotFirstDayOfWeekStartOnFriday(date2)).toBeFalsy(); }); it('has isNotFirstDayOfWeekStartOnSaturday', () => { const date = new Date(Date.UTC(2018, 10, 25)); expect(utcUtils.isNotFirstDayOfWeekStartOnSaturday(date)).toBeTruthy(); const date2 = new Date(Date.UTC(2018, 10, 24)); expect(utcUtils.isNotFirstDayOfWeekStartOnSaturday(date2)).toBeFalsy(); }); }); describe('localTimeUtils', () => { it('has isNotFirstDayOfWeekStartOnSunday', () => { const date = new Date(2018, 10, 19); expect( localTimeUtils.isNotFirstDayOfWeekStartOnSunday(date), ).toBeTruthy(); const date2 = new Date(2018, 10, 18); expect( localTimeUtils.isNotFirstDayOfWeekStartOnSunday(date2), ).toBeFalsy(); }); it('has isNotFirstDayOfWeekStartOnMonday', () => { const date = new Date(2018, 10, 20); expect( localTimeUtils.isNotFirstDayOfWeekStartOnMonday(date), ).toBeTruthy(); const date2 = new Date(2018, 10, 19); expect( localTimeUtils.isNotFirstDayOfWeekStartOnMonday(date2), ).toBeFalsy(); }); it('has isNotFirstDayOfWeekStartOnTuesday', () => { const date = new Date(2018, 10, 21); expect( localTimeUtils.isNotFirstDayOfWeekStartOnTuesday(date), ).toBeTruthy(); const date2 = new Date(2018, 10, 20); expect( localTimeUtils.isNotFirstDayOfWeekStartOnTuesday(date2), ).toBeFalsy(); }); it('has isNotFirstDayOfWeekStartOnWednesday', () => { const date = new Date(2018, 10, 22); expect( localTimeUtils.isNotFirstDayOfWeekStartOnWednesday(date), ).toBeTruthy(); const date2 = new Date(2018, 10, 21); expect( localTimeUtils.isNotFirstDayOfWeekStartOnWednesday(date2), ).toBeFalsy(); }); it('has isNotFirstDayOfWeekStartOnThursday', () => { const date = new Date(2018, 10, 23); expect( localTimeUtils.isNotFirstDayOfWeekStartOnThursday(date), ).toBeTruthy(); const date2 = new Date(2018, 10, 22); expect( localTimeUtils.isNotFirstDayOfWeekStartOnThursday(date2), ).toBeFalsy(); }); it('has isNotFirstDayOfWeekStartOnFriday', () => { const date = new Date(2018, 10, 24); expect( localTimeUtils.isNotFirstDayOfWeekStartOnFriday(date), ).toBeTruthy(); const date2 = new Date(2018, 10, 23); expect( localTimeUtils.isNotFirstDayOfWeekStartOnFriday(date2), ).toBeFalsy(); }); it('has isNotFirstDayOfWeekStartOnSaturday', () => { const date = new Date(2018, 10, 25); expect( localTimeUtils.isNotFirstDayOfWeekStartOnSaturday(date), ).toBeTruthy(); const date2 = new Date(2018, 10, 24); expect( localTimeUtils.isNotFirstDayOfWeekStartOnSaturday(date2), ).toBeFalsy(); }); }); });
5,584
0
petrpan-code/apache/superset/superset-frontend/packages/superset-ui-core/test/time-format
petrpan-code/apache/superset/superset-frontend/packages/superset-ui-core/test/time-format/utils/denormalizeTimestamp.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 denormalizeTimestamp from '../../../src/time-format/utils/denormalizeTimestamp'; test('denormalizeTimestamp should normalize typical timestamps', () => { expect(denormalizeTimestamp('2023-03-11 08:26:52.695 UTC')).toEqual( '2023-03-11T08:26:52.695', ); expect( denormalizeTimestamp('2023-03-11 08:26:52.695 Europe/Helsinki'), ).toEqual('2023-03-11T08:26:52.695'); expect(denormalizeTimestamp('2023-03-11T08:26:52.695 UTC')).toEqual( '2023-03-11T08:26:52.695', ); expect(denormalizeTimestamp('2023-03-11T08:26:52.695')).toEqual( '2023-03-11T08:26:52.695', ); expect(denormalizeTimestamp('2023-03-11 08:26:52')).toEqual( '2023-03-11T08:26:52', ); }); test('denormalizeTimestamp should return unmatched timestamps as-is', () => { expect(denormalizeTimestamp('abcd')).toEqual('abcd'); expect(denormalizeTimestamp('03/11/2023')).toEqual('03/11/2023'); });
5,585
0
petrpan-code/apache/superset/superset-frontend/packages/superset-ui-core/test/time-format
petrpan-code/apache/superset/superset-frontend/packages/superset-ui-core/test/time-format/utils/normalizeTimestamp.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 normalizeTimestamp from '../../../src/time-format/utils/normalizeTimestamp'; test('normalizeTimestamp should normalize typical timestamps', () => { expect(normalizeTimestamp('2023-03-11 08:26:52.695 UTC')).toEqual( '2023-03-11T08:26:52.695Z', ); expect(normalizeTimestamp('2023-03-11 08:26:52.695 Europe/Helsinki')).toEqual( '2023-03-11T08:26:52.695Z', ); expect(normalizeTimestamp('2023-03-11T08:26:52.695 UTC')).toEqual( '2023-03-11T08:26:52.695Z', ); expect(normalizeTimestamp('2023-03-11T08:26:52.695')).toEqual( '2023-03-11T08:26:52.695Z', ); expect(normalizeTimestamp('2023-03-11 08:26:52')).toEqual( '2023-03-11T08:26:52Z', ); }); test('normalizeTimestamp should return unmatched timestamps as-is', () => { expect(normalizeTimestamp('abcd')).toEqual('abcd'); expect(normalizeTimestamp('03/11/2023')).toEqual('03/11/2023'); });
5,586
0
petrpan-code/apache/superset/superset-frontend/packages/superset-ui-core/test
petrpan-code/apache/superset/superset-frontend/packages/superset-ui-core/test/translation/Translator.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 { logging, configure, t, tn, addLocaleData, addTranslation, addTranslations, } from '@superset-ui/core'; import Translator from '../../src/translation/Translator'; import languagePackZh from './languagePacks/zh'; import languagePackEn from './languagePacks/en'; configure({ languagePack: languagePackEn, }); describe('Translator', () => { const spy = jest.spyOn(logging, 'warn'); beforeAll(() => { spy.mockImplementation((info: any) => { throw new Error(info); }); process.env.WEBPACK_MODE = 'production'; }); afterAll(() => { spy.mockRestore(); process.env.WEBPACK_MODE = 'test'; }); describe('new Translator(config)', () => { it('initializes when config is not specified', () => { expect(new Translator()).toBeInstanceOf(Translator); }); it('initializes when config is an empty object', () => { expect(new Translator({})).toBeInstanceOf(Translator); }); it('initializes when config is specified', () => { expect( new Translator({ languagePack: languagePackZh, }), ).toBeInstanceOf(Translator); }); }); describe('.translate(input, ...args)', () => { const translator = new Translator({ languagePack: languagePackZh, }); it('returns original text for unknown text', () => { expect(translator.translate('abc')).toEqual('abc'); }); it('translates simple text', () => { expect(translator.translate('second')).toEqual('秒'); }); it('translates template text with an argument', () => { expect(translator.translate('Copy of %s', 1)).toEqual('1 的副本'); expect(translator.translate('Copy of %s', 2)).toEqual('2 的副本'); }); it('translates template text with multiple arguments', () => { expect(translator.translate('test %d %d', 1, 2)).toEqual('test 1 2'); }); }); describe('.translateWithNumber(singular, plural, num, ...args)', () => { const translator = new Translator({ languagePack: languagePackZh, }); it('returns original text for unknown text', () => { expect(translator.translateWithNumber('fish', 'fishes', 1)).toEqual( 'fish', ); }); it('uses 0 as default value', () => { expect(translator.translateWithNumber('box', 'boxes')).toEqual('boxes'); }); it('translates simple text', () => { expect(translator.translateWithNumber('second', 'seconds', 1)).toEqual( '秒', ); }); it('translates template text with an argument', () => { expect( translator.translateWithNumber('Copy of %s', 'Copies of %s', 12, 12), ).toEqual('12 的副本'); }); it('translates template text with multiple arguments', () => { expect( translator.translateWithNumber( '%d glass %s', '%d glasses %s', 3, 3, 'abc', ), ).toEqual('3 glasses abc'); }); }); describe('.translateWithNumber(key, num, ...args)', () => { const translator = new Translator({ languagePack: languagePackEn, }); it('translates template text with an argument', () => { expect(translator.translateWithNumber('%s copies', 1)).toEqual('1 copy'); expect(translator.translateWithNumber('%s copies', 2)).toEqual( '2 copies', ); }); }); // Extending language pack describe('.addTranslation(...)', () => { it('can add new translation', () => { addTranslation('haha', ['Hahaha']); expect(t('haha')).toEqual('Hahaha'); }); }); describe('.addTranslations(...)', () => { it('can add new translations', () => { addTranslations({ foo: ['bar', '%s bars'], bar: ['foo'], }); // previous translation still exists expect(t('haha')).toEqual('Hahaha'); // new translations work as expected expect(tn('foo', 1)).toEqual('bar'); expect(tn('foo', 2)).toEqual('2 bars'); expect(tn('bar', 2)).toEqual('bar'); }); it('throw warning on invalid arguments', () => { expect(() => addTranslations(undefined as never)).toThrow( 'Invalid translations', ); expect(tn('bar', '2 foo', 2)).toEqual('2 foo'); }); it('throw warning on duplicates', () => { expect(() => { addTranslations({ haha: ['this is duplicate'], }); }).toThrow('Duplicate translation key "haha"'); expect(t('haha')).toEqual('Hahaha'); }); }); describe('.addLocaleData(...)', () => { it('can add new translations for language', () => { addLocaleData({ en: { yes: ['ok'], }, }); expect(t('yes')).toEqual('ok'); }); it('throw on unknown locale', () => { expect(() => { addLocaleData({ zh: { haha: ['yes'], }, }); }).toThrow('Invalid locale data'); }); it('missing locale falls back to English', () => { configure({ languagePack: languagePackZh, }); // expect and error because zh is not current locale expect(() => { addLocaleData({ en: { yes: ['OK'], }, }); }).not.toThrow(); expect(t('yes')).toEqual('OK'); }); }); });
5,587
0
petrpan-code/apache/superset/superset-frontend/packages/superset-ui-core/test
petrpan-code/apache/superset/superset-frontend/packages/superset-ui-core/test/translation/TranslatorSingleton.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. */ /* eslint no-console: 0 */ import mockConsole from 'jest-mock-console'; import { configure, resetTranslation, t, tn } from '@superset-ui/core'; import Translator from '../../src/translation/Translator'; import languagePackEn from './languagePacks/en'; import languagePackZh from './languagePacks/zh'; describe('TranslatorSingleton', () => { describe('before configure()', () => { beforeAll(() => { resetTranslation(); }); describe('t()', () => { it('returns untranslated input and issues a warning', () => { const restoreConsole = mockConsole(); expect(t('second')).toEqual('second'); expect(console.warn).toHaveBeenCalled(); restoreConsole(); }); }); describe('tn()', () => { it('returns untranslated input and issues a warning', () => { const restoreConsole = mockConsole(); expect(tn('ox', 'oxen', 2)).toEqual('oxen'); expect(console.warn).toHaveBeenCalled(); restoreConsole(); }); }); }); describe('after configure()', () => { describe('configure()', () => { it('creates and returns a translator', () => { expect(configure()).toBeInstanceOf(Translator); }); }); describe('t()', () => { it('after configure() returns translated text', () => { configure({ languagePack: languagePackZh, }); expect(t('second')).toEqual('秒'); }); }); describe('tn()', () => { it('after configure() returns translated text with singular/plural', () => { configure({ languagePack: languagePackEn, }); expect(tn('ox', 'oxen', 2)).toEqual('oxen'); }); }); }); it('should be reset translation setting', () => { configure(); expect(t('second')).toEqual('second'); resetTranslation(); const restoreConsole = mockConsole(); expect(t('second')).toEqual('second'); resetTranslation(); expect(t('second')).toEqual('second'); expect(console.warn).toBeCalledTimes(2); restoreConsole(); }); });
5,588
0
petrpan-code/apache/superset/superset-frontend/packages/superset-ui-core/test
petrpan-code/apache/superset/superset-frontend/packages/superset-ui-core/test/translation/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 { configure, t, tn } from '@superset-ui/core'; describe('index', () => { it('exports configure()', () => { expect(configure).toBeDefined(); expect(configure).toBeInstanceOf(Function); }); it('exports t()', () => { expect(t).toBeDefined(); expect(t).toBeInstanceOf(Function); }); it('exports tn()', () => { expect(tn).toBeDefined(); expect(tn).toBeInstanceOf(Function); }); });
5,591
0
petrpan-code/apache/superset/superset-frontend/packages/superset-ui-core/test
petrpan-code/apache/superset/superset-frontend/packages/superset-ui-core/test/ui-overrides/ExtensionsRegistry.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 { getExtensionsRegistry } from '@superset-ui/core'; test('should get instance of getExtensionsRegistry', () => { expect(getExtensionsRegistry().name).toBe('ExtensionsRegistry'); });
5,592
0
petrpan-code/apache/superset/superset-frontend/packages/superset-ui-core/test
petrpan-code/apache/superset/superset-frontend/packages/superset-ui-core/test/utils/convertKeysToCamelCase.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 { convertKeysToCamelCase } from '@superset-ui/core'; describe('convertKeysToCamelCase(object)', () => { it('returns undefined for undefined input', () => { expect(convertKeysToCamelCase(undefined)).toBeUndefined(); }); it('returns null for null input', () => { expect(convertKeysToCamelCase(null)).toBeNull(); }); it('returns a new object that has all keys in camelCase', () => { const input = { is_happy: true, 'is-angry': false, isHungry: false, }; expect(convertKeysToCamelCase(input)).toEqual({ isHappy: true, isAngry: false, isHungry: false, }); }); it('throws error if input is not a plain object', () => { expect(() => { convertKeysToCamelCase({}); }).not.toThrow(); expect(() => { convertKeysToCamelCase(''); }).toThrow(); expect(() => { convertKeysToCamelCase(new Map()); }).toThrow(); }); });
5,593
0
petrpan-code/apache/superset/superset-frontend/packages/superset-ui-core/test
petrpan-code/apache/superset/superset-frontend/packages/superset-ui-core/test/utils/ensureIsArray.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 { ensureIsArray } from '@superset-ui/core'; describe('ensureIsArray', () => { it('handle inputs correctly', () => { expect(ensureIsArray(undefined)).toEqual([]); expect(ensureIsArray(null)).toEqual([]); expect(ensureIsArray([])).toEqual([]); expect(ensureIsArray('my_metric')).toEqual(['my_metric']); expect(ensureIsArray(['my_metric'])).toEqual(['my_metric']); expect(ensureIsArray(['my_metric_1', 'my_metric_2'])).toEqual([ 'my_metric_1', 'my_metric_2', ]); }); });
5,594
0
petrpan-code/apache/superset/superset-frontend/packages/superset-ui-core/test
petrpan-code/apache/superset/superset-frontend/packages/superset-ui-core/test/utils/ensureIsInt.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 { ensureIsInt } from '@superset-ui/core'; describe('ensureIsInt', () => { it('handle inputs correctly', () => { expect(ensureIsInt(undefined, 0)).toEqual(0); expect(ensureIsInt('abc', 1)).toEqual(1); expect(ensureIsInt(undefined)).toEqual(NaN); expect(ensureIsInt('abc')).toEqual(NaN); expect(ensureIsInt('12.5')).toEqual(12); expect(ensureIsInt(12)).toEqual(12); expect(ensureIsInt(12, 0)).toEqual(12); }); });
5,595
0
petrpan-code/apache/superset/superset-frontend/packages/superset-ui-core/test
petrpan-code/apache/superset/superset-frontend/packages/superset-ui-core/test/utils/featureFlag.test.ts
/** * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ import * as uiCore from '@superset-ui/core'; it('initializes feature flags', () => { Object.defineProperty(window, 'featureFlags', { value: undefined, }); uiCore.initFeatureFlags(); expect(window.featureFlags).toEqual({}); }); it('initializes feature flags with predefined values', () => { Object.defineProperty(window, 'featureFlags', { value: undefined, }); const featureFlags = { CLIENT_CACHE: true, DRILL_BY: false, }; uiCore.initFeatureFlags(featureFlags); expect(window.featureFlags).toEqual(featureFlags); }); it('does nothing if feature flags are already initialized', () => { const featureFlags = { DRILL_BY: false }; Object.defineProperty(window, 'featureFlags', { value: featureFlags, }); uiCore.initFeatureFlags({ DRILL_BY: true }); expect(window.featureFlags).toEqual(featureFlags); }); it('returns false and raises console error if feature flags have not been initialized', () => { const logging = jest.spyOn(uiCore.logging, 'error'); Object.defineProperty(window, 'featureFlags', { value: undefined, }); expect(uiCore.isFeatureEnabled(uiCore.FeatureFlag.DRILL_BY)).toEqual(false); expect(uiCore.logging.error).toHaveBeenCalled(); expect(logging).toHaveBeenCalledWith('Failed to query feature flag DRILL_BY'); }); it('returns false for unset feature flag', () => { Object.defineProperty(window, 'featureFlags', { value: {}, }); expect(uiCore.isFeatureEnabled(uiCore.FeatureFlag.DRILL_BY)).toEqual(false); }); it('returns true for set feature flag', () => { Object.defineProperty(window, 'featureFlags', { value: { CLIENT_CACHE: true, }, }); expect(uiCore.isFeatureEnabled(uiCore.FeatureFlag.CLIENT_CACHE)).toEqual( true, ); });
5,596
0
petrpan-code/apache/superset/superset-frontend/packages/superset-ui-core/test
petrpan-code/apache/superset/superset-frontend/packages/superset-ui-core/test/utils/getSelectedText.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 { getSelectedText } from '@superset-ui/core'; test('Returns null if Selection object is null', () => { jest.spyOn(window, 'getSelection').mockImplementationOnce(() => null); expect(getSelectedText()).toEqual(undefined); jest.restoreAllMocks(); }); test('Returns selection text if Selection object is not null', () => { jest .spyOn(window, 'getSelection') // @ts-ignore .mockImplementationOnce(() => ({ toString: () => 'test string' })); expect(getSelectedText()).toEqual('test string'); jest.restoreAllMocks(); });
5,597
0
petrpan-code/apache/superset/superset-frontend/packages/superset-ui-core/test
petrpan-code/apache/superset/superset-frontend/packages/superset-ui-core/test/utils/isDefined.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 { isDefined } from '@superset-ui/core'; describe('isDefined(value)', () => { it('returns true if value is not null and not undefined', () => { expect(isDefined(0)).toBe(true); expect(isDefined(1)).toBe(true); expect(isDefined('')).toBe(true); expect(isDefined('a')).toBe(true); expect(isDefined([])).toBe(true); expect(isDefined([0])).toBe(true); expect(isDefined([1])).toBe(true); expect(isDefined({})).toBe(true); expect(isDefined({ a: 1 })).toBe(true); expect(isDefined([{}])).toBe(true); }); it('returns false otherwise', () => { expect(isDefined(null)).toBe(false); expect(isDefined(undefined)).toBe(false); }); });
5,598
0
petrpan-code/apache/superset/superset-frontend/packages/superset-ui-core/test
petrpan-code/apache/superset/superset-frontend/packages/superset-ui-core/test/utils/isRequired.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 { isRequired } from '@superset-ui/core'; describe('isRequired(field)', () => { it('should throw error with the given field in the message', () => { expect(() => isRequired('myField')).toThrow(Error); }); });
5,599
0
petrpan-code/apache/superset/superset-frontend/packages/superset-ui-core/test
petrpan-code/apache/superset/superset-frontend/packages/superset-ui-core/test/utils/logging.test.ts
/* eslint-disable @typescript-eslint/no-var-requires */ /* eslint-disable global-require */ /** * 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. */ describe('logging', () => { beforeEach(() => { jest.resetModules(); jest.resetAllMocks(); }); it('should pipe to `console` methods', () => { const { logging } = require('@superset-ui/core'); jest.spyOn(logging, 'debug').mockImplementation(); jest.spyOn(logging, 'log').mockImplementation(); jest.spyOn(logging, 'info').mockImplementation(); expect(() => { logging.debug(); logging.log(); logging.info(); }).not.toThrow(); jest.spyOn(logging, 'warn').mockImplementation(() => { throw new Error('warn'); }); expect(() => logging.warn()).toThrow('warn'); jest.spyOn(logging, 'error').mockImplementation(() => { throw new Error('error'); }); expect(() => logging.error()).toThrow('error'); jest.spyOn(logging, 'trace').mockImplementation(() => { throw new Error('Trace:'); }); expect(() => logging.trace()).toThrow('Trace:'); }); it('should use noop functions when console unavailable', () => { const { console } = window; Object.assign(window, { console: undefined }); const { logging } = require('@superset-ui/core'); afterAll(() => { Object.assign(window, { console }); }); expect(() => { logging.debug(); logging.log(); logging.info(); logging.warn('warn'); logging.error('error'); logging.trace(); logging.table([ [1, 2], [3, 4], ]); }).not.toThrow(); }); });
5,600
0
petrpan-code/apache/superset/superset-frontend/packages/superset-ui-core/test
petrpan-code/apache/superset/superset-frontend/packages/superset-ui-core/test/utils/lruCache.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 { lruCache } from '@superset-ui/core'; test('initial LRU', () => { expect(lruCache().capacity).toBe(100); expect(lruCache(10).capacity).toBe(10); expect(lruCache(10).size).toBe(0); expect(() => lruCache(0)).toThrow(Error); }); test('LRU operations', () => { const cache = lruCache<string>(3); cache.set('1', 'a'); cache.set('2', 'b'); cache.set('3', 'c'); cache.set('4', 'd'); expect(cache.size).toBe(3); expect(cache.has('1')).toBeFalsy(); expect(cache.get('1')).toBeUndefined(); cache.get('2'); cache.set('5', 'e'); expect(cache.has('2')).toBeTruthy(); expect(cache.has('3')).toBeFalsy(); // @ts-expect-error expect(() => cache.set(0)).toThrow(TypeError); // @ts-expect-error expect(() => cache.get(0)).toThrow(TypeError); expect(cache.size).toBe(3); cache.clear(); expect(cache.size).toBe(0); expect(cache.capacity).toBe(3); }); test('LRU handle null and undefined', () => { const cache = lruCache(); cache.set('a', null); cache.set('b', undefined); expect(cache.has('a')).toBeTruthy(); expect(cache.has('b')).toBeTruthy(); expect(cache.get('a')).toBeNull(); expect(cache.get('b')).toBeUndefined(); });
5,601
0
petrpan-code/apache/superset/superset-frontend/packages/superset-ui-core/test
petrpan-code/apache/superset/superset-frontend/packages/superset-ui-core/test/utils/makeSingleton.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 { makeSingleton } from '@superset-ui/core'; describe('makeSingleton()', () => { class Dog { name: string; isSitting?: boolean; constructor(name?: string) { this.name = name || 'Pluto'; } sit() { this.isSitting = true; } } describe('makeSingleton(BaseClass)', () => { const getInstance = makeSingleton(Dog); it('returns a function for getting singleton instance of a given base class', () => { expect(typeof getInstance).toBe('function'); expect(getInstance()).toBeInstanceOf(Dog); }); it('returned function returns same instance across all calls', () => { expect(getInstance()).toBe(getInstance()); }); }); describe('makeSingleton(BaseClass, ...args)', () => { const getInstance = makeSingleton(Dog, 'Doug'); it('returns a function for getting singleton instance of a given base class constructed with the given arguments', () => { expect(typeof getInstance).toBe('function'); expect(getInstance()).toBeInstanceOf(Dog); expect(getInstance().name).toBe('Doug'); }); it('returned function returns same instance across all calls', () => { expect(getInstance()).toBe(getInstance()); }); }); });
5,602
0
petrpan-code/apache/superset/superset-frontend/packages/superset-ui-core/test
petrpan-code/apache/superset/superset-frontend/packages/superset-ui-core/test/utils/promiseTimeout.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 { promiseTimeout } from '@superset-ui/core'; describe('promiseTimeout(func, delay)', () => { beforeEach(() => { jest.useFakeTimers(); }); afterEach(() => { jest.useRealTimers(); }); it('resolves after delay', async () => { const promise = promiseTimeout(() => 'abcd', 10); jest.advanceTimersByTime(10); const result = await promise; expect(result).toEqual('abcd'); expect(result).toHaveLength(4); }); it('uses the timer', async () => { const promise = Promise.race([ promiseTimeout(() => 'abc', 10), promiseTimeout(() => 'def', 20), ]); jest.advanceTimersByTime(10); const result = await promise; expect(result).toEqual('abc'); }); });
5,603
0
petrpan-code/apache/superset/superset-frontend/packages/superset-ui-core/test
petrpan-code/apache/superset/superset-frontend/packages/superset-ui-core/test/utils/random.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 { seed, seedRandom } from '@superset-ui/core'; describe('random', () => { it('seeded random should return the same value', () => { expect(seedRandom()).toEqual(0.7237953289342797); }); it('should allow update seed', () => { const a = seed('abc'); const b = seed('abc'); expect(a()).toEqual(b()); }); });
5,604
0
petrpan-code/apache/superset/superset-frontend/packages/superset-ui-core/test
petrpan-code/apache/superset/superset-frontend/packages/superset-ui-core/test/utils/removeDuplicates.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 { removeDuplicates } from '@superset-ui/core'; describe('removeDuplicates([...])', () => { it('should remove duplicates from a simple list', () => { expect(removeDuplicates([1, 2, 4, 1, 1, 5, 2])).toEqual([1, 2, 4, 5]); }); it('should remove duplicates by key getter', () => { expect(removeDuplicates([{ a: 1 }, { a: 1 }, { b: 2 }], x => x.a)).toEqual([ { a: 1 }, { b: 2 }, ]); }); });
5,605
0
petrpan-code/apache/superset/superset-frontend/packages/superset-ui-core/test
petrpan-code/apache/superset/superset-frontend/packages/superset-ui-core/test/validator/legacyValidateInteger.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 { legacyValidateInteger } from '@superset-ui/core'; import './setup'; describe('legacyValidateInteger()', () => { it('returns the warning message if invalid', () => { expect(legacyValidateInteger(10.1)).toBeTruthy(); expect(legacyValidateInteger('abc')).toBeTruthy(); expect(legacyValidateInteger(Infinity)).toBeTruthy(); }); it('returns false if the input is valid', () => { // superset seems to operate on this incorrect behavior at the moment expect(legacyValidateInteger(NaN)).toBeFalsy(); expect(legacyValidateInteger(undefined)).toBeFalsy(); expect(legacyValidateInteger(null)).toBeFalsy(); expect(legacyValidateInteger('')).toBeFalsy(); expect(legacyValidateInteger(0)).toBeFalsy(); expect(legacyValidateInteger(10)).toBeFalsy(); expect(legacyValidateInteger('10')).toBeFalsy(); }); });
5,606
0
petrpan-code/apache/superset/superset-frontend/packages/superset-ui-core/test
petrpan-code/apache/superset/superset-frontend/packages/superset-ui-core/test/validator/legacyValidateNumber.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 { legacyValidateNumber } from '@superset-ui/core'; import './setup'; describe('legacyValidateNumber()', () => { it('returns the warning message if invalid', () => { expect(legacyValidateNumber('abc')).toBeTruthy(); }); it('returns false if the input is valid', () => { // superset seems to operate on this incorrect behavior at the moment expect(legacyValidateNumber(NaN)).toBeFalsy(); expect(legacyValidateNumber(Infinity)).toBeFalsy(); expect(legacyValidateNumber(undefined)).toBeFalsy(); expect(legacyValidateNumber(null)).toBeFalsy(); expect(legacyValidateNumber('')).toBeFalsy(); expect(legacyValidateNumber(0)).toBeFalsy(); expect(legacyValidateNumber(10.1)).toBeFalsy(); expect(legacyValidateNumber(10)).toBeFalsy(); expect(legacyValidateNumber('10')).toBeFalsy(); }); });
5,608
0
petrpan-code/apache/superset/superset-frontend/packages/superset-ui-core/test
petrpan-code/apache/superset/superset-frontend/packages/superset-ui-core/test/validator/validateInteger.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 { validateInteger } from '@superset-ui/core'; import './setup'; describe('validateInteger()', () => { it('returns the warning message if invalid', () => { expect(validateInteger(10.1)).toBeTruthy(); expect(validateInteger(NaN)).toBeTruthy(); expect(validateInteger(Infinity)).toBeTruthy(); expect(validateInteger(undefined)).toBeTruthy(); expect(validateInteger(null)).toBeTruthy(); expect(validateInteger('abc')).toBeTruthy(); expect(validateInteger('')).toBeTruthy(); }); it('returns false if the input is valid', () => { expect(validateInteger(0)).toBeFalsy(); expect(validateInteger(10)).toBeFalsy(); expect(validateInteger('10')).toBeFalsy(); }); });
5,609
0
petrpan-code/apache/superset/superset-frontend/packages/superset-ui-core/test
petrpan-code/apache/superset/superset-frontend/packages/superset-ui-core/test/validator/validateNonEmpty.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 { validateNonEmpty } from '@superset-ui/core'; import './setup'; describe('validateNonEmpty()', () => { it('returns the warning message if invalid', () => { expect(validateNonEmpty([])).toBeTruthy(); expect(validateNonEmpty(undefined)).toBeTruthy(); expect(validateNonEmpty(null)).toBeTruthy(); expect(validateNonEmpty('')).toBeTruthy(); }); it('returns false if the input is valid', () => { expect(validateNonEmpty(0)).toBeFalsy(); expect(validateNonEmpty(10)).toBeFalsy(); expect(validateNonEmpty('abc')).toBeFalsy(); }); });
5,610
0
petrpan-code/apache/superset/superset-frontend/packages/superset-ui-core/test
petrpan-code/apache/superset/superset-frontend/packages/superset-ui-core/test/validator/validateNumber.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 { validateNumber } from '@superset-ui/core'; import './setup'; describe('validateNumber()', () => { it('returns the warning message if invalid', () => { expect(validateNumber(NaN)).toBeTruthy(); expect(validateNumber(Infinity)).toBeTruthy(); expect(validateNumber(undefined)).toBeTruthy(); expect(validateNumber(null)).toBeTruthy(); expect(validateNumber('abc')).toBeTruthy(); expect(validateNumber('')).toBeTruthy(); }); it('returns false if the input is valid', () => { expect(validateNumber(0)).toBeFalsy(); expect(validateNumber(10.1)).toBeFalsy(); expect(validateNumber(10)).toBeFalsy(); expect(validateNumber('10')).toBeFalsy(); }); });
5,767
0
petrpan-code/apache/superset/superset-frontend/packages/superset-ui-switchboard
petrpan-code/apache/superset/superset-frontend/packages/superset-ui-switchboard/src/switchboard.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 SingletonSwitchboard, { Switchboard } from './switchboard'; type EventHandler = (event: MessageEvent) => void; // A note on these fakes: // // jsdom doesn't supply a MessageChannel or a MessagePort, // so we have to build our own unless we want to unit test in-browser. // Might want to open a PR in jsdom: https://github.com/jsdom/jsdom/issues/2448 /** Matches the MessagePort api as closely as necessary (it's a small api) */ class FakeMessagePort { otherPort?: FakeMessagePort; isStarted = false; queue: MessageEvent[] = []; listeners: Set<EventHandler> = new Set(); dispatchEvent(event: MessageEvent) { if (this.isStarted) { this.listeners.forEach(listener => { try { listener(event); } catch (err) { if (typeof this.onmessageerror === 'function') { this.onmessageerror(err); } } }); } else { this.queue.push(event); } return true; } addEventListener(eventType: 'message', handler: EventHandler) { this.listeners.add(handler); } removeEventListener(eventType: 'message', handler: EventHandler) { this.listeners.delete(handler); } postMessage(data: any) { this.otherPort!.dispatchEvent({ data } as MessageEvent); } start() { if (this.isStarted) return; this.isStarted = true; this.queue.forEach(event => { this.dispatchEvent(event); }); this.queue = []; } close() { this.isStarted = false; } onmessage: EventHandler | null = null; // not implemented, requires some kinda proxy thingy to mock correctly onmessageerror: ((err: any) => void) | null = null; } /** Matches the MessageChannel api as closely as necessary (an even smaller api than MessagePort) */ class FakeMessageChannel { port1: MessagePort; port2: MessagePort; constructor() { const port1 = new FakeMessagePort(); const port2 = new FakeMessagePort(); port1.otherPort = port2; port2.otherPort = port1; this.port1 = port1; this.port2 = port2; } } describe('comms', () => { let originalConsoleDebug: any = null; let originalConsoleError: any = null; beforeAll(() => { Object.defineProperty(global, 'MessageChannel', { value: FakeMessageChannel, }); originalConsoleDebug = console.debug; originalConsoleError = console.error; }); beforeEach(() => { console.debug = jest.fn(); // silencio bruno console.error = jest.fn(); }); afterEach(() => { console.debug = originalConsoleDebug; console.error = originalConsoleError; }); it('constructs with defaults', () => { const sb = new Switchboard({ port: new MessageChannel().port1 }); expect(sb).not.toBeNull(); expect(sb).toHaveProperty('name'); expect(sb).toHaveProperty('debugMode'); }); it('singleton', async () => { SingletonSwitchboard.start(); expect(console.error).toHaveBeenCalledWith( '[]', 'Switchboard not initialised', ); SingletonSwitchboard.emit('someEvent', 42); expect(console.error).toHaveBeenCalledWith( '[]', 'Switchboard not initialised', ); await expect(SingletonSwitchboard.get('failing')).rejects.toThrow( 'Switchboard not initialised', ); SingletonSwitchboard.init({ port: new MessageChannel().port1 }); expect(SingletonSwitchboard).toHaveProperty('name'); expect(SingletonSwitchboard).toHaveProperty('debugMode'); SingletonSwitchboard.init({ port: new MessageChannel().port1 }); expect(console.error).toHaveBeenCalledWith( '[switchboard]', 'already initialized', ); }); describe('emit', () => { it('triggers the method', async () => { const channel = new MessageChannel(); const ours = new Switchboard({ port: channel.port1, name: 'ours' }); const theirs = new Switchboard({ port: channel.port2, name: 'theirs' }); const handler = jest.fn(); theirs.defineMethod('someEvent', handler); theirs.start(); ours.emit('someEvent', 42); expect(handler).toHaveBeenCalledWith(42); }); it('handles a missing method', async () => { const channel = new MessageChannel(); const ours = new Switchboard({ port: channel.port1, name: 'ours' }); const theirs = new Switchboard({ port: channel.port2, name: 'theirs' }); theirs.start(); channel.port2.onmessageerror = jest.fn(); ours.emit('fakemethod'); await new Promise(setImmediate); expect(channel.port2.onmessageerror).not.toHaveBeenCalled(); }); }); describe('get', () => { it('returns the value', async () => { const channel = new MessageChannel(); const ours = new Switchboard({ port: channel.port1, name: 'ours' }); const theirs = new Switchboard({ port: channel.port2, name: 'theirs' }); theirs.defineMethod('theirMethod', ({ x }: { x: number }) => Promise.resolve(x + 42), ); theirs.start(); const value = await ours.get('theirMethod', { x: 1 }); expect(value).toEqual(43); }); it('removes the listener after', async () => { const channel = new MessageChannel(); const ours = new Switchboard({ port: channel.port1, name: 'ours' }); const theirs = new Switchboard({ port: channel.port2, name: 'theirs' }); theirs.defineMethod('theirMethod', () => Promise.resolve(420)); theirs.start(); expect((channel.port1 as FakeMessagePort).listeners).toHaveProperty( 'size', 1, ); const promise = ours.get('theirMethod'); expect((channel.port1 as FakeMessagePort).listeners).toHaveProperty( 'size', 2, ); await promise; expect((channel.port1 as FakeMessagePort).listeners).toHaveProperty( 'size', 1, ); }); it('can handle one way concurrency', async () => { const channel = new MessageChannel(); const ours = new Switchboard({ port: channel.port1, name: 'ours' }); const theirs = new Switchboard({ port: channel.port2, name: 'theirs' }); theirs.defineMethod('theirMethod', () => Promise.resolve(42)); theirs.defineMethod( 'theirMethod2', () => new Promise(resolve => setImmediate(() => resolve(420))), ); theirs.start(); const [value1, value2] = await Promise.all([ ours.get('theirMethod'), ours.get('theirMethod2'), ]); expect(value1).toEqual(42); expect(value2).toEqual(420); }); it('can handle two way concurrency', async () => { const channel = new MessageChannel(); const ours = new Switchboard({ port: channel.port1, name: 'ours' }); const theirs = new Switchboard({ port: channel.port2, name: 'theirs' }); theirs.defineMethod('theirMethod', () => Promise.resolve(42)); ours.defineMethod( 'ourMethod', () => new Promise(resolve => setImmediate(() => resolve(420))), ); theirs.start(); const [value1, value2] = await Promise.all([ ours.get('theirMethod'), theirs.get('ourMethod'), ]); expect(value1).toEqual(42); expect(value2).toEqual(420); }); it('handles when the method is not defined', async () => { const channel = new MessageChannel(); const ours = new Switchboard({ port: channel.port1, name: 'ours' }); const theirs = new Switchboard({ port: channel.port2, name: 'theirs' }); theirs.start(); await expect(ours.get('fakemethod')).rejects.toThrow( '[theirs] Method "fakemethod" is not defined', ); }); it('handles when the method throws', async () => { const channel = new MessageChannel(); const ours = new Switchboard({ port: channel.port1, name: 'ours' }); const theirs = new Switchboard({ port: channel.port2, name: 'theirs' }); theirs.defineMethod('failing', () => { throw new Error('i dont feel like writing a clever message here'); }); theirs.start(); console.error = jest.fn(); // will be restored by the afterEach await expect(ours.get('failing')).rejects.toThrow( '[theirs] Method "failing" threw an error', ); }); it('handles receiving an unexpected non-reply, non-error response', async () => { const { port1, port2 } = new MessageChannel(); const ours = new Switchboard({ port: port1, name: 'ours' }); // This test is required for 100% coverage. But there's no way to set up these conditions // within the switchboard interface, so we gotta hack together the ports directly. port2.addEventListener('message', event => { const { messageId } = event.data; port1.dispatchEvent({ data: { messageId } } as MessageEvent); }); port2.start(); await expect(ours.get('someMethod')).rejects.toThrowError( 'Unexpected response message', ); }); }); it('logs in debug mode', async () => { const { port1, port2 } = new MessageChannel(); const ours = new Switchboard({ port: port1, name: 'ours', debug: true, }); const theirs = new Switchboard({ port: port2, name: 'theirs', debug: true, }); theirs.defineMethod('blah', () => {}); theirs.start(); await ours.emit('blah'); expect(console.debug).toHaveBeenCalledTimes(1); expect((console.debug as any).mock.calls[0][0]).toBe('[theirs]'); }); it('does not log outside debug mode', async () => { const { port1, port2 } = new MessageChannel(); const ours = new Switchboard({ port: port1, name: 'ours', }); const theirs = new Switchboard({ port: port2, name: 'theirs', }); theirs.defineMethod('blah', () => {}); theirs.start(); await ours.emit('blah'); expect(console.debug).toHaveBeenCalledTimes(0); }); });
5,944
0
petrpan-code/apache/superset/superset-frontend/plugins/legacy-plugin-chart-map-box
petrpan-code/apache/superset/superset-frontend/plugins/legacy-plugin-chart-map-box/test/tsconfig.json
{ "compilerOptions": { "composite": false, "emitDeclarationOnly": false, "noEmit": true, "rootDir": "." }, "extends": "../../../tsconfig.json", "include": [ "**/*", "../types/**/*", "../../../types/**/*" ], "references": [ { "path": ".." } ] }
5,949
0
petrpan-code/apache/superset/superset-frontend/plugins
petrpan-code/apache/superset/superset-frontend/plugins/legacy-plugin-chart-paired-t-test/tsconfig.json
{ "compilerOptions": { "declarationDir": "lib", "outDir": "lib", "rootDir": "src" }, "exclude": [ "lib", "test" ], "extends": "../../tsconfig.json", "include": [ "src/**/*", "types/**/*", "../../types/**/*" ], "references": [ { "path": "../../packages/superset-ui-chart-controls" }, { "path": "../../packages/superset-ui-core" } ] }
5,977
0
petrpan-code/apache/superset/superset-frontend/plugins/legacy-plugin-chart-partition
petrpan-code/apache/superset/superset-frontend/plugins/legacy-plugin-chart-partition/test/tsconfig.json
{ "compilerOptions": { "composite": false, "emitDeclarationOnly": false, "noEmit": true, "rootDir": "." }, "extends": "../../../tsconfig.json", "include": [ "**/*", "../types/**/*", "../../../types/**/*" ], "references": [ { "path": ".." } ] }
6,088
0
petrpan-code/apache/superset/superset-frontend/plugins/legacy-preset-chart-deckgl/test
petrpan-code/apache/superset/superset-frontend/plugins/legacy-preset-chart-deckgl/test/utils/colors.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 { hexToRGB } from '../../src/utils/colors'; describe('colors', () => { it('hexToRGB()', () => { expect(hexToRGB('#ffffff')).toEqual([255, 255, 255, 255]); }); });
6,089
0
petrpan-code/apache/superset/superset-frontend/plugins/legacy-preset-chart-deckgl/test
petrpan-code/apache/superset/superset-frontend/plugins/legacy-preset-chart-deckgl/test/utils/getPointsFromPolygon.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 getPointsFromPolygon from '../../src/utils/getPointsFromPolygon'; describe('getPointsFromPolygon', () => { it('handle original input', () => { expect( getPointsFromPolygon({ polygon: [ [1, 2], [3, 4], ], }), ).toEqual([ [1, 2], [3, 4], ]); }); it('handle geojson features', () => { expect( getPointsFromPolygon({ polygon: { type: 'Feature', geometry: { type: 'Polygon', coordinates: [ [ [1, 2], [3, 4], ], ], }, }, }), ).toEqual([ [1, 2], [3, 4], ]); }); });
6,126
0
petrpan-code/apache/superset/superset-frontend/plugins/legacy-preset-chart-nvd3
petrpan-code/apache/superset/superset-frontend/plugins/legacy-preset-chart-nvd3/test/tsconfig.json
{ "compilerOptions": { "composite": false, "emitDeclarationOnly": false, "noEmit": true, "rootDir": "." }, "extends": "../../../tsconfig.json", "include": [ "**/*", "../types/**/*", "../../../types/**/*" ], "references": [ { "path": ".." } ] }
6,262
0
petrpan-code/apache/superset/superset-frontend/plugins/plugin-chart-echarts
petrpan-code/apache/superset/superset-frontend/plugins/plugin-chart-echarts/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 { EchartsBoxPlotChartPlugin, EchartsPieChartPlugin, EchartsTimeseriesChartPlugin, EchartsGraphChartPlugin, EchartsFunnelChartPlugin, EchartsTreemapChartPlugin, EchartsAreaChartPlugin, EchartsTimeseriesBarChartPlugin, EchartsTimeseriesLineChartPlugin, EchartsTimeseriesScatterChartPlugin, EchartsTimeseriesSmoothLineChartPlugin, EchartsTimeseriesStepChartPlugin, EchartsMixedTimeseriesChartPlugin, EchartsGaugeChartPlugin, EchartsRadarChartPlugin, EchartsTreeChartPlugin, BigNumberChartPlugin, BigNumberTotalChartPlugin, EchartsSunburstChartPlugin, } from '../src'; import { EchartsChartPlugin } from '../src/types'; test('@superset-ui/plugin-chart-echarts exists', () => { expect(EchartsBoxPlotChartPlugin).toBeDefined(); expect(EchartsPieChartPlugin).toBeDefined(); expect(EchartsTimeseriesChartPlugin).toBeDefined(); expect(EchartsGraphChartPlugin).toBeDefined(); expect(EchartsFunnelChartPlugin).toBeDefined(); expect(EchartsTreemapChartPlugin).toBeDefined(); expect(EchartsAreaChartPlugin).toBeDefined(); expect(EchartsTimeseriesBarChartPlugin).toBeDefined(); expect(EchartsTimeseriesLineChartPlugin).toBeDefined(); expect(EchartsTimeseriesScatterChartPlugin).toBeDefined(); expect(EchartsTimeseriesSmoothLineChartPlugin).toBeDefined(); expect(EchartsTimeseriesStepChartPlugin).toBeDefined(); expect(EchartsMixedTimeseriesChartPlugin).toBeDefined(); expect(EchartsGaugeChartPlugin).toBeDefined(); expect(EchartsRadarChartPlugin).toBeDefined(); expect(EchartsTreeChartPlugin).toBeDefined(); expect(BigNumberChartPlugin).toBeDefined(); expect(BigNumberTotalChartPlugin).toBeDefined(); expect(EchartsSunburstChartPlugin).toBeDefined(); }); test('@superset-ui/plugin-chart-echarts-parsemethod-validation', () => { const plugins: EchartsChartPlugin[] = [ new EchartsBoxPlotChartPlugin().configure({ key: 'box_plot', }), new EchartsPieChartPlugin().configure({ key: 'pie', }), new EchartsTimeseriesChartPlugin().configure({ key: 'echarts_timeseries', }), new EchartsGraphChartPlugin().configure({ key: 'graph_chart', }), new EchartsFunnelChartPlugin().configure({ key: 'funnel', }), new EchartsTreemapChartPlugin().configure({ key: 'treemap_v2', }), new EchartsAreaChartPlugin().configure({ key: 'echarts_area', }), new EchartsTimeseriesBarChartPlugin().configure({ key: 'echarts_timeseries_bar', }), new EchartsTimeseriesLineChartPlugin().configure({ key: 'echarts_timeseries_line', }), new EchartsTimeseriesScatterChartPlugin().configure({ key: 'echarts_timeseries_scatter', }), new EchartsTimeseriesSmoothLineChartPlugin().configure({ key: 'echarts_timeseries_smooth', }), new EchartsTimeseriesStepChartPlugin().configure({ key: 'echarts_timeseries_step', }), new EchartsMixedTimeseriesChartPlugin().configure({ key: 'mixed_timeseries', }), new EchartsGaugeChartPlugin().configure({ key: 'gauge_chart', }), new EchartsRadarChartPlugin().configure({ key: 'radar', }), new EchartsTreeChartPlugin().configure({ key: 'tree', }), new BigNumberChartPlugin().configure({ key: 'big_number', }), new BigNumberTotalChartPlugin().configure({ key: 'big_number_total', }), new EchartsSunburstChartPlugin().configure({ key: 'sunburst', }), ]; plugins.forEach(plugin => { expect(plugin.metadata.parseMethod).toEqual('json'); }); });
6,263
0
petrpan-code/apache/superset/superset-frontend/plugins/plugin-chart-echarts
petrpan-code/apache/superset/superset-frontend/plugins/plugin-chart-echarts/test/tsconfig.json
{ "compilerOptions": { "composite": false, "emitDeclarationOnly": false, "noEmit": true, "rootDir": "." }, "extends": "../../../tsconfig.json", "include": [ "**/*", "../types/**/*", "../../../types/**/*" ], "references": [ { "path": "../../../packages/superset-ui-chart-controls" }, { "path": "../../../packages/superset-ui-core" } ] }
6,264
0
petrpan-code/apache/superset/superset-frontend/plugins/plugin-chart-echarts/test
petrpan-code/apache/superset/superset-frontend/plugins/plugin-chart-echarts/test/BigNumber/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 { DatasourceType, supersetTheme, TimeGranularity, } from '@superset-ui/core'; import transformProps from '../../src/BigNumber/BigNumberWithTrendline/transformProps'; import { BigNumberDatum, BigNumberWithTrendlineChartProps, BigNumberWithTrendlineFormData, } from '../../src/BigNumber/types'; const formData = { metric: 'value', colorPicker: { r: 0, g: 122, b: 135, a: 1, }, compareLag: 1, timeGrainSqla: TimeGranularity.QUARTER, granularitySqla: 'ds', compareSuffix: 'over last quarter', viz_type: 'big_number', yAxisFormat: '.3s', datasource: 'test_datasource', }; const rawFormData: BigNumberWithTrendlineFormData = { colorPicker: { b: 0, g: 0, r: 0 }, datasource: '1__table', metric: 'value', color_picker: { r: 0, g: 122, b: 135, a: 1, }, compare_lag: 1, time_grain_sqla: TimeGranularity.QUARTER, granularity_sqla: 'ds', compare_suffix: 'over last quarter', viz_type: 'big_number', y_axis_format: '.3s', }; function generateProps( data: BigNumberDatum[], extraFormData = {}, extraQueryData: any = {}, ): BigNumberWithTrendlineChartProps { return { width: 200, height: 500, annotationData: {}, datasource: { id: 0, name: '', type: DatasourceType.Table, columns: [], metrics: [], columnFormats: {}, verboseMap: {}, }, rawDatasource: {}, rawFormData, hooks: {}, initialValues: {}, formData: { ...formData, ...extraFormData, }, queriesData: [ { data, ...extraQueryData, }, ], ownState: {}, filterState: {}, behaviors: [], theme: supersetTheme, }; } describe('BigNumberWithTrendline', () => { const props = generateProps( [ { __timestamp: 0, value: 1.2345, }, { __timestamp: 100, value: null, }, ], { showTrendLine: true }, ); describe('transformProps()', () => { it('should fallback and format time', () => { const transformed = transformProps(props); // the first item is the last item sorted by __timestamp const lastDatum = transformed.trendLineData?.pop(); // should use last available value expect(lastDatum?.[0]).toStrictEqual(100); expect(lastDatum?.[1]).toBeNull(); // should note this is a fallback expect(transformed.bigNumber).toStrictEqual(1.2345); expect(transformed.bigNumberFallback).not.toBeNull(); // should successfully formatTime by granularity // @ts-ignore expect(transformed.formatTime(new Date('2020-01-01'))).toStrictEqual( '2020-01-01 00:00:00', ); }); it('should respect datasource d3 format', () => { const propsWithDatasource = { ...props, datasource: { ...props.datasource, metrics: [ { label: 'value', metric_name: 'value', d3format: '.2f', }, ], }, }; const transformed = transformProps(propsWithDatasource); // @ts-ignore expect(transformed.headerFormatter(transformed.bigNumber)).toStrictEqual( '1.23', ); }); it('should format with datasource currency', () => { const propsWithDatasource = { ...props, datasource: { ...props.datasource, currencyFormats: { value: { symbol: 'USD', symbolPosition: 'prefix' }, }, metrics: [ { label: 'value', metric_name: 'value', d3format: '.2f', currency: `{symbol: 'USD', symbolPosition: 'prefix' }`, }, ], }, }; const transformed = transformProps(propsWithDatasource); // @ts-ignore expect(transformed.headerFormatter(transformed.bigNumber)).toStrictEqual( '$ 1.23', ); }); }); });
6,265
0
petrpan-code/apache/superset/superset-frontend/plugins/plugin-chart-echarts/test
petrpan-code/apache/superset/superset-frontend/plugins/plugin-chart-echarts/test/BoxPlot/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 { isPostProcessingBoxplot, PostProcessingBoxplot, } from '@superset-ui/core'; import { DEFAULT_TITLE_FORM_DATA } from '../../src/constants'; import buildQuery from '../../src/BoxPlot/buildQuery'; import { BoxPlotQueryFormData } from '../../src/BoxPlot/types'; describe('BoxPlot buildQuery', () => { const formData: BoxPlotQueryFormData = { ...DEFAULT_TITLE_FORM_DATA, columns: [], datasource: '5__table', granularity_sqla: 'ds', groupby: ['bar'], metrics: ['foo'], time_grain_sqla: 'P1Y', viz_type: 'my_chart', whiskerOptions: 'Tukey', yAxisFormat: 'SMART_NUMBER', }; it('should build timeseries when series columns is empty', () => { const queryContext = buildQuery(formData); const [query] = queryContext.queries; expect(query.metrics).toEqual(['foo']); expect(query.columns).toEqual(['ds', 'bar']); expect(query.series_columns).toEqual(['bar']); const [rule] = query.post_processing || []; expect(isPostProcessingBoxplot(rule)).toEqual(true); expect((rule as PostProcessingBoxplot)?.options?.groupby).toEqual(['bar']); }); it('should build non-timeseries query object when columns is defined', () => { const queryContext = buildQuery({ ...formData, columns: ['qwerty'] }); const [query] = queryContext.queries; expect(query.metrics).toEqual(['foo']); expect(query.columns).toEqual(['qwerty', 'bar']); expect(query.series_columns).toEqual(['bar']); const [rule] = query.post_processing || []; expect(isPostProcessingBoxplot(rule)).toEqual(true); expect((rule as PostProcessingBoxplot)?.options?.groupby).toEqual(['bar']); }); });
6,266
0
petrpan-code/apache/superset/superset-frontend/plugins/plugin-chart-echarts/test
petrpan-code/apache/superset/superset-frontend/plugins/plugin-chart-echarts/test/BoxPlot/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 { EchartsBoxPlotChartProps } from '../../src/BoxPlot/types'; import transformProps from '../../src/BoxPlot/transformProps'; describe('BoxPlot transformProps', () => { const formData: SqlaFormData = { datasource: '5__table', granularity_sqla: 'ds', time_grain_sqla: 'P1Y', columns: [], metrics: ['AVG(averageprice)'], groupby: ['type', 'region'], whiskerOptions: 'Tukey', yAxisFormat: 'SMART_NUMBER', viz_type: 'my_chart', }; const chartProps = new ChartProps({ formData, width: 800, height: 600, queriesData: [ { data: [ { type: 'organic', region: 'Charlotte', 'AVG(averageprice)__mean': 1.9405512820512825, 'AVG(averageprice)__median': 1.9025, 'AVG(averageprice)__max': 2.505, 'AVG(averageprice)__min': 1.4775, 'AVG(averageprice)__q1': 1.73875, 'AVG(averageprice)__q3': 2.105, 'AVG(averageprice)__count': 39, 'AVG(averageprice)__outliers': [2.735], }, { type: 'organic', region: 'Hartford Springfield', 'AVG(averageprice)__mean': 2.231141025641026, 'AVG(averageprice)__median': 2.265, 'AVG(averageprice)__max': 2.595, 'AVG(averageprice)__min': 1.862, 'AVG(averageprice)__q1': 2.1285, 'AVG(averageprice)__q3': 2.32625, 'AVG(averageprice)__count': 39, 'AVG(averageprice)__outliers': [], }, ], }, ], theme: supersetTheme, }); it('should transform chart props for viz', () => { expect(transformProps(chartProps as EchartsBoxPlotChartProps)).toEqual( expect.objectContaining({ width: 800, height: 600, echartOptions: expect.objectContaining({ series: expect.arrayContaining([ expect.objectContaining({ name: 'boxplot', data: expect.arrayContaining([ expect.objectContaining({ name: 'organic, Charlotte', value: [ 1.4775, 1.73875, 1.9025, 2.105, 2.505, 1.9405512820512825, 39, [2.735], ], }), expect.objectContaining({ name: 'organic, Hartford Springfield', value: [ 1.862, 2.1285, 2.265, 2.32625, 2.595, 2.231141025641026, 39, [], ], }), ]), }), expect.objectContaining({ name: 'outlier', data: [['organic, Charlotte', 2.735]], }), ]), }), }), ); }); });
6,267
0
petrpan-code/apache/superset/superset-frontend/plugins/plugin-chart-echarts/test
petrpan-code/apache/superset/superset-frontend/plugins/plugin-chart-echarts/test/Bubble/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/Bubble/buildQuery'; describe('Bubble buildQuery', () => { const formData = { datasource: '1__table', viz_type: 'echarts_bubble', entity: 'customer_name', x: 'count', y: { aggregate: 'sum', column: { column_name: 'price_each', }, expressionType: 'simple', label: 'SUM(price_each)', }, size: { aggregate: 'sum', column: { column_name: 'sales', }, expressionType: 'simple', label: 'SUM(sales)', }, }; it('Should build query without dimension', () => { const queryContext = buildQuery(formData); const [query] = queryContext.queries; expect(query.columns).toEqual(['customer_name']); expect(query.metrics).toEqual([ 'count', { aggregate: 'sum', column: { column_name: 'price_each', }, expressionType: 'simple', label: 'SUM(price_each)', }, { aggregate: 'sum', column: { column_name: 'sales', }, expressionType: 'simple', label: 'SUM(sales)', }, ]); }); it('Should build query with dimension', () => { const queryContext = buildQuery({ ...formData, series: 'state' }); const [query] = queryContext.queries; expect(query.columns).toEqual(['customer_name', 'state']); expect(query.metrics).toEqual([ 'count', { aggregate: 'sum', column: { column_name: 'price_each', }, expressionType: 'simple', label: 'SUM(price_each)', }, { aggregate: 'sum', column: { column_name: 'sales', }, expressionType: 'simple', label: 'SUM(sales)', }, ]); }); });
6,268
0
petrpan-code/apache/superset/superset-frontend/plugins/plugin-chart-echarts/test
petrpan-code/apache/superset/superset-frontend/plugins/plugin-chart-echarts/test/Bubble/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 { EchartsBubbleChartProps } from 'plugins/plugin-chart-echarts/src/Bubble/types'; import transformProps, { formatTooltip } from '../../src/Bubble/transformProps'; describe('Bubble transformProps', () => { const formData: SqlaFormData = { datasource: '1__table', viz_type: 'echarts_bubble', entity: 'customer_name', x: 'count', y: { aggregate: 'sum', column: { column_name: 'price_each', }, expressionType: 'simple', label: 'SUM(price_each)', }, size: { aggregate: 'sum', column: { column_name: 'sales', }, expressionType: 'simple', label: 'SUM(sales)', }, yAxisBounds: [null, null], }; const chartProps = new ChartProps({ formData, height: 800, width: 800, queriesData: [ { data: [ { customer_name: 'AV Stores, Co.', count: 10, 'SUM(price_each)': 20, 'SUM(sales)': 30, }, { customer_name: 'Alpha Cognac', count: 40, 'SUM(price_each)': 50, 'SUM(sales)': 60, }, { customer_name: 'Amica Models & Co.', count: 70, 'SUM(price_each)': 80, 'SUM(sales)': 90, }, ], }, ], theme: supersetTheme, }); it('Should transform props for viz', () => { expect(transformProps(chartProps as EchartsBubbleChartProps)).toEqual( expect.objectContaining({ width: 800, height: 800, echartOptions: expect.objectContaining({ series: expect.arrayContaining([ expect.objectContaining({ data: expect.arrayContaining([ [10, 20, 30, 'AV Stores, Co.', null], ]), }), expect.objectContaining({ data: expect.arrayContaining([ [40, 50, 60, 'Alpha Cognac', null], ]), }), expect.objectContaining({ data: expect.arrayContaining([ [70, 80, 90, 'Amica Models & Co.', null], ]), }), ]), }), }), ); }); }); describe('Bubble formatTooltip', () => { const dollerFormatter = getNumberFormatter('$,.2f'); const percentFormatter = getNumberFormatter(',.1%'); it('Should generate correct bubble label content with dimension', () => { const params = { data: [10000, 20000, 3, 'bubble title', 'bubble dimension'], }; expect( formatTooltip( params, 'x-axis-label', 'y-axis-label', 'size-label', dollerFormatter, dollerFormatter, percentFormatter, ), ).toEqual( `<p>bubble title </br> bubble dimension</p> x-axis-label: $10,000.00 <br/> y-axis-label: $20,000.00 <br/> size-label: 300.0%`, ); }); it('Should generate correct bubble label content without dimension', () => { const params = { data: [10000, 25000, 3, 'bubble title', null], }; expect( formatTooltip( params, 'x-axis-label', 'y-axis-label', 'size-label', dollerFormatter, dollerFormatter, percentFormatter, ), ).toEqual( `<p>bubble title</p> x-axis-label: $10,000.00 <br/> y-axis-label: $25,000.00 <br/> size-label: 300.0%`, ); }); });