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,064
0
petrpan-code/apache/superset/superset-frontend/cypress-base/cypress/e2e
petrpan-code/apache/superset/superset-frontend/cypress-base/cypress/e2e/dashboard/nativeFilters.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 qs from 'querystring'; import { dashboardView, nativeFilters, exploreView, dataTestChartName, } from 'cypress/support/directories'; import { SAMPLE_DASHBOARD_1 } from 'cypress/utils/urls'; import { addCountryNameFilter, addParentFilterWithValue, applyAdvancedTimeRangeFilterOnDashboard, applyNativeFilterValueWithIndex, cancelNativeFilterSettings, checkNativeFilterTooltip, clickOnAddFilterInModal, collapseFilterOnLeftPanel, deleteNativeFilter, enterNativeFilterEditModal, expandFilterOnLeftPanel, fillNativeFilterForm, getNativeFilterPlaceholderWithIndex, inputNativeFilterDefaultValue, saveNativeFilterSettings, nativeFilterTooltips, undoDeleteNativeFilter, validateFilterContentOnDashboard, valueNativeFilterOptions, validateFilterNameOnDashboard, testItems, WORLD_HEALTH_CHARTS, interceptGet, interceptCharts, interceptDatasets, interceptFilterState, } from './utils'; const SAMPLE_CHART = { name: 'Most Populated Countries', viz: 'table' }; function visitDashboard(createSample = true) { interceptCharts(); interceptGet(); interceptDatasets(); if (createSample) { cy.createSampleDashboards([0]); } cy.visit(SAMPLE_DASHBOARD_1); cy.wait('@get'); cy.wait('@getCharts'); cy.wait('@getDatasets'); cy.url().should('contain', 'native_filters_key'); } function prepareDashboardFilters( filters: { name: string; column: string; datasetId: number }[], ) { cy.createSampleDashboards([0]); cy.request({ method: 'GET', url: `api/v1/dashboard/1-sample-dashboard`, }).then(res => { const { body } = res; const dashboardId = body.result.id; const allFilters: Record<string, unknown>[] = []; filters.forEach((f, i) => { allFilters.push({ id: `NATIVE_FILTER-fLH0pxFQ${i}`, controlValues: { enableEmptyFilter: false, defaultToFirstItem: false, multiSelect: true, searchAllOptions: false, inverseSelection: false, }, name: f.name, filterType: 'filter_select', targets: [ { datasetId: f.datasetId, column: { name: f.column }, }, ], defaultDataMask: { extraFormData: {}, filterState: {}, ownState: {}, }, cascadeParentIds: [], scope: { rootPath: ['ROOT_ID'], excluded: [], }, type: 'NATIVE_FILTER', description: '', chartsInScope: [6], tabsInScope: [], }); }); if (dashboardId) { const jsonMetadata = { native_filter_configuration: allFilters, timed_refresh_immune_slices: [], expanded_slices: {}, refresh_frequency: 0, color_scheme: '', label_colors: {}, shared_label_colors: {}, color_scheme_domain: [], cross_filters_enabled: false, positions: { DASHBOARD_VERSION_KEY: 'v2', ROOT_ID: { type: 'ROOT', id: 'ROOT_ID', children: ['GRID_ID'] }, GRID_ID: { type: 'GRID', id: 'GRID_ID', children: ['ROW-0rHnUz4nMA'], parents: ['ROOT_ID'], }, HEADER_ID: { id: 'HEADER_ID', type: 'HEADER', meta: { text: '1 - Sample dashboard' }, }, 'CHART-DF6EfI55F-': { type: 'CHART', id: 'CHART-DF6EfI55F-', children: [], parents: ['ROOT_ID', 'GRID_ID', 'ROW-0rHnUz4nMA'], meta: { width: 4, height: 50, chartId: 6, sliceName: 'Most Populated Countries', }, }, 'ROW-0rHnUz4nMA': { type: 'ROW', id: 'ROW-0rHnUz4nMA', children: ['CHART-DF6EfI55F-'], parents: ['ROOT_ID', 'GRID_ID'], meta: { background: 'BACKGROUND_TRANSPARENT' }, }, }, default_filters: '{}', filter_scopes: {}, chart_configuration: {}, }; return cy .request({ method: 'PUT', url: `api/v1/dashboard/${dashboardId}`, body: { json_metadata: JSON.stringify(jsonMetadata), }, }) .then(() => visitDashboard(false)); } return cy; }); } function selectFilter(index: number) { cy.get("[data-test='filter-title-container'] [draggable='true']") .eq(index) .click(); } function closeFilterModal() { cy.get('body').then($body => { if ($body.find('[data-test="native-filter-modal-cancel-button"]').length) { cy.getBySel('native-filter-modal-cancel-button').click(); } }); } function openVerticalFilterBar() { cy.getBySel('dashboard-filters-panel').should('exist'); cy.getBySel('filter-bar__expand-button').click(); } function setFilterBarOrientation(orientation: 'vertical' | 'horizontal') { cy.getBySel('filterbar-orientation-icon').click(); cy.wait(250); cy.getBySel('dropdown-selectable-icon-submenu') .contains('Orientation of filter bar') .should('exist') .trigger('mouseover'); if (orientation === 'vertical') { cy.get('.ant-dropdown-menu-item-selected') .contains('Horizontal (Top)') .should('exist'); cy.get('.ant-dropdown-menu-item').contains('Vertical (Left)').click(); cy.getBySel('dashboard-filters-panel').should('exist'); } else { cy.get('.ant-dropdown-menu-item-selected') .contains('Vertical (Left)') .should('exist'); cy.get('.ant-dropdown-menu-item').contains('Horizontal (Top)').click(); cy.getBySel('loading-indicator').should('exist'); cy.getBySel('filter-bar').should('exist'); cy.getBySel('dashboard-filters-panel').should('not.exist'); } } function openMoreFilters(intercetFilterState = true) { interceptFilterState(); cy.getBySel('dropdown-container-btn').click(); if (intercetFilterState) { cy.wait('@postFilterState'); } } describe('Horizontal FilterBar', () => { it('should go from vertical to horizontal and the opposite', () => { visitDashboard(); openVerticalFilterBar(); setFilterBarOrientation('horizontal'); setFilterBarOrientation('vertical'); }); it('should show all default actions in horizontal mode', () => { visitDashboard(); openVerticalFilterBar(); setFilterBarOrientation('horizontal'); cy.getBySel('horizontal-filterbar-empty') .contains('No filters are currently added to this dashboard.') .should('exist'); cy.getBySel('filter-bar__create-filter').should('exist'); cy.getBySel('filterbar-action-buttons').should('exist'); }); it('should stay in horizontal mode when reloading', () => { visitDashboard(); openVerticalFilterBar(); setFilterBarOrientation('horizontal'); cy.reload(); cy.getBySel('dashboard-filters-panel').should('not.exist'); }); it('should show all filters in available space on load', () => { prepareDashboardFilters([ { name: 'test_1', column: 'country_name', datasetId: 2 }, { name: 'test_2', column: 'country_code', datasetId: 2 }, { name: 'test_3', column: 'region', datasetId: 2 }, ]); setFilterBarOrientation('horizontal'); cy.get('.filter-item-wrapper').should('have.length', 3); }); it('should show "more filters" on window resizing up and down', () => { prepareDashboardFilters([ { name: 'test_1', column: 'country_name', datasetId: 2 }, { name: 'test_2', column: 'country_code', datasetId: 2 }, { name: 'test_3', column: 'region', datasetId: 2 }, ]); setFilterBarOrientation('horizontal'); cy.getBySel('form-item-value').should('have.length', 3); cy.viewport(768, 1024); cy.getBySel('form-item-value').should('have.length', 0); openMoreFilters(false); cy.getBySel('form-item-value').should('have.length', 3); cy.getBySel('filter-bar').click(); cy.viewport(1000, 1024); openMoreFilters(false); cy.getBySel('form-item-value').should('have.length', 3); cy.getBySel('filter-bar').click(); cy.viewport(1300, 1024); cy.getBySel('form-item-value').should('have.length', 3); cy.getBySel('dropdown-container-btn').should('not.exist'); }); it('should show "more filters" and scroll', () => { prepareDashboardFilters([ { name: 'test_1', column: 'country_name', datasetId: 2 }, { name: 'test_2', column: 'country_code', datasetId: 2 }, { name: 'test_3', column: 'region', datasetId: 2 }, { name: 'test_4', column: 'year', datasetId: 2 }, { name: 'test_5', column: 'country_name', datasetId: 2 }, { name: 'test_6', column: 'country_code', datasetId: 2 }, { name: 'test_7', column: 'region', datasetId: 2 }, { name: 'test_8', column: 'year', datasetId: 2 }, { name: 'test_9', column: 'country_name', datasetId: 2 }, { name: 'test_10', column: 'country_code', datasetId: 2 }, { name: 'test_11', column: 'region', datasetId: 2 }, { name: 'test_12', column: 'year', datasetId: 2 }, ]); setFilterBarOrientation('horizontal'); cy.get('.filter-item-wrapper').should('have.length', 3); openMoreFilters(); cy.getBySel('form-item-value').should('have.length', 12); cy.getBySel('filter-control-name').contains('test_10').should('be.visible'); cy.getBySel('filter-control-name') .contains('test_12') .should('not.be.visible'); cy.get('.ant-popover-inner-content').scrollTo('bottom'); cy.getBySel('filter-control-name').contains('test_12').should('be.visible'); }); it('should display newly added filter', () => { visitDashboard(); openVerticalFilterBar(); setFilterBarOrientation('horizontal'); enterNativeFilterEditModal(false); addCountryNameFilter(); saveNativeFilterSettings([]); validateFilterNameOnDashboard(testItems.topTenChart.filterColumn); }); it('should spot changes in "more filters" and apply their values', () => { cy.intercept(`/api/v1/chart/data?form_data=**`).as('chart'); prepareDashboardFilters([ { name: 'test_1', column: 'country_name', datasetId: 2 }, { name: 'test_2', column: 'country_code', datasetId: 2 }, { name: 'test_3', column: 'region', datasetId: 2 }, { name: 'test_4', column: 'year', datasetId: 2 }, { name: 'test_5', column: 'country_name', datasetId: 2 }, { name: 'test_6', column: 'country_code', datasetId: 2 }, { name: 'test_7', column: 'region', datasetId: 2 }, { name: 'test_8', column: 'year', datasetId: 2 }, { name: 'test_9', column: 'country_name', datasetId: 2 }, { name: 'test_10', column: 'country_code', datasetId: 2 }, { name: 'test_11', column: 'region', datasetId: 2 }, { name: 'test_12', column: 'year', datasetId: 2 }, ]); setFilterBarOrientation('horizontal'); openMoreFilters(); applyNativeFilterValueWithIndex(8, testItems.filterDefaultValue); cy.get(nativeFilters.applyFilter).click({ force: true }); cy.wait('@chart'); cy.get('.ant-scroll-number.ant-badge-count').should( 'have.attr', 'title', '1', ); }); it('should focus filter and open "more filters" programmatically', () => { prepareDashboardFilters([ { name: 'test_1', column: 'country_name', datasetId: 2 }, { name: 'test_2', column: 'country_code', datasetId: 2 }, { name: 'test_3', column: 'region', datasetId: 2 }, { name: 'test_4', column: 'year', datasetId: 2 }, { name: 'test_5', column: 'country_name', datasetId: 2 }, { name: 'test_6', column: 'country_code', datasetId: 2 }, { name: 'test_7', column: 'region', datasetId: 2 }, { name: 'test_8', column: 'year', datasetId: 2 }, { name: 'test_9', column: 'country_name', datasetId: 2 }, { name: 'test_10', column: 'country_code', datasetId: 2 }, { name: 'test_11', column: 'region', datasetId: 2 }, { name: 'test_12', column: 'year', datasetId: 2 }, ]); setFilterBarOrientation('horizontal'); openMoreFilters(); applyNativeFilterValueWithIndex(8, testItems.filterDefaultValue); cy.get(nativeFilters.applyFilter).click({ force: true }); cy.getBySel('slice-header').within(() => { cy.get('.filter-counts').trigger('mouseover'); }); cy.get('.filterStatusPopover').contains('test_9').click(); cy.getBySel('dropdown-content').should('be.visible'); cy.get('.ant-select-focused').should('be.visible'); }); it('should show tag count and one plain tag on focus and only count on blur in select ', () => { prepareDashboardFilters([ { name: 'test_1', column: 'country_name', datasetId: 2 }, ]); setFilterBarOrientation('horizontal'); enterNativeFilterEditModal(); inputNativeFilterDefaultValue('Albania'); cy.get('.ant-select-selection-search-input').clear({ force: true }); inputNativeFilterDefaultValue('Algeria', true); saveNativeFilterSettings([SAMPLE_CHART]); cy.getBySel('filter-bar').within(() => { cy.get(nativeFilters.filterItem).contains('Albania').should('be.visible'); cy.get(nativeFilters.filterItem).contains('+ 1 ...').should('be.visible'); cy.get('.ant-select-selection-search-input').click(); cy.get(nativeFilters.filterItem).contains('+ 2 ...').should('be.visible'); }); }); }); describe('Native filters', () => { describe('Nativefilters tests initial state required', () => { beforeEach(() => { cy.createSampleDashboards([0]); }); it('Verify that default value is respected after revisit', () => { prepareDashboardFilters([ { name: 'country_name', column: 'country_name', datasetId: 2 }, ]); enterNativeFilterEditModal(); inputNativeFilterDefaultValue(testItems.filterDefaultValue); saveNativeFilterSettings([SAMPLE_CHART]); cy.get(nativeFilters.filterItem) .contains(testItems.filterDefaultValue) .should('be.visible'); cy.get(dataTestChartName(testItems.topTenChart.name)).within(() => { cy.contains(testItems.filterDefaultValue).should('be.visible'); cy.contains(testItems.filterOtherCountry).should('not.exist'); }); // reload dashboard cy.reload(); cy.get(dataTestChartName(testItems.topTenChart.name)).within(() => { cy.contains(testItems.filterDefaultValue).should('be.visible'); cy.contains(testItems.filterOtherCountry).should('not.exist'); }); validateFilterContentOnDashboard(testItems.filterDefaultValue); }); it('User can create parent filters using "Values are dependent on other filters"', () => { prepareDashboardFilters([ { name: 'region', column: 'region', datasetId: 2 }, { name: 'country_name', column: 'country_name', datasetId: 2 }, ]); enterNativeFilterEditModal(); selectFilter(1); cy.get(nativeFilters.filterConfigurationSections.displayedSection).within( () => { cy.contains('Values are dependent on other filters') .should('be.visible') .click(); }, ); addParentFilterWithValue(0, testItems.topTenChart.filterColumnRegion); saveNativeFilterSettings([SAMPLE_CHART]); [ testItems.topTenChart.filterColumnRegion, testItems.topTenChart.filterColumn, ].forEach(it => { cy.get(nativeFilters.filterFromDashboardView.filterName) .contains(it) .should('be.visible'); }); getNativeFilterPlaceholderWithIndex(1) .invoke('text') .should('equal', '214 options', { timeout: 20000 }); // apply first filter value and validate 2nd filter is depden on 1st filter. applyNativeFilterValueWithIndex(0, 'North America'); getNativeFilterPlaceholderWithIndex(0).should('have.text', '3 options', { timeout: 20000, }); }); it('user can delete dependent filter', () => { prepareDashboardFilters([ { name: 'region', column: 'region', datasetId: 2 }, { name: 'country_name', column: 'country_name', datasetId: 2 }, ]); enterNativeFilterEditModal(); selectFilter(1); cy.get(nativeFilters.filterConfigurationSections.displayedSection).within( () => { cy.contains('Values are dependent on other filters') .should('be.visible') .click(); }, ); addParentFilterWithValue(0, testItems.topTenChart.filterColumnRegion); // remove year native filter to cause it disappears from parent filter input in global sales cy.get(nativeFilters.modal.tabsList.removeTab) .should('be.visible') .first() .click(); // make sure you are seeing global sales filter which had parent filter cy.get(nativeFilters.modal.tabsList.filterItemsContainer) .children() .last() .click(); // cy.wait(1000); cy.get(nativeFilters.filterConfigurationSections.displayedSection).within( () => { cy.contains('Values are dependent on other filters').should( 'not.exist', ); }, ); }); it('User can create filter depend on 2 other filters', () => { prepareDashboardFilters([ { name: 'region', column: 'region', datasetId: 2 }, { name: 'country_name', column: 'country_name', datasetId: 2 }, { name: 'country_code', column: 'country_code', datasetId: 2 }, ]); enterNativeFilterEditModal(); selectFilter(2); cy.get(nativeFilters.filterConfigurationSections.displayedSection).within( () => { cy.contains('Values are dependent on other filters') .should('be.visible') .click(); cy.get(exploreView.controlPanel.addFieldValue).click(); }, ); // add value to the first input addParentFilterWithValue(0, testItems.topTenChart.filterColumnRegion); // add value to the second input addParentFilterWithValue(1, testItems.topTenChart.filterColumn); saveNativeFilterSettings([SAMPLE_CHART]); // filters should be displayed in the left panel [ testItems.topTenChart.filterColumnRegion, testItems.topTenChart.filterColumn, testItems.topTenChart.filterColumnCountryCode, ].forEach(it => { validateFilterNameOnDashboard(it); }); // initially first filter shows 39 options getNativeFilterPlaceholderWithIndex(0).should('have.text', '7 options'); // initially second filter shows 409 options getNativeFilterPlaceholderWithIndex(1).should('have.text', '214 options'); // verify third filter shows 409 options getNativeFilterPlaceholderWithIndex(2).should('have.text', '214 options'); // apply first filter value applyNativeFilterValueWithIndex(0, 'North America'); // verify second filter shows 409 options available still getNativeFilterPlaceholderWithIndex(0).should('have.text', '214 options'); // verify second filter shows 69 options available still getNativeFilterPlaceholderWithIndex(1).should('have.text', '3 options'); // apply second filter value applyNativeFilterValueWithIndex(1, 'United States'); // verify number of available options for third filter - should be decreased to only one getNativeFilterPlaceholderWithIndex(0).should('have.text', '1 option'); }); it('User can remove parent filters', () => { prepareDashboardFilters([ { name: 'region', column: 'region', datasetId: 2 }, { name: 'country_name', column: 'country_name', datasetId: 2 }, ]); enterNativeFilterEditModal(); selectFilter(1); // Select dependdent option and auto use platform for genre cy.get(nativeFilters.filterConfigurationSections.displayedSection).within( () => { cy.contains('Values are dependent on other filters') .should('be.visible') .click(); }, ); saveNativeFilterSettings([SAMPLE_CHART]); enterNativeFilterEditModal(false); cy.get(nativeFilters.modal.tabsList.removeTab) .should('be.visible') .first() .click({ force: true, }); saveNativeFilterSettings([SAMPLE_CHART]); cy.get(dataTestChartName(testItems.topTenChart.name)).within(() => { cy.contains(testItems.filterDefaultValue).should('be.visible'); cy.contains(testItems.filterOtherCountry).should('be.visible'); }); }); }); describe('Nativefilters basic interactions', () => { before(() => { visitDashboard(); }); beforeEach(() => { cy.createSampleDashboards([0]); closeFilterModal(); }); it('User can expand / retract native filter sidebar on a dashboard', () => { cy.get(nativeFilters.addFilterButton.button).should('not.exist'); expandFilterOnLeftPanel(); cy.get(nativeFilters.filterFromDashboardView.createFilterButton).should( 'be.visible', ); cy.get(nativeFilters.filterFromDashboardView.expand).should( 'not.be.visible', ); collapseFilterOnLeftPanel(); }); it('User can enter filter edit pop-up by clicking on native filter edit icon', () => { enterNativeFilterEditModal(false); }); it('User can delete a native filter', () => { enterNativeFilterEditModal(false); cy.get(nativeFilters.filtersList.removeIcon).first().click(); cy.contains('Restore Filter').should('not.exist', { timeout: 10000 }); }); it('User can cancel creating a new filter', () => { enterNativeFilterEditModal(false); cancelNativeFilterSettings(); }); it('Verify setting options and tooltips for value filter', () => { enterNativeFilterEditModal(false); cy.contains('Filter value is required').should('be.visible').click(); checkNativeFilterTooltip(0, nativeFilterTooltips.preFilter); checkNativeFilterTooltip(1, nativeFilterTooltips.defaultValue); cy.get(nativeFilters.modal.container).should('be.visible'); valueNativeFilterOptions.forEach(el => { cy.contains(el); }); cy.contains('Values are dependent on other filters').should('not.exist'); cy.get( nativeFilters.filterConfigurationSections.checkedCheckbox, ).contains('Can select multiple values'); checkNativeFilterTooltip(2, nativeFilterTooltips.required); checkNativeFilterTooltip(3, nativeFilterTooltips.defaultToFirstItem); checkNativeFilterTooltip(4, nativeFilterTooltips.searchAllFilterOptions); checkNativeFilterTooltip(5, nativeFilterTooltips.inverseSelection); clickOnAddFilterInModal(); cy.contains('Values are dependent on other filters').should('exist'); }); }); describe('Nativefilters initial state not required', () => { it("User can check 'Filter has default value'", () => { prepareDashboardFilters([ { name: 'country_name', column: 'country_name', datasetId: 2 }, ]); enterNativeFilterEditModal(); inputNativeFilterDefaultValue(testItems.filterDefaultValue); }); it('User can add a new native filter', () => { prepareDashboardFilters([]); let filterKey: string; const removeFirstChar = (search: string) => search.split('').slice(1, search.length).join(''); cy.location().then(loc => { cy.url().should('contain', 'native_filters_key'); const queryParams = qs.parse(removeFirstChar(loc.search)); filterKey = queryParams.native_filters_key as string; expect(typeof filterKey).eq('string'); }); enterNativeFilterEditModal(); addCountryNameFilter(); saveNativeFilterSettings([SAMPLE_CHART]); cy.location().then(loc => { cy.url().should('contain', 'native_filters_key'); const queryParams = qs.parse(removeFirstChar(loc.search)); const newfilterKey = queryParams.native_filters_key; expect(newfilterKey).eq(filterKey); }); cy.get(nativeFilters.modal.container).should('not.exist'); }); it('User can restore a deleted native filter', () => { prepareDashboardFilters([ { name: 'country_code', column: 'country_code', datasetId: 2 }, ]); enterNativeFilterEditModal(); cy.get(nativeFilters.filtersList.removeIcon).first().click(); cy.get('[data-test="restore-filter-button"]') .should('be.visible') .click(); cy.get(nativeFilters.modal.container) .find(nativeFilters.filtersPanel.filterName) .should( 'have.attr', 'value', testItems.topTenChart.filterColumnCountryCode, ); }); it('User can create a time grain filter', () => { prepareDashboardFilters([]); enterNativeFilterEditModal(); fillNativeFilterForm( testItems.filterType.timeGrain, testItems.filterType.timeGrain, testItems.datasetForNativeFilter, ); saveNativeFilterSettings([SAMPLE_CHART]); applyNativeFilterValueWithIndex(0, testItems.filterTimeGrain); cy.get(nativeFilters.applyFilter).click(); cy.url().then(u => { const ur = new URL(u); expect(ur.search).to.include('native_filters'); }); validateFilterNameOnDashboard(testItems.filterType.timeGrain); validateFilterContentOnDashboard(testItems.filterTimeGrain); }); it.skip('User can create a time range filter', () => { enterNativeFilterEditModal(); fillNativeFilterForm( testItems.filterType.timeRange, testItems.filterType.timeRange, ); saveNativeFilterSettings(WORLD_HEALTH_CHARTS); cy.get(dashboardView.salesDashboardSpecific.vehicleSalesFilterTimeRange) .should('be.visible') .click(); applyAdvancedTimeRangeFilterOnDashboard('2005-12-17', '2006-12-17'); cy.url().then(u => { const ur = new URL(u); expect(ur.search).to.include('native_filters'); }); validateFilterNameOnDashboard(testItems.filterType.timeRange); cy.get(nativeFilters.filterFromDashboardView.timeRangeFilterContent) .contains('2005-12-17') .should('be.visible'); }); it.skip('User can create a time column filter', () => { enterNativeFilterEditModal(); fillNativeFilterForm( testItems.filterType.timeColumn, testItems.filterType.timeColumn, testItems.datasetForNativeFilter, ); saveNativeFilterSettings(WORLD_HEALTH_CHARTS); cy.intercept(`/api/v1/chart/data?form_data=**`).as('chart'); cy.get(nativeFilters.modal.container).should('not.exist'); // assert that native filter is created validateFilterNameOnDashboard(testItems.filterType.timeColumn); applyNativeFilterValueWithIndex( 0, testItems.topTenChart.filterColumnYear, ); cy.get(nativeFilters.applyFilter).click({ force: true }); cy.wait('@chart'); validateFilterContentOnDashboard(testItems.topTenChart.filterColumnYear); }); it('User can create a numerical range filter', () => { visitDashboard(); enterNativeFilterEditModal(false); fillNativeFilterForm( testItems.filterType.numerical, testItems.filterNumericalColumn, testItems.datasetForNativeFilter, testItems.filterNumericalColumn, ); saveNativeFilterSettings([]); // assertions cy.get(nativeFilters.slider.slider).should('be.visible').click('center'); cy.get(nativeFilters.applyFilter).click(); // assert that the url contains 'native_filters' in the url cy.url().then(u => { const ur = new URL(u); expect(ur.search).to.include('native_filters'); // assert that the start handle has a value cy.get(nativeFilters.slider.startHandle) .invoke('attr', 'aria-valuenow') .should('exist'); // assert that the end handle has a value cy.get(nativeFilters.slider.endHandle) .invoke('attr', 'aria-valuenow') .should('exist'); // assert slider text matches what we should have cy.get(nativeFilters.slider.sliderText).should('have.text', '49'); }); }); it('User can undo deleting a native filter', () => { prepareDashboardFilters([ { name: 'country_name', column: 'country_name', datasetId: 2 }, ]); enterNativeFilterEditModal(); undoDeleteNativeFilter(); cy.get(nativeFilters.modal.container) .find(nativeFilters.filtersPanel.filterName) .should('have.attr', 'value', testItems.topTenChart.filterColumn); }); it('User can cancel changes in native filter', () => { prepareDashboardFilters([ { name: 'country_name', column: 'country_name', datasetId: 2 }, ]); enterNativeFilterEditModal(); cy.getBySel('filters-config-modal__name-input').type('|EDITED', { force: true, }); cancelNativeFilterSettings(); enterNativeFilterEditModal(false); cy.get(nativeFilters.filtersList.removeIcon).first().click(); cy.contains('You have removed this filter.').should('be.visible'); }); it('User can create a value filter', () => { visitDashboard(); enterNativeFilterEditModal(false); addCountryNameFilter(); cy.get(nativeFilters.filtersPanel.filterTypeInput) .find(nativeFilters.filtersPanel.filterTypeItem) .should('have.text', testItems.filterType.value); saveNativeFilterSettings([]); validateFilterNameOnDashboard(testItems.topTenChart.filterColumn); }); it('User can apply value filter with selected values', () => { prepareDashboardFilters([ { name: 'country_name', column: 'country_name', datasetId: 2 }, ]); applyNativeFilterValueWithIndex(0, testItems.filterDefaultValue); cy.get(nativeFilters.applyFilter).click(); cy.get(dataTestChartName(testItems.topTenChart.name)).within(() => { cy.contains(testItems.filterDefaultValue).should('be.visible'); cy.contains(testItems.filterOtherCountry).should('not.exist'); }); }); it('User can stop filtering when filter is removed', () => { prepareDashboardFilters([ { name: 'country_name', column: 'country_name', datasetId: 2 }, ]); enterNativeFilterEditModal(); inputNativeFilterDefaultValue(testItems.filterDefaultValue); saveNativeFilterSettings([SAMPLE_CHART]); cy.get(dataTestChartName(testItems.topTenChart.name)).within(() => { cy.contains(testItems.filterDefaultValue).should('be.visible'); cy.contains(testItems.filterOtherCountry).should('not.exist'); }); cy.get(nativeFilters.filterItem) .contains(testItems.filterDefaultValue) .should('be.visible'); validateFilterNameOnDashboard(testItems.topTenChart.filterColumn); enterNativeFilterEditModal(false); deleteNativeFilter(); saveNativeFilterSettings([SAMPLE_CHART]); cy.get(dataTestChartName(testItems.topTenChart.name)).within(() => { cy.contains(testItems.filterDefaultValue).should('be.visible'); cy.contains(testItems.filterOtherCountry).should('be.visible'); }); }); }); });
5,065
0
petrpan-code/apache/superset/superset-frontend/cypress-base/cypress/e2e
petrpan-code/apache/superset/superset-frontend/cypress-base/cypress/e2e/dashboard/tabs.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 { parsePostForm, waitForChartLoad, getChartAliasBySpec, } from 'cypress/utils'; import { TABBED_DASHBOARD } from 'cypress/utils/urls'; import { expandFilterOnLeftPanel } from './utils'; const TREEMAP = { name: 'Treemap', viz: 'treemap_v2' }; const FILTER_BOX = { name: 'Region Filter', viz: 'filter_box' }; const LINE_CHART = { name: 'Growth Rate', viz: 'line' }; const BOX_PLOT = { name: 'Box plot', viz: 'box_plot' }; const BIG_NUMBER = { name: 'Number of Girls', viz: 'big_number_total' }; const TABLE = { name: 'Names Sorted by Num in California', viz: 'table' }; function topLevelTabs() { cy.getBySel('dashboard-component-tabs') .first() .find('[data-test="nav-list"] .ant-tabs-nav-list > .ant-tabs-tab') .as('top-level-tabs'); } function resetTabs() { topLevelTabs(); cy.get('@top-level-tabs').first().click(); waitForChartLoad(FILTER_BOX); waitForChartLoad(TREEMAP); waitForChartLoad(BIG_NUMBER); waitForChartLoad(TABLE); } describe('Dashboard tabs', () => { before(() => { cy.visit(TABBED_DASHBOARD); }); beforeEach(() => { resetTabs(); }); it('should switch tabs', () => { topLevelTabs(); cy.get('@top-level-tabs') .first() .click() .should('have.class', 'ant-tabs-tab-active'); cy.get('@top-level-tabs') .last() .should('not.have.class', 'ant-tabs-tab-active'); cy.getBySel('grid-container').find('.box_plot').should('not.exist'); cy.getBySel('grid-container').find('.line').should('not.exist'); cy.get('@top-level-tabs') .last() .click() .should('have.class', 'ant-tabs-tab-active'); cy.get('@top-level-tabs') .first() .should('not.have.class', 'ant-tabs-tab-active'); waitForChartLoad(BOX_PLOT); cy.getBySel('grid-container').find('.box_plot').should('be.visible'); resetTabs(); // click row level tab, see 1 more chart cy.getBySel('dashboard-component-tabs') .eq(2) .find('[data-test="nav-list"] .ant-tabs-nav-list > .ant-tabs-tab') .as('row-level-tabs'); cy.get('@row-level-tabs').last().click(); waitForChartLoad(LINE_CHART); cy.getBySel('grid-container').find('.line').should('be.visible'); cy.get('@row-level-tabs').first().click(); }); it.skip('should send new queries when tab becomes visible', () => { // landing in first tab waitForChartLoad(FILTER_BOX); waitForChartLoad(TREEMAP); getChartAliasBySpec(TREEMAP).then(treemapAlias => { // apply filter cy.get('.Select__control').first().should('be.visible').click(); cy.get('.Select__control input[type=text]').first().focus().type('South'); cy.get('.Select__option').contains('South Asia').click(); cy.get('.filter_box button:not(:disabled)').contains('Apply').click(); // send new query from same tab cy.wait(treemapAlias).then(({ request }) => { const requestBody = parsePostForm(request.body); const requestParams = JSON.parse(requestBody.form_data as string); expect(requestParams.extra_filters[0]).deep.eq({ col: 'region', op: 'IN', val: ['South Asia'], }); }); }); cy.intercept('/superset/explore_json/?*').as('legacyChartData'); // click row level tab, send 1 more query cy.get('.ant-tabs-tab').contains('row tab 2').click(); cy.wait('@legacyChartData').then(({ request }) => { const requestBody = parsePostForm(request.body); const requestParams = JSON.parse(requestBody.form_data as string); expect(requestParams.extra_filters[0]).deep.eq({ col: 'region', op: 'IN', val: ['South Asia'], }); expect(requestParams.viz_type).eq(LINE_CHART.viz); }); cy.intercept('POST', '/api/v1/chart/data?*').as('v1ChartData'); // click top level tab, send 1 more query cy.get('.ant-tabs-tab').contains('Tab B').click(); cy.wait('@v1ChartData').then(({ request }) => { expect(request.body.queries[0].filters[0]).deep.eq({ col: 'region', op: 'IN', val: ['South Asia'], }); }); getChartAliasBySpec(BOX_PLOT).then(boxPlotAlias => { // navigate to filter and clear filter cy.get('.ant-tabs-tab').contains('Tab A').click(); cy.get('.ant-tabs-tab').contains('row tab 1').click(); cy.get('.Select__clear-indicator').click(); cy.get('.filter_box button:not(:disabled)').contains('Apply').click(); // trigger 1 new query waitForChartLoad(TREEMAP); // make sure query API not requested multiple times cy.on('fail', err => { expect(err.message).to.include('timed out waiting'); return false; }); cy.wait(boxPlotAlias, { timeout: 1000 }).then(() => { throw new Error('Unexpected API call.'); }); }); }); it('should update size when switch tab', () => { cy.get('@top-level-tabs') .last() .click() .should('have.class', 'ant-tabs-tab-active'); expandFilterOnLeftPanel(); cy.wait(1000); cy.get('@top-level-tabs') .first() .click() .should('have.class', 'ant-tabs-tab-active'); cy.wait(1000); cy.get("[data-test-viz-type='treemap_v2'] .chart-container").then( $chartContainer => { expect($chartContainer.get(0).scrollWidth).eq( $chartContainer.get(0).offsetWidth, ); }, ); }); });
5,067
0
petrpan-code/apache/superset/superset-frontend/cypress-base/cypress/e2e
petrpan-code/apache/superset/superset-frontend/cypress-base/cypress/e2e/dashboard_list/dashboardlist.applitools.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 { DASHBOARD_LIST } from 'cypress/utils/urls'; describe('dashboard list view', () => { beforeEach(() => { cy.visit(DASHBOARD_LIST); }); afterEach(() => { cy.eyesClose(); }); it('should load the Dashboards list', () => { cy.get('[aria-label="list-view"]').click(); cy.eyesOpen({ testName: 'Dashboards list-view', }); cy.eyesCheckWindow('Dashboards list-view loaded'); }); it('should load the Dashboards card list', () => { cy.get('[aria-label="card-view"]').click(); cy.eyesOpen({ testName: 'Dashboards card-view', }); cy.eyesCheckWindow('Dashboards card-view loaded'); }); });
5,068
0
petrpan-code/apache/superset/superset-frontend/cypress-base/cypress/e2e
petrpan-code/apache/superset/superset-frontend/cypress-base/cypress/e2e/dashboard_list/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 { DASHBOARD_LIST } from 'cypress/utils/urls'; import { setGridMode, clearAllInputs } from 'cypress/utils'; import { setFilter } from '../dashboard/utils'; describe('Dashboards filters', () => { before(() => { cy.visit(DASHBOARD_LIST); setGridMode('card'); }); beforeEach(() => { clearAllInputs(); }); it('should allow filtering by "Owner" correctly', () => { setFilter('Owner', 'alpha user'); setFilter('Owner', 'admin user'); }); it('should allow filtering by "Created by" correctly', () => { setFilter('Created by', 'alpha user'); setFilter('Created by', 'admin user'); }); it('should allow filtering by "Status" correctly', () => { setFilter('Status', 'Published'); setFilter('Status', 'Draft'); }); });
5,069
0
petrpan-code/apache/superset/superset-frontend/cypress-base/cypress/e2e
petrpan-code/apache/superset/superset-frontend/cypress-base/cypress/e2e/dashboard_list/list.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 { DASHBOARD_LIST } from 'cypress/utils/urls'; import { setGridMode, toggleBulkSelect } from 'cypress/utils'; import { setFilter, interceptBulkDelete, interceptUpdate, interceptDelete, interceptFav, interceptUnfav, } from '../dashboard/utils'; function orderAlphabetical() { setFilter('Sort', 'Alphabetical'); } function openProperties() { cy.get('[aria-label="more-vert"]').first().click(); cy.getBySel('dashboard-card-option-edit-button').click(); } function openMenu() { cy.get('[aria-label="more-vert"]').first().click(); } function confirmDelete() { cy.getBySel('delete-modal-input').type('DELETE'); cy.getBySel('modal-confirm-button').click(); } describe('Dashboards list', () => { describe('list mode', () => { before(() => { cy.visit(DASHBOARD_LIST); setGridMode('list'); }); it('should load rows in list mode', () => { cy.getBySel('listview-table').should('be.visible'); cy.getBySel('sort-header').eq(1).contains('Title'); cy.getBySel('sort-header').eq(2).contains('Modified by'); cy.getBySel('sort-header').eq(3).contains('Status'); cy.getBySel('sort-header').eq(4).contains('Modified'); cy.getBySel('sort-header').eq(5).contains('Created by'); cy.getBySel('sort-header').eq(6).contains('Owners'); cy.getBySel('sort-header').eq(7).contains('Actions'); }); it('should sort correctly in list mode', () => { cy.getBySel('sort-header').eq(1).click(); cy.getBySel('table-row').first().contains('Supported Charts Dashboard'); cy.getBySel('sort-header').eq(1).click(); cy.getBySel('table-row').first().contains("World Bank's Data"); cy.getBySel('sort-header').eq(1).click(); }); it('should bulk select in list mode', () => { toggleBulkSelect(); cy.get('#header-toggle-all').click(); cy.get('[aria-label="checkbox-on"]').should('have.length', 6); cy.getBySel('bulk-select-copy').contains('5 Selected'); cy.getBySel('bulk-select-action') .should('have.length', 2) .then($btns => { expect($btns).to.contain('Delete'); expect($btns).to.contain('Export'); }); cy.getBySel('bulk-select-deselect-all').click(); cy.get('[aria-label="checkbox-on"]').should('have.length', 0); cy.getBySel('bulk-select-copy').contains('0 Selected'); cy.getBySel('bulk-select-action').should('not.exist'); }); }); describe('card mode', () => { before(() => { cy.visit(DASHBOARD_LIST); setGridMode('card'); }); it('should load rows in card mode', () => { cy.getBySel('listview-table').should('not.exist'); cy.getBySel('styled-card').should('have.length', 5); }); it('should bulk select in card mode', () => { toggleBulkSelect(); cy.getBySel('styled-card').click({ multiple: true }); cy.getBySel('bulk-select-copy').contains('5 Selected'); cy.getBySel('bulk-select-action') .should('have.length', 2) .then($btns => { expect($btns).to.contain('Delete'); expect($btns).to.contain('Export'); }); cy.getBySel('bulk-select-deselect-all').click(); cy.getBySel('bulk-select-copy').contains('0 Selected'); cy.getBySel('bulk-select-action').should('not.exist'); }); it('should sort in card mode', () => { orderAlphabetical(); cy.getBySel('styled-card').first().contains('Supported Charts Dashboard'); }); }); describe('common actions', () => { beforeEach(() => { cy.createSampleDashboards([0, 1, 2, 3]); cy.visit(DASHBOARD_LIST); }); it('should allow to favorite/unfavorite dashboard', () => { interceptFav(); interceptUnfav(); setGridMode('card'); orderAlphabetical(); cy.getBySel('styled-card').first().contains('1 - Sample dashboard'); cy.getBySel('styled-card') .first() .find("[aria-label='favorite-unselected']") .click(); cy.wait('@select'); cy.getBySel('styled-card') .first() .find("[aria-label='favorite-selected']") .click(); cy.wait('@unselect'); cy.getBySel('styled-card') .first() .find("[aria-label='favorite-selected']") .should('not.exist'); }); it('should bulk delete correctly', () => { interceptBulkDelete(); toggleBulkSelect(); // bulk deletes in card-view setGridMode('card'); orderAlphabetical(); cy.getBySel('styled-card').eq(0).contains('1 - Sample dashboard').click(); cy.getBySel('styled-card').eq(1).contains('2 - Sample dashboard').click(); cy.getBySel('bulk-select-action').eq(0).contains('Delete').click(); confirmDelete(); cy.wait('@bulkDelete'); cy.getBySel('styled-card') .eq(0) .should('not.contain', '1 - Sample dashboard'); cy.getBySel('styled-card') .eq(1) .should('not.contain', '2 - Sample dashboard'); // bulk deletes in list-view setGridMode('list'); cy.getBySel('table-row').eq(0).contains('3 - Sample dashboard'); cy.getBySel('table-row').eq(1).contains('4 - Sample dashboard'); cy.get('[data-test="table-row"] input[type="checkbox"]').eq(0).click(); cy.get('[data-test="table-row"] input[type="checkbox"]').eq(1).click(); cy.getBySel('bulk-select-action').eq(0).contains('Delete').click(); confirmDelete(); cy.wait('@bulkDelete'); cy.getBySel('table-row') .eq(0) .should('not.contain', '3 - Sample dashboard'); cy.getBySel('table-row') .eq(1) .should('not.contain', '4 - Sample dashboard'); }); it('should delete correctly', () => { interceptDelete(); // deletes in card-view setGridMode('card'); orderAlphabetical(); cy.getBySel('styled-card').eq(0).contains('1 - Sample dashboard'); openMenu(); cy.getBySel('dashboard-card-option-delete-button').click(); confirmDelete(); cy.wait('@delete'); cy.getBySel('styled-card') .eq(0) .should('not.contain', '1 - Sample dashboard'); // deletes in list-view setGridMode('list'); cy.getBySel('table-row').eq(0).contains('2 - Sample dashboard'); cy.getBySel('dashboard-list-trash-icon').eq(0).click(); confirmDelete(); cy.wait('@delete'); cy.getBySel('table-row') .eq(0) .should('not.contain', '2 - Sample dashboard'); }); it('should edit correctly', () => { interceptUpdate(); // edits in card-view setGridMode('card'); orderAlphabetical(); cy.getBySel('styled-card').eq(0).contains('1 - Sample dashboard'); // change title openProperties(); cy.getBySel('dashboard-title-input').type(' | EDITED'); cy.get('button:contains("Save")').click(); cy.wait('@update'); cy.getBySel('styled-card') .eq(0) .contains('1 - Sample dashboard | EDITED'); // edits in list-view setGridMode('list'); cy.getBySel('edit-alt').eq(0).click(); cy.getBySel('dashboard-title-input').clear().type('1 - Sample dashboard'); cy.get('button:contains("Save")').click(); cy.wait('@update'); cy.getBySel('table-row').eq(0).contains('1 - Sample dashboard'); }); }); });
5,070
0
petrpan-code/apache/superset/superset-frontend/cypress-base/cypress/e2e
petrpan-code/apache/superset/superset-frontend/cypress-base/cypress/e2e/database/modal.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 { DATABASE_LIST } from 'cypress/utils/urls'; function closeModal() { cy.get('body').then($body => { if ($body.find('[data-test="database-modal"]').length) { cy.get('[aria-label="Close"]').eq(1).click(); } }); } describe('Add database', () => { before(() => { cy.visit(DATABASE_LIST); }); beforeEach(() => { closeModal(); cy.getBySel('btn-create-database').click(); }); it('should open dynamic form', () => { // click postgres dynamic form cy.get('.preferred > :nth-child(1)').click(); // make sure all the fields are rendering cy.get('input[name="host"]').should('have.value', ''); cy.get('input[name="port"]').should('have.value', ''); cy.get('input[name="database"]').should('have.value', ''); cy.get('input[name="password"]').should('have.value', ''); cy.get('input[name="database_name"]').should('have.value', ''); }); it('should open sqlalchemy form', () => { // click postgres dynamic form cy.get('.preferred > :nth-child(1)').click(); cy.getBySel('sqla-connect-btn').click(); // check if the sqlalchemy form is showing up cy.getBySel('database-name-input').should('be.visible'); cy.getBySel('sqlalchemy-uri-input').should('be.visible'); }); it('show error alerts on dynamic form for bad host', () => { // click postgres dynamic form cy.get('.preferred > :nth-child(1)').click(); cy.get('input[name="host"]').focus().type('badhost', { force: true }); cy.get('input[name="port"]').focus().type('5432', { force: true }); cy.get('.ant-form-item-explain-error').contains( "The hostname provided can't be resolved", ); }); it('show error alerts on dynamic form for bad port', () => { // click postgres dynamic form cy.get('.preferred > :nth-child(1)').click(); cy.get('input[name="host"]').focus().type('localhost', { force: true }); cy.get('input[name="port"]').focus().type('123', { force: true }); cy.get('input[name="database"]').focus(); cy.get('.ant-form-item-explain-error').contains('The port is closed'); }); });
5,071
0
petrpan-code/apache/superset/superset-frontend/cypress-base/cypress/e2e
petrpan-code/apache/superset/superset-frontend/cypress-base/cypress/e2e/dataset/dataset_list.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 { DATASET_LIST_PATH } from 'cypress/utils/urls'; describe('Dataset list', () => { before(() => { cy.visit(DATASET_LIST_PATH); }); xit('should open Explore on dataset name click', () => { cy.intercept('**/api/v1/explore/**').as('explore'); cy.get('[data-test="listview-table"] [data-test="internal-link"]') .contains('birth_names') .click(); cy.wait('@explore'); cy.get('[data-test="datasource-control"] .title-select').contains( 'birth_names', ); cy.get('.metric-option-label').first().contains('COUNT(*)'); cy.get('.column-option-label').first().contains('ds'); cy.get('[data-test="fast-viz-switcher"] > div:not([role="button"]') .contains('Table') .should('be.visible'); }); });
5,072
0
petrpan-code/apache/superset/superset-frontend/cypress-base/cypress/e2e
petrpan-code/apache/superset/superset-frontend/cypress-base/cypress/e2e/explore/AdhocMetrics.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. */ describe('AdhocMetrics', () => { beforeEach(() => { cy.intercept('POST', '/superset/explore_json/**').as('postJson'); cy.intercept('GET', '/superset/explore_json/**').as('getJson'); cy.visitChartByName('Num Births Trend'); cy.verifySliceSuccess({ waitAlias: '@postJson' }); }); it('Clear metric and set simple adhoc metric', () => { const metric = 'sum(num_girls)'; const metricName = 'Sum Girls'; cy.get('[data-test=metrics]') .find('[data-test="remove-control-button"]') .click(); cy.get('[data-test=metrics]') .contains('Drop columns/metrics here or click') .click(); // Title edit for saved metrics is disabled - switch to Simple cy.get('[id="adhoc-metric-edit-tabs-tab-SIMPLE"]').click(); cy.get('[data-test="AdhocMetricEditTitle#trigger"]').click(); cy.get('[data-test="AdhocMetricEditTitle#input"]').type(metricName); cy.get('input[aria-label="Select column"]') .click() .type('num_girls{enter}'); cy.get('input[aria-label="Select aggregate options"]') .click() .type('sum{enter}'); cy.get('[data-test="AdhocMetricEdit#save"]').contains('Save').click(); cy.get('[data-test="control-label"]').contains(metricName); cy.get('button[data-test="run-query-button"]').click(); cy.verifySliceSuccess({ waitAlias: '@postJson', querySubstring: `${metric} AS "${metricName}"`, // SQL statement chartSelector: 'svg', }); }); xit('Switch from simple to custom sql', () => { cy.get('[data-test=metrics]') .find('[data-test="metric-option"]') .should('have.length', 1); // select column "num" cy.get('[data-test=metrics]').find('.Select__clear-indicator').click(); cy.get('[data-test=metrics]').find('.Select__control').click(); cy.get('[data-test=metrics]').find('.Select__control input').type('num'); cy.get('[data-test=metrics]') .find('.option-label') .first() .should('have.text', 'num') .click(); // add custom SQL cy.get('#adhoc-metric-edit-tabs-tab-SQL').click(); cy.get('[data-test=metrics-edit-popover]').within(() => { cy.get('.ace_content').click(); cy.get('.ace_text-input').type('/COUNT(DISTINCT name)', { force: true }); cy.get('[data-test="AdhocMetricEdit#save"]').contains('Save').click(); }); cy.get('button[data-test="run-query-button"]').click(); const metric = 'SUM(num)/COUNT(DISTINCT name)'; cy.verifySliceSuccess({ waitAlias: '@postJson', querySubstring: `${metric} AS "${metric}"`, chartSelector: 'svg', }); }); xit('Switch from custom sql tabs to simple', () => { cy.get('[data-test=metrics]').within(() => { cy.get('.Select__dropdown-indicator').click(); cy.get('input[type=text]').type('num_girls{enter}'); }); cy.get('[data-test=metrics]') .find('[data-test="metric-option"]') .should('have.length', 2); cy.get('#metrics-edit-popover').within(() => { cy.get('#adhoc-metric-edit-tabs-tab-SQL').click(); cy.get('.ace_identifier').contains('num_girls'); cy.get('.ace_content').click(); cy.get('.ace_text-input').type('{selectall}{backspace}SUM(num)'); cy.get('#adhoc-metric-edit-tabs-tab-SIMPLE').click(); cy.get('.Select__single-value').contains(/^num$/); cy.get('button').contains('Save').click(); }); cy.get('button[data-test="run-query-button"]').click(); const metric = 'SUM(num)'; cy.verifySliceSuccess({ waitAlias: '@postJson', querySubstring: `${metric} AS "${metric}"`, chartSelector: 'svg', }); }); });
5,073
0
petrpan-code/apache/superset/superset-frontend/cypress-base/cypress/e2e
petrpan-code/apache/superset/superset-frontend/cypress-base/cypress/e2e/explore/_skip.AdhocFilters.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. */ describe.skip('AdhocFilters', () => { beforeEach(() => { cy.intercept('GET', '/api/v1/datasource/table/*/column/name/values').as( 'filterValues', ); cy.intercept('POST', '/superset/explore_json/**').as('postJson'); cy.intercept('GET', '/superset/explore_json/**').as('getJson'); cy.visitChartByName('Boys'); // a table chart cy.verifySliceSuccess({ waitAlias: '@postJson' }); }); let numScripts = 0; it('Should load AceEditor scripts when needed', () => { cy.get('script').then(nodes => { numScripts = nodes.length; }); cy.get('[data-test=adhoc_filters]').within(() => { cy.get('.Select__control').scrollIntoView().click(); cy.get('input[type=text]').focus().type('name{enter}'); cy.get("div[role='button']").first().click(); }); // antd tabs do lazy loading, so we need to click on tab with ace editor cy.get('#filter-edit-popover').within(() => { cy.get('.ant-tabs-tab').contains('Custom SQL').click(); cy.get('.ant-tabs-tab').contains('Simple').click(); }); cy.get('script').then(nodes => { // should load new script chunks for SQL editor expect(nodes.length).to.greaterThan(numScripts); }); }); it('Set simple adhoc filter', () => { cy.get('[aria-label="Comparator option"] .Select__control').click(); cy.get('[data-test=adhoc-filter-simple-value] input[type=text]') .focus() .type('Jack{enter}', { delay: 20 }); cy.get('[data-test="adhoc-filter-edit-popover-save-button"]').click(); cy.get( '[data-test=adhoc_filters] .Select__control span.option-label', ).contains('name = Jack'); cy.get('button[data-test="run-query-button"]').click(); cy.verifySliceSuccess({ waitAlias: '@postJson', chartSelector: 'svg', }); }); it('Set custom adhoc filter', () => { const filterType = 'name'; const filterContent = "'Amy' OR name = 'Donald'"; cy.get('[data-test=adhoc_filters] .Select__control') .scrollIntoView() .click(); // remove previous input cy.get('[data-test=adhoc_filters] input[type=text]') .focus() .type('{backspace}'); cy.get('[data-test=adhoc_filters] input[type=text]') .focus() .type(`${filterType}{enter}`); cy.wait('@filterValues'); // selecting a new filter should auto-open the popup, // so the tabshould be visible by now cy.get('#filter-edit-popover #adhoc-filter-edit-tabs-tab-SQL').click(); cy.get('#filter-edit-popover .ace_content').click(); cy.get('#filter-edit-popover .ace_text-input').type(filterContent); cy.get('[data-test="adhoc-filter-edit-popover-save-button"]').click(); // check if the filter was saved correctly cy.get( '[data-test=adhoc_filters] .Select__control span.option-label', ).contains(`${filterType} = ${filterContent}`); cy.get('button[data-test="run-query-button"]').click(); cy.verifySliceSuccess({ waitAlias: '@postJson', chartSelector: 'svg', }); }); });
5,074
0
petrpan-code/apache/superset/superset-frontend/cypress-base/cypress/e2e
petrpan-code/apache/superset/superset-frontend/cypress-base/cypress/e2e/explore/advanced_analytics.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. */ describe('Advanced analytics', () => { beforeEach(() => { cy.intercept('POST', '/superset/explore_json/**').as('postJson'); cy.intercept('GET', '/superset/explore_json/**').as('getJson'); cy.intercept('PUT', '/api/v1/explore/**').as('putExplore'); cy.intercept('GET', '/explore/**').as('getExplore'); }); it('Create custom time compare', () => { cy.visitChartByName('Num Births Trend'); cy.verifySliceSuccess({ waitAlias: '@postJson' }); cy.get('.ant-collapse-header') .contains('Advanced Analytics') .click({ force: true }); cy.get('[data-test=time_compare]').find('.ant-select').click(); cy.get('[data-test=time_compare]') .find('input[type=search]') .type('28 days{enter}'); cy.get('[data-test=time_compare]') .find('input[type=search]') .clear() .type('1 year{enter}'); cy.get('button[data-test="run-query-button"]').click(); cy.wait('@postJson'); cy.wait('@putExplore'); cy.reload(); cy.verifySliceSuccess({ waitAlias: '@postJson', chartSelector: 'svg', }); cy.wait('@getExplore'); cy.get('.ant-collapse-header') .contains('Advanced Analytics') .click({ force: true }); cy.get('[data-test=time_compare]') .find('.ant-select-selector') .contains('28 days'); cy.get('[data-test=time_compare]') .find('.ant-select-selector') .contains('1 year'); }); });
5,075
0
petrpan-code/apache/superset/superset-frontend/cypress-base/cypress/e2e
petrpan-code/apache/superset/superset-frontend/cypress-base/cypress/e2e/explore/annotations.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. */ describe('Annotations', () => { beforeEach(() => { cy.intercept('POST', '/superset/explore_json/**').as('postJson'); cy.intercept('GET', '/superset/explore_json/**').as('getJson'); }); it('Create formula annotation y-axis goal line', () => { cy.visitChartByName('Num Births Trend'); cy.verifySliceSuccess({ waitAlias: '@postJson' }); const layerLabel = 'Goal line'; cy.get('[data-test=annotation_layers]').click(); cy.get('[data-test="popover-content"]').within(() => { cy.get('[aria-label=Name]').type(layerLabel); cy.get('[aria-label=Formula]').type('y=1400000'); cy.get('button').contains('OK').click(); }); cy.get('button[data-test="run-query-button"]').click(); cy.get('[data-test=annotation_layers]').contains(layerLabel); cy.verifySliceSuccess({ waitAlias: '@postJson', chartSelector: 'svg', }); cy.get('.nv-legend-text').should('have.length', 2); }); });
5,077
0
petrpan-code/apache/superset/superset-frontend/cypress-base/cypress/e2e
petrpan-code/apache/superset/superset-frontend/cypress-base/cypress/e2e/explore/control.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. */ // *********************************************** // Tests for setting controls in the UI // *********************************************** import { interceptChart } from 'cypress/utils'; import { FORM_DATA_DEFAULTS, NUM_METRIC } from './visualizations/shared.helper'; describe('Datasource control', () => { const newMetricName = `abc${Date.now()}`; it('should allow edit dataset', () => { interceptChart({ legacy: true }).as('chartData'); cy.visitChartByName('Num Births Trend'); cy.verifySliceSuccess({ waitAlias: '@chartData' }); cy.get('[data-test="datasource-menu-trigger"]').click(); cy.get('[data-test="edit-dataset"]').click(); cy.get('[data-test="edit-dataset-tabs"]').within(() => { cy.contains('Metrics').click(); }); // create new metric cy.get('[data-test="crud-add-table-item"]', { timeout: 10000 }).click(); cy.wait(1000); cy.get( '[data-test="table-content-rows"] [data-test="editable-title-input"]', ) .first() .click(); cy.get( '[data-test="table-content-rows"] [data-test="editable-title-input"]', ) .first() .focus() .clear() .type(`${newMetricName}{enter}`); cy.get('[data-test="datasource-modal-save"]').click(); cy.get('.ant-modal-confirm-btns button').contains('OK').click(); // select new metric cy.get('[data-test=metrics]') .contains('Drop columns/metrics here or click') .click(); cy.get('input[aria-label="Select saved metrics"]').type( `${newMetricName}{enter}`, ); // delete metric cy.get('[data-test="datasource-menu-trigger"]').click(); cy.get('[data-test="edit-dataset"]').click(); cy.get('.ant-modal-content').within(() => { cy.get('[data-test="collection-tab-Metrics"]') .contains('Metrics') .click(); }); cy.get(`input[value="${newMetricName}"]`) .closest('tr') .find('[data-test="crud-delete-icon"]') .click(); cy.get('[data-test="datasource-modal-save"]').click(); cy.get('.ant-modal-confirm-btns button').contains('OK').click(); cy.get('[data-test="metrics"]').contains(newMetricName).should('not.exist'); }); }); describe('Color scheme control', () => { beforeEach(() => { interceptChart({ legacy: true }).as('chartData'); cy.visitChartByName('Num Births Trend'); cy.verifySliceSuccess({ waitAlias: '@chartData' }); }); it('should show color options with and without tooltips', () => { cy.get('#controlSections-tab-display').click(); cy.get('.ant-select-selection-item .color-scheme-label').contains( 'Superset Colors', ); cy.get('.ant-select-selection-item .color-scheme-label').trigger( 'mouseover', ); cy.get('.color-scheme-tooltip').contains('Superset Colors'); cy.get('.Control[data-test="color_scheme"]').scrollIntoView(); cy.get('.Control[data-test="color_scheme"] input[type="search"]') .focus() .type('lyftColors{enter}'); cy.get( '.Control[data-test="color_scheme"] .ant-select-selection-item [data-test="lyftColors"]', ).should('exist'); cy.get('.ant-select-selection-item .color-scheme-label').trigger( 'mouseover', ); cy.get('.color-scheme-tooltip').should('not.exist'); }); }); describe('VizType control', () => { beforeEach(() => { interceptChart({ legacy: false }).as('tableChartData'); interceptChart({ legacy: true }).as('lineChartData'); }); it('Can change vizType', () => { cy.visitChartByName('Daily Totals'); cy.verifySliceSuccess({ waitAlias: '@tableChartData' }); cy.contains('View all charts').click(); cy.get('.ant-modal-content').within(() => { cy.get('button').contains('Evolution').click(); // change categories cy.get('[role="button"]').contains('Line Chart').click(); cy.get('button').contains('Select').click(); }); cy.get('button[data-test="run-query-button"]').click(); cy.verifySliceSuccess({ waitAlias: '@lineChartData', chartSelector: 'svg', }); }); }); describe('Test datatable', () => { beforeEach(() => { interceptChart({ legacy: false }).as('tableChartData'); interceptChart({ legacy: true }).as('lineChartData'); cy.visitChartByName('Daily Totals'); }); it('Data Pane opens and loads results', () => { cy.contains('Results').click(); cy.get('[data-test="row-count-label"]').contains('26 rows'); cy.get('.ant-empty-description').should('not.exist'); }); it('Datapane loads view samples', () => { cy.intercept( 'datasource/samples?force=false&datasource_type=table&datasource_id=*', ).as('Samples'); cy.contains('Samples') .click() .then(() => { cy.wait('@Samples'); cy.get('.ant-tabs-tab-active').contains('Samples'); cy.get('[data-test="row-count-label"]').contains('1k rows'); cy.get('.ant-empty-description').should('not.exist'); }); }); }); describe('Time range filter', () => { beforeEach(() => { interceptChart({ legacy: true }).as('chartData'); }); it('Advanced time_range params', () => { const formData = { ...FORM_DATA_DEFAULTS, viz_type: 'line', time_range: '100 years ago : now', metrics: [NUM_METRIC], }; cy.visitChartByParams(formData); cy.verifySliceSuccess({ waitAlias: '@chartData' }); cy.get('[data-test=time-range-trigger]') .click() .then(() => { cy.get('.footer').find('button').its('length').should('eq', 2); cy.get('.ant-popover-content').within(() => { cy.get('input[value="100 years ago"]'); cy.get('input[value="now"]'); }); cy.get('[data-test=cancel-button]').click(); cy.wait(500); cy.get('.ant-popover').should('not.exist'); }); }); it('Common time_range params', () => { const formData = { ...FORM_DATA_DEFAULTS, viz_type: 'line', metrics: [NUM_METRIC], time_range: 'Last year', }; cy.visitChartByParams(formData); cy.verifySliceSuccess({ waitAlias: '@chartData' }); cy.get('[data-test=time-range-trigger]') .click() .then(() => { cy.get('.ant-radio-group').children().its('length').should('eq', 5); cy.get('.ant-radio-checked + span').contains('last year'); cy.get('[data-test=cancel-button]').click(); }); }); it('Previous time_range params', () => { const formData = { ...FORM_DATA_DEFAULTS, viz_type: 'line', metrics: [NUM_METRIC], time_range: 'previous calendar month', }; cy.visitChartByParams(formData); cy.verifySliceSuccess({ waitAlias: '@chartData' }); cy.get('[data-test=time-range-trigger]') .click() .then(() => { cy.get('.ant-radio-group').children().its('length').should('eq', 3); cy.get('.ant-radio-checked + span').contains('previous calendar month'); cy.get('[data-test=cancel-button]').click(); }); }); it('Custom time_range params', () => { const formData = { ...FORM_DATA_DEFAULTS, viz_type: 'line', metrics: [NUM_METRIC], time_range: 'DATEADD(DATETIME("today"), -7, day) : today', }; cy.visitChartByParams(formData); cy.verifySliceSuccess({ waitAlias: '@chartData' }); cy.get('[data-test=time-range-trigger]') .click() .then(() => { cy.get('[data-test=custom-frame]').then(() => { cy.get('.ant-input-number-input-wrap > input') .invoke('attr', 'value') .should('eq', '7'); }); cy.get('[data-test=cancel-button]').click(); }); }); it('No filter time_range params', () => { const formData = { ...FORM_DATA_DEFAULTS, viz_type: 'line', metrics: [NUM_METRIC], time_range: 'No filter', }; cy.visitChartByParams(formData); cy.verifySliceSuccess({ waitAlias: '@chartData' }); cy.get('[data-test=time-range-trigger]') .click() .then(() => { cy.get('[data-test=no-filter]'); }); cy.get('[data-test=cancel-button]').click(); }); }); describe('Groupby control', () => { it('Set groupby', () => { interceptChart({ legacy: true }).as('chartData'); cy.visitChartByName('Num Births Trend'); cy.verifySliceSuccess({ waitAlias: '@chartData' }); cy.get('[data-test=groupby]') .contains('Drop columns here or click') .click(); cy.get('[id="adhoc-metric-edit-tabs-tab-simple"]').click(); cy.get('input[aria-label="Column"]').click().type('state{enter}'); cy.get('[data-test="ColumnEdit#save"]').contains('Save').click(); cy.get('button[data-test="run-query-button"]').click(); cy.verifySliceSuccess({ waitAlias: '@chartData', chartSelector: 'svg' }); }); });
5,078
0
petrpan-code/apache/superset/superset-frontend/cypress-base/cypress/e2e
petrpan-code/apache/superset/superset-frontend/cypress-base/cypress/e2e/explore/explore.applitools.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 { FORM_DATA_DEFAULTS, NUM_METRIC } from './visualizations/shared.helper'; describe('explore view', () => { beforeEach(() => { cy.intercept('POST', '/superset/explore_json/**').as('getJson'); }); afterEach(() => { cy.eyesClose(); }); it('should load Explore', () => { const LINE_CHART_DEFAULTS = { ...FORM_DATA_DEFAULTS, viz_type: 'line' }; const formData = { ...LINE_CHART_DEFAULTS, metrics: [NUM_METRIC] }; cy.visitChartByParams(formData); cy.verifySliceSuccess({ waitAlias: '@getJson', chartSelector: 'svg' }); cy.eyesOpen({ testName: 'Explore page', }); cy.eyesCheckWindow('Explore loaded'); }); });
5,080
0
petrpan-code/apache/superset/superset-frontend/cypress-base/cypress/e2e
petrpan-code/apache/superset/superset-frontend/cypress-base/cypress/e2e/explore/link.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. */ // *********************************************** // Tests for links in the explore UI // *********************************************** import rison from 'rison'; import shortid from 'shortid'; import { interceptChart } from 'cypress/utils'; import { HEALTH_POP_FORM_DATA_DEFAULTS } from './visualizations/shared.helper'; const apiURL = (endpoint: string, queryObject: Record<string, unknown>) => `${endpoint}?q=${rison.encode(queryObject)}`; describe('Test explore links', () => { beforeEach(() => { interceptChart({ legacy: true }).as('chartData'); }); it('Open and close view query modal', () => { cy.visitChartByName('Growth Rate'); cy.verifySliceSuccess({ waitAlias: '@chartData' }); cy.get('[aria-label="Menu actions trigger"]').click(); cy.get('span').contains('View query').parent().click(); cy.wait('@chartData').then(() => { cy.get('code'); }); cy.get('.ant-modal-content').within(() => { cy.get('button.ant-modal-close').first().click({ force: true }); }); }); it('Test iframe link', () => { cy.visitChartByName('Growth Rate'); cy.verifySliceSuccess({ waitAlias: '@chartData' }); cy.get('[aria-label="Menu actions trigger"]').click(); cy.get('div[title="Share"]').trigger('mouseover'); // need to use [id= syntax, otherwise error gets triggered because of special character in id cy.get('[id="share_submenu$Menu"]').within(() => { cy.contains('Embed code').parent().click(); }); cy.get('#embed-code-popover').within(() => { cy.get('textarea[name=embedCode]').contains('iframe'); }); }); it('Test chart save as AND overwrite', () => { interceptChart({ legacy: false }).as('tableChartData'); const formData = { ...HEALTH_POP_FORM_DATA_DEFAULTS, viz_type: 'table', metrics: ['sum__SP_POP_TOTL'], groupby: ['country_name'], }; const newChartName = `Test chart [${shortid.generate()}]`; cy.visitChartByParams(formData); cy.verifySliceSuccess({ waitAlias: '@tableChartData' }); cy.url().then(() => { cy.get('[data-test="query-save-button"]').click(); cy.get('[data-test="saveas-radio"]').check(); cy.get('[data-test="new-chart-name"]').type(newChartName); cy.get('[data-test="btn-modal-save"]').click(); cy.verifySliceSuccess({ waitAlias: '@tableChartData' }); cy.visitChartByName(newChartName); // Overwriting! cy.get('[data-test="query-save-button"]').click(); cy.get('[data-test="save-overwrite-radio"]').check(); cy.get('[data-test="btn-modal-save"]').click(); cy.verifySliceSuccess({ waitAlias: '@tableChartData' }); const query = { filters: [ { col: 'slice_name', opr: 'eq', value: newChartName, }, ], }; cy.request(apiURL('/api/v1/chart/', query)).then(response => { expect(response.body.count).equals(1); }); cy.deleteChartByName(newChartName, true); }); }); it('Test chart save as and add to new dashboard', () => { const chartName = 'Growth Rate'; const newChartName = `${chartName} [${shortid.generate()}]`; const dashboardTitle = `Test dashboard [${shortid.generate()}]`; cy.visitChartByName(chartName); cy.verifySliceSuccess({ waitAlias: '@chartData' }); cy.get('[data-test="query-save-button"]').click(); cy.get('[data-test="saveas-radio"]').check(); cy.get('[data-test="new-chart-name"]').click().clear().type(newChartName); // Add a new option using the "CreatableSelect" feature cy.get('[data-test="save-chart-modal-select-dashboard-form"]') .find('input[aria-label="Select a dashboard"]') .type(`${dashboardTitle}`, { force: true }); cy.get(`.ant-select-item[label="${dashboardTitle}"]`).click({ force: true, }); cy.get('[data-test="btn-modal-save"]').click(); cy.verifySliceSuccess({ waitAlias: '@chartData' }); let query = { filters: [ { col: 'dashboard_title', opr: 'eq', value: dashboardTitle, }, ], }; cy.request(apiURL('/api/v1/dashboard/', query)).then(response => { expect(response.body.count).equals(1); }); cy.visitChartByName(newChartName); cy.verifySliceSuccess({ waitAlias: '@chartData' }); cy.get('[data-test="query-save-button"]').click(); cy.get('[data-test="save-overwrite-radio"]').check(); cy.get('[data-test="new-chart-name"]').click().clear().type(newChartName); // This time around, typing the same dashboard name // will select the existing one cy.get('[data-test="save-chart-modal-select-dashboard-form"]') .find('input[aria-label="Select a dashboard"]') .type(`${dashboardTitle}{enter}`, { force: true }); cy.get(`.ant-select-item[label="${dashboardTitle}"]`).click({ force: true, }); cy.get('[data-test="btn-modal-save"]').click(); cy.verifySliceSuccess({ waitAlias: '@chartData' }); query = { filters: [ { col: 'slice_name', opr: 'eq', value: chartName, }, ], }; cy.request(apiURL('/api/v1/chart/', query)).then(response => { expect(response.body.count).equals(1); }); query = { filters: [ { col: 'dashboard_title', opr: 'eq', value: dashboardTitle, }, ], }; cy.request(apiURL('/api/v1/dashboard/', query)).then(response => { expect(response.body.count).equals(1); }); cy.deleteDashboardByName(dashboardTitle, true); }); });
5,091
0
petrpan-code/apache/superset/superset-frontend/cypress-base/cypress/e2e/explore
petrpan-code/apache/superset/superset-frontend/cypress-base/cypress/e2e/explore/visualizations/graph.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. */ type adhocFilter = { expressionType: string; subject: string; operator: string; comparator: string; clause: string; sqlExpression: string | null; filterOptionName: string; }; describe('Visualization > Graph', () => { beforeEach(() => { cy.intercept('POST', '/api/v1/chart/data*').as('getJson'); }); const GRAPH_FORM_DATA = { datasource: '1__table', viz_type: 'graph_chart', slice_id: 55, granularity_sqla: 'ds', time_grain_sqla: 'P1D', time_range: '100 years ago : now', metric: 'sum__value', adhoc_filters: [], source: 'source', target: 'target', row_limit: 50000, show_legend: true, color_scheme: 'bnbColors', }; function verify(formData: { [name: string]: string | boolean | number | Array<adhocFilter>; }): void { cy.visitChartByParams(formData); cy.verifySliceSuccess({ waitAlias: '@getJson' }); } it('should work with ad-hoc metric', () => { verify(GRAPH_FORM_DATA); cy.get('.chart-container .graph_chart canvas').should('have.length', 1); }); it('should work with simple filter', () => { verify({ ...GRAPH_FORM_DATA, adhoc_filters: [ { expressionType: 'SIMPLE', subject: 'source', operator: '==', comparator: 'Agriculture', clause: 'WHERE', sqlExpression: null, filterOptionName: 'filter_tqx1en70hh_7nksse7nqic', }, ], }); cy.get('.chart-container .graph_chart canvas').should('have.length', 1); }); it('should allow type to search color schemes', () => { verify(GRAPH_FORM_DATA); cy.get('#controlSections-tab-display').click(); cy.get('.Control[data-test="color_scheme"]').scrollIntoView(); cy.get('.Control[data-test="color_scheme"] input[type="search"]') .focus() .type('bnbColors{enter}'); cy.get( '.Control[data-test="color_scheme"] .ant-select-selection-item [data-test="bnbColors"]', ).should('exist'); }); });
5,092
0
petrpan-code/apache/superset/superset-frontend/cypress-base/cypress/e2e/explore
petrpan-code/apache/superset/superset-frontend/cypress-base/cypress/e2e/explore/visualizations/histogram.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 { QueryFormData } from '@superset-ui/core'; describe('Visualization > Histogram', () => { beforeEach(() => { cy.intercept('POST', '/superset/explore_json/**').as('getJson'); }); const HISTOGRAM_FORM_DATA: QueryFormData = { datasource: '3__table', viz_type: 'histogram', slice_id: 60, granularity_sqla: 'ds', time_grain_sqla: 'P1D', time_range: '100 years ago : now', all_columns_x: ['num'], adhoc_filters: [], row_limit: 50000, groupby: [], color_scheme: 'bnbColors', link_length: 5, // number of bins x_axis_label: 'Frequency', y_axis_label: 'Num', global_opacity: 1, normalized: false, }; function verify(formData: QueryFormData) { cy.visitChartByParams(formData); cy.verifySliceSuccess({ waitAlias: '@getJson', chartSelector: 'svg' }); } it('should work without groupby', () => { verify(HISTOGRAM_FORM_DATA); cy.get('.chart-container svg .vx-bar').should( 'have.length', HISTOGRAM_FORM_DATA.link_length, ); }); it('should work with group by', () => { verify({ ...HISTOGRAM_FORM_DATA, groupby: ['gender'], }); cy.get('.chart-container svg .vx-bar').should( 'have.length', HISTOGRAM_FORM_DATA.link_length * 2, ); }); it('should work with filter and update num bins', () => { const numBins = 2; verify({ ...HISTOGRAM_FORM_DATA, link_length: numBins, adhoc_filters: [ { expressionType: 'SIMPLE', clause: 'WHERE', subject: 'state', operator: '==', comparator: 'CA', }, ], }); cy.get('.chart-container svg .vx-bar').should('have.length', numBins); }); it('should allow type to search color schemes and apply the scheme', () => { verify(HISTOGRAM_FORM_DATA); cy.get('#controlSections-tab-display').click(); cy.get('.Control[data-test="color_scheme"]').scrollIntoView(); cy.get('.Control[data-test="color_scheme"] input[type="search"]') .focus() .type('supersetColors{enter}'); cy.get( '.Control[data-test="color_scheme"] .ant-select-selection-item [data-test="supersetColors"]', ).should('exist'); cy.get('.histogram .vx-legend .vx-legend-shape div') .first() .should('have.css', 'background') .and('contains', 'rgb(31, 168, 201)'); }); });
5,093
0
petrpan-code/apache/superset/superset-frontend/cypress-base/cypress/e2e/explore
petrpan-code/apache/superset/superset-frontend/cypress-base/cypress/e2e/explore/visualizations/line.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 { FORM_DATA_DEFAULTS, NUM_METRIC, SIMPLE_FILTER } from './shared.helper'; describe('Visualization > Line', () => { beforeEach(() => { cy.intercept('POST', '/superset/explore_json/**').as('getJson'); }); const LINE_CHART_DEFAULTS = { ...FORM_DATA_DEFAULTS, viz_type: 'line' }; it('should show validator error when no metric', () => { const formData = { ...LINE_CHART_DEFAULTS, metrics: [] }; cy.visitChartByParams(formData); cy.get('.panel-body').contains( `Add required control values to preview chart`, ); }); it('should not show validator error when metric added', () => { const formData = { ...LINE_CHART_DEFAULTS, metrics: [] }; cy.visitChartByParams(formData); cy.get('.panel-body').contains( `Add required control values to preview chart`, ); cy.get('[data-test="metrics-header"]').contains('Metrics'); cy.get('[data-test="metrics-header"] [data-test="error-tooltip"]').should( 'exist', ); cy.get('[data-test=metrics]') .contains('Drop columns/metrics here or click') .click(); // Title edit for saved metrics is disabled - switch to Simple cy.get('[id="adhoc-metric-edit-tabs-tab-SIMPLE"]').click(); cy.get('input[aria-label="Select column"]').click().type('num{enter}'); cy.get('input[aria-label="Select aggregate options"]') .click() .type('sum{enter}'); cy.get('[data-test="AdhocMetricEdit#save"]').contains('Save').click(); cy.get('[data-test="metrics-header"]').contains('Metrics'); cy.get('[data-test="metrics-header"] [data-test="error-tooltip"]').should( 'not.exist', ); cy.get('.ant-alert-warning').should('not.exist'); }); it('should allow negative values in Y bounds', () => { const formData = { ...LINE_CHART_DEFAULTS, metrics: [NUM_METRIC] }; cy.visitChartByParams(formData); cy.get('#controlSections-tab-display').click(); cy.get('span').contains('Y Axis Bounds').scrollIntoView(); cy.get('input[placeholder="Min"]').type('-0.1', { delay: 100 }); cy.get('.ant-alert-warning').should('not.exist'); }); it('should allow type to search color schemes and apply the scheme', () => { cy.get('#controlSections-tab-display').click(); cy.get('.Control[data-test="color_scheme"]').scrollIntoView(); cy.get('.Control[data-test="color_scheme"] input[type="search"]') .focus() .type('bnbColors{enter}'); cy.get( '.Control[data-test="color_scheme"] .ant-select-selection-item [data-test="bnbColors"]', ).should('exist'); cy.get('.line .nv-legend .nv-legend-symbol') .first() .should('have.css', 'fill', 'rgb(41, 105, 107)'); }); it('should work with adhoc metric', () => { const formData = { ...LINE_CHART_DEFAULTS, metrics: [NUM_METRIC] }; cy.visitChartByParams(formData); cy.verifySliceSuccess({ waitAlias: '@getJson', chartSelector: 'svg' }); }); it('should work with groupby', () => { const metrics = ['count']; const groupby = ['gender']; const formData = { ...LINE_CHART_DEFAULTS, metrics, groupby }; cy.visitChartByParams(formData); cy.verifySliceSuccess({ waitAlias: '@getJson', chartSelector: 'svg' }); }); it('should work with simple filter', () => { const metrics = ['count']; const filters = [SIMPLE_FILTER]; const formData = { ...LINE_CHART_DEFAULTS, metrics, adhoc_filters: filters, }; cy.visitChartByParams(formData); cy.verifySliceSuccess({ waitAlias: '@getJson', chartSelector: 'svg' }); }); it('should work with series limit sort asc', () => { const formData = { ...LINE_CHART_DEFAULTS, metrics: [NUM_METRIC], limit: 10, groupby: ['name'], timeseries_limit_metric: NUM_METRIC, }; cy.visitChartByParams(formData); cy.verifySliceSuccess({ waitAlias: '@getJson', chartSelector: 'svg' }); }); it('should work with series limit sort desc', () => { const formData = { ...LINE_CHART_DEFAULTS, metrics: [NUM_METRIC], limit: 10, groupby: ['name'], timeseries_limit_metric: NUM_METRIC, order_desc: true, }; cy.visitChartByParams(formData); cy.verifySliceSuccess({ waitAlias: '@getJson', chartSelector: 'svg' }); }); it('should work with rolling avg', () => { const metrics = [NUM_METRIC]; const formData = { ...LINE_CHART_DEFAULTS, metrics, rolling_type: 'mean', rolling_periods: 10, }; cy.visitChartByParams(formData); cy.verifySliceSuccess({ waitAlias: '@getJson', chartSelector: 'svg' }); }); it('should work with time shift 1 year', () => { const metrics = [NUM_METRIC]; const formData = { ...LINE_CHART_DEFAULTS, metrics, time_compare: ['1 year'], comparison_type: 'values', groupby: ['gender'], }; cy.visitChartByParams(formData); cy.verifySliceSuccess({ waitAlias: '@getJson', chartSelector: 'svg' }); // Offset color should match original line color cy.get('.nv-legend-text') .contains('boy') .siblings() .first() .should('have.attr', 'style') .then(style => { cy.get('.nv-legend-text') .contains('boy, 1 year offset') .siblings() .first() .should('have.attr', 'style') .and('eq', style); }); cy.get('.nv-legend-text') .contains('girl') .siblings() .first() .should('have.attr', 'style') .then(style => { cy.get('.nv-legend-text') .contains('girl, 1 year offset') .siblings() .first() .should('have.attr', 'style') .and('eq', style); }); }); it('should work with time shift yoy', () => { const metrics = [NUM_METRIC]; const formData = { ...LINE_CHART_DEFAULTS, metrics, time_compare: ['1 year'], comparison_type: 'ratio', }; cy.visitChartByParams(formData); cy.verifySliceSuccess({ waitAlias: '@getJson', chartSelector: 'svg' }); }); it('should work with time shift percentage change', () => { const metrics = [NUM_METRIC]; const formData = { ...LINE_CHART_DEFAULTS, metrics, time_compare: ['1 year'], comparison_type: 'percentage', }; cy.visitChartByParams(formData); cy.verifySliceSuccess({ waitAlias: '@getJson', chartSelector: 'svg' }); }); it('Test verbose name shows up in legend', () => { const formData = { ...LINE_CHART_DEFAULTS, metrics: ['count'], }; cy.visitChartByParams(formData); cy.verifySliceSuccess({ waitAlias: '@getJson', chartSelector: 'svg' }); cy.get('text.nv-legend-text').contains('COUNT(*)'); }); it('Test hidden annotation', () => { const formData = { ...LINE_CHART_DEFAULTS, metrics: ['count'], annotation_layers: [ { name: 'Goal line', annotationType: 'FORMULA', sourceType: '', value: 'y=140000', overrides: { time_range: null }, show: false, showLabel: false, titleColumn: '', descriptionColumns: [], timeColumn: '', intervalEndColumn: '', color: null, opacity: '', style: 'solid', width: 1, showMarkers: false, hideLine: false, }, ], }; cy.visitChartByParams(formData); cy.verifySliceSuccess({ waitAlias: '@getJson', chartSelector: 'svg' }); cy.get('.slice_container').within(() => { // Goal line annotation doesn't show up in legend cy.get('.nv-legend-text').should('have.length', 1); }); }); it('Test event annotation time override', () => { cy.request('/chart/api/read?_flt_3_slice_name=Daily+Totals').then( response => { const value = response.body.pks[0]; const formData = { ...LINE_CHART_DEFAULTS, metrics: ['count'], annotation_layers: [ { name: 'Yearly date', annotationType: 'EVENT', sourceType: 'table', value, overrides: { time_range: null }, show: true, showLabel: false, titleColumn: 'ds', descriptionColumns: ['ds'], timeColumn: 'ds', color: null, opacity: '', style: 'solid', width: 1, showMarkers: false, hideLine: false, }, ], }; cy.visitChartByParams(formData); }, ); cy.verifySliceSuccess({ waitAlias: '@getJson', chartSelector: 'svg' }); cy.get('.slice_container').within(() => { cy.get('.nv-event-annotation-layer-0') .children() .should('have.length', 44); }); }); });
5,099
0
petrpan-code/apache/superset/superset-frontend/cypress-base/cypress/e2e/explore
petrpan-code/apache/superset/superset-frontend/cypress-base/cypress/e2e/explore/visualizations/table.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 { interceptChart } from 'cypress/utils'; import { FORM_DATA_DEFAULTS, NUM_METRIC, MAX_DS, MAX_STATE, SIMPLE_FILTER, } from './shared.helper'; // Table describe('Visualization > Table', () => { beforeEach(() => { interceptChart({ legacy: false }).as('chartData'); }); const VIZ_DEFAULTS = { ...FORM_DATA_DEFAULTS, viz_type: 'table', row_limit: 1000, }; const PERCENT_METRIC = { expressionType: 'SQL', sqlExpression: 'CAST(SUM(num_girls) AS FLOAT)/SUM(num)', column: null, aggregate: null, hasCustomLabel: true, label: 'Girls', optionName: 'metric_6qwzgc8bh2v_zox7hil1mzs', }; it('Use default time column', () => { cy.visitChartByParams({ ...VIZ_DEFAULTS, granularity_sqla: undefined, metrics: ['count'], }); cy.get('[data-test=adhoc_filters]').contains('ds'); }); it('Format non-numeric metrics correctly', () => { cy.visitChartByParams({ ...VIZ_DEFAULTS, include_time: true, granularity_sqla: 'ds', time_grain_sqla: 'P3M', metrics: [NUM_METRIC, MAX_DS, MAX_STATE], }); // when format with smart_date, time column use format by granularity cy.get('.chart-container td:nth-child(1)').contains('2008 Q1'); // other column with timestamp use adaptive formatting cy.get('.chart-container td:nth-child(3)').contains('2008'); cy.get('.chart-container td:nth-child(4)').contains('TX'); }); it('Format with table_timestamp_format', () => { cy.visitChartByParams({ ...VIZ_DEFAULTS, include_time: true, granularity_sqla: 'ds', time_grain_sqla: 'P3M', table_timestamp_format: '%Y-%m-%d %H:%M', metrics: [NUM_METRIC, MAX_DS, MAX_STATE], }); // time column and MAX(ds) metric column both use UTC time cy.get('.chart-container td:nth-child(1)').contains('2008-01-01 00:00'); cy.get('.chart-container td:nth-child(3)').contains('2008-01-01 00:00'); cy.get('.chart-container td') .contains('2008-01-01 08:00') .should('not.exist'); // time column should not use time granularity when timestamp format is set cy.get('.chart-container td').contains('2008 Q1').should('not.exist'); // other num numeric metric column should stay as string cy.get('.chart-container td').contains('TX'); }); it('Test table with groupby', () => { cy.visitChartByParams({ ...VIZ_DEFAULTS, metrics: [NUM_METRIC, MAX_DS], groupby: ['name'], }); cy.verifySliceSuccess({ waitAlias: '@chartData', querySubstring: /group by.*name/i, chartSelector: 'table', }); }); it('Test table with groupby + time column', () => { cy.visitChartByParams({ ...VIZ_DEFAULTS, include_time: true, granularity_sqla: 'ds', time_grain_sqla: 'P3M', metrics: [NUM_METRIC, MAX_DS], groupby: ['name'], }); cy.wait('@chartData').then(({ response }) => { cy.verifySliceContainer('table'); const records = response?.body.result[0].data; // should sort by first metric when no sort by metric is set expect(records[0][NUM_METRIC.label]).greaterThan( records[1][NUM_METRIC.label], ); }); // should handle frontend sorting correctly cy.get('.chart-container th').contains('name').click(); cy.get('.chart-container td:nth-child(2):eq(0)').contains('Adam'); cy.get('.chart-container th').contains('ds').click().click(); cy.get('.chart-container td:nth-child(1):eq(0)').contains('2008'); }); it('Test table with percent metrics and groupby', () => { cy.visitChartByParams({ ...VIZ_DEFAULTS, percent_metrics: PERCENT_METRIC, metrics: [], groupby: ['name'], }); cy.verifySliceSuccess({ waitAlias: '@chartData', chartSelector: 'table' }); }); it('Test table with groupby order desc', () => { cy.visitChartByParams({ ...VIZ_DEFAULTS, metrics: NUM_METRIC, groupby: ['name'], order_desc: true, }); cy.verifySliceSuccess({ waitAlias: '@chartData', chartSelector: 'table' }); }); it('Test table with groupby + order by + no metric', () => { cy.visitChartByParams({ ...VIZ_DEFAULTS, metrics: [], groupby: ['name'], timeseries_limit_metric: NUM_METRIC, order_desc: true, }); // should contain only the group by column cy.get('.chart-container th').its('length').should('eq', 1); // should order correctly cy.get('.chart-container td:eq(0)').contains('Michael'); cy.verifySliceSuccess({ waitAlias: '@chartData', chartSelector: 'table' }); }); it('Test table with groupby and limit', () => { const limit = 10; const formData = { ...VIZ_DEFAULTS, metrics: NUM_METRIC, groupby: ['name'], row_limit: limit, }; cy.visitChartByParams(formData); cy.wait('@chartData').then(({ response }) => { cy.verifySliceContainer('table'); expect(response?.body.result[0].data.length).to.eq(limit); }); cy.get('[data-test="row-count-label"]').contains('10 rows'); }); it('Test table with columns and row limit', () => { cy.visitChartByParams({ ...VIZ_DEFAULTS, // should still work when query_mode is not-set/invalid query_mode: undefined, all_columns: ['state'], metrics: [], row_limit: 100, }); // should display in raw records mode cy.get('div[data-test="query_mode"] .btn.active').contains('Raw records'); cy.get('div[data-test="all_columns"]').should('be.visible'); cy.get('div[data-test="groupby"]').should('not.exist'); cy.verifySliceSuccess({ waitAlias: '@chartData', chartSelector: 'table' }); cy.get('[data-test="row-count-label"]').contains('100 rows'); // should allow switch back to aggregate mode cy.get('div[data-test="query_mode"] .btn').contains('Aggregate').click(); cy.get('div[data-test="query_mode"] .btn.active').contains('Aggregate'); cy.get('div[data-test="all_columns"]').should('not.exist'); cy.get('div[data-test="groupby"]').should('be.visible'); }); it('Test table with columns, ordering, and row limit', () => { const limit = 10; const formData = { ...VIZ_DEFAULTS, query_mode: 'raw', all_columns: ['name', 'state', 'ds', 'num'], metrics: [], row_limit: limit, order_by_cols: ['["num", false]'], }; cy.visitChartByParams(formData); cy.wait('@chartData').then(({ response }) => { cy.verifySliceContainer('table'); const records = response?.body.result[0].data; expect(records[0].num).greaterThan(records[records.length - 1].num); }); }); it('Test table with simple filter', () => { const metrics = ['count']; const filters = [SIMPLE_FILTER]; const formData = { ...VIZ_DEFAULTS, metrics, adhoc_filters: filters }; cy.visitChartByParams(formData); cy.verifySliceSuccess({ waitAlias: '@chartData', chartSelector: 'table' }); }); it('Tests table number formatting with % in metric name', () => { const formData = { ...VIZ_DEFAULTS, percent_metrics: PERCENT_METRIC, groupby: ['state'], }; cy.visitChartByParams(formData); cy.verifySliceSuccess({ waitAlias: '@chartData', querySubstring: /group by.*state/i, chartSelector: 'table', }); cy.get('td').contains(/\d*%/); }); });
5,103
0
petrpan-code/apache/superset/superset-frontend/cypress-base/cypress/e2e
petrpan-code/apache/superset/superset-frontend/cypress-base/cypress/e2e/sqllab/query.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 shortid from 'shortid'; import { selectResultsTab, assertSQLLabResultsAreEqual } from './sqllab.helper'; function parseClockStr(node: JQuery) { return Number.parseFloat(node.text().replace(/:/g, '')); } describe('SqlLab query panel', () => { beforeEach(() => { cy.visit('/sqllab'); }); it.skip('supports entering and running a query', () => { // row limit has to be < ~10 for us to be able to determine how many rows // are fetched below (because React _Virtualized_ does not render all rows) let clockTime = 0; cy.intercept({ method: 'POST', url: '/api/v1/sqllab/execute/', }).as('mockSQLResponse'); cy.get('.TableSelector .Select:eq(0)').click(); cy.get('.TableSelector .Select:eq(0) input[type=text]') .focus() .type('{enter}'); cy.get('#brace-editor textarea') .focus() .clear() .type(`{selectall}{backspace}SELECT 1`); cy.get('#js-sql-toolbar button:eq(0)').eq(0).click(); // wait for 300 milliseconds cy.wait(300); // started timer cy.get('.sql-toolbar .label-success').then(node => { clockTime = parseClockStr(node); // should be longer than 0.2s expect(clockTime).greaterThan(0.2); }); cy.wait('@mockSQLResponse'); // timer is increasing cy.get('.sql-toolbar .label-success').then(node => { const newClockTime = parseClockStr(node); expect(newClockTime).greaterThan(0.9); clockTime = newClockTime; }); // rerun the query cy.get('#js-sql-toolbar button:eq(0)').eq(0).click(); // should restart the timer cy.get('.sql-toolbar .label-success').contains('00:00:00'); cy.wait('@mockSQLResponse'); cy.get('.sql-toolbar .label-success').then(node => { expect(parseClockStr(node)).greaterThan(0.9); }); }); it.skip('successfully saves a query', () => { cy.intercept('api/v1/database/**/tables/**').as('getTables'); cy.intercept('savedqueryviewapi/**').as('getSavedQuery'); const query = 'SELECT ds, gender, name, num FROM main.birth_names ORDER BY name LIMIT 3'; const savedQueryTitle = `CYPRESS TEST QUERY ${shortid.generate()}`; // we will assert that the results of the query we save, and the saved query are the same let initialResultsTable: HTMLElement | null = null; let savedQueryResultsTable = null; cy.get('#brace-editor textarea') .clear({ force: true }) .type(`{selectall}{backspace}${query}`, { force: true }) .focus() // focus => blur is required for updating the query that is to be saved .blur(); // ctrl + r also runs query cy.get('#brace-editor textarea').type('{ctrl}r', { force: true }); cy.wait('@sqlLabQuery'); // Save results to check against below selectResultsTab().then(resultsA => { initialResultsTable = resultsA[0]; }); cy.get('#js-sql-toolbar button') .eq(1) // save query .click(); // Enter name + save into modal cy.get('.modal-sm input') .clear({ force: true }) .type(`{selectall}{backspace}${savedQueryTitle}`, { force: true, }); cy.get('.modal-sm .modal-body button') .eq(0) // save .click(); // visit saved queries cy.visit('/sqllab/my_queries/'); // first row contains most recent link, follow back to SqlLab cy.get('table tr:first-child a[href*="savedQueryId"').click(); // will timeout without explicitly waiting here cy.wait(['@getSavedQuery', '@getTables']); // run the saved query cy.get('#js-sql-toolbar button') .eq(0) // run query .click(); cy.wait('@sqlLabQuery'); // assert the results of the saved query match the initial results selectResultsTab().then(resultsB => { savedQueryResultsTable = resultsB[0]; assertSQLLabResultsAreEqual(initialResultsTable, savedQueryResultsTable); }); }); it('Create a chart from a query', () => { cy.intercept('/api/v1/sqllab/execute/').as('queryFinished'); cy.intercept('**/api/v1/explore/**').as('explore'); cy.intercept('**/api/v1/chart/**').as('chart'); // cypress doesn't handle opening a new tab, override window.open to open in the same tab cy.window().then(win => { cy.stub(win, 'open', url => { // eslint-disable-next-line no-param-reassign win.location.href = url; }); }); const query = 'SELECT gender, name FROM birth_names'; cy.get('.ace_text-input') .focus() .clear({ force: true }) .type(`{selectall}{backspace}${query}`, { force: true }); cy.get('.sql-toolbar button').contains('Run').click(); cy.wait('@queryFinished'); cy.get( '.SouthPane .ant-tabs-content > .ant-tabs-tabpane-active > div button:first', { timeout: 10000 }, ).click(); cy.wait('@explore'); cy.get('[data-test="datasource-control"] .title-select').contains(query); cy.get('.column-option-label').first().contains('gender'); cy.get('.column-option-label').last().contains('name'); cy.get( '[data-test="all_columns"] [data-test="dnd-labels-container"] > div:first-child', ).contains('gender'); cy.get( '[data-test="all_columns"] [data-test="dnd-labels-container"] > div:nth-child(2)', ).contains('name'); cy.wait('@chart'); cy.get('[data-test="slice-container"] table > thead th') .first() .contains('gender'); cy.get('[data-test="slice-container"] table > thead th') .last() .contains('name'); }); });
5,104
0
petrpan-code/apache/superset/superset-frontend/cypress-base/cypress/e2e
petrpan-code/apache/superset/superset-frontend/cypress-base/cypress/e2e/sqllab/sqllab.applitools.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. */ describe('SqlLab view', () => { beforeEach(() => { cy.visit('/sqllab'); }); it('should load the SqlLab', () => { cy.eyesOpen({ testName: 'SqlLab page', }); cy.eyesCheckWindow('SqlLab loaded'); cy.eyesClose(); }); });
5,106
0
petrpan-code/apache/superset/superset-frontend/cypress-base/cypress/e2e
petrpan-code/apache/superset/superset-frontend/cypress-base/cypress/e2e/sqllab/tabs.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. */ describe('SqlLab query tabs', () => { beforeEach(() => { cy.visit('/sqllab'); }); const tablistSelector = '[data-test="sql-editor-tabs"] > [role="tablist"]'; const tabSelector = `${tablistSelector} [role="tab"]`; it('allows you to create and close a tab', () => { cy.get(tabSelector).then(tabs => { const initialTabCount = tabs.length; const initialUntitledCount = Math.max( 0, ...tabs .map( (i, tabItem) => Number(tabItem.textContent?.match(/Untitled Query (\d+)/)?.[1]) || 0, ) .toArray(), ); // add two new tabs cy.get('[data-test="add-tab-icon"]:visible:last').click({ force: true }); cy.contains('[role="tab"]', `Untitled Query ${initialUntitledCount + 1}`); cy.get(tabSelector).should('have.length', initialTabCount + 1); cy.get('[data-test="add-tab-icon"]:visible:last').click({ force: true }); cy.contains('[role="tab"]', `Untitled Query ${initialUntitledCount + 2}`); cy.get(tabSelector).should('have.length', initialTabCount + 2); // close the tabs cy.get(`${tabSelector}:last [data-test="dropdown-trigger"]`).click({ force: true, }); cy.get('[data-test="close-tab-menu-option"]').click(); cy.get(tabSelector).should('have.length', initialTabCount + 1); cy.contains('[role="tab"]', `Untitled Query ${initialUntitledCount + 1}`); cy.get(`${tablistSelector} [aria-label="remove"]:last`).click(); cy.get(tabSelector).should('have.length', initialTabCount); }); }); it('opens a new tab by a button and a shortcut', () => { const editorContent = '#ace-editor .ace_content'; const editorInput = '#ace-editor textarea'; const queryLimitSelector = '#js-sql-toolbar .limitDropdown'; cy.get(tabSelector).then(tabs => { const initialTabCount = tabs.length; const initialUntitledCount = Math.max( 0, ...tabs .map( (i, tabItem) => Number(tabItem.textContent?.match(/Untitled Query (\d+)/)?.[1]) || 0, ) .toArray(), ); // configure some editor settings cy.get(editorInput).type('some random query string', { force: true }); cy.get(queryLimitSelector).parent().click({ force: true }); cy.get('.ant-dropdown-menu') .last() .find('.ant-dropdown-menu-item') .first() .click({ force: true }); // open a new tab by a button cy.get('[data-test="add-tab-icon"]:visible:last').click({ force: true }); cy.contains('[role="tab"]', `Untitled Query ${initialUntitledCount + 1}`); cy.get(tabSelector).should('have.length', initialTabCount + 1); cy.get(editorContent).contains('SELECT ...'); cy.get(queryLimitSelector).contains('10'); // close the tab cy.get(`${tabSelector}:last [data-test="dropdown-trigger"]`).click({ force: true, }); cy.get(`${tablistSelector} [aria-label="remove"]:last`).click({ force: true, }); cy.get(tabSelector).should('have.length', initialTabCount); // open a new tab by a shortcut cy.get('body').type('{ctrl}t'); cy.get(tabSelector).should('have.length', initialTabCount + 1); cy.contains('[role="tab"]', `Untitled Query ${initialUntitledCount + 1}`); cy.get(editorContent).contains('SELECT ...'); cy.get(queryLimitSelector).contains('10'); }); }); });
5,215
0
petrpan-code/apache/superset/superset-frontend/packages/superset-ui-chart-controls
petrpan-code/apache/superset/superset-frontend/packages/superset-ui-chart-controls/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 { sections } from '../src'; describe('@superset-ui/chart-controls', () => { it('exports sections', () => { expect(sections).toBeDefined(); expect(sections.datasourceAndVizType).toBeDefined(); }); });
5,216
0
petrpan-code/apache/superset/superset-frontend/packages/superset-ui-chart-controls
petrpan-code/apache/superset/superset-frontend/packages/superset-ui-chart-controls/test/tsconfig.json
{ "compilerOptions": { "composite": false, "emitDeclarationOnly": false, "noEmit": true, "rootDir": "." }, "extends": "../../../tsconfig.json", "include": [ "**/*", "../types/**/*", "../../../types/**/*" ], "references": [ { "path": ".." } ] }
5,217
0
petrpan-code/apache/superset/superset-frontend/packages/superset-ui-chart-controls
petrpan-code/apache/superset/superset-frontend/packages/superset-ui-chart-controls/test/types.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 { AdhocColumn } from '@superset-ui/core'; import { ColumnMeta, ControlPanelSectionConfig, isColumnMeta, isControlPanelSectionConfig, isSavedExpression, } from '../src'; const ADHOC_COLUMN: AdhocColumn = { hasCustomLabel: true, label: 'Adhoc column', sqlExpression: 'case when 1 = 1 then 1 else 2 end', expressionType: 'SQL', }; const COLUMN_META: ColumnMeta = { column_name: 'my_col', }; const SAVED_EXPRESSION: ColumnMeta = { column_name: 'Saved expression', expression: 'case when 1 = 1 then 1 else 2 end', }; const CONTROL_PANEL_SECTION_CONFIG: ControlPanelSectionConfig = { label: 'My Section', description: 'My Description', controlSetRows: [], }; test('isColumnMeta returns false for AdhocColumn', () => { expect(isColumnMeta(ADHOC_COLUMN)).toEqual(false); }); test('isColumnMeta returns true for ColumnMeta', () => { expect(isColumnMeta(COLUMN_META)).toEqual(true); }); test('isSavedExpression returns false for AdhocColumn', () => { expect(isSavedExpression(ADHOC_COLUMN)).toEqual(false); }); test('isSavedExpression returns false for ColumnMeta without expression', () => { expect(isSavedExpression(COLUMN_META)).toEqual(false); }); test('isSavedExpression returns true for ColumnMeta with expression', () => { expect(isSavedExpression(SAVED_EXPRESSION)).toEqual(true); }); test('isControlPanelSectionConfig returns true for section', () => { expect(isControlPanelSectionConfig(CONTROL_PANEL_SECTION_CONFIG)).toEqual( true, ); }); test('isControlPanelSectionConfig returns true for null value', () => { expect(isControlPanelSectionConfig(null)).toEqual(false); });
5,218
0
petrpan-code/apache/superset/superset-frontend/packages/superset-ui-chart-controls/test
petrpan-code/apache/superset/superset-frontend/packages/superset-ui-chart-controls/test/components/ColumnOption.test.tsx
/** * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ import React from 'react'; import { shallow, ShallowWrapper } from 'enzyme'; import { GenericDataType } from '@superset-ui/core'; import { ColumnOption, ColumnOptionProps, ColumnTypeLabel } from '../../src'; import { SQLPopover } from '../../src/components/SQLPopover'; describe('ColumnOption', () => { const defaultProps: ColumnOptionProps = { column: { column_name: 'foo', verbose_name: 'Foo', expression: 'SUM(foo)', description: 'Foo is the greatest column of all', }, showType: false, }; let wrapper: ShallowWrapper; let props: ColumnOptionProps; const factory = (o: ColumnOptionProps) => <ColumnOption {...o} />; beforeEach(() => { wrapper = shallow(factory(defaultProps)); props = { ...defaultProps }; }); it('is a valid element', () => { expect(React.isValidElement(<ColumnOption {...defaultProps} />)).toBe(true); }); it('shows a label with verbose_name', () => { const lbl = wrapper.find('.option-label'); expect(lbl).toHaveLength(1); expect(lbl.first().text()).toBe('Foo'); }); it('shows SQL Popover trigger', () => { expect(wrapper.find(SQLPopover)).toHaveLength(1); }); it('shows a label with column_name when no verbose_name', () => { delete props.column.verbose_name; wrapper = shallow(factory(props)); expect(wrapper.find('.option-label').first().text()).toBe('foo'); }); it('shows a column type label when showType is true', () => { wrapper = shallow( factory({ ...props, showType: true, column: { column_name: 'foo', type: 'VARCHAR', type_generic: GenericDataType.STRING, }, }), ); expect(wrapper.find(ColumnTypeLabel)).toHaveLength(1); }); it('column with expression has correct column label if showType is true', () => { props.showType = true; wrapper = shallow(factory(props)); expect(wrapper.find(ColumnTypeLabel)).toHaveLength(1); expect(wrapper.find(ColumnTypeLabel).props().type).toBe('expression'); }); it('shows no column type label when type is null', () => { wrapper = shallow( factory({ ...props, showType: true, column: { column_name: 'foo', }, }), ); expect(wrapper.find(ColumnTypeLabel)).toHaveLength(0); }); it('dttm column has correct column label if showType is true', () => { props.showType = true; props.column.expression = undefined; props.column.type_generic = GenericDataType.TEMPORAL; wrapper = shallow(factory(props)); expect(wrapper.find(ColumnTypeLabel)).toHaveLength(1); expect(wrapper.find(ColumnTypeLabel).props().type).toBe( GenericDataType.TEMPORAL, ); }); });
5,219
0
petrpan-code/apache/superset/superset-frontend/packages/superset-ui-chart-controls/test
petrpan-code/apache/superset/superset-frontend/packages/superset-ui-chart-controls/test/components/ColumnTypeLabel.test.tsx
/** * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ import React from 'react'; import { render, screen } from '@testing-library/react'; import '@testing-library/jest-dom'; import { GenericDataType } from '@superset-ui/core'; import { ColumnTypeLabel, ColumnTypeLabelProps } from '../../src'; describe('ColumnOption', () => { const defaultProps = { type: GenericDataType.STRING, }; const props = { ...defaultProps }; function renderColumnTypeLabel(overrides: Partial<ColumnTypeLabelProps>) { render(<ColumnTypeLabel {...props} {...overrides} />); } it('is a valid element', () => { expect(React.isValidElement(<ColumnTypeLabel {...defaultProps} />)).toBe( true, ); }); it('string type shows ABC icon', () => { renderColumnTypeLabel({ type: GenericDataType.STRING }); expect(screen.getByLabelText('string type icon')).toBeVisible(); }); it('int type shows # icon', () => { renderColumnTypeLabel({ type: GenericDataType.NUMERIC }); expect(screen.getByLabelText('numeric type icon')).toBeVisible(); }); it('bool type shows 1|0 icon', () => { renderColumnTypeLabel({ type: GenericDataType.BOOLEAN }); expect(screen.getByLabelText('boolean type icon')).toBeVisible(); }); it('expression type shows function icon', () => { renderColumnTypeLabel({ type: 'expression' }); expect(screen.getByLabelText('function type icon')).toBeVisible(); }); it('unknown type shows question mark', () => { renderColumnTypeLabel({ type: undefined }); expect(screen.getByLabelText('unknown type icon')).toBeVisible(); }); it('datetime type displays', () => { renderColumnTypeLabel({ type: GenericDataType.TEMPORAL }); expect(screen.getByLabelText('temporal type icon')).toBeVisible(); }); });
5,220
0
petrpan-code/apache/superset/superset-frontend/packages/superset-ui-chart-controls/test
petrpan-code/apache/superset/superset-frontend/packages/superset-ui-chart-controls/test/components/InfoTooltipWithTrigger.test.tsx
/** * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ import React from 'react'; import { shallow } from 'enzyme'; import { Tooltip } from '../../src/components/Tooltip'; import { InfoTooltipWithTrigger } from '../../src'; describe('InfoTooltipWithTrigger', () => { it('renders a tooltip', () => { const wrapper = shallow( <InfoTooltipWithTrigger label="test" tooltip="this is a test" />, ); expect(wrapper.find(Tooltip)).toHaveLength(1); }); it('renders an info icon', () => { const wrapper = shallow(<InfoTooltipWithTrigger />); expect(wrapper.find('.fa-info-circle')).toHaveLength(1); }); it('responds to keypresses', () => { const clickHandler = jest.fn(); const wrapper = shallow( <InfoTooltipWithTrigger label="test" tooltip="this is a test" onClick={clickHandler} />, ); wrapper.find('.fa-info-circle').simulate('keypress', { key: 'Tab' }); expect(clickHandler).toHaveBeenCalledTimes(0); wrapper.find('.fa-info-circle').simulate('keypress', { key: 'Enter' }); expect(clickHandler).toHaveBeenCalledTimes(1); wrapper.find('.fa-info-circle').simulate('keypress', { key: ' ' }); expect(clickHandler).toHaveBeenCalledTimes(2); }); it('has a bsStyle', () => { const wrapper = shallow(<InfoTooltipWithTrigger bsStyle="something" />); expect(wrapper.find('.text-something')).toHaveLength(1); }); });
5,221
0
petrpan-code/apache/superset/superset-frontend/packages/superset-ui-chart-controls/test
petrpan-code/apache/superset/superset-frontend/packages/superset-ui-chart-controls/test/components/MetricOption.test.tsx
/** * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ import React from 'react'; import { shallow, ShallowWrapper } from 'enzyme'; import { MetricOption, MetricOptionProps } from '../../src'; describe('MetricOption', () => { const defaultProps = { metric: { metric_name: 'foo', verbose_name: 'Foo', expression: 'SUM(foo)', label: 'test', description: 'Foo is the greatest metric of all', warning_text: 'Be careful when using foo', }, openInNewWindow: false, showFormula: true, showType: true, url: '', }; let wrapper: ShallowWrapper; let props: MetricOptionProps; const factory = (o: MetricOptionProps) => <MetricOption {...o} />; beforeEach(() => { wrapper = shallow(factory(defaultProps)); props = { ...defaultProps }; }); it('is a valid element', () => { expect(React.isValidElement(<MetricOption {...defaultProps} />)).toBe(true); }); it('shows a label with verbose_name', () => { const lbl = wrapper.find('.option-label'); expect(lbl).toHaveLength(1); expect(lbl.first().text()).toBe('Foo'); }); it('shows a InfoTooltipWithTrigger', () => { expect(wrapper.find('InfoTooltipWithTrigger')).toHaveLength(1); }); it('shows SQL Popover trigger', () => { expect(wrapper.find('SQLPopover')).toHaveLength(1); }); it('shows a label with metric_name when no verbose_name', () => { props.metric.verbose_name = ''; wrapper = shallow(factory(props)); expect(wrapper.find('.option-label').first().text()).toBe('foo'); }); it('doesnt show InfoTooltipWithTrigger when no warning', () => { props.metric.warning_text = ''; wrapper = shallow(factory(props)); expect(wrapper.find('InfoTooltipWithTrigger')).toHaveLength(0); }); it('sets target="_blank" when openInNewWindow is true', () => { props.url = 'https://github.com/apache/incubator-superset'; wrapper = shallow(factory(props)); expect(wrapper.find('a').prop('target')).toBe(''); props.openInNewWindow = true; wrapper = shallow(factory(props)); expect(wrapper.find('a').prop('target')).toBe('_blank'); }); it('shows a metric type label when showType is true', () => { props.showType = true; wrapper = shallow(factory(props)); expect(wrapper.find('ColumnTypeLabel')).toHaveLength(1); }); it('shows a Tooltip for the verbose metric name', () => { expect(wrapper.find('Tooltip')).toHaveLength(1); }); });
5,222
0
petrpan-code/apache/superset/superset-frontend/packages/superset-ui-chart-controls/test
petrpan-code/apache/superset/superset-frontend/packages/superset-ui-chart-controls/test/components/labelUtils.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, { ReactElement } from 'react'; import { render, screen } from '@testing-library/react'; import '@testing-library/jest-dom'; import { ThemeProvider, supersetTheme } from '@superset-ui/core'; import { getColumnLabelText, getColumnTooltipNode, getMetricTooltipNode, getColumnTypeTooltipNode, } from '../../src/components/labelUtils'; const renderWithTheme = (ui: ReactElement) => render(<ThemeProvider theme={supersetTheme}>{ui}</ThemeProvider>); test("should get column name when column doesn't have verbose_name", () => { expect( getColumnLabelText({ id: 123, column_name: 'column name', verbose_name: '', }), ).toBe('column name'); }); test('should get verbose name when column have verbose_name', () => { expect( getColumnLabelText({ id: 123, column_name: 'column name', verbose_name: 'verbose name', }), ).toBe('verbose name'); }); test('should get null as tooltip', () => { const ref = { current: { scrollWidth: 100, clientWidth: 100 } }; expect( getColumnTooltipNode( { id: 123, column_name: 'column name', verbose_name: '', description: '', }, ref, ), ).toBe(null); }); test('should get null for column datatype tooltip when type is blank', () => { expect( getColumnTypeTooltipNode({ id: 123, column_name: 'column name', verbose_name: '', description: '', type: '', }), ).toBe(null); }); test('should get column datatype rendered as tooltip when column has a type', () => { renderWithTheme( <> {getColumnTypeTooltipNode({ id: 123, column_name: 'column name', verbose_name: 'verbose name', description: 'A very important column', type: 'text', })} </>, ); expect(screen.getByText('Column datatype')).toBeVisible(); expect(screen.getByText('text')).toBeVisible(); }); test('should get column name, verbose name and description when it has a verbose name', () => { const ref = { current: { scrollWidth: 100, clientWidth: 100 } }; renderWithTheme( <> {getColumnTooltipNode( { id: 123, column_name: 'column name', verbose_name: 'verbose name', description: 'A very important column', }, ref, )} </>, ); expect(screen.getByText('Column name')).toBeVisible(); expect(screen.getByText('column name')).toBeVisible(); expect(screen.getByText('Label')).toBeVisible(); expect(screen.getByText('verbose name')).toBeVisible(); expect(screen.getByText('Description')).toBeVisible(); expect(screen.getByText('A very important column')).toBeVisible(); }); test('should get column name as tooltip if it overflowed', () => { const ref = { current: { scrollWidth: 200, clientWidth: 100 } }; renderWithTheme( <> {getColumnTooltipNode( { id: 123, column_name: 'long long long long column name', verbose_name: '', description: '', }, ref, )} </>, ); expect(screen.getByText('Column name')).toBeVisible(); expect(screen.getByText('long long long long column name')).toBeVisible(); expect(screen.queryByText('Label')).not.toBeInTheDocument(); expect(screen.queryByText('Description')).not.toBeInTheDocument(); }); test('should get column name, verbose name and description as tooltip if it overflowed', () => { const ref = { current: { scrollWidth: 200, clientWidth: 100 } }; renderWithTheme( <> {getColumnTooltipNode( { id: 123, column_name: 'long long long long column name', verbose_name: 'long long long long verbose name', description: 'A very important column', }, ref, )} </>, ); expect(screen.getByText('Column name')).toBeVisible(); expect(screen.getByText('long long long long column name')).toBeVisible(); expect(screen.getByText('Label')).toBeVisible(); expect(screen.getByText('long long long long verbose name')).toBeVisible(); expect(screen.getByText('Description')).toBeVisible(); expect(screen.getByText('A very important column')).toBeVisible(); }); test('should get null as tooltip in metric', () => { const ref = { current: { scrollWidth: 100, clientWidth: 100 } }; expect( getMetricTooltipNode( { metric_name: 'count', label: '', verbose_name: '', description: '', }, ref, ), ).toBe(null); }); test('should get metric name, verbose name and description as tooltip in metric', () => { const ref = { current: { scrollWidth: 100, clientWidth: 100 } }; renderWithTheme( <> {getMetricTooltipNode( { metric_name: 'count', label: 'count(*)', verbose_name: 'count(*)', description: 'Count metric', }, ref, )} </>, ); expect(screen.getByText('Metric name')).toBeVisible(); expect(screen.getByText('count')).toBeVisible(); expect(screen.getByText('Label')).toBeVisible(); expect(screen.getByText('count(*)')).toBeVisible(); expect(screen.getByText('Description')).toBeVisible(); expect(screen.getByText('Count metric')).toBeVisible(); }); test('should get metric name as tooltip if it overflowed', () => { const ref = { current: { scrollWidth: 200, clientWidth: 100 } }; renderWithTheme( <> {getMetricTooltipNode( { metric_name: 'long long long long metric name', label: '', verbose_name: '', description: '', }, ref, )} </>, ); expect(screen.getByText('Metric name')).toBeVisible(); expect(screen.getByText('long long long long metric name')).toBeVisible(); expect(screen.queryByText('Label')).not.toBeInTheDocument(); expect(screen.queryByText('Description')).not.toBeInTheDocument(); }); test('should get metric name, verbose name and description in tooltip if it overflowed', () => { const ref = { current: { scrollWidth: 200, clientWidth: 100 } }; renderWithTheme( <> {getMetricTooltipNode( { metric_name: 'count', label: '', verbose_name: 'longlonglonglonglong verbose metric', description: 'Count metric', }, ref, )} </>, ); expect(screen.getByText('Metric name')).toBeVisible(); expect(screen.getByText('count')).toBeVisible(); expect(screen.getByText('Label')).toBeVisible(); expect(screen.getByText('longlonglonglonglong verbose metric')).toBeVisible(); expect(screen.getByText('Description')).toBeVisible(); expect(screen.getByText('Count metric')).toBeVisible(); });
5,223
0
petrpan-code/apache/superset/superset-frontend/packages/superset-ui-chart-controls/test
petrpan-code/apache/superset/superset-frontend/packages/superset-ui-chart-controls/test/operators/boxplotOperator.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 { QueryObject, SqlaFormData } from '@superset-ui/core'; import { boxplotOperator } from '@superset-ui/chart-controls'; const formData: SqlaFormData = { metrics: [ 'count(*)', { label: 'sum(val)', expressionType: 'SQL', sqlExpression: 'sum(val)' }, ], time_range: '2015 : 2016', time_grain_sqla: 'P1Y', datasource: 'foo', viz_type: 'table', }; const queryObject: QueryObject = { metrics: [ 'count(*)', { label: 'sum(val)', expressionType: 'SQL', sqlExpression: 'sum(val)' }, ], time_range: '2015 : 2016', granularity: 'P1Y', }; test('should skip boxplotOperator', () => { expect(boxplotOperator(formData, queryObject)).toEqual(undefined); }); test('should do tukey boxplot', () => { expect( boxplotOperator( { ...formData, whiskerOptions: 'Tukey', }, queryObject, ), ).toEqual({ operation: 'boxplot', options: { whisker_type: 'tukey', percentiles: undefined, groupby: [], metrics: ['count(*)', 'sum(val)'], }, }); }); test('should do min/max boxplot', () => { expect( boxplotOperator( { ...formData, whiskerOptions: 'Min/max (no outliers)', }, queryObject, ), ).toEqual({ operation: 'boxplot', options: { whisker_type: 'min/max', percentiles: undefined, groupby: [], metrics: ['count(*)', 'sum(val)'], }, }); }); test('should do percentile boxplot', () => { expect( boxplotOperator( { ...formData, whiskerOptions: '1/4 percentiles', }, queryObject, ), ).toEqual({ operation: 'boxplot', options: { whisker_type: 'percentile', percentiles: [1, 4], groupby: [], metrics: ['count(*)', 'sum(val)'], }, }); }); test('should throw an error', () => { expect(() => boxplotOperator( { ...formData, whiskerOptions: 'foobar', }, queryObject, ), ).toThrow('Unsupported whisker type: foobar'); });
5,224
0
petrpan-code/apache/superset/superset-frontend/packages/superset-ui-chart-controls/test
petrpan-code/apache/superset/superset-frontend/packages/superset-ui-chart-controls/test/operators/contributionOperator.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 { QueryObject, SqlaFormData } from '@superset-ui/core'; import { contributionOperator } from '@superset-ui/chart-controls'; const formData: SqlaFormData = { metrics: [ 'count(*)', { label: 'sum(val)', expressionType: 'SQL', sqlExpression: 'sum(val)' }, ], time_range: '2015 : 2016', granularity: 'month', datasource: 'foo', viz_type: 'table', }; const queryObject: QueryObject = { metrics: [ 'count(*)', { label: 'sum(val)', expressionType: 'SQL', sqlExpression: 'sum(val)' }, ], time_range: '2015 : 2016', granularity: 'month', }; test('should skip contributionOperator', () => { expect(contributionOperator(formData, queryObject)).toEqual(undefined); }); test('should do contributionOperator', () => { expect( contributionOperator({ ...formData, contributionMode: 'row' }, queryObject), ).toEqual({ operation: 'contribution', options: { orientation: 'row', }, }); });
5,225
0
petrpan-code/apache/superset/superset-frontend/packages/superset-ui-chart-controls/test
petrpan-code/apache/superset/superset-frontend/packages/superset-ui-chart-controls/test/operators/flattenOperator.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 { QueryObject, SqlaFormData } from '@superset-ui/core'; import { flattenOperator } from '@superset-ui/chart-controls'; const formData: SqlaFormData = { metrics: [ 'count(*)', { label: 'sum(val)', expressionType: 'SQL', sqlExpression: 'sum(val)' }, ], time_range: '2015 : 2016', granularity: 'month', datasource: 'foo', viz_type: 'table', }; const queryObject: QueryObject = { metrics: [ 'count(*)', { label: 'sum(val)', expressionType: 'SQL', sqlExpression: 'sum(val)' }, ], time_range: '2015 : 2016', granularity: 'month', post_processing: [ { operation: 'pivot', options: { index: ['__timestamp'], columns: ['nation'], aggregates: { 'count(*)': { operator: 'sum', }, }, }, }, ], }; test('should do flattenOperator', () => { expect(flattenOperator(formData, queryObject)).toEqual({ operation: 'flatten', }); });
5,226
0
petrpan-code/apache/superset/superset-frontend/packages/superset-ui-chart-controls/test
petrpan-code/apache/superset/superset-frontend/packages/superset-ui-chart-controls/test/operators/pivotOperator.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 { QueryObject, SqlaFormData } from '@superset-ui/core'; import { pivotOperator } from '@superset-ui/chart-controls'; const formData: SqlaFormData = { metrics: [ 'count(*)', { label: 'sum(val)', expressionType: 'SQL', sqlExpression: 'sum(val)' }, ], time_range: '2015 : 2016', granularity: 'month', datasource: 'foo', viz_type: 'table', show_empty_columns: true, }; const queryObject: QueryObject = { metrics: [ 'count(*)', { label: 'sum(val)', expressionType: 'SQL', sqlExpression: 'sum(val)' }, ], time_range: '2015 : 2016', granularity: 'month', post_processing: [ { operation: 'pivot', options: { index: ['__timestamp'], columns: ['nation'], aggregates: { 'count(*)': { operator: 'mean', }, }, drop_missing_columns: false, }, }, ], }; test('skip pivot', () => { expect(pivotOperator(formData, queryObject)).toEqual(undefined); expect( pivotOperator(formData, { ...queryObject, metrics: [], }), ).toEqual(undefined); }); test('pivot by __timestamp without columns', () => { expect( pivotOperator( { ...formData, granularity_sqla: 'time_column' }, queryObject, ), ).toEqual({ operation: 'pivot', options: { index: ['__timestamp'], columns: [], aggregates: { 'count(*)': { operator: 'mean' }, 'sum(val)': { operator: 'mean' }, }, drop_missing_columns: false, }, }); }); test('pivot by __timestamp with columns', () => { expect( pivotOperator( { ...formData, granularity_sqla: 'time_column' }, { ...queryObject, columns: ['foo', 'bar'], }, ), ).toEqual({ operation: 'pivot', options: { index: ['__timestamp'], columns: ['foo', 'bar'], aggregates: { 'count(*)': { operator: 'mean' }, 'sum(val)': { operator: 'mean' }, }, drop_missing_columns: false, }, }); }); test('pivot by __timestamp with series_columns', () => { expect( pivotOperator( { ...formData, granularity_sqla: 'time_column' }, { ...queryObject, series_columns: ['foo', 'bar'], }, ), ).toEqual({ operation: 'pivot', options: { index: ['__timestamp'], columns: ['foo', 'bar'], aggregates: { 'count(*)': { operator: 'mean' }, 'sum(val)': { operator: 'mean' }, }, drop_missing_columns: false, }, }); }); test('pivot by x_axis with groupby', () => { expect( pivotOperator( { ...formData, x_axis: 'baz', }, { ...queryObject, series_columns: ['foo', 'bar'], }, ), ).toEqual({ operation: 'pivot', options: { index: ['baz'], columns: ['foo', 'bar'], aggregates: { 'count(*)': { operator: 'mean' }, 'sum(val)': { operator: 'mean' }, }, drop_missing_columns: false, }, }); }); test('pivot by adhoc x_axis', () => { expect( pivotOperator( { ...formData, x_axis: { label: 'my_case_expr', expressionType: 'SQL', sqlExpression: 'case when a = 1 then 1 else 0 end', }, }, { ...queryObject, series_columns: ['foo', 'bar'], }, ), ).toEqual({ operation: 'pivot', options: { index: ['my_case_expr'], columns: ['foo', 'bar'], aggregates: { 'count(*)': { operator: 'mean' }, 'sum(val)': { operator: 'mean' }, }, drop_missing_columns: false, }, }); }); test('pivot by x_axis with extra metrics', () => { expect( pivotOperator( { ...formData, x_axis: 'foo', x_axis_sort: 'bar', groupby: [], timeseries_limit_metric: 'bar', }, { ...queryObject, series_columns: [], }, ), ).toEqual({ operation: 'pivot', options: { index: ['foo'], columns: [], aggregates: { 'count(*)': { operator: 'mean' }, 'sum(val)': { operator: 'mean' }, bar: { operator: 'mean' }, }, drop_missing_columns: false, }, }); });
5,227
0
petrpan-code/apache/superset/superset-frontend/packages/superset-ui-chart-controls/test
petrpan-code/apache/superset/superset-frontend/packages/superset-ui-chart-controls/test/operators/prophetOperator.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 { DTTM_ALIAS, QueryObject, SqlaFormData } from '@superset-ui/core'; import { prophetOperator } from '@superset-ui/chart-controls'; const formData: SqlaFormData = { metrics: [ 'count(*)', { label: 'sum(val)', expressionType: 'SQL', sqlExpression: 'sum(val)' }, ], time_range: '2015 : 2016', time_grain_sqla: 'P1Y', datasource: 'foo', viz_type: 'table', }; const queryObject: QueryObject = { metrics: [ 'count(*)', { label: 'sum(val)', expressionType: 'SQL', sqlExpression: 'sum(val)' }, ], time_range: '2015 : 2016', granularity: 'P1Y', }; test('should skip prophetOperator', () => { expect(prophetOperator(formData, queryObject)).toEqual(undefined); }); test('should do prophetOperator with default index', () => { expect( prophetOperator( { ...formData, granularity_sqla: 'time_column', forecastEnabled: true, forecastPeriods: '3', forecastInterval: '5', forecastSeasonalityYearly: true, forecastSeasonalityWeekly: false, forecastSeasonalityDaily: false, }, queryObject, ), ).toEqual({ operation: 'prophet', options: { time_grain: 'P1Y', periods: 3.0, confidence_interval: 5.0, yearly_seasonality: true, weekly_seasonality: false, daily_seasonality: false, index: DTTM_ALIAS, }, }); }); test('should do prophetOperator over named column', () => { expect( prophetOperator( { ...formData, x_axis: 'ds', forecastEnabled: true, forecastPeriods: '3', forecastInterval: '5', forecastSeasonalityYearly: true, forecastSeasonalityWeekly: false, forecastSeasonalityDaily: false, }, queryObject, ), ).toEqual({ operation: 'prophet', options: { time_grain: 'P1Y', periods: 3.0, confidence_interval: 5.0, yearly_seasonality: true, weekly_seasonality: false, daily_seasonality: false, index: 'ds', }, }); }); test('should do prophetOperator over adhoc column', () => { expect( prophetOperator( { ...formData, x_axis: { label: 'my_case_expr', expressionType: 'SQL', sqlExpression: 'case when a = 1 then 1 else 0 end', }, forecastEnabled: true, forecastPeriods: '3', forecastInterval: '5', forecastSeasonalityYearly: true, forecastSeasonalityWeekly: false, forecastSeasonalityDaily: false, }, queryObject, ), ).toEqual({ operation: 'prophet', options: { time_grain: 'P1Y', periods: 3.0, confidence_interval: 5.0, yearly_seasonality: true, weekly_seasonality: false, daily_seasonality: false, index: 'my_case_expr', }, }); });
5,228
0
petrpan-code/apache/superset/superset-frontend/packages/superset-ui-chart-controls/test
petrpan-code/apache/superset/superset-frontend/packages/superset-ui-chart-controls/test/operators/renameOperator.test.ts
/** * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ import { ComparisonType, QueryObject, SqlaFormData } from '@superset-ui/core'; import { renameOperator } from '@superset-ui/chart-controls'; const formData: SqlaFormData = { x_axis: 'dttm', metrics: ['count(*)'], groupby: ['gender'], time_range: '2015 : 2016', granularity: 'month', datasource: 'foo', viz_type: 'table', truncate_metric: true, }; const queryObject: QueryObject = { is_timeseries: true, metrics: ['count(*)'], columns: ['gender', 'dttm'], time_range: '2015 : 2016', granularity: 'month', post_processing: [], }; test('should skip renameOperator if exists multiple metrics', () => { expect( renameOperator(formData, { ...queryObject, ...{ metrics: ['count(*)', 'sum(sales)'], }, }), ).toEqual(undefined); }); test('should skip renameOperator if series does not exist', () => { expect( renameOperator(formData, { ...queryObject, ...{ columns: [], }, }), ).toEqual(undefined); }); test('should skip renameOperator if does not exist x_axis and is_timeseries', () => { expect( renameOperator( { ...formData, ...{ x_axis: null }, }, { ...queryObject, ...{ is_timeseries: false } }, ), ).toEqual(undefined); }); test('should skip renameOperator if exists derived metrics', () => { [ ComparisonType.Difference, ComparisonType.Ratio, ComparisonType.Percentage, ].forEach(type => { expect( renameOperator( { ...formData, ...{ comparison_type: type, time_compare: ['1 year ago'], }, }, { ...queryObject, ...{ metrics: ['count(*)'], }, }, ), ).toEqual(undefined); }); }); test('should add renameOperator', () => { expect(renameOperator(formData, queryObject)).toEqual({ operation: 'rename', options: { columns: { 'count(*)': null }, inplace: true, level: 0 }, }); }); test('should add renameOperator if x_axis does not exist', () => { expect( renameOperator( { ...formData, ...{ x_axis: null, granularity_sqla: 'time column' }, }, queryObject, ), ).toEqual({ operation: 'rename', options: { columns: { 'count(*)': null }, inplace: true, level: 0 }, }); }); test('should add renameOperator if based on series_columns', () => { expect( renameOperator( { ...formData, ...{ x_axis: null, granularity_sqla: 'time column' }, }, { ...queryObject, columns: [], series_columns: ['gender', 'dttm'], }, ), ).toEqual({ operation: 'rename', options: { columns: { 'count(*)': null }, inplace: true, level: 0 }, }); }); test('should add renameOperator if exist "actual value" time comparison', () => { expect( renameOperator( { ...formData, ...{ comparison_type: ComparisonType.Values, time_compare: ['1 year ago', '1 year later'], }, }, queryObject, ), ).toEqual({ operation: 'rename', options: { columns: { 'count(*)': null, 'count(*)__1 year ago': '1 year ago', 'count(*)__1 year later': '1 year later', }, inplace: true, level: 0, }, }); }); test('should remove renameOperator', () => { expect( renameOperator( { ...formData, truncate_metric: false, }, queryObject, ), ).toEqual(undefined); expect( renameOperator( { ...formData, truncate_metric: undefined, }, queryObject, ), ).toEqual(undefined); });
5,229
0
petrpan-code/apache/superset/superset-frontend/packages/superset-ui-chart-controls/test
petrpan-code/apache/superset/superset-frontend/packages/superset-ui-chart-controls/test/operators/resampleOperator.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 { QueryObject, SqlaFormData } from '@superset-ui/core'; import { resampleOperator } from '@superset-ui/chart-controls'; const formData: SqlaFormData = { metrics: [ 'count(*)', { label: 'sum(val)', expressionType: 'SQL', sqlExpression: 'sum(val)' }, ], time_range: '2015 : 2016', granularity: 'month', datasource: 'foo', viz_type: 'table', }; const queryObject: QueryObject = { metrics: [ 'count(*)', { label: 'sum(val)', expressionType: 'SQL', sqlExpression: 'sum(val)' }, ], time_range: '2015 : 2016', granularity: 'month', post_processing: [ { operation: 'pivot', options: { index: ['__timestamp'], columns: ['nation'], aggregates: { 'count(*)': { operator: 'sum', }, }, }, }, ], }; test('should skip resampleOperator', () => { expect(resampleOperator(formData, queryObject)).toEqual(undefined); expect( resampleOperator({ ...formData, resample_method: 'ffill' }, queryObject), ).toEqual(undefined); expect( resampleOperator({ ...formData, resample_rule: '1D' }, queryObject), ).toEqual(undefined); }); test('should do resample on implicit time column', () => { expect( resampleOperator( { ...formData, resample_method: 'ffill', resample_rule: '1D' }, queryObject, ), ).toEqual({ operation: 'resample', options: { method: 'ffill', rule: '1D', fill_value: null, }, }); }); test('should do resample on x-axis', () => { expect( resampleOperator( { ...formData, x_axis: 'ds', resample_method: 'ffill', resample_rule: '1D', }, queryObject, ), ).toEqual({ operation: 'resample', options: { fill_value: null, method: 'ffill', rule: '1D', }, }); }); test('should do zerofill resample', () => { expect( resampleOperator( { ...formData, resample_method: 'zerofill', resample_rule: '1D' }, queryObject, ), ).toEqual({ operation: 'resample', options: { method: 'asfreq', rule: '1D', fill_value: 0, }, }); });
5,230
0
petrpan-code/apache/superset/superset-frontend/packages/superset-ui-chart-controls/test
petrpan-code/apache/superset/superset-frontend/packages/superset-ui-chart-controls/test/operators/rollingWindowOperator.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 { QueryObject, SqlaFormData } from '@superset-ui/core'; import { rollingWindowOperator } from '@superset-ui/chart-controls'; const formData: SqlaFormData = { metrics: [ 'count(*)', { label: 'sum(val)', expressionType: 'SQL', sqlExpression: 'sum(val)' }, ], time_range: '2015 : 2016', granularity: 'month', datasource: 'foo', viz_type: 'table', }; const queryObject: QueryObject = { metrics: [ 'count(*)', { label: 'sum(val)', expressionType: 'SQL', sqlExpression: 'sum(val)' }, ], time_range: '2015 : 2016', granularity: 'month', post_processing: [ { operation: 'pivot', options: { index: ['__timestamp'], columns: ['nation'], aggregates: { 'count(*)': { operator: 'sum', }, }, }, }, ], }; test('skip transformation', () => { expect(rollingWindowOperator(formData, queryObject)).toEqual(undefined); expect( rollingWindowOperator({ ...formData, rolling_type: 'None' }, queryObject), ).toEqual(undefined); expect( rollingWindowOperator({ ...formData, rolling_type: 'foobar' }, queryObject), ).toEqual(undefined); const formDataWithoutMetrics = { ...formData }; delete formDataWithoutMetrics.metrics; expect(rollingWindowOperator(formDataWithoutMetrics, queryObject)).toEqual( undefined, ); }); test('rolling_type: cumsum', () => { expect( rollingWindowOperator({ ...formData, rolling_type: 'cumsum' }, queryObject), ).toEqual({ operation: 'cum', options: { operator: 'sum', columns: { 'count(*)': 'count(*)', 'sum(val)': 'sum(val)', }, }, }); }); test('rolling_type: sum/mean/std', () => { const rollingTypes = ['sum', 'mean', 'std']; rollingTypes.forEach(rollingType => { expect( rollingWindowOperator( { ...formData, rolling_type: rollingType }, queryObject, ), ).toEqual({ operation: 'rolling', options: { rolling_type: rollingType, window: 1, min_periods: 0, columns: { 'count(*)': 'count(*)', 'sum(val)': 'sum(val)', }, }, }); }); }); test('should append compared metrics when sets time compare type', () => { const comparisonTypes = ['values', 'difference', 'percentage', 'ratio']; comparisonTypes.forEach(cType => { expect( rollingWindowOperator( { ...formData, rolling_type: 'cumsum', comparison_type: cType, time_compare: ['1 year ago', '1 year later'], }, queryObject, ), ).toEqual({ operation: 'cum', options: { operator: 'sum', columns: { 'count(*)': 'count(*)', 'count(*)__1 year ago': 'count(*)__1 year ago', 'count(*)__1 year later': 'count(*)__1 year later', 'sum(val)': 'sum(val)', 'sum(val)__1 year ago': 'sum(val)__1 year ago', 'sum(val)__1 year later': 'sum(val)__1 year later', }, }, }); }); });
5,231
0
petrpan-code/apache/superset/superset-frontend/packages/superset-ui-chart-controls/test
petrpan-code/apache/superset/superset-frontend/packages/superset-ui-chart-controls/test/operators/sortOperator.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 { QueryObject, SqlaFormData } from '@superset-ui/core'; import { sortOperator } from '@superset-ui/chart-controls'; import * as supersetCoreModule from '@superset-ui/core'; const formData: SqlaFormData = { metrics: [ 'count(*)', { label: 'sum(val)', expressionType: 'SQL', sqlExpression: 'sum(val)' }, ], time_range: '2015 : 2016', granularity: 'month', datasource: 'foo', viz_type: 'table', }; const queryObject: QueryObject = { metrics: [ 'count(*)', { label: 'sum(val)', expressionType: 'SQL', sqlExpression: 'sum(val)' }, ], time_range: '2015 : 2016', granularity: 'month', post_processing: [ { operation: 'pivot', options: { index: ['__timestamp'], columns: ['nation'], aggregates: { 'count(*)': { operator: 'sum', }, }, }, }, ], }; test('should ignore the sortOperator', () => { // FF is disabled Object.defineProperty(supersetCoreModule, 'hasGenericChartAxes', { value: false, }); expect(sortOperator(formData, queryObject)).toEqual(undefined); // FF is enabled Object.defineProperty(supersetCoreModule, 'hasGenericChartAxes', { value: true, }); expect( sortOperator( { ...formData, ...{ x_axis_sort: undefined, x_axis_sort_asc: true, }, }, queryObject, ), ).toEqual(undefined); // sortOperator doesn't support multiple series Object.defineProperty(supersetCoreModule, 'hasGenericChartAxes', { value: true, }); expect( sortOperator( { ...formData, ...{ x_axis_sort: 'metric label', x_axis_sort_asc: true, groupby: ['col1'], x_axis: 'axis column', }, }, queryObject, ), ).toEqual(undefined); }); test('should sort by metric', () => { Object.defineProperty(supersetCoreModule, 'hasGenericChartAxes', { value: true, }); expect( sortOperator( { ...formData, ...{ metrics: ['a metric label'], x_axis_sort: 'a metric label', x_axis_sort_asc: true, }, }, queryObject, ), ).toEqual({ operation: 'sort', options: { by: 'a metric label', ascending: true, }, }); }); test('should sort by axis', () => { Object.defineProperty(supersetCoreModule, 'hasGenericChartAxes', { value: true, }); expect( sortOperator( { ...formData, ...{ x_axis_sort: 'Categorical Column', x_axis_sort_asc: true, x_axis: 'Categorical Column', }, }, queryObject, ), ).toEqual({ operation: 'sort', options: { is_sort_index: true, ascending: true, }, }); }); test('should sort by extra metric', () => { Object.defineProperty(supersetCoreModule, 'hasGenericChartAxes', { value: true, }); expect( sortOperator( { ...formData, x_axis_sort: 'my_limit_metric', x_axis_sort_asc: true, x_axis: 'Categorical Column', groupby: [], timeseries_limit_metric: 'my_limit_metric', }, queryObject, ), ).toEqual({ operation: 'sort', options: { by: 'my_limit_metric', ascending: true, }, }); });
5,232
0
petrpan-code/apache/superset/superset-frontend/packages/superset-ui-chart-controls/test
petrpan-code/apache/superset/superset-frontend/packages/superset-ui-chart-controls/test/operators/timeCompareOperator.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 { QueryObject, SqlaFormData } from '@superset-ui/core'; import { timeCompareOperator } from '@superset-ui/chart-controls'; const formData: SqlaFormData = { metrics: [ 'count(*)', { label: 'sum(val)', expressionType: 'SQL', sqlExpression: 'sum(val)' }, ], time_range: '2015 : 2016', granularity: 'month', datasource: 'foo', viz_type: 'table', }; const queryObject: QueryObject = { metrics: [ 'count(*)', { label: 'sum(val)', expressionType: 'SQL', sqlExpression: 'sum(val)' }, ], time_range: '2015 : 2016', granularity: 'month', post_processing: [ { operation: 'pivot', options: { index: ['__timestamp'], columns: ['nation'], aggregates: { 'count(*)': { operator: 'mean', }, 'sum(val)': { operator: 'mean', }, }, drop_missing_columns: false, }, }, { operation: 'aggregation', options: { groupby: ['col1'], aggregates: {}, }, }, ], }; test('should skip CompareOperator', () => { expect(timeCompareOperator(formData, queryObject)).toEqual(undefined); expect( timeCompareOperator({ ...formData, time_compare: [] }, queryObject), ).toEqual(undefined); expect( timeCompareOperator({ ...formData, comparison_type: null }, queryObject), ).toEqual(undefined); expect( timeCompareOperator( { ...formData, comparison_type: 'foobar' }, queryObject, ), ).toEqual(undefined); expect( timeCompareOperator( { ...formData, comparison_type: 'values', time_compare: ['1 year ago', '1 year later'], }, queryObject, ), ).toEqual(undefined); }); test('should generate difference/percentage/ratio CompareOperator', () => { const comparisonTypes = ['difference', 'percentage', 'ratio']; comparisonTypes.forEach(cType => { expect( timeCompareOperator( { ...formData, comparison_type: cType, time_compare: ['1 year ago', '1 year later'], }, queryObject, ), ).toEqual({ operation: 'compare', options: { source_columns: ['count(*)', 'count(*)', 'sum(val)', 'sum(val)'], compare_columns: [ 'count(*)__1 year ago', 'count(*)__1 year later', 'sum(val)__1 year ago', 'sum(val)__1 year later', ], compare_type: cType, drop_original_columns: true, }, }); }); });
5,233
0
petrpan-code/apache/superset/superset-frontend/packages/superset-ui-chart-controls/test
petrpan-code/apache/superset/superset-frontend/packages/superset-ui-chart-controls/test/operators/timeComparePivotOperator.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 { QueryObject, SqlaFormData } from '@superset-ui/core'; import { timeCompareOperator, timeComparePivotOperator, } from '@superset-ui/chart-controls'; const formData: SqlaFormData = { metrics: [ 'count(*)', { label: 'sum(val)', expressionType: 'SQL', sqlExpression: 'sum(val)' }, ], time_range: '2015 : 2016', granularity: 'month', datasource: 'foo', viz_type: 'table', show_empty_columns: true, }; const queryObject: QueryObject = { metrics: [ 'count(*)', { label: 'sum(val)', expressionType: 'SQL', sqlExpression: 'sum(val)' }, ], columns: ['foo', 'bar'], time_range: '2015 : 2016', granularity: 'month', post_processing: [], }; test('should skip pivot', () => { expect(timeComparePivotOperator(formData, queryObject)).toEqual(undefined); expect( timeComparePivotOperator({ ...formData, time_compare: [] }, queryObject), ).toEqual(undefined); expect( timeComparePivotOperator( { ...formData, comparison_type: null }, queryObject, ), ).toEqual(undefined); expect( timeCompareOperator( { ...formData, comparison_type: 'foobar' }, queryObject, ), ).toEqual(undefined); }); test('should pivot on any type of timeCompare', () => { const anyTimeCompareTypes = ['values', 'difference', 'percentage', 'ratio']; anyTimeCompareTypes.forEach(cType => { expect( timeComparePivotOperator( { ...formData, comparison_type: cType, time_compare: ['1 year ago', '1 year later'], granularity_sqla: 'time_column', }, { ...queryObject, }, ), ).toEqual({ operation: 'pivot', options: { aggregates: { 'count(*)': { operator: 'mean' }, 'count(*)__1 year ago': { operator: 'mean' }, 'count(*)__1 year later': { operator: 'mean' }, 'sum(val)': { operator: 'mean' }, 'sum(val)__1 year ago': { operator: 'mean', }, 'sum(val)__1 year later': { operator: 'mean', }, }, drop_missing_columns: false, columns: ['foo', 'bar'], index: ['__timestamp'], }, }); }); }); test('should pivot on x-axis', () => { expect( timeComparePivotOperator( { ...formData, comparison_type: 'values', time_compare: ['1 year ago', '1 year later'], x_axis: 'ds', }, queryObject, ), ).toEqual({ operation: 'pivot', options: { aggregates: { 'count(*)': { operator: 'mean' }, 'count(*)__1 year ago': { operator: 'mean' }, 'count(*)__1 year later': { operator: 'mean' }, 'sum(val)': { operator: 'mean', }, 'sum(val)__1 year ago': { operator: 'mean', }, 'sum(val)__1 year later': { operator: 'mean', }, }, drop_missing_columns: false, columns: ['foo', 'bar'], index: ['ds'], }, }); }); test('should pivot on x-axis with series_columns', () => { expect( timeComparePivotOperator( { ...formData, comparison_type: 'values', time_compare: ['1 year ago', '1 year later'], x_axis: 'ds', }, { ...queryObject, columns: ['ds', 'foo', 'bar'], series_columns: ['foo', 'bar'], }, ), ).toEqual({ operation: 'pivot', options: { aggregates: { 'count(*)': { operator: 'mean' }, 'count(*)__1 year ago': { operator: 'mean' }, 'count(*)__1 year later': { operator: 'mean' }, 'sum(val)': { operator: 'mean', }, 'sum(val)__1 year ago': { operator: 'mean', }, 'sum(val)__1 year later': { operator: 'mean', }, }, drop_missing_columns: false, columns: ['foo', 'bar'], index: ['ds'], }, }); }); test('should pivot on adhoc x-axis', () => { expect( timeComparePivotOperator( { ...formData, comparison_type: 'values', time_compare: ['1 year ago', '1 year later'], x_axis: { label: 'my_case_expr', expressionType: 'SQL', sqlExpression: 'case when a = 1 then 1 else 0 end', }, }, queryObject, ), ).toEqual({ operation: 'pivot', options: { aggregates: { 'count(*)': { operator: 'mean' }, 'count(*)__1 year ago': { operator: 'mean' }, 'count(*)__1 year later': { operator: 'mean' }, 'sum(val)': { operator: 'mean', }, 'sum(val)__1 year ago': { operator: 'mean', }, 'sum(val)__1 year later': { operator: 'mean', }, }, drop_missing_columns: false, columns: ['foo', 'bar'], index: ['my_case_expr'], }, }); });
5,234
0
petrpan-code/apache/superset/superset-frontend/packages/superset-ui-chart-controls/test/operators
petrpan-code/apache/superset/superset-frontend/packages/superset-ui-chart-controls/test/operators/utils/extractExtraMetrics.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 { QueryFormData, QueryFormMetric } from '@superset-ui/core'; import { extractExtraMetrics } from '@superset-ui/chart-controls'; const baseFormData: QueryFormData = { datasource: 'dummy', viz_type: 'table', metrics: ['a', 'b'], columns: ['foo', 'bar'], limit: 100, metrics_b: ['c', 'd'], columns_b: ['hello', 'world'], limit_b: 200, }; const metric: QueryFormMetric = { expressionType: 'SQL', sqlExpression: 'case when 1 then 1 else 2 end', label: 'foo', }; test('returns empty array if relevant controls missing', () => { expect( extractExtraMetrics({ ...baseFormData, }), ).toEqual([]); }); test('returns empty array if x_axis_sort is not same as timeseries_limit_metric', () => { expect( extractExtraMetrics({ ...baseFormData, timeseries_limit_metric: 'foo', x_axis_sort: 'bar', }), ).toEqual([]); }); test('returns correct column if sort columns match', () => { expect( extractExtraMetrics({ ...baseFormData, timeseries_limit_metric: 'foo', x_axis_sort: 'foo', }), ).toEqual(['foo']); }); test('handles adhoc metrics correctly', () => { expect( extractExtraMetrics({ ...baseFormData, timeseries_limit_metric: metric, x_axis_sort: 'foo', }), ).toEqual([metric]); expect( extractExtraMetrics({ ...baseFormData, timeseries_limit_metric: metric, x_axis_sort: 'bar', }), ).toEqual([]); }); test('returns empty array if groupby populated', () => { expect( extractExtraMetrics({ ...baseFormData, groupby: ['bar'], timeseries_limit_metric: 'foo', x_axis_sort: 'foo', }), ).toEqual([]); }); test('returns empty array if timeseries_limit_metric and x_axis_sort are included in main metrics array', () => { expect( extractExtraMetrics({ ...baseFormData, timeseries_limit_metric: 'a', x_axis_sort: 'a', }), ).toEqual([]); }); test('returns empty array if timeseries_limit_metric and x_axis_sort are included in main metrics array with adhoc metrics', () => { expect( extractExtraMetrics({ ...baseFormData, metrics: [ 'a', { expressionType: 'SIMPLE', aggregate: 'SUM', column: { column_name: 'num' }, }, ], timeseries_limit_metric: { expressionType: 'SIMPLE', aggregate: 'SUM', column: { column_name: 'num' }, }, x_axis_sort: 'SUM(num)', }), ).toEqual([]); }); test('returns emoty array if timeseries_limit_metric is an empty array', () => { expect( extractExtraMetrics({ ...baseFormData, // @ts-ignore timeseries_limit_metric: [], }), ).toEqual([]); });
5,235
0
petrpan-code/apache/superset/superset-frontend/packages/superset-ui-chart-controls/test/operators
petrpan-code/apache/superset/superset-frontend/packages/superset-ui-chart-controls/test/operators/utils/isDerivedSeries.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 { isDerivedSeries } from '@superset-ui/chart-controls'; import { SqlaFormData, ComparisonType } from '@superset-ui/core'; const formData: SqlaFormData = { datasource: 'foo', viz_type: 'table', }; const series = { id: 'metric__1 month ago', name: 'metric__1 month ago', data: [100], }; test('should be false if comparison type is not actual values', () => { expect(isDerivedSeries(series, formData)).toEqual(false); Object.keys(ComparisonType) .filter(type => type === ComparisonType.Values) .forEach(type => { const formDataWithComparisonType = { ...formData, comparison_type: type, time_compare: ['1 month ago'], }; expect(isDerivedSeries(series, formDataWithComparisonType)).toEqual( false, ); }); }); test('should be true if comparison type is values', () => { const formDataWithActualTypes = { ...formData, comparison_type: ComparisonType.Values, time_compare: ['1 month ago', '1 month later'], }; expect(isDerivedSeries(series, formDataWithActualTypes)).toEqual(true); }); test('should be false if series name does not match time_compare', () => { const arbitrary_series = { id: 'arbitrary column', name: 'arbitrary column', data: [100], }; const formDataWithActualTypes = { ...formData, comparison_type: ComparisonType.Values, time_compare: ['1 month ago', '1 month later'], }; expect(isDerivedSeries(arbitrary_series, formDataWithActualTypes)).toEqual( false, ); }); test('should be false if time compare is not suffix', () => { const series = { id: '1 month ago__metric', name: '1 month ago__metric', data: [100], }; const formDataWithActualTypes = { ...formData, comparison_type: ComparisonType.Values, time_compare: ['1 month ago', '1 month later'], }; expect(isDerivedSeries(series, formDataWithActualTypes)).toEqual(false); }); test('should be false if series name invalid', () => { const series = { id: 123, name: 123, data: [100], }; const formDataWithActualTypes = { ...formData, comparison_type: ComparisonType.Values, time_compare: ['1 month ago', '1 month later'], }; expect(isDerivedSeries(series, formDataWithActualTypes)).toEqual(false); });
5,236
0
petrpan-code/apache/superset/superset-frontend/packages/superset-ui-chart-controls/test/operators
petrpan-code/apache/superset/superset-frontend/packages/superset-ui-chart-controls/test/operators/utils/timeOffset.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 { getOriginalSeries } from '@superset-ui/chart-controls'; test('returns the series name when time compare is empty', () => { const seriesName = 'sum'; expect(getOriginalSeries(seriesName, [])).toEqual(seriesName); }); test('returns the original series name', () => { const seriesName = 'sum__1_month_ago'; const timeCompare = ['1_month_ago']; expect(getOriginalSeries(seriesName, timeCompare)).toEqual('sum'); });
5,237
0
petrpan-code/apache/superset/superset-frontend/packages/superset-ui-chart-controls/test
petrpan-code/apache/superset/superset-frontend/packages/superset-ui-chart-controls/test/utils/columnChoices.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 { DatasourceType, testQueryResponse } from '@superset-ui/core'; import { columnChoices } from '../../src'; describe('columnChoices()', () => { it('should convert columns to choices when source is a Dataset', () => { expect( columnChoices({ id: 1, metrics: [], type: DatasourceType.Table, main_dttm_col: 'test', time_grain_sqla: [], columns: [ { column_name: 'fiz', }, { column_name: 'about', verbose_name: 'right', }, { column_name: 'foo', verbose_name: 'bar', }, ], verbose_map: {}, column_formats: { fiz: 'NUMERIC', about: 'STRING', foo: 'DATE' }, currency_formats: {}, datasource_name: 'my_datasource', description: 'this is my datasource', }), ).toEqual([ ['foo', 'bar'], ['fiz', 'fiz'], ['about', 'right'], ]); }); it('should return empty array when no columns', () => { expect(columnChoices(undefined)).toEqual([]); }); it('should convert columns to choices when source is a Query', () => { expect(columnChoices(testQueryResponse)).toEqual([ ['Column 1', 'Column 1'], ['Column 2', 'Column 2'], ['Column 3', 'Column 3'], ]); expect.anything(); }); });
5,238
0
petrpan-code/apache/superset/superset-frontend/packages/superset-ui-chart-controls/test
petrpan-code/apache/superset/superset-frontend/packages/superset-ui-chart-controls/test/utils/defineSavedMetrics.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 { DatasourceType, DEFAULT_METRICS, QueryResponse, testQuery, } from '@superset-ui/core'; import { defineSavedMetrics } from '@superset-ui/chart-controls'; describe('defineSavedMetrics', () => { it('defines saved metrics if source is a Dataset', () => { const dataset = { id: 1, metrics: [ { metric_name: 'COUNT(*) non-default-dataset-metric', expression: 'COUNT(*) non-default-dataset-metric', }, ], type: DatasourceType.Table, main_dttm_col: 'test', time_grain_sqla: [], columns: [], verbose_map: {}, column_formats: {}, currency_formats: {}, datasource_name: 'my_datasource', description: 'this is my datasource', }; expect(defineSavedMetrics(dataset)).toEqual([ { metric_name: 'COUNT(*) non-default-dataset-metric', expression: 'COUNT(*) non-default-dataset-metric', }, ]); // @ts-ignore expect(defineSavedMetrics({ ...dataset, metrics: undefined })).toEqual([]); }); it('returns default saved metrics if souce is a Query', () => { expect(defineSavedMetrics(testQuery as QueryResponse)).toEqual( DEFAULT_METRICS, ); }); });
5,239
0
petrpan-code/apache/superset/superset-frontend/packages/superset-ui-chart-controls/test
petrpan-code/apache/superset/superset-frontend/packages/superset-ui-chart-controls/test/utils/expandControlConfig.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 { expandControlConfig, sharedControls, CustomControlItem, sharedControlComponents, } from '../../src'; describe('expandControlConfig()', () => { it('expands shared control alias', () => { expect(expandControlConfig('metrics')).toEqual({ name: 'metrics', config: sharedControls.metrics, }); }); it('expands control with overrides', () => { expect( expandControlConfig({ name: 'metrics', override: { label: 'Custom Metric', }, }), ).toEqual({ name: 'metrics', config: { ...sharedControls.metrics, label: 'Custom Metric', }, }); }); it('leave full control untouched', () => { const input = { name: 'metrics', config: { type: 'SelectControl', label: 'Custom Metric', }, }; expect(expandControlConfig(input)).toEqual(input); }); it('load shared components in chart-controls', () => { const input = { name: 'metrics', config: { type: 'RadioButtonControl', label: 'Custom Metric', }, }; expect( (expandControlConfig(input) as CustomControlItem).config.type, ).toEqual(sharedControlComponents.RadioButtonControl); }); it('leave NULL and ReactElement untouched', () => { expect(expandControlConfig(null)).toBeNull(); const input = <h1>Test</h1>; expect(expandControlConfig(input)).toBe(input); }); it('leave unknown text untouched', () => { const input = 'superset-ui'; expect(expandControlConfig(input as never)).toBe(input); }); it('return null for invalid configs', () => { expect( expandControlConfig({ type: 'SelectControl', label: 'Hello' } as never), ).toBeNull(); }); });
5,240
0
petrpan-code/apache/superset/superset-frontend/packages/superset-ui-chart-controls/test
petrpan-code/apache/superset/superset-frontend/packages/superset-ui-chart-controls/test/utils/getColorFormatters.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 } from '@superset-ui/core'; import { COMPARATOR, getOpacity, round, getColorFormatters, getColorFunction, } from '../../src'; configure(); const mockData = [ { count: 50, sum: 200 }, { count: 100, sum: 400 }, ]; const countValues = mockData.map(row => row.count); describe('round', () => { it('round', () => { expect(round(1)).toEqual(1); expect(round(1, 2)).toEqual(1); expect(round(0.6)).toEqual(1); expect(round(0.6, 1)).toEqual(0.6); expect(round(0.64999, 2)).toEqual(0.65); }); }); describe('getOpacity', () => { it('getOpacity', () => { expect(getOpacity(100, 100, 100)).toEqual(1); expect(getOpacity(75, 50, 100)).toEqual(0.53); expect(getOpacity(75, 100, 50)).toEqual(0.53); expect(getOpacity(100, 100, 50)).toEqual(0.05); expect(getOpacity(100, 100, 100, 0, 0.8)).toEqual(0.8); expect(getOpacity(100, 100, 50, 0, 1)).toEqual(0); expect(getOpacity(999, 100, 50, 0, 1)).toEqual(1); expect(getOpacity(100, 100, 50, 0.99, 1)).toEqual(0.99); expect(getOpacity(99, 100, 50, 0, 1)).toEqual(0.02); }); }); describe('getColorFunction()', () => { it('getColorFunction GREATER_THAN', () => { const colorFunction = getColorFunction( { operator: COMPARATOR.GREATER_THAN, targetValue: 50, colorScheme: '#FF0000', column: 'count', }, countValues, ); expect(colorFunction(50)).toBeUndefined(); expect(colorFunction(100)).toEqual('#FF0000FF'); }); it('getColorFunction LESS_THAN', () => { const colorFunction = getColorFunction( { operator: COMPARATOR.LESS_THAN, targetValue: 100, colorScheme: '#FF0000', column: 'count', }, countValues, ); expect(colorFunction(100)).toBeUndefined(); expect(colorFunction(50)).toEqual('#FF0000FF'); }); it('getColorFunction GREATER_OR_EQUAL', () => { const colorFunction = getColorFunction( { operator: COMPARATOR.GREATER_OR_EQUAL, targetValue: 50, colorScheme: '#FF0000', column: 'count', }, countValues, ); expect(colorFunction(50)).toEqual('#FF00000D'); expect(colorFunction(100)).toEqual('#FF0000FF'); expect(colorFunction(0)).toBeUndefined(); }); it('getColorFunction LESS_OR_EQUAL', () => { const colorFunction = getColorFunction( { operator: COMPARATOR.LESS_OR_EQUAL, targetValue: 100, colorScheme: '#FF0000', column: 'count', }, countValues, ); expect(colorFunction(50)).toEqual('#FF0000FF'); expect(colorFunction(100)).toEqual('#FF00000D'); expect(colorFunction(150)).toBeUndefined(); }); it('getColorFunction EQUAL', () => { const colorFunction = getColorFunction( { operator: COMPARATOR.EQUAL, targetValue: 100, colorScheme: '#FF0000', column: 'count', }, countValues, ); expect(colorFunction(50)).toBeUndefined(); expect(colorFunction(100)).toEqual('#FF0000FF'); }); it('getColorFunction NOT_EQUAL', () => { let colorFunction = getColorFunction( { operator: COMPARATOR.NOT_EQUAL, targetValue: 60, colorScheme: '#FF0000', column: 'count', }, countValues, ); expect(colorFunction(60)).toBeUndefined(); expect(colorFunction(100)).toEqual('#FF0000FF'); expect(colorFunction(50)).toEqual('#FF00004A'); colorFunction = getColorFunction( { operator: COMPARATOR.NOT_EQUAL, targetValue: 90, colorScheme: '#FF0000', column: 'count', }, countValues, ); expect(colorFunction(90)).toBeUndefined(); expect(colorFunction(100)).toEqual('#FF00004A'); expect(colorFunction(50)).toEqual('#FF0000FF'); }); it('getColorFunction BETWEEN', () => { const colorFunction = getColorFunction( { operator: COMPARATOR.BETWEEN, targetValueLeft: 75, targetValueRight: 125, colorScheme: '#FF0000', column: 'count', }, countValues, ); expect(colorFunction(50)).toBeUndefined(); expect(colorFunction(100)).toEqual('#FF000087'); }); it('getColorFunction BETWEEN_OR_EQUAL', () => { const colorFunction = getColorFunction( { operator: COMPARATOR.BETWEEN_OR_EQUAL, targetValueLeft: 50, targetValueRight: 100, colorScheme: '#FF0000', column: 'count', }, countValues, ); expect(colorFunction(50)).toEqual('#FF00000D'); expect(colorFunction(100)).toEqual('#FF0000FF'); expect(colorFunction(150)).toBeUndefined(); }); it('getColorFunction BETWEEN_OR_EQUAL without opacity', () => { const colorFunction = getColorFunction( { operator: COMPARATOR.BETWEEN_OR_EQUAL, targetValueLeft: 50, targetValueRight: 100, colorScheme: '#FF0000', column: 'count', }, countValues, false, ); expect(colorFunction(25)).toBeUndefined(); expect(colorFunction(50)).toEqual('#FF0000'); expect(colorFunction(75)).toEqual('#FF0000'); expect(colorFunction(100)).toEqual('#FF0000'); expect(colorFunction(125)).toBeUndefined(); }); it('getColorFunction BETWEEN_OR_LEFT_EQUAL', () => { const colorFunction = getColorFunction( { operator: COMPARATOR.BETWEEN_OR_LEFT_EQUAL, targetValueLeft: 50, targetValueRight: 100, colorScheme: '#FF0000', column: 'count', }, countValues, ); expect(colorFunction(50)).toEqual('#FF00000D'); expect(colorFunction(100)).toBeUndefined(); }); it('getColorFunction BETWEEN_OR_RIGHT_EQUAL', () => { const colorFunction = getColorFunction( { operator: COMPARATOR.BETWEEN_OR_RIGHT_EQUAL, targetValueLeft: 50, targetValueRight: 100, colorScheme: '#FF0000', column: 'count', }, countValues, ); expect(colorFunction(50)).toBeUndefined(); expect(colorFunction(100)).toEqual('#FF0000FF'); }); it('getColorFunction GREATER_THAN with target value undefined', () => { const colorFunction = getColorFunction( { operator: COMPARATOR.GREATER_THAN, targetValue: undefined, colorScheme: '#FF0000', column: 'count', }, countValues, ); expect(colorFunction(50)).toBeUndefined(); expect(colorFunction(100)).toBeUndefined(); }); it('getColorFunction BETWEEN with target value left undefined', () => { const colorFunction = getColorFunction( { operator: COMPARATOR.BETWEEN, targetValueLeft: undefined, targetValueRight: 100, colorScheme: '#FF0000', column: 'count', }, countValues, ); expect(colorFunction(50)).toBeUndefined(); expect(colorFunction(100)).toBeUndefined(); }); it('getColorFunction BETWEEN with target value right undefined', () => { const colorFunction = getColorFunction( { operator: COMPARATOR.BETWEEN, targetValueLeft: 50, targetValueRight: undefined, colorScheme: '#FF0000', column: 'count', }, countValues, ); expect(colorFunction(50)).toBeUndefined(); expect(colorFunction(100)).toBeUndefined(); }); it('getColorFunction unsupported operator', () => { const colorFunction = getColorFunction( { // @ts-ignore operator: 'unsupported operator', targetValue: 50, colorScheme: '#FF0000', column: 'count', }, countValues, ); expect(colorFunction(50)).toBeUndefined(); expect(colorFunction(100)).toBeUndefined(); }); it('getColorFunction with operator None', () => { const colorFunction = getColorFunction( { operator: COMPARATOR.NONE, colorScheme: '#FF0000', column: 'count', }, countValues, ); expect(colorFunction(20)).toEqual(undefined); expect(colorFunction(50)).toEqual('#FF000000'); expect(colorFunction(75)).toEqual('#FF000080'); expect(colorFunction(100)).toEqual('#FF0000FF'); expect(colorFunction(120)).toEqual(undefined); }); it('getColorFunction with operator undefined', () => { const colorFunction = getColorFunction( { operator: undefined, targetValue: 150, colorScheme: '#FF0000', column: 'count', }, countValues, ); expect(colorFunction(50)).toBeUndefined(); expect(colorFunction(100)).toBeUndefined(); }); it('getColorFunction with colorScheme undefined', () => { const colorFunction = getColorFunction( { operator: COMPARATOR.GREATER_THAN, targetValue: 150, colorScheme: undefined, column: 'count', }, countValues, ); expect(colorFunction(50)).toBeUndefined(); expect(colorFunction(100)).toBeUndefined(); }); }); describe('getColorFormatters()', () => { it('correct column config', () => { const columnConfig = [ { operator: COMPARATOR.GREATER_THAN, targetValue: 50, colorScheme: '#FF0000', column: 'count', }, { operator: COMPARATOR.LESS_THAN, targetValue: 300, colorScheme: '#FF0000', column: 'sum', }, { operator: COMPARATOR.BETWEEN, targetValueLeft: 75, targetValueRight: 125, colorScheme: '#FF0000', column: 'count', }, { operator: COMPARATOR.GREATER_THAN, targetValue: 150, colorScheme: '#FF0000', column: undefined, }, ]; const colorFormatters = getColorFormatters(columnConfig, mockData); expect(colorFormatters.length).toEqual(3); expect(colorFormatters[0].column).toEqual('count'); expect(colorFormatters[0].getColorFromValue(100)).toEqual('#FF0000FF'); expect(colorFormatters[1].column).toEqual('sum'); expect(colorFormatters[1].getColorFromValue(200)).toEqual('#FF0000FF'); expect(colorFormatters[1].getColorFromValue(400)).toBeUndefined(); expect(colorFormatters[2].column).toEqual('count'); expect(colorFormatters[2].getColorFromValue(100)).toEqual('#FF000087'); }); it('undefined column config', () => { const colorFormatters = getColorFormatters(undefined, mockData); expect(colorFormatters.length).toEqual(0); }); });
5,241
0
petrpan-code/apache/superset/superset-frontend/packages/superset-ui-chart-controls/test
petrpan-code/apache/superset/superset-frontend/packages/superset-ui-chart-controls/test/utils/getStandardizedControls.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 { QueryFormData } from '@superset-ui/core'; import { getStandardizedControls } from '../../src'; const formData: QueryFormData = { datasource: '30__table', viz_type: 'table', standardizedFormData: { controls: { metrics: ['count(*)', 'sum(sales)'], columns: ['gender', 'gender'], }, memorizedFormData: [], }, }; test('without standardizedFormData', () => { getStandardizedControls().setStandardizedControls({ datasource: '30__table', viz_type: 'table', }); expect(getStandardizedControls().controls).toEqual({ metrics: [], columns: [], }); }); test('getStandardizedControls', () => { expect(getStandardizedControls().controls).toEqual({ metrics: [], columns: [], }); getStandardizedControls().setStandardizedControls(formData); expect(getStandardizedControls().controls).toEqual({ metrics: ['count(*)', 'sum(sales)'], columns: ['gender', 'gender'], }); expect(getStandardizedControls().shiftMetric()).toEqual('count(*)'); expect(getStandardizedControls().controls).toEqual({ metrics: ['sum(sales)'], columns: ['gender', 'gender'], }); expect(getStandardizedControls().popAllMetrics()).toEqual(['sum(sales)']); expect(getStandardizedControls().controls).toEqual({ metrics: [], columns: ['gender', 'gender'], }); expect(getStandardizedControls().shiftColumn()).toEqual('gender'); expect(getStandardizedControls().controls).toEqual({ metrics: [], columns: ['gender'], }); expect(getStandardizedControls().popAllColumns()).toEqual(['gender']); expect(getStandardizedControls().controls).toEqual({ metrics: [], columns: [], }); getStandardizedControls().setStandardizedControls(formData); getStandardizedControls().clear(); expect(getStandardizedControls().controls).toEqual({ metrics: [], columns: [], }); });
5,242
0
petrpan-code/apache/superset/superset-frontend/packages/superset-ui-chart-controls/test
petrpan-code/apache/superset/superset-frontend/packages/superset-ui-chart-controls/test/utils/getTemporalColumns.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 { testQueryResponse, testQueryResults } from '@superset-ui/core'; import { Dataset, getTemporalColumns, isTemporalColumn, TestDataset, } from '../../src'; test('get temporal columns from a Dataset', () => { expect(getTemporalColumns(TestDataset)).toEqual({ temporalColumns: [ { advanced_data_type: undefined, certification_details: null, certified_by: null, column_name: 'ds', description: null, expression: '', filterable: true, groupby: true, id: 329, is_certified: false, is_dttm: true, python_date_format: null, type: 'TIMESTAMP WITHOUT TIME ZONE', type_generic: 2, verbose_name: null, warning_markdown: null, }, ], defaultTemporalColumn: 'ds', }); }); test('get temporal columns from a QueryResponse', () => { expect(getTemporalColumns(testQueryResponse)).toEqual({ temporalColumns: [ { column_name: 'Column 2', type: 'TIMESTAMP', is_dttm: true, }, ], defaultTemporalColumn: 'Column 2', }); }); test('get temporal columns from null', () => { expect(getTemporalColumns(null)).toEqual({ temporalColumns: [], defaultTemporalColumn: undefined, }); }); test('should accept empty Dataset or queryResponse', () => { expect( getTemporalColumns({ ...TestDataset, ...{ columns: [], main_dttm_col: undefined, }, } as any as Dataset), ).toEqual({ temporalColumns: [], defaultTemporalColumn: undefined, }); expect( getTemporalColumns({ ...testQueryResponse, ...{ columns: [], results: { ...testQueryResults.results, ...{ columns: [] } }, }, }), ).toEqual({ temporalColumns: [], defaultTemporalColumn: undefined, }); }); test('should determine temporal columns in a Dataset', () => { expect(isTemporalColumn('ds', TestDataset)).toBeTruthy(); expect(isTemporalColumn('num', TestDataset)).toBeFalsy(); });
5,243
0
petrpan-code/apache/superset/superset-frontend/packages/superset-ui-chart-controls/test
petrpan-code/apache/superset/superset-frontend/packages/superset-ui-chart-controls/test/utils/mainMetric.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 { mainMetric } from '../../src'; describe('mainMetric', () => { it('is null when no options', () => { expect(mainMetric([])).toBeUndefined(); expect(mainMetric(null)).toBeUndefined(); }); it('prefers the "count" metric when first', () => { const metrics = [{ metric_name: 'count' }, { metric_name: 'foo' }]; expect(mainMetric(metrics)).toBe('count'); }); it('prefers the "count" metric when not first', () => { const metrics = [{ metric_name: 'foo' }, { metric_name: 'count' }]; expect(mainMetric(metrics)).toBe('count'); }); it('selects the first metric when "count" is not an option', () => { const metrics = [{ metric_name: 'foo' }, { metric_name: 'not_count' }]; expect(mainMetric(metrics)).toBe('foo'); }); });
5,244
0
petrpan-code/apache/superset/superset-frontend/packages/superset-ui-chart-controls/test
petrpan-code/apache/superset/superset-frontend/packages/superset-ui-chart-controls/test/utils/selectOptions.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 { formatSelectOptions, formatSelectOptionsForRange } from '../../src'; describe('formatSelectOptions', () => { it('formats an array of options', () => { expect(formatSelectOptions([1, 5, 10, 25, 50, 'unlimited'])).toEqual([ [1, '1'], [5, '5'], [10, '10'], [25, '25'], [50, '50'], ['unlimited', 'unlimited'], ]); }); it('formats a mix of values and already formated options', () => { expect( formatSelectOptions<number | string>([ [0, 'all'], 1, 5, 10, 25, 50, 'unlimited', ]), ).toEqual([ [0, 'all'], [1, '1'], [5, '5'], [10, '10'], [25, '25'], [50, '50'], ['unlimited', 'unlimited'], ]); }); }); describe('formatSelectOptionsForRange', () => { it('generates select options from a range', () => { expect(formatSelectOptionsForRange(1, 5)).toEqual([ [1, '1'], [2, '2'], [3, '3'], [4, '4'], [5, '5'], ]); }); });
5,338
0
petrpan-code/apache/superset/superset-frontend/packages/superset-ui-core/src/hooks
petrpan-code/apache/superset/superset-frontend/packages/superset-ui-core/src/hooks/useChangeEffect/useChangeEffect.test.ts
/** * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ import { renderHook } from '@testing-library/react-hooks'; import { useChangeEffect } from './useChangeEffect'; test('call callback the first time with undefined and value', () => { const callback = jest.fn(); renderHook(props => useChangeEffect(props.value, props.callback), { initialProps: { value: 'value', callback }, }); expect(callback).toBeCalledTimes(1); expect(callback).nthCalledWith(1, undefined, 'value'); }); test('do not call callback 2 times if the value do not change', () => { const callback = jest.fn(); const hook = renderHook( props => useChangeEffect(props.value, props.callback), { initialProps: { value: 'value', callback }, }, ); hook.rerender({ value: 'value', callback }); expect(callback).toBeCalledTimes(1); }); test('call callback whenever the value changes', () => { const callback = jest.fn(); const hook = renderHook( props => useChangeEffect(props.value, props.callback), { initialProps: { value: 'value', callback }, }, ); hook.rerender({ value: 'value-2', callback }); expect(callback).toBeCalledTimes(2); expect(callback).nthCalledWith(2, 'value', 'value-2'); });
5,341
0
petrpan-code/apache/superset/superset-frontend/packages/superset-ui-core/src/hooks
petrpan-code/apache/superset/superset-frontend/packages/superset-ui-core/src/hooks/useComponentDidMount/useComponentDidMount.test.ts
/** * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ import { renderHook } from '@testing-library/react-hooks'; import { useComponentDidMount } from './useComponentDidMount'; test('the effect should only be executed on the first render', () => { const effect = jest.fn(); const hook = renderHook(() => useComponentDidMount(effect)); expect(effect).toBeCalledTimes(1); hook.rerender(); expect(effect).toBeCalledTimes(1); });
5,344
0
petrpan-code/apache/superset/superset-frontend/packages/superset-ui-core/src/hooks
petrpan-code/apache/superset/superset-frontend/packages/superset-ui-core/src/hooks/useComponentDidUpdate/useComponentDidUpdate.test.ts
/** * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ import { renderHook } from '@testing-library/react-hooks'; import { useComponentDidUpdate } from './useComponentDidUpdate'; test('the effect should not be executed on the first render', () => { const effect = jest.fn(); const hook = renderHook(props => useComponentDidUpdate(props.effect), { initialProps: { effect }, }); expect(effect).toBeCalledTimes(0); const changedEffect = jest.fn(); hook.rerender({ effect: changedEffect }); expect(changedEffect).toBeCalledTimes(1); });
5,347
0
petrpan-code/apache/superset/superset-frontend/packages/superset-ui-core/src/hooks
petrpan-code/apache/superset/superset-frontend/packages/superset-ui-core/src/hooks/useElementOnScreen/useElementOnScreen.test.ts
/** * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ import { renderHook } from '@testing-library/react-hooks'; import React from 'react'; import { useElementOnScreen } from './useElementOnScreen'; const observeMock = jest.fn(); const unobserveMock = jest.fn(); const IntersectionObserverMock = jest.fn(); IntersectionObserverMock.prototype.observe = observeMock; IntersectionObserverMock.prototype.unobserve = unobserveMock; beforeEach(() => { window.IntersectionObserver = IntersectionObserverMock; }); afterEach(() => { IntersectionObserverMock.mockClear(); jest.clearAllMocks(); }); test('should return null and false on first render', () => { const hook = renderHook(() => useElementOnScreen({ rootMargin: '-50px 0px 0px 0px' }), ); expect(hook.result.current).toEqual([{ current: null }, false]); }); test('should return isSticky as true when intersectionRatio < 1', async () => { const hook = renderHook(() => useElementOnScreen({ rootMargin: '-50px 0px 0px 0px' }), ); const callback = IntersectionObserverMock.mock.calls[0][0]; const callBack = callback([{ isIntersecting: true, intersectionRatio: 0.5 }]); const observer = new IntersectionObserverMock(callBack, {}); const newDiv = document.createElement('div'); observer.observe(newDiv); expect(hook.result.current[1]).toEqual(true); }); test('should return isSticky as false when intersectionRatio >= 1', async () => { const hook = renderHook(() => useElementOnScreen({ rootMargin: '-50px 0px 0px 0px' }), ); const callback = IntersectionObserverMock.mock.calls[0][0]; const callBack = callback([{ isIntersecting: true, intersectionRatio: 1 }]); const observer = new IntersectionObserverMock(callBack, {}); const newDiv = document.createElement('div'); observer.observe(newDiv); expect(hook.result.current[1]).toEqual(false); }); test('should observe and unobserve element with IntersectionObserver', async () => { jest.spyOn(React, 'useRef').mockReturnValue({ current: 'test' }); const options = { threshold: 0.5 }; const { result, unmount } = renderHook(() => useElementOnScreen(options)); const [elementRef] = result.current; expect(IntersectionObserverMock).toHaveBeenCalledWith( expect.any(Function), options, ); expect(elementRef).not.toBe(null); expect(observeMock).toHaveBeenCalledWith(elementRef.current); unmount(); expect(unobserveMock).toHaveBeenCalledWith(elementRef.current); }); test('should not observe an element if it is null', () => { jest.spyOn(React, 'useRef').mockReturnValue({ current: null }); const options = {}; const { result } = renderHook(() => useElementOnScreen(options)); const [ref, isSticky] = result.current; expect(ref.current).toBe(null); expect(isSticky).toBe(false); expect(observeMock).not.toHaveBeenCalled(); }); test('should not unobserve the element if it is null', () => { jest.spyOn(React, 'useRef').mockReturnValue({ current: null }); const options = {}; const { result, unmount } = renderHook(() => useElementOnScreen(options)); const [ref, isSticky] = result.current; expect(ref.current).toBe(null); expect(isSticky).toBe(false); unmount(); expect(unobserveMock).not.toHaveBeenCalled(); });
5,350
0
petrpan-code/apache/superset/superset-frontend/packages/superset-ui-core/src/hooks
petrpan-code/apache/superset/superset-frontend/packages/superset-ui-core/src/hooks/usePrevious/usePrevious.test.ts
/** * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ import { renderHook } from '@testing-library/react-hooks'; import { usePrevious } from './usePrevious'; test('get undefined on the first render when initialValue is not defined', () => { const hook = renderHook(() => usePrevious('state')); expect(hook.result.current).toBeUndefined(); }); test('get initial value on the first render when initialValue is defined', () => { const hook = renderHook(() => usePrevious('state', 'initial')); expect(hook.result.current).toBe('initial'); }); test('get state value on second render', () => { const hook = renderHook(() => usePrevious('state', 'initial')); hook.rerender(() => usePrevious('state')); expect(hook.result.current).toBe('state'); }); test('get state value on third render', () => { const hook = renderHook(() => usePrevious('state')); hook.rerender(() => usePrevious('state')); hook.rerender(() => usePrevious('state-2')); expect(hook.result.current).toBe('state'); });
5,353
0
petrpan-code/apache/superset/superset-frontend/packages/superset-ui-core/src/hooks
petrpan-code/apache/superset/superset-frontend/packages/superset-ui-core/src/hooks/useTruncation/useCSSTextTruncation.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 { renderHook } from '@testing-library/react-hooks'; import React from 'react'; import useCSSTextTruncation from './useCSSTextTruncation'; afterEach(() => { jest.clearAllMocks(); }); test('should be false by default', () => { const { result } = renderHook(() => useCSSTextTruncation<HTMLParagraphElement>(), ); const [paragraphRef, isTruncated] = result.current; expect(paragraphRef.current).toBe(null); expect(isTruncated).toBe(false); }); test('should not truncate', () => { const ref = { current: document.createElement('p') }; Object.defineProperty(ref.current, 'offsetWidth', { get: () => 100 }); Object.defineProperty(ref.current, 'scrollWidth', { get: () => 50 }); jest.spyOn(React, 'useRef').mockReturnValue({ current: ref.current }); const { result } = renderHook(() => useCSSTextTruncation<HTMLParagraphElement>(), ); const [, isTruncated] = result.current; expect(isTruncated).toBe(false); }); test('should truncate', () => { const ref = { current: document.createElement('p') }; Object.defineProperty(ref.current, 'offsetWidth', { get: () => 50 }); Object.defineProperty(ref.current, 'scrollWidth', { get: () => 100 }); jest.spyOn(React, 'useRef').mockReturnValue({ current: ref.current }); const { result } = renderHook(() => useCSSTextTruncation<HTMLParagraphElement>(), ); const [, isTruncated] = result.current; expect(isTruncated).toBe(true); });
5,355
0
petrpan-code/apache/superset/superset-frontend/packages/superset-ui-core/src/hooks
petrpan-code/apache/superset/superset-frontend/packages/superset-ui-core/src/hooks/useTruncation/useChildElementTruncation.test.ts
/** * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ import { renderHook } from '@testing-library/react-hooks'; import { RefObject } from 'react'; import useChildElementTruncation from './useChildElementTruncation'; const genElements = ( scrollWidth: number, clientWidth: number, offsetWidth: number | undefined, childNodes: any = [], ) => { const elementRef: RefObject<Partial<HTMLElement>> = { current: { scrollWidth, clientWidth, childNodes }, }; const plusRef: RefObject<Partial<HTMLElement>> = { current: { offsetWidth }, }; return [elementRef, plusRef]; }; const useTruncation = (elementRef: any, plusRef: any) => useChildElementTruncation( elementRef as RefObject<HTMLElement>, plusRef as RefObject<HTMLElement>, ); test('should return [0, false] when elementRef.current is not defined', () => { const { result } = renderHook(() => useTruncation({ current: undefined }, { current: undefined }), ); expect(result.current).toEqual([0, false]); }); test('should not recompute when previousEffectInfo is the same as previous', () => { const elementRef = { current: document.createElement('div') }; const plusRef = { current: document.createElement('div') }; const { result, rerender } = renderHook(() => useTruncation(elementRef, plusRef), ); const previousEffectInfo = result.current; rerender(); expect(result.current).toEqual(previousEffectInfo); }); test('should return [0, false] when there are no truncated/hidden elements', () => { const [elementRef, plusRef] = genElements(100, 100, 10); const { result } = renderHook(() => useTruncation(elementRef, plusRef)); expect(result.current).toEqual([0, false]); }); test('should return [1, false] when there is only one truncated element', () => { const [elementRef, plusRef] = genElements(150, 100, 10); const { result } = renderHook(() => useTruncation(elementRef, plusRef)); expect(result.current).toEqual([1, false]); }); test('should return [1, true] with one truncated and hidden elements', () => { const [elementRef, plusRef] = genElements(150, 100, 10, [ { offsetWidth: 150 } as HTMLElement, { offsetWidth: 150 } as HTMLElement, ]); const { result } = renderHook(() => useTruncation(elementRef, plusRef)); expect(result.current).toEqual([1, true]); }); test('should return [2, true] with 2 truncated and hidden elements', () => { const [elementRef, plusRef] = genElements(150, 100, 10, [ { offsetWidth: 150 } as HTMLElement, { offsetWidth: 150 } as HTMLElement, { offsetWidth: 150 } as HTMLElement, ]); const { result } = renderHook(() => useTruncation(elementRef, plusRef)); expect(result.current).toEqual([2, true]); }); test('should return [1, true] with plusSize offsetWidth undefined', () => { const [elementRef, plusRef] = genElements(150, 100, undefined, [ { offsetWidth: 150 } as HTMLElement, { offsetWidth: 150 } as HTMLElement, ]); const { result } = renderHook(() => useTruncation(elementRef, plusRef)); expect(result.current).toEqual([1, true]); });
5,429
0
petrpan-code/apache/superset/superset-frontend/packages/superset-ui-core/src/time-format
petrpan-code/apache/superset/superset-frontend/packages/superset-ui-core/src/time-format/formatters/finestTemporalGrain.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 finestTemporalGrain from './finestTemporalGrain'; test('finestTemporalGrain', () => { const monthFormatter = finestTemporalGrain([ new Date('2003-01-01 00:00:00Z').getTime(), new Date('2003-02-01 00:00:00Z').getTime(), ]); expect(monthFormatter(new Date('2003-01-01 00:00:00Z').getTime())).toBe( '2003-01-01', ); expect(monthFormatter(new Date('2003-02-01 00:00:00Z').getTime())).toBe( '2003-02-01', ); const yearFormatter = finestTemporalGrain([ new Date('2003-01-01 00:00:00Z').getTime(), new Date('2004-01-01 00:00:00Z').getTime(), ]); expect(yearFormatter(new Date('2003-01-01 00:00:00Z').getTime())).toBe( '2003', ); expect(yearFormatter(new Date('2004-01-01 00:00:00Z').getTime())).toBe( '2004', ); const milliSecondFormatter = finestTemporalGrain([ new Date('2003-01-01 00:00:00Z').getTime(), new Date('2003-04-05 06:07:08.123Z').getTime(), ]); expect(milliSecondFormatter(new Date('2003-01-01 00:00:00Z').getTime())).toBe( '2003-01-01 00:00:00.000', ); const localTimeFormatter = finestTemporalGrain( [ new Date('2003-01-01 00:00:00Z').getTime(), new Date('2003-02-01 00:00:00Z').getTime(), ], true, ); expect(localTimeFormatter(new Date('2003-01-01 00:00:00Z').getTime())).toBe( '2002-12-31 19:00', ); });
5,455
0
petrpan-code/apache/superset/superset-frontend/packages/superset-ui-core/src
petrpan-code/apache/superset/superset-frontend/packages/superset-ui-core/src/utils/html.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 { sanitizeHtml, isProbablyHTML, sanitizeHtmlIfNeeded, safeHtmlSpan, removeHTMLTags, } from './html'; describe('sanitizeHtml', () => { test('should sanitize the HTML string', () => { const htmlString = '<script>alert("XSS")</script>'; const sanitizedString = sanitizeHtml(htmlString); expect(sanitizedString).not.toContain('script'); }); }); describe('isProbablyHTML', () => { test('should return true if the text contains HTML tags', () => { const htmlText = '<div>Some HTML content</div>'; const isHTML = isProbablyHTML(htmlText); expect(isHTML).toBe(true); }); test('should return false if the text does not contain HTML tags', () => { const plainText = 'Just a plain text'; const isHTML = isProbablyHTML(plainText); expect(isHTML).toBe(false); const trickyText = 'a <= 10 and b > 10'; expect(isProbablyHTML(trickyText)).toBe(false); }); }); describe('sanitizeHtmlIfNeeded', () => { test('should sanitize the HTML string if it contains HTML tags', () => { const htmlString = '<div>Some <b>HTML</b> content</div>'; const sanitizedString = sanitizeHtmlIfNeeded(htmlString); expect(sanitizedString).toEqual(htmlString); }); test('should return the string as is if it does not contain HTML tags', () => { const plainText = 'Just a plain text'; const sanitizedString = sanitizeHtmlIfNeeded(plainText); expect(sanitizedString).toEqual(plainText); }); }); describe('safeHtmlSpan', () => { test('should return a safe HTML span when the input is HTML', () => { const htmlString = '<div>Some <b>HTML</b> content</div>'; const safeSpan = safeHtmlSpan(htmlString); expect(safeSpan).toEqual( <span className="safe-html-wrapper" dangerouslySetInnerHTML={{ __html: htmlString }} />, ); }); test('should return the input string as is when it is not HTML', () => { const plainText = 'Just a plain text'; const result = safeHtmlSpan(plainText); expect(result).toEqual(plainText); }); }); describe('removeHTMLTags', () => { test('should remove HTML tags from the string', () => { const input = '<p>Hello, <strong>World!</strong></p>'; const output = removeHTMLTags(input); expect(output).toBe('Hello, World!'); }); test('should return the same string when no HTML tags are present', () => { const input = 'This is a plain text.'; const output = removeHTMLTags(input); expect(output).toBe('This is a plain text.'); }); test('should remove nested HTML tags and return combined text content', () => { const input = '<div><h1>Title</h1><p>Content</p></div>'; const output = removeHTMLTags(input); expect(output).toBe('TitleContent'); }); test('should handle self-closing tags and return an empty string', () => { const input = '<img src="image.png" alt="Image">'; const output = removeHTMLTags(input); expect(output).toBe(''); }); test('should handle malformed HTML tags and remove only well-formed tags', () => { const input = '<div><h1>Unclosed tag'; const output = removeHTMLTags(input); expect(output).toBe('Unclosed tag'); }); });
5,459
0
petrpan-code/apache/superset/superset-frontend/packages/superset-ui-core/src
petrpan-code/apache/superset/superset-frontend/packages/superset-ui-core/src/utils/isEqualArray.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 isEqualArray from './isEqualArray'; test('isEqualArray', () => { expect(isEqualArray([], [])).toBe(true); expect(isEqualArray([1, 2], [1, 2])).toBe(true); const item1 = { a: 1 }; expect(isEqualArray([item1], [item1])).toBe(true); expect(isEqualArray(null, undefined)).toBe(true); // compare is shallow expect(isEqualArray([{ a: 1 }], [{ a: 1 }])).toBe(false); expect(isEqualArray(null, [])).toBe(false); expect(isEqualArray([1, 2], [])).toBe(false); });
5,476
0
petrpan-code/apache/superset/superset-frontend/packages/superset-ui-core
petrpan-code/apache/superset/superset-frontend/packages/superset-ui-core/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 { ExtensibleFunction, Plugin, Preset, Registry, RegistryWithDefaultKey, convertKeysToCamelCase, isDefined, isRequired, makeSingleton, } from '@superset-ui/core'; describe('index', () => { it('exports modules', () => { [ ExtensibleFunction, Plugin, Preset, Registry, RegistryWithDefaultKey, convertKeysToCamelCase, isDefined, isRequired, makeSingleton, ].forEach(x => expect(x).toBeDefined()); }); });
5,477
0
petrpan-code/apache/superset/superset-frontend/packages/superset-ui-core
petrpan-code/apache/superset/superset-frontend/packages/superset-ui-core/test/tsconfig.json
{ "compilerOptions": { "composite": false, "emitDeclarationOnly": false, "noEmit": true, "rootDir": "." }, "extends": "../../../tsconfig.json", "include": ["**/*", "../types/**/*", "../../../types/**/*"], "references": [ { "path": ".." } ] }
5,479
0
petrpan-code/apache/superset/superset-frontend/packages/superset-ui-core/test
petrpan-code/apache/superset/superset-frontend/packages/superset-ui-core/test/chart-composition/ChartFrame.test.tsx
/* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ import React from 'react'; import { shallow } from 'enzyme'; import { ChartFrame } from '@superset-ui/core'; describe('TooltipFrame', () => { it('renders content that requires smaller space than frame', () => { const wrapper = shallow( <ChartFrame width={400} height={400} contentWidth={300} contentHeight={300} renderContent={({ width, height }) => ( <div> {width}/{height} </div> )} />, ); expect(wrapper.find('div').text()).toEqual('400/400'); }); it('renders content without specifying content size', () => { const wrapper = shallow( <ChartFrame width={400} height={400} renderContent={({ width, height }) => ( <div> {width}/{height} </div> )} />, ); expect(wrapper.find('div').text()).toEqual('400/400'); }); it('renders content that requires same size with frame', () => { const wrapper = shallow( <ChartFrame width={400} height={400} contentWidth={400} contentHeight={400} renderContent={({ width, height }) => ( <div> {width}/{height} </div> )} />, ); expect(wrapper.find('div').text()).toEqual('400/400'); }); it('renders content that requires space larger than frame', () => { const wrapper = shallow( <ChartFrame width={400} height={400} contentWidth={500} contentHeight={500} renderContent={({ width, height }) => ( <div className="chart"> {width}/{height} </div> )} />, ); expect(wrapper.find('div.chart').text()).toEqual('500/500'); }); it('renders content that width is larger than frame', () => { const wrapper = shallow( <ChartFrame width={400} height={400} contentWidth={500} renderContent={({ width, height }) => ( <div className="chart"> {width}/{height} </div> )} />, ); expect(wrapper.find('div.chart').text()).toEqual('500/400'); }); it('renders content that height is larger than frame', () => { const wrapper = shallow( <ChartFrame width={400} height={400} contentHeight={600} renderContent={({ width, height }) => ( <div className="chart"> {width}/{height} </div> )} />, ); expect(wrapper.find('div.chart').text()).toEqual('400/600'); }); it('renders an empty frame when renderContent is not given', () => { const wrapper = shallow(<ChartFrame width={400} height={400} />); expect(wrapper.find('div')).toHaveLength(0); }); });
5,480
0
petrpan-code/apache/superset/superset-frontend/packages/superset-ui-core/test/chart-composition
petrpan-code/apache/superset/superset-frontend/packages/superset-ui-core/test/chart-composition/legend/WithLegend.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, shallow } from 'enzyme'; import { triggerResizeObserver } from 'resize-observer-polyfill'; import { promiseTimeout, WithLegend } from '@superset-ui/core'; let renderChart = jest.fn(); let renderLegend = jest.fn(); describe('WithLegend', () => { beforeEach(() => { renderChart = jest.fn(() => <div className="chart" />); renderLegend = jest.fn(() => <div className="legend" />); }); it('sets className', () => { const wrapper = shallow( <WithLegend className="test-class" renderChart={renderChart} renderLegend={renderLegend} />, ); expect(wrapper.hasClass('test-class')).toEqual(true); }); it('renders when renderLegend is not set', () => { const wrapper = mount( <WithLegend debounceTime={1} width={500} height={500} renderChart={renderChart} />, ); triggerResizeObserver(); // Have to delay more than debounceTime (1ms) return promiseTimeout(() => { expect(renderChart).toHaveBeenCalledTimes(1); expect(wrapper.render().find('div.chart')).toHaveLength(1); expect(wrapper.render().find('div.legend')).toHaveLength(0); }, 100); }); it('renders', () => { const wrapper = mount( <WithLegend debounceTime={1} width={500} height={500} renderChart={renderChart} renderLegend={renderLegend} />, ); triggerResizeObserver(); // Have to delay more than debounceTime (1ms) return promiseTimeout(() => { expect(renderChart).toHaveBeenCalledTimes(1); expect(renderLegend).toHaveBeenCalledTimes(1); expect(wrapper.render().find('div.chart')).toHaveLength(1); expect(wrapper.render().find('div.legend')).toHaveLength(1); }, 100); }); it('renders without width or height', () => { const wrapper = mount( <WithLegend debounceTime={1} renderChart={renderChart} renderLegend={renderLegend} />, ); triggerResizeObserver(); // Have to delay more than debounceTime (1ms) return promiseTimeout(() => { expect(renderChart).toHaveBeenCalledTimes(1); expect(renderLegend).toHaveBeenCalledTimes(1); expect(wrapper.render().find('div.chart')).toHaveLength(1); expect(wrapper.render().find('div.legend')).toHaveLength(1); }, 100); }); it('renders legend on the left', () => { const wrapper = mount( <WithLegend debounceTime={1} position="left" renderChart={renderChart} renderLegend={renderLegend} />, ); triggerResizeObserver(); // Have to delay more than debounceTime (1ms) return promiseTimeout(() => { expect(renderChart).toHaveBeenCalledTimes(1); expect(renderLegend).toHaveBeenCalledTimes(1); expect(wrapper.render().find('div.chart')).toHaveLength(1); expect(wrapper.render().find('div.legend')).toHaveLength(1); }, 100); }); it('renders legend on the right', () => { const wrapper = mount( <WithLegend debounceTime={1} position="right" renderChart={renderChart} renderLegend={renderLegend} />, ); triggerResizeObserver(); // Have to delay more than debounceTime (1ms) return promiseTimeout(() => { expect(renderChart).toHaveBeenCalledTimes(1); expect(renderLegend).toHaveBeenCalledTimes(1); expect(wrapper.render().find('div.chart')).toHaveLength(1); expect(wrapper.render().find('div.legend')).toHaveLength(1); }, 100); }); it('renders legend on the top', () => { const wrapper = mount( <WithLegend debounceTime={1} position="top" renderChart={renderChart} renderLegend={renderLegend} />, ); triggerResizeObserver(); // Have to delay more than debounceTime (1ms) return promiseTimeout(() => { expect(renderChart).toHaveBeenCalledTimes(1); expect(renderLegend).toHaveBeenCalledTimes(1); expect(wrapper.render().find('div.chart')).toHaveLength(1); expect(wrapper.render().find('div.legend')).toHaveLength(1); }, 100); }); it('renders legend on the bottom', () => { const wrapper = mount( <WithLegend debounceTime={1} position="bottom" renderChart={renderChart} renderLegend={renderLegend} />, ); triggerResizeObserver(); // Have to delay more than debounceTime (1ms) return promiseTimeout(() => { expect(renderChart).toHaveBeenCalledTimes(1); expect(renderLegend).toHaveBeenCalledTimes(1); expect(wrapper.render().find('div.chart')).toHaveLength(1); expect(wrapper.render().find('div.legend')).toHaveLength(1); }, 100); }); it('renders legend with justifyContent set', () => { const wrapper = mount( <WithLegend debounceTime={1} position="right" legendJustifyContent="flex-start" renderChart={renderChart} renderLegend={renderLegend} />, ); triggerResizeObserver(); // Have to delay more than debounceTime (1ms) return promiseTimeout(() => { expect(renderChart).toHaveBeenCalledTimes(1); expect(renderLegend).toHaveBeenCalledTimes(1); expect(wrapper.render().find('div.chart')).toHaveLength(1); expect(wrapper.render().find('div.legend')).toHaveLength(1); }, 100); }); });
5,481
0
petrpan-code/apache/superset/superset-frontend/packages/superset-ui-core/test/chart-composition
petrpan-code/apache/superset/superset-frontend/packages/superset-ui-core/test/chart-composition/tooltip/TooltipFrame.test.tsx
/* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ import React from 'react'; import { shallow } from 'enzyme'; import { TooltipFrame } from '@superset-ui/core'; describe('TooltipFrame', () => { it('sets className', () => { const wrapper = shallow( <TooltipFrame className="test-class"> <span>Hi!</span> </TooltipFrame>, ); expect(wrapper.hasClass('test-class')).toEqual(true); }); it('renders', () => { const wrapper = shallow( <TooltipFrame> <span>Hi!</span> </TooltipFrame>, ); const span = wrapper.find('span'); expect(span).toHaveLength(1); expect(span.text()).toEqual('Hi!'); }); });
5,482
0
petrpan-code/apache/superset/superset-frontend/packages/superset-ui-core/test/chart-composition
petrpan-code/apache/superset/superset-frontend/packages/superset-ui-core/test/chart-composition/tooltip/TooltipTable.test.tsx
/* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ import React from 'react'; import { shallow } from 'enzyme'; import { TooltipTable } from '@superset-ui/core'; describe('TooltipTable', () => { it('sets className', () => { const wrapper = shallow(<TooltipTable className="test-class" />); expect(wrapper.render().hasClass('test-class')).toEqual(true); }); it('renders empty table', () => { const wrapper = shallow(<TooltipTable />); expect(wrapper.find('tbody')).toHaveLength(1); expect(wrapper.find('tr')).toHaveLength(0); }); it('renders table with content', () => { const wrapper = shallow( <TooltipTable data={[ { key: 'Cersei', keyColumn: 'Cersei', keyStyle: { padding: '10' }, valueColumn: 2, valueStyle: { textAlign: 'right' }, }, { key: 'Jaime', keyColumn: 'Jaime', keyStyle: { padding: '10' }, valueColumn: 1, valueStyle: { textAlign: 'right' }, }, { key: 'Tyrion', keyStyle: { padding: '10' }, valueColumn: 2, }, ]} />, ); expect(wrapper.find('tbody')).toHaveLength(1); expect(wrapper.find('tr')).toHaveLength(3); expect(wrapper.find('tr > td').first().text()).toEqual('Cersei'); }); });
5,483
0
petrpan-code/apache/superset/superset-frontend/packages/superset-ui-core/test
petrpan-code/apache/superset/superset-frontend/packages/superset-ui-core/test/chart/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 { ChartClient, ChartMetadata, ChartPlugin, ChartProps, createLoadableRenderer, getChartBuildQueryRegistry, getChartComponentRegistry, getChartControlPanelRegistry, getChartMetadataRegistry, getChartTransformPropsRegistry, reactify, } from '@superset-ui/core'; describe('index', () => { it('exports modules', () => { [ ChartClient, ChartMetadata, ChartPlugin, ChartProps, createLoadableRenderer, getChartBuildQueryRegistry, getChartComponentRegistry, getChartControlPanelRegistry, getChartMetadataRegistry, getChartTransformPropsRegistry, reactify, ].forEach(x => expect(x).toBeDefined()); }); });
5,484
0
petrpan-code/apache/superset/superset-frontend/packages/superset-ui-core/test/chart
petrpan-code/apache/superset/superset-frontend/packages/superset-ui-core/test/chart/clients/ChartClient.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 { SupersetClientClass, SupersetClient, buildQueryContext, QueryFormData, configure as configureTranslation, ChartClient, getChartBuildQueryRegistry, getChartMetadataRegistry, ChartMetadata, } from '@superset-ui/core'; import { LOGIN_GLOB } from '../fixtures/constants'; import { sankeyFormData } from '../fixtures/formData'; import { SliceIdAndOrFormData } from '../../../src/chart/clients/ChartClient'; configureTranslation(); describe('ChartClient', () => { let chartClient: ChartClient; beforeAll(() => { fetchMock.get(LOGIN_GLOB, { result: '1234' }); SupersetClient.reset(); SupersetClient.configure().init(); }); beforeEach(() => { chartClient = new ChartClient(); }); afterEach(fetchMock.restore); describe('new ChartClient(config)', () => { it('creates a client without argument', () => { expect(chartClient).toBeInstanceOf(ChartClient); }); it('creates a client with specified config.client', () => { const customClient = new SupersetClientClass(); chartClient = new ChartClient({ client: customClient }); expect(chartClient).toBeInstanceOf(ChartClient); expect(chartClient.client).toBe(customClient); }); }); describe('.loadFormData({ sliceId, formData }, options)', () => { const sliceId = 123; it('fetches formData if given only sliceId', () => { fetchMock.get( `glob:*/api/v1/form_data/?slice_id=${sliceId}`, sankeyFormData, ); return expect(chartClient.loadFormData({ sliceId })).resolves.toEqual( sankeyFormData, ); }); it('fetches formData from sliceId and merges with specify formData if both fields are specified', () => { fetchMock.get( `glob:*/api/v1/form_data/?slice_id=${sliceId}`, sankeyFormData, ); return expect( chartClient.loadFormData({ sliceId, formData: { granularity: 'second', viz_type: 'bar', }, }), ).resolves.toEqual({ ...sankeyFormData, granularity: 'second', viz_type: 'bar', }); }); it('returns promise of formData if only formData was given', () => expect( chartClient.loadFormData({ formData: { datasource: '1__table', granularity: 'minute', viz_type: 'line', }, }), ).resolves.toEqual({ datasource: '1__table', granularity: 'minute', viz_type: 'line', })); it('rejects if none of sliceId or formData is specified', () => expect( chartClient.loadFormData({} as SliceIdAndOrFormData), ).rejects.toEqual( new Error('At least one of sliceId or formData must be specified'), )); }); describe('.loadQueryData(formData, options)', () => { it('returns a promise of query data for known chart type', () => { getChartMetadataRegistry().registerValue( 'word_cloud', new ChartMetadata({ name: 'Word Cloud', thumbnail: '' }), ); getChartBuildQueryRegistry().registerValue( 'word_cloud', (formData: QueryFormData) => buildQueryContext(formData), ); fetchMock.post('glob:*/api/v1/chart/data', [ { field1: 'abc', field2: 'def', }, ]); return expect( chartClient.loadQueryData({ granularity: 'minute', viz_type: 'word_cloud', datasource: '1__table', }), ).resolves.toEqual([ { field1: 'abc', field2: 'def', }, ]); }); it('returns a promise that rejects for unknown chart type', () => expect( chartClient.loadQueryData({ granularity: 'minute', viz_type: 'rainbow_3d_pie', datasource: '1__table', }), ).rejects.toEqual(new Error('Unknown chart type: rainbow_3d_pie'))); it('fetches data from the legacy API if ChartMetadata has useLegacyApi=true,', () => { // note legacy charts do not register a buildQuery function in the registry getChartMetadataRegistry().registerValue( 'word_cloud_legacy', new ChartMetadata({ name: 'Legacy Word Cloud', thumbnail: '.png', useLegacyApi: true, }), ); fetchMock.post('glob:*/api/v1/chart/data', () => Promise.reject(new Error('Unexpected all to v1 API')), ); fetchMock.post('glob:*/superset/explore_json/', { field1: 'abc', field2: 'def', }); return expect( chartClient.loadQueryData({ granularity: 'minute', viz_type: 'word_cloud_legacy', datasource: '1__table', }), ).resolves.toEqual([ { field1: 'abc', field2: 'def', }, ]); }); }); describe('.loadDatasource(datasourceKey, options)', () => { it('fetches datasource', () => { fetchMock.get( 'glob:*/superset/fetch_datasource_metadata?datasourceKey=1__table', { field1: 'abc', field2: 'def', }, ); return expect(chartClient.loadDatasource('1__table')).resolves.toEqual({ field1: 'abc', field2: 'def', }); }); }); describe('.loadAnnotation(annotationLayer)', () => { it('returns an empty object if the annotation layer does not require query', () => expect( chartClient.loadAnnotation({ name: 'my-annotation', }), ).resolves.toEqual({})); it('otherwise returns a rejected promise because it is not implemented yet', () => expect( chartClient.loadAnnotation({ name: 'my-annotation', sourceType: 'abc', }), ).rejects.toEqual(new Error('This feature is not implemented yet.'))); }); describe('.loadAnnotations(annotationLayers)', () => { it('loads multiple annotation layers and combine results', () => expect( chartClient.loadAnnotations([ { name: 'anno1', }, { name: 'anno2', }, { name: 'anno3', }, ]), ).resolves.toEqual({ anno1: {}, anno2: {}, anno3: {}, })); it('returns an empty object if input is not an array', () => expect(chartClient.loadAnnotations()).resolves.toEqual({})); it('returns an empty object if input is an empty array', () => expect(chartClient.loadAnnotations()).resolves.toEqual({})); }); describe('.loadChartData({ sliceId, formData })', () => { const sliceId = 10120; it('loadAllDataNecessaryForAChart', () => { fetchMock.get(`glob:*/api/v1/form_data/?slice_id=${sliceId}`, { granularity: 'minute', viz_type: 'line', datasource: '1__table', color: 'living-coral', }); fetchMock.get( 'glob:*/superset/fetch_datasource_metadata?datasourceKey=1__table', { name: 'transactions', schema: 'staging', }, ); fetchMock.post('glob:*/api/v1/chart/data', { lorem: 'ipsum', dolor: 'sit', amet: true, }); getChartMetadataRegistry().registerValue( 'line', new ChartMetadata({ name: 'Line', thumbnail: '.gif' }), ); getChartBuildQueryRegistry().registerValue( 'line', (formData: QueryFormData) => buildQueryContext(formData), ); return expect( chartClient.loadChartData({ sliceId, }), ).resolves.toEqual({ annotationData: {}, datasource: { name: 'transactions', schema: 'staging', }, formData: { granularity: 'minute', viz_type: 'line', datasource: '1__table', color: 'living-coral', }, queriesData: [ { lorem: 'ipsum', dolor: 'sit', amet: true, }, ], }); }); }); });
5,485
0
petrpan-code/apache/superset/superset-frontend/packages/superset-ui-core/test/chart
petrpan-code/apache/superset/superset-frontend/packages/superset-ui-core/test/chart/components/ChartDataProvider.test.tsx
/* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ import React from 'react'; import { shallow } from 'enzyme'; import ChartClient from '../../../src/chart/clients/ChartClient'; import ChartDataProvider, { ChartDataProviderProps, } from '../../../src/chart/components/ChartDataProvider'; import { bigNumberFormData } from '../fixtures/formData'; // Note: the mock implementation of these function directly affects the expected results below const defaultMockLoadFormData = jest.fn(({ formData }: { formData: unknown }) => Promise.resolve(formData), ); type MockLoadFormData = | typeof defaultMockLoadFormData | jest.Mock<Promise<unknown>, unknown[]>; let mockLoadFormData: MockLoadFormData = defaultMockLoadFormData; function createPromise<T>(input: T) { return Promise.resolve(input); } function createArrayPromise<T>(input: T) { return Promise.resolve([input]); } const mockLoadDatasource = jest.fn<Promise<unknown>, unknown[]>(createPromise); const mockLoadQueryData = jest.fn<Promise<unknown>, unknown[]>( createArrayPromise, ); // ChartClient is now a mock jest.mock('../../../src/chart/clients/ChartClient', () => jest.fn().mockImplementation(() => ({ loadDatasource: mockLoadDatasource, loadFormData: mockLoadFormData, loadQueryData: mockLoadQueryData, })), ); const ChartClientMock = ChartClient as jest.Mock<ChartClient>; describe('ChartDataProvider', () => { beforeEach(() => { ChartClientMock.mockClear(); mockLoadFormData = defaultMockLoadFormData; mockLoadFormData.mockClear(); mockLoadDatasource.mockClear(); mockLoadQueryData.mockClear(); }); const props: ChartDataProviderProps = { formData: { ...bigNumberFormData }, children: () => <div />, }; function setup(overrideProps?: Partial<ChartDataProviderProps>) { return shallow(<ChartDataProvider {...props} {...overrideProps} />); } it('instantiates a new ChartClient()', () => { setup(); expect(ChartClientMock).toHaveBeenCalledTimes(1); }); describe('ChartClient.loadFormData', () => { it('calls method on mount', () => { setup(); expect(mockLoadFormData.mock.calls).toHaveLength(1); expect(mockLoadFormData.mock.calls[0][0]).toEqual({ sliceId: props.sliceId, formData: props.formData, }); }); it('should pass formDataRequestOptions to ChartClient.loadFormData', () => { const options = { host: 'override' }; setup({ formDataRequestOptions: options }); expect(mockLoadFormData.mock.calls).toHaveLength(1); expect(mockLoadFormData.mock.calls[0][1]).toEqual(options); }); it('calls ChartClient.loadFormData when formData or sliceId change', () => { const wrapper = setup(); const newProps = { sliceId: 123, formData: undefined }; expect(mockLoadFormData.mock.calls).toHaveLength(1); wrapper.setProps(newProps); expect(mockLoadFormData.mock.calls).toHaveLength(2); expect(mockLoadFormData.mock.calls[1][0]).toEqual(newProps); }); }); describe('ChartClient.loadDatasource', () => { it('does not method if loadDatasource is false', () => new Promise(done => { expect.assertions(1); setup({ loadDatasource: false }); setTimeout(() => { expect(mockLoadDatasource.mock.calls).toHaveLength(0); done(undefined); }, 0); })); it('calls method on mount if loadDatasource is true', () => new Promise(done => { expect.assertions(2); setup({ loadDatasource: true }); setTimeout(() => { expect(mockLoadDatasource.mock.calls).toHaveLength(1); expect(mockLoadDatasource.mock.calls[0][0]).toEqual( props.formData.datasource, ); done(undefined); }, 0); })); it('should pass datasourceRequestOptions to ChartClient.loadDatasource', () => new Promise(done => { expect.assertions(2); const options = { host: 'override' }; setup({ loadDatasource: true, datasourceRequestOptions: options }); setTimeout(() => { expect(mockLoadDatasource.mock.calls).toHaveLength(1); expect(mockLoadDatasource.mock.calls[0][1]).toEqual(options); done(undefined); }, 0); })); it('calls ChartClient.loadDatasource if loadDatasource is true and formData or sliceId change', () => new Promise(done => { expect.assertions(3); const newDatasource = 'test'; const wrapper = setup({ loadDatasource: true }); wrapper.setProps({ formData: { datasource: newDatasource }, sliceId: undefined, }); setTimeout(() => { expect(mockLoadDatasource.mock.calls).toHaveLength(2); expect(mockLoadDatasource.mock.calls[0][0]).toEqual( props.formData.datasource, ); expect(mockLoadDatasource.mock.calls[1][0]).toEqual(newDatasource); done(undefined); }, 0); })); }); describe('ChartClient.loadQueryData', () => { it('calls method on mount', () => new Promise(done => { expect.assertions(2); setup(); setTimeout(() => { expect(mockLoadQueryData.mock.calls).toHaveLength(1); expect(mockLoadQueryData.mock.calls[0][0]).toEqual(props.formData); done(undefined); }, 0); })); it('should pass queryDataRequestOptions to ChartClient.loadQueryData', () => new Promise(done => { expect.assertions(2); const options = { host: 'override' }; setup({ queryRequestOptions: options }); setTimeout(() => { expect(mockLoadQueryData.mock.calls).toHaveLength(1); expect(mockLoadQueryData.mock.calls[0][1]).toEqual(options); done(undefined); }, 0); })); it('calls ChartClient.loadQueryData when formData or sliceId change', () => new Promise(done => { expect.assertions(3); const newFormData = { key: 'test' }; const wrapper = setup(); wrapper.setProps({ formData: newFormData, sliceId: undefined }); setTimeout(() => { expect(mockLoadQueryData.mock.calls).toHaveLength(2); expect(mockLoadQueryData.mock.calls[0][0]).toEqual(props.formData); expect(mockLoadQueryData.mock.calls[1][0]).toEqual(newFormData); done(undefined); }, 0); })); }); describe('children', () => { it('calls children({ loading: true }) when loading', () => { const children = jest.fn<React.ReactNode, unknown[]>(); setup({ children }); // during the first tick (before more promises resolve) loading is true expect(children.mock.calls).toHaveLength(1); expect(children.mock.calls[0][0]).toEqual({ loading: true }); }); it('calls children({ payload }) when loaded', () => new Promise(done => { expect.assertions(2); const children = jest.fn<React.ReactNode, unknown[]>(); setup({ children, loadDatasource: true }); setTimeout(() => { expect(children.mock.calls).toHaveLength(2); expect(children.mock.calls[1][0]).toEqual({ payload: { formData: props.formData, datasource: props.formData.datasource, queriesData: [props.formData], }, }); done(undefined); }, 0); })); it('calls children({ error }) upon request error', () => new Promise(done => { expect.assertions(2); const children = jest.fn<React.ReactNode, unknown[]>(); mockLoadFormData = jest.fn(() => Promise.reject(new Error('error'))); setup({ children }); setTimeout(() => { expect(children.mock.calls).toHaveLength(2); // loading + error expect(children.mock.calls[1][0]).toEqual({ error: new Error('error'), }); done(undefined); }, 0); })); it('calls children({ error }) upon JS error', () => new Promise(done => { expect.assertions(2); const children = jest.fn<React.ReactNode, unknown[]>(); mockLoadFormData = jest.fn(() => { throw new Error('non-async error'); }); setup({ children }); setTimeout(() => { expect(children.mock.calls).toHaveLength(2); // loading + error expect(children.mock.calls[1][0]).toEqual({ error: new Error('non-async error'), }); done(undefined); }, 0); })); }); describe('callbacks', () => { it('calls onLoad(payload) when loaded', () => new Promise(done => { expect.assertions(2); const onLoaded = jest.fn<void, unknown[]>(); setup({ onLoaded, loadDatasource: true }); setTimeout(() => { expect(onLoaded.mock.calls).toHaveLength(1); expect(onLoaded.mock.calls[0][0]).toEqual({ formData: props.formData, datasource: props.formData.datasource, queriesData: [props.formData], }); done(undefined); }, 0); })); it('calls onError(error) upon request error', () => new Promise(done => { expect.assertions(2); const onError = jest.fn<void, unknown[]>(); mockLoadFormData = jest.fn(() => Promise.reject(new Error('error'))); setup({ onError }); setTimeout(() => { expect(onError.mock.calls).toHaveLength(1); expect(onError.mock.calls[0][0]).toEqual(new Error('error')); done(undefined); }, 0); })); it('calls onError(error) upon JS error', () => new Promise(done => { expect.assertions(2); const onError = jest.fn<void, unknown[]>(); mockLoadFormData = jest.fn(() => { throw new Error('non-async error'); }); setup({ onError }); setTimeout(() => { expect(onError.mock.calls).toHaveLength(1); expect(onError.mock.calls[0][0]).toEqual( new Error('non-async error'), ); done(undefined); }, 0); })); }); });
5,486
0
petrpan-code/apache/superset/superset-frontend/packages/superset-ui-core/test/chart
petrpan-code/apache/superset/superset-frontend/packages/superset-ui-core/test/chart/components/FallbackComponent.test.tsx
/* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ import React from 'react'; import { shallow } from 'enzyme'; import FallbackComponent from '../../../src/chart/components/FallbackComponent'; describe('FallbackComponent', () => { const ERROR = new Error('CaffeineOverLoadException'); const STACK_TRACE = 'Error at line 1: x.drink(coffee)'; it('renders error and stack trace', () => { const wrapper = shallow( <FallbackComponent componentStack={STACK_TRACE} error={ERROR} />, ); const messages = wrapper.find('code'); expect(messages).toHaveLength(2); expect(messages.at(0).text()).toEqual('Error: CaffeineOverLoadException'); expect(messages.at(1).text()).toEqual('Error at line 1: x.drink(coffee)'); }); it('renders error only', () => { const wrapper = shallow(<FallbackComponent error={ERROR} />); const messages = wrapper.find('code'); expect(messages).toHaveLength(1); expect(messages.at(0).text()).toEqual('Error: CaffeineOverLoadException'); }); it('renders stacktrace only', () => { const wrapper = shallow(<FallbackComponent componentStack={STACK_TRACE} />); const messages = wrapper.find('code'); expect(messages).toHaveLength(2); expect(messages.at(0).text()).toEqual('Unknown Error'); expect(messages.at(1).text()).toEqual('Error at line 1: x.drink(coffee)'); }); it('renders when nothing is given', () => { const wrapper = shallow(<FallbackComponent />); const messages = wrapper.find('code'); expect(messages).toHaveLength(1); expect(messages.at(0).text()).toEqual('Unknown Error'); }); });
5,488
0
petrpan-code/apache/superset/superset-frontend/packages/superset-ui-core/test/chart
petrpan-code/apache/superset/superset-frontend/packages/superset-ui-core/test/chart/components/NoResultsComponent.test.tsx
/* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ import React from 'react'; import { shallow } from 'enzyme'; import { configure } from '@superset-ui/core'; import NoResultsComponent from '../../../src/chart/components/NoResultsComponent'; configure(); describe('NoResultsComponent', () => { it('renders the no results error', () => { const wrapper = shallow(<NoResultsComponent height="400" width="300" />); expect(wrapper.text()).toEqual( 'No ResultsNo results were returned for this query. If you expected results to be returned, ensure any filters are configured properly and the datasource contains data for the selected time range.', ); }); });
5,489
0
petrpan-code/apache/superset/superset-frontend/packages/superset-ui-core/test/chart
petrpan-code/apache/superset/superset-frontend/packages/superset-ui-core/test/chart/components/SuperChart.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, { ReactElement } from 'react'; import mockConsole, { RestoreConsole } from 'jest-mock-console'; import { triggerResizeObserver } from 'resize-observer-polyfill'; import ErrorBoundary from 'react-error-boundary'; import { promiseTimeout, SuperChart, supersetTheme, ThemeProvider, } from '@superset-ui/core'; import { mount as enzymeMount } from 'enzyme'; import { WrapperProps } from '../../../src/chart/components/SuperChart'; import NoResultsComponent from '../../../src/chart/components/NoResultsComponent'; import { ChartKeys, DiligentChartPlugin, BuggyChartPlugin, } from './MockChartPlugins'; const DEFAULT_QUERY_DATA = { data: ['foo', 'bar'] }; const DEFAULT_QUERIES_DATA = [ { data: ['foo', 'bar'] }, { data: ['foo2', 'bar2'] }, ]; function expectDimension( renderedWrapper: Cheerio, width: number, height: number, ) { expect(renderedWrapper.find('.dimension').text()).toEqual( [width, height].join('x'), ); } const mount = (component: ReactElement) => enzymeMount(component, { wrappingComponent: ThemeProvider, wrappingComponentProps: { theme: supersetTheme }, }); describe('SuperChart', () => { const plugins = [ new DiligentChartPlugin().configure({ key: ChartKeys.DILIGENT }), new BuggyChartPlugin().configure({ key: ChartKeys.BUGGY }), ]; let restoreConsole: RestoreConsole; beforeAll(() => { plugins.forEach(p => { p.unregister().register(); }); }); afterAll(() => { plugins.forEach(p => { p.unregister(); }); }); beforeEach(() => { restoreConsole = mockConsole(); }); afterEach(() => { restoreConsole(); }); describe('includes ErrorBoundary', () => { let expectedErrors = 0; let actualErrors = 0; function onError(e: Event) { e.preventDefault(); actualErrors += 1; } beforeEach(() => { expectedErrors = 0; actualErrors = 0; window.addEventListener('error', onError); }); afterEach(() => { window.removeEventListener('error', onError); // eslint-disable-next-line jest/no-standalone-expect expect(actualErrors).toBe(expectedErrors); expectedErrors = 0; }); it('renders default FallbackComponent', async () => { expectedErrors = 1; const wrapper = mount( <SuperChart chartType={ChartKeys.BUGGY} queriesData={[DEFAULT_QUERY_DATA]} width="200" height="200" />, ); await new Promise(resolve => setImmediate(resolve)); wrapper.update(); expect(wrapper.text()).toContain('Oops! An error occurred!'); }); it('renders custom FallbackComponent', () => { expectedErrors = 1; const CustomFallbackComponent = jest.fn(() => ( <div>Custom Fallback!</div> )); const wrapper = mount( <SuperChart chartType={ChartKeys.BUGGY} queriesData={[DEFAULT_QUERY_DATA]} width="200" height="200" FallbackComponent={CustomFallbackComponent} />, ); return promiseTimeout(() => { expect(wrapper.render().find('div.test-component')).toHaveLength(0); expect(CustomFallbackComponent).toHaveBeenCalledTimes(1); }); }); it('call onErrorBoundary', () => { expectedErrors = 1; const handleError = jest.fn(); mount( <SuperChart chartType={ChartKeys.BUGGY} queriesData={[DEFAULT_QUERY_DATA]} width="200" height="200" onErrorBoundary={handleError} />, ); return promiseTimeout(() => { expect(handleError).toHaveBeenCalledTimes(1); }); }); it('does not include ErrorBoundary if told so', () => { expectedErrors = 1; const inactiveErrorHandler = jest.fn(); const activeErrorHandler = jest.fn(); mount( <ErrorBoundary onError={activeErrorHandler}> <SuperChart disableErrorBoundary chartType={ChartKeys.BUGGY} queriesData={[DEFAULT_QUERY_DATA]} width="200" height="200" onErrorBoundary={inactiveErrorHandler} /> </ErrorBoundary>, ); return promiseTimeout(() => { expect(activeErrorHandler).toHaveBeenCalledTimes(1); expect(inactiveErrorHandler).toHaveBeenCalledTimes(0); }); }); }); it('passes the props to renderer correctly', () => { const wrapper = mount( <SuperChart chartType={ChartKeys.DILIGENT} queriesData={[DEFAULT_QUERY_DATA]} width={101} height={118} formData={{ abc: 1 }} />, ); return promiseTimeout(() => { const renderedWrapper = wrapper.render(); expect(renderedWrapper.find('div.test-component')).toHaveLength(1); expectDimension(renderedWrapper, 101, 118); }); }); it('passes the props with multiple queries to renderer correctly', () => { const wrapper = mount( <SuperChart chartType={ChartKeys.DILIGENT} queriesData={DEFAULT_QUERIES_DATA} width={101} height={118} formData={{ abc: 1 }} />, ); return promiseTimeout(() => { const renderedWrapper = wrapper.render(); expect(renderedWrapper.find('div.test-component')).toHaveLength(1); expectDimension(renderedWrapper, 101, 118); }); }); it('passes the props with multiple queries and single query to renderer correctly (backward compatibility)', () => { const wrapper = mount( <SuperChart chartType={ChartKeys.DILIGENT} queriesData={DEFAULT_QUERIES_DATA} width={101} height={118} formData={{ abc: 1 }} />, ); return promiseTimeout(() => { const renderedWrapper = wrapper.render(); expect(renderedWrapper.find('div.test-component')).toHaveLength(1); expectDimension(renderedWrapper, 101, 118); }); }); describe('supports NoResultsComponent', () => { it('renders NoResultsComponent when queriesData is missing', () => { const wrapper = mount( <SuperChart chartType={ChartKeys.DILIGENT} width="200" height="200" />, ); expect(wrapper.find(NoResultsComponent)).toHaveLength(1); }); it('renders NoResultsComponent when queriesData data is null', () => { const wrapper = mount( <SuperChart chartType={ChartKeys.DILIGENT} queriesData={[{ data: null }]} width="200" height="200" />, ); expect(wrapper.find(NoResultsComponent)).toHaveLength(1); }); }); describe('supports dynamic width and/or height', () => { it('works with width and height that are numbers', () => { const wrapper = mount( <SuperChart chartType={ChartKeys.DILIGENT} queriesData={[DEFAULT_QUERY_DATA]} width={100} height={100} />, ); return promiseTimeout(() => { const renderedWrapper = wrapper.render(); expect(renderedWrapper.find('div.test-component')).toHaveLength(1); expectDimension(renderedWrapper, 100, 100); }); }); it('works when width and height are percent', () => { const wrapper = mount( <SuperChart chartType={ChartKeys.DILIGENT} queriesData={[DEFAULT_QUERY_DATA]} debounceTime={1} width="100%" height="100%" />, ); triggerResizeObserver(); return promiseTimeout(() => { const renderedWrapper = wrapper.render(); expect(renderedWrapper.find('div.test-component')).toHaveLength(1); expectDimension(renderedWrapper, 300, 300); }, 100); }); it('works when only width is percent', () => { const wrapper = mount( <SuperChart chartType={ChartKeys.DILIGENT} queriesData={[DEFAULT_QUERY_DATA]} debounceTime={1} width="50%" height="125" />, ); // @ts-ignore triggerResizeObserver([{ contentRect: { height: 125, width: 150 } }]); return promiseTimeout(() => { const renderedWrapper = wrapper.render(); const boundingBox = renderedWrapper .find('div.test-component') .parent() .parent() .parent(); expect(boundingBox.css('width')).toEqual('50%'); expect(boundingBox.css('height')).toEqual('125px'); expect(renderedWrapper.find('div.test-component')).toHaveLength(1); expectDimension(renderedWrapper, 150, 125); }, 100); }); it('works when only height is percent', () => { const wrapper = mount( <SuperChart chartType={ChartKeys.DILIGENT} queriesData={[DEFAULT_QUERY_DATA]} debounceTime={1} width="50" height="25%" />, ); // @ts-ignore triggerResizeObserver([{ contentRect: { height: 75, width: 50 } }]); return promiseTimeout(() => { const renderedWrapper = wrapper.render(); const boundingBox = renderedWrapper .find('div.test-component') .parent() .parent() .parent(); expect(boundingBox.css('width')).toEqual('50px'); expect(boundingBox.css('height')).toEqual('25%'); expect(renderedWrapper.find('div.test-component')).toHaveLength(1); expectDimension(renderedWrapper, 50, 75); }, 100); }); it('works when width and height are not specified', () => { const wrapper = mount( <SuperChart chartType={ChartKeys.DILIGENT} queriesData={[DEFAULT_QUERY_DATA]} debounceTime={1} />, ); triggerResizeObserver(); return promiseTimeout(() => { const renderedWrapper = wrapper.render(); expect(renderedWrapper.find('div.test-component')).toHaveLength(1); expectDimension(renderedWrapper, 300, 400); }, 100); }); }); describe('supports Wrapper', () => { function MyWrapper({ width, height, children }: WrapperProps) { return ( <div> <div className="wrapper-insert"> {width}x{height} </div> {children} </div> ); } it('works with width and height that are numbers', () => { const wrapper = mount( <SuperChart chartType={ChartKeys.DILIGENT} queriesData={[DEFAULT_QUERY_DATA]} width={100} height={100} Wrapper={MyWrapper} />, ); return promiseTimeout(() => { const renderedWrapper = wrapper.render(); expect(renderedWrapper.find('div.wrapper-insert')).toHaveLength(1); expect(renderedWrapper.find('div.wrapper-insert').text()).toEqual( '100x100', ); expect(renderedWrapper.find('div.test-component')).toHaveLength(1); expectDimension(renderedWrapper, 100, 100); }, 100); }); it('works when width and height are percent', () => { const wrapper = mount( <SuperChart chartType={ChartKeys.DILIGENT} queriesData={[DEFAULT_QUERY_DATA]} debounceTime={1} width="100%" height="100%" Wrapper={MyWrapper} />, ); triggerResizeObserver(); return promiseTimeout(() => { const renderedWrapper = wrapper.render(); expect(renderedWrapper.find('div.wrapper-insert')).toHaveLength(1); expect(renderedWrapper.find('div.wrapper-insert').text()).toEqual( '300x300', ); expect(renderedWrapper.find('div.test-component')).toHaveLength(1); expectDimension(renderedWrapper, 300, 300); }, 100); }); }); });
5,490
0
petrpan-code/apache/superset/superset-frontend/packages/superset-ui-core/test/chart
petrpan-code/apache/superset/superset-frontend/packages/superset-ui-core/test/chart/components/SuperChartCore.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, { ReactElement, ReactNode } from 'react'; import { mount } from 'enzyme'; import mockConsole, { RestoreConsole } from 'jest-mock-console'; import { ChartProps, promiseTimeout, supersetTheme, SupersetTheme, ThemeProvider, } from '@superset-ui/core'; import SuperChartCore from '../../../src/chart/components/SuperChartCore'; import { ChartKeys, DiligentChartPlugin, LazyChartPlugin, SlowChartPlugin, } from './MockChartPlugins'; const Wrapper = ({ theme, children, }: { theme: SupersetTheme; children: ReactNode; }) => <ThemeProvider theme={theme}>{children}</ThemeProvider>; const styledMount = (component: ReactElement) => mount(component, { wrappingComponent: Wrapper, wrappingComponentProps: { theme: supersetTheme, }, }); describe('SuperChartCore', () => { const chartProps = new ChartProps(); const plugins = [ new DiligentChartPlugin().configure({ key: ChartKeys.DILIGENT }), new LazyChartPlugin().configure({ key: ChartKeys.LAZY }), new SlowChartPlugin().configure({ key: ChartKeys.SLOW }), ]; let restoreConsole: RestoreConsole; beforeAll(() => { plugins.forEach(p => { p.unregister().register(); }); }); afterAll(() => { plugins.forEach(p => { p.unregister(); }); }); beforeEach(() => { restoreConsole = mockConsole(); }); afterEach(() => { restoreConsole(); }); describe('registered charts', () => { it('renders registered chart', () => { const wrapper = styledMount( <SuperChartCore chartType={ChartKeys.DILIGENT} chartProps={chartProps} />, ); return promiseTimeout(() => { expect(wrapper.render().find('div.test-component')).toHaveLength(1); }); }); it('renders registered chart with lazy loading', () => { const wrapper = styledMount( <SuperChartCore chartType={ChartKeys.LAZY} />, ); return promiseTimeout(() => { expect(wrapper.render().find('div.test-component')).toHaveLength(1); }); }); it('does not render if chartType is not set', () => { // Suppress warning // @ts-ignore chartType is required const wrapper = styledMount(<SuperChartCore />); return promiseTimeout(() => { expect(wrapper.render().children()).toHaveLength(0); }, 5); }); it('adds id to container if specified', () => { const wrapper = styledMount( <SuperChartCore chartType={ChartKeys.DILIGENT} id="the-chart" />, ); return promiseTimeout(() => { expect(wrapper.render().attr('id')).toEqual('the-chart'); }); }); it('adds class to container if specified', () => { const wrapper = styledMount( <SuperChartCore chartType={ChartKeys.DILIGENT} className="the-chart" />, ); return promiseTimeout(() => { expect(wrapper.hasClass('the-chart')).toBeTruthy(); }, 0); }); it('uses overrideTransformProps when specified', () => { const wrapper = styledMount( <SuperChartCore chartType={ChartKeys.DILIGENT} overrideTransformProps={() => ({ message: 'hulk' })} />, ); return promiseTimeout(() => { expect(wrapper.render().find('.message').text()).toEqual('hulk'); }); }); it('uses preTransformProps when specified', () => { const chartPropsWithPayload = new ChartProps({ queriesData: [{ message: 'hulk' }], theme: supersetTheme, }); const wrapper = styledMount( <SuperChartCore chartType={ChartKeys.DILIGENT} preTransformProps={() => chartPropsWithPayload} overrideTransformProps={props => props.queriesData[0]} />, ); return promiseTimeout(() => { expect(wrapper.render().find('.message').text()).toEqual('hulk'); }); }); it('uses postTransformProps when specified', () => { const wrapper = styledMount( <SuperChartCore chartType={ChartKeys.DILIGENT} postTransformProps={() => ({ message: 'hulk' })} />, ); return promiseTimeout(() => { expect(wrapper.render().find('.message').text()).toEqual('hulk'); }); }); it('renders if chartProps is not specified', () => { const wrapper = styledMount( <SuperChartCore chartType={ChartKeys.DILIGENT} />, ); return promiseTimeout(() => { expect(wrapper.render().find('div.test-component')).toHaveLength(1); }); }); it('does not render anything while waiting for Chart code to load', () => { const wrapper = styledMount( <SuperChartCore chartType={ChartKeys.SLOW} />, ); return promiseTimeout(() => { expect(wrapper.render().children()).toHaveLength(0); }); }); it('eventually renders after Chart is loaded', () => { // Suppress warning const wrapper = styledMount( <SuperChartCore chartType={ChartKeys.SLOW} />, ); return promiseTimeout(() => { expect(wrapper.render().find('div.test-component')).toHaveLength(1); }, 1500); }); it('does not render if chartProps is null', () => { const wrapper = styledMount( <SuperChartCore chartType={ChartKeys.DILIGENT} chartProps={null} />, ); return promiseTimeout(() => { expect(wrapper.render().find('div.test-component')).toHaveLength(0); }); }); }); describe('unregistered charts', () => { it('renders error message', () => { const wrapper = styledMount( <SuperChartCore chartType="4d-pie-chart" chartProps={chartProps} />, ); return promiseTimeout(() => { expect(wrapper.render().find('.alert')).toHaveLength(1); }); }); }); describe('.processChartProps()', () => { it('use identity functions for unspecified transforms', () => { const chart = new SuperChartCore({ chartType: ChartKeys.DILIGENT, }); const chartProps2 = new ChartProps(); expect(chart.processChartProps({ chartProps: chartProps2 })).toBe( chartProps2, ); }); }); });
5,491
0
petrpan-code/apache/superset/superset-frontend/packages/superset-ui-core/test/chart
petrpan-code/apache/superset/superset-frontend/packages/superset-ui-core/test/chart/components/createLoadableRenderer.test.tsx
/* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ import React from 'react'; import { shallow } from 'enzyme'; import mockConsole, { RestoreConsole } from 'jest-mock-console'; import createLoadableRenderer, { LoadableRenderer as LoadableRendererType, } from '../../../src/chart/components/createLoadableRenderer'; describe('createLoadableRenderer', () => { function TestComponent() { return <div className="test-component">test</div>; } let loadChartSuccess = jest.fn(() => Promise.resolve(TestComponent)); let render: (loaded: { Chart: React.ComponentType }) => JSX.Element; let loading: () => JSX.Element; let LoadableRenderer: LoadableRendererType<{}>; let restoreConsole: RestoreConsole; beforeEach(() => { restoreConsole = mockConsole(); loadChartSuccess = jest.fn(() => Promise.resolve(TestComponent)); render = jest.fn(loaded => { const { Chart } = loaded; return <Chart />; }); loading = jest.fn(() => <div>Loading</div>); LoadableRenderer = createLoadableRenderer({ loader: { Chart: loadChartSuccess, }, loading, render, }); }); afterEach(() => { restoreConsole(); }); describe('returns a LoadableRenderer class', () => { it('LoadableRenderer.preload() preloads the lazy-load components', () => { expect(LoadableRenderer.preload).toBeInstanceOf(Function); LoadableRenderer.preload(); expect(loadChartSuccess).toHaveBeenCalledTimes(1); }); it('calls onRenderSuccess when succeeds', async () => { const onRenderSuccess = jest.fn(); const onRenderFailure = jest.fn(); shallow( <LoadableRenderer onRenderSuccess={onRenderSuccess} onRenderFailure={onRenderFailure} />, ); expect(loadChartSuccess).toHaveBeenCalled(); jest.useRealTimers(); await new Promise(resolve => setTimeout(resolve, 10)); expect(render).toHaveBeenCalledTimes(1); expect(onRenderSuccess).toHaveBeenCalledTimes(1); expect(onRenderFailure).not.toHaveBeenCalled(); }); it('calls onRenderFailure when fails', () => new Promise(done => { const loadChartFailure = jest.fn(() => Promise.reject(new Error('Invalid chart')), ); const FailedRenderer = createLoadableRenderer({ loader: { Chart: loadChartFailure, }, loading, render, }); const onRenderSuccess = jest.fn(); const onRenderFailure = jest.fn(); shallow( <FailedRenderer onRenderSuccess={onRenderSuccess} onRenderFailure={onRenderFailure} />, ); expect(loadChartFailure).toHaveBeenCalledTimes(1); setTimeout(() => { expect(render).not.toHaveBeenCalled(); expect(onRenderSuccess).not.toHaveBeenCalled(); expect(onRenderFailure).toHaveBeenCalledTimes(1); done(undefined); }, 10); })); it('onRenderFailure is optional', () => new Promise(done => { const loadChartFailure = jest.fn(() => Promise.reject(new Error('Invalid chart')), ); const FailedRenderer = createLoadableRenderer({ loader: { Chart: loadChartFailure, }, loading, render, }); shallow(<FailedRenderer />); expect(loadChartFailure).toHaveBeenCalledTimes(1); setTimeout(() => { expect(render).not.toHaveBeenCalled(); done(undefined); }, 10); })); it('renders the lazy-load components', () => new Promise(done => { const wrapper = shallow(<LoadableRenderer />); // lazy-loaded component not rendered immediately expect(wrapper.find(TestComponent)).toHaveLength(0); setTimeout(() => { // but rendered after the component is loaded. expect(wrapper.find(TestComponent)).toHaveLength(1); done(undefined); }, 10); })); it('does not throw if loaders are empty', () => { const NeverLoadingRenderer = createLoadableRenderer({ loader: {}, loading, render: () => <div />, }); expect(() => shallow(<NeverLoadingRenderer />)).not.toThrow(); }); }); });
5,492
0
petrpan-code/apache/superset/superset-frontend/packages/superset-ui-core/test/chart
petrpan-code/apache/superset/superset-frontend/packages/superset-ui-core/test/chart/components/reactify.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 PropTypes from 'prop-types'; import React from 'react'; import { mount } from 'enzyme'; import { reactify } from '@superset-ui/core'; import { RenderFuncType } from '../../../src/chart/components/reactify'; describe('reactify(renderFn)', () => { const renderFn: RenderFuncType<{ content?: string }> = jest.fn( (element, props) => { const container = element; container.innerHTML = ''; const child = document.createElement('b'); child.innerHTML = props.content ?? ''; container.append(child); }, ); renderFn.displayName = 'BoldText'; renderFn.propTypes = { content: PropTypes.string, }; renderFn.defaultProps = { content: 'ghi', }; const willUnmountCb = jest.fn(); const TheChart = reactify(renderFn); const TheChartWithWillUnmountHook = reactify(renderFn, { componentWillUnmount: willUnmountCb, }); class TestComponent extends React.PureComponent<{}, { content: string }> { constructor(props = {}) { super(props); this.state = { content: 'abc' }; } componentDidMount() { setTimeout(() => { this.setState({ content: 'def' }); }, 10); } render() { const { content } = this.state; return <TheChart id="test" content={content} />; } } class AnotherTestComponent extends React.PureComponent<{}, {}> { render() { return <TheChartWithWillUnmountHook id="another_test" />; } } it('returns a React component class', () => new Promise(done => { const wrapper = mount(<TestComponent />); expect(renderFn).toHaveBeenCalledTimes(1); expect(wrapper.html()).toEqual('<div id="test"><b>abc</b></div>'); setTimeout(() => { expect(renderFn).toHaveBeenCalledTimes(2); expect(wrapper.html()).toEqual('<div id="test"><b>def</b></div>'); wrapper.unmount(); done(undefined); }, 20); })); describe('displayName', () => { it('has displayName if renderFn.displayName is defined', () => { expect(TheChart.displayName).toEqual('BoldText'); }); it('does not have displayName if renderFn.displayName is not defined', () => { const AnotherChart = reactify(() => {}); expect(AnotherChart.displayName).toBeUndefined(); }); }); describe('propTypes', () => { it('has propTypes if renderFn.propTypes is defined', () => { /* eslint-disable-next-line react/forbid-foreign-prop-types */ expect(Object.keys(TheChart.propTypes ?? {})).toEqual([ 'id', 'className', 'content', ]); }); it('does not have propTypes if renderFn.propTypes is not defined', () => { const AnotherChart = reactify(() => {}); /* eslint-disable-next-line react/forbid-foreign-prop-types */ expect(Object.keys(AnotherChart.propTypes ?? {})).toEqual([ 'id', 'className', ]); }); }); describe('defaultProps', () => { it('has defaultProps if renderFn.defaultProps is defined', () => { expect(TheChart.defaultProps).toBe(renderFn.defaultProps); const wrapper = mount(<TheChart id="test" />); expect(wrapper.html()).toEqual('<div id="test"><b>ghi</b></div>'); }); it('does not have defaultProps if renderFn.defaultProps is not defined', () => { const AnotherChart = reactify(() => {}); expect(AnotherChart.defaultProps).toBeUndefined(); }); }); it('does not try to render if not mounted', () => { const anotherRenderFn = jest.fn(); const AnotherChart = reactify(anotherRenderFn); // enables valid new AnotherChart() call // @ts-ignore new AnotherChart({ id: 'test' }).execute(); expect(anotherRenderFn).not.toHaveBeenCalled(); }); it('calls willUnmount hook when it is provided', () => new Promise(done => { const wrapper = mount(<AnotherTestComponent />); setTimeout(() => { wrapper.unmount(); expect(willUnmountCb).toHaveBeenCalledTimes(1); done(undefined); }, 20); })); });
5,495
0
petrpan-code/apache/superset/superset-frontend/packages/superset-ui-core/test/chart
petrpan-code/apache/superset/superset-frontend/packages/superset-ui-core/test/chart/models/ChartMetadata.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 { ChartMetadata } from '@superset-ui/core'; describe('ChartMetadata', () => { it('exists', () => { expect(ChartMetadata).toBeDefined(); }); describe('new ChartMetadata({})', () => { it('creates new metadata instance', () => { const metadata = new ChartMetadata({ name: 'test chart', credits: [], description: 'some kind of chart', thumbnail: 'test.png', }); expect(metadata).toBeInstanceOf(ChartMetadata); }); }); describe('.canBeAnnotationType(type)', () => { const metadata = new ChartMetadata({ name: 'test chart', canBeAnnotationTypes: ['event'], credits: [], description: 'some kind of chart', thumbnail: 'test.png', }); it('returns true if can', () => { expect(metadata.canBeAnnotationType('event')).toBeTruthy(); }); it('returns false otherwise', () => { expect(metadata.canBeAnnotationType('invalid-type')).toBeFalsy(); }); }); describe('.clone()', () => { const metadata = new ChartMetadata({ name: 'test chart', canBeAnnotationTypes: ['event'], credits: [], description: 'some kind of chart', thumbnail: 'test.png', }); const clone = metadata.clone(); it('returns a new instance', () => { expect(metadata).not.toBe(clone); }); it('returns a new instance with same field values', () => { expect(metadata.name).toEqual(clone.name); expect(metadata.credits).toEqual(clone.credits); expect(metadata.description).toEqual(clone.description); expect(metadata.canBeAnnotationTypes).toEqual(clone.canBeAnnotationTypes); expect(metadata.thumbnail).toEqual(clone.thumbnail); }); }); });
5,496
0
petrpan-code/apache/superset/superset-frontend/packages/superset-ui-core/test/chart
petrpan-code/apache/superset/superset-frontend/packages/superset-ui-core/test/chart/models/ChartPlugin.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 { ChartPlugin, ChartMetadata, ChartProps, BuildQueryFunction, TransformProps, getChartMetadataRegistry, getChartComponentRegistry, getChartTransformPropsRegistry, getChartBuildQueryRegistry, getChartControlPanelRegistry, QueryFormData, DatasourceType, supersetTheme, } from '@superset-ui/core'; describe('ChartPlugin', () => { const FakeChart = () => <span>test</span>; const metadata = new ChartMetadata({ name: 'test-chart', thumbnail: '', }); const buildQuery = () => ({ datasource: { id: 1, type: DatasourceType.Table }, queries: [{ granularity: 'day' }], force: false, result_format: 'json', result_type: 'full', }); const controlPanel = { abc: 1 }; it('exists', () => { expect(ChartPlugin).toBeDefined(); }); describe('new ChartPlugin()', () => { const FORM_DATA = { datasource: '1__table', granularity: 'day', viz_type: 'table', }; it('creates a new plugin', () => { const plugin = new ChartPlugin({ metadata, Chart: FakeChart, }); expect(plugin).toBeInstanceOf(ChartPlugin); }); describe('buildQuery', () => { it('defaults to undefined', () => { const plugin = new ChartPlugin({ metadata, Chart: FakeChart, }); expect(plugin.loadBuildQuery).toBeUndefined(); }); it('uses loadBuildQuery field if specified', () => { expect.assertions(2); const plugin = new ChartPlugin({ metadata, Chart: FakeChart, loadBuildQuery: () => buildQuery, }); const fn = plugin.loadBuildQuery!() as BuildQueryFunction<QueryFormData>; expect(fn(FORM_DATA).queries[0]).toEqual({ granularity: 'day' }); expect(fn(FORM_DATA).force).toEqual(false); }); it('uses buildQuery field if specified', () => { expect.assertions(1); const plugin = new ChartPlugin({ metadata, Chart: FakeChart, buildQuery, }); const fn = plugin.loadBuildQuery!() as BuildQueryFunction<QueryFormData>; expect(fn(FORM_DATA).queries[0]).toEqual({ granularity: 'day' }); }); }); describe('Chart', () => { it('uses loadChart if specified', () => { const loadChart = () => FakeChart; const plugin = new ChartPlugin({ metadata, loadChart, }); // the loader is sanitized, so assert on the value expect(plugin.loadChart()).toBe(loadChart()); }); it('uses Chart field if specified', () => { const plugin = new ChartPlugin({ metadata, Chart: FakeChart, }); expect(plugin.loadChart()).toEqual(FakeChart); }); it('throws an error if none of Chart or loadChart is specified', () => { expect(() => new ChartPlugin({ metadata })).toThrow(Error); }); }); describe('transformProps', () => { const PROPS = new ChartProps({ formData: FORM_DATA, width: 400, height: 400, queriesData: [{}], theme: supersetTheme, }); it('defaults to identity function', () => { const plugin = new ChartPlugin({ metadata, Chart: FakeChart, }); const fn = plugin.loadTransformProps() as TransformProps; expect(fn(PROPS)).toBe(PROPS); }); it('uses loadTransformProps field if specified', () => { const plugin = new ChartPlugin({ metadata, Chart: FakeChart, loadTransformProps: () => () => ({ field2: 2 }), }); const fn = plugin.loadTransformProps() as TransformProps; expect(fn(PROPS)).toEqual({ field2: 2 }); }); it('uses transformProps field if specified', () => { const plugin = new ChartPlugin({ metadata, Chart: FakeChart, transformProps: () => ({ field2: 2 }), }); const fn = plugin.loadTransformProps() as TransformProps; expect(fn(PROPS)).toEqual({ field2: 2 }); }); }); describe('controlPanel', () => { it('takes controlPanel from input', () => { const plugin = new ChartPlugin({ metadata, Chart: FakeChart, controlPanel, }); expect(plugin.controlPanel).toBe(controlPanel); }); it('defaults to empty object', () => { const plugin = new ChartPlugin({ metadata, Chart: FakeChart, }); expect(plugin.controlPanel).toEqual({}); }); }); }); describe('.register()', () => { let plugin: ChartPlugin; beforeEach(() => { plugin = new ChartPlugin({ metadata, Chart: FakeChart, buildQuery, controlPanel, }); }); it('throws an error if key is not provided', () => { expect(() => plugin.register()).toThrow(Error); expect(() => plugin.configure({ key: 'ab' }).register()).not.toThrow( Error, ); }); it('add the plugin to the registries', () => { plugin.configure({ key: 'cd' }).register(); expect(getChartMetadataRegistry().get('cd')).toBe(metadata); expect(getChartComponentRegistry().get('cd')).toBe(FakeChart); expect(getChartTransformPropsRegistry().has('cd')).toEqual(true); expect(getChartBuildQueryRegistry().get('cd')).toBe(buildQuery); expect(getChartControlPanelRegistry().get('cd')).toBe(controlPanel); }); it('does not register buildQuery when it is not specified in the ChartPlugin', () => { new ChartPlugin({ metadata, Chart: FakeChart, }) .configure({ key: 'ef' }) .register(); expect(getChartBuildQueryRegistry().has('ef')).toEqual(false); }); it('returns itself', () => { expect(plugin.configure({ key: 'gh' }).register()).toBe(plugin); }); }); describe('.unregister()', () => { let plugin: ChartPlugin; beforeEach(() => { plugin = new ChartPlugin({ metadata, Chart: FakeChart, buildQuery, controlPanel, }); }); it('throws an error if key is not provided', () => { expect(() => plugin.unregister()).toThrow(Error); expect(() => plugin.configure({ key: 'abc' }).unregister()).not.toThrow( Error, ); }); it('removes the chart from the registries', () => { plugin.configure({ key: 'def' }).register(); expect(getChartMetadataRegistry().get('def')).toBe(metadata); expect(getChartComponentRegistry().get('def')).toBe(FakeChart); expect(getChartTransformPropsRegistry().has('def')).toEqual(true); expect(getChartBuildQueryRegistry().get('def')).toBe(buildQuery); expect(getChartControlPanelRegistry().get('def')).toBe(controlPanel); plugin.unregister(); expect(getChartMetadataRegistry().has('def')).toBeFalsy(); expect(getChartComponentRegistry().has('def')).toBeFalsy(); expect(getChartTransformPropsRegistry().has('def')).toBeFalsy(); expect(getChartBuildQueryRegistry().has('def')).toBeFalsy(); expect(getChartControlPanelRegistry().has('def')).toBeFalsy(); }); it('returns itself', () => { expect(plugin.configure({ key: 'xyz' }).unregister()).toBe(plugin); }); }); });
5,497
0
petrpan-code/apache/superset/superset-frontend/packages/superset-ui-core/test/chart
petrpan-code/apache/superset/superset-frontend/packages/superset-ui-core/test/chart/models/ChartProps.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 { Behavior, ChartProps, supersetTheme } from '@superset-ui/core'; const RAW_FORM_DATA = { some_field: 1, }; const RAW_DATASOURCE = { column_formats: { test: '%s' }, }; const QUERY_DATA = { data: {} }; const QUERIES_DATA = [QUERY_DATA]; const BEHAVIORS = [Behavior.NATIVE_FILTER, Behavior.INTERACTIVE_CHART]; describe('ChartProps', () => { it('exists', () => { expect(ChartProps).toBeDefined(); }); describe('new ChartProps({})', () => { it('returns new instance', () => { const props = new ChartProps({ width: 800, height: 600, formData: RAW_FORM_DATA, queriesData: QUERIES_DATA, theme: supersetTheme, }); expect(props).toBeInstanceOf(ChartProps); }); it('processes formData and datasource to convert field names to camelCase', () => { const props = new ChartProps({ width: 800, height: 600, datasource: RAW_DATASOURCE, formData: RAW_FORM_DATA, queriesData: QUERIES_DATA, theme: supersetTheme, }); expect(props.formData.someField as number).toEqual(1); expect(props.datasource.columnFormats).toEqual( RAW_DATASOURCE.column_formats, ); expect(props.rawFormData).toEqual(RAW_FORM_DATA); expect(props.rawDatasource).toEqual(RAW_DATASOURCE); }); }); describe('ChartProps.createSelector()', () => { const selector = ChartProps.createSelector(); it('returns a selector function', () => { expect(selector).toBeInstanceOf(Function); }); it('selector returns previous chartProps if all input fields do not change', () => { const props1 = selector({ width: 800, height: 600, datasource: RAW_DATASOURCE, formData: RAW_FORM_DATA, queriesData: QUERIES_DATA, behaviors: BEHAVIORS, isRefreshing: false, theme: supersetTheme, }); const props2 = selector({ width: 800, height: 600, datasource: RAW_DATASOURCE, formData: RAW_FORM_DATA, queriesData: QUERIES_DATA, behaviors: BEHAVIORS, isRefreshing: false, theme: supersetTheme, }); expect(props1).toBe(props2); }); it('selector returns a new chartProps if the 13th field changes', () => { /** this test is here to test for selectors that exceed 12 arguments ( * isRefreshing is the 13th argument, which is missing TS declarations). * See: https://github.com/reduxjs/reselect/issues/378 */ const props1 = selector({ width: 800, height: 600, datasource: RAW_DATASOURCE, formData: RAW_FORM_DATA, queriesData: QUERIES_DATA, behaviors: BEHAVIORS, isRefreshing: false, theme: supersetTheme, }); const props2 = selector({ width: 800, height: 600, datasource: RAW_DATASOURCE, formData: RAW_FORM_DATA, queriesData: QUERIES_DATA, behaviors: BEHAVIORS, isRefreshing: true, theme: supersetTheme, }); expect(props1).not.toBe(props2); }); it('selector returns a new chartProps if some input fields change', () => { const props1 = selector({ width: 800, height: 600, datasource: RAW_DATASOURCE, formData: RAW_FORM_DATA, queriesData: QUERIES_DATA, theme: supersetTheme, }); const props2 = selector({ width: 800, height: 600, datasource: RAW_DATASOURCE, formData: { new_field: 3 }, queriesData: QUERIES_DATA, theme: supersetTheme, }); const props3 = selector({ width: 800, height: 600, datasource: RAW_DATASOURCE, formData: RAW_FORM_DATA, queriesData: QUERIES_DATA, theme: supersetTheme, }); expect(props1).not.toBe(props2); expect(props1).not.toBe(props3); }); }); });
5,498
0
petrpan-code/apache/superset/superset-frontend/packages/superset-ui-core/test
petrpan-code/apache/superset/superset-frontend/packages/superset-ui-core/test/color/CategoricalColorNameSpace.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 { CategoricalScheme, getCategoricalSchemeRegistry, CategoricalColorNamespace, } from '@superset-ui/core'; import { getNamespace, getScale, getColor, DEFAULT_NAMESPACE, } from '../../src/color/CategoricalColorNamespace'; describe('CategoricalColorNamespace', () => { beforeAll(() => { getCategoricalSchemeRegistry() .registerValue( 'testColors', new CategoricalScheme({ id: 'testColors', colors: ['red', 'green', 'blue'], }), ) .registerValue( 'testColors2', new CategoricalScheme({ id: 'testColors2', colors: ['red', 'green', 'blue'], }), ); }); it('The class constructor cannot be accessed directly', () => { expect(typeof CategoricalColorNamespace).not.toBe('Function'); }); describe('static getNamespace()', () => { it('returns default namespace if name is not specified', () => { const namespace = getNamespace(); expect(namespace !== undefined).toBe(true); expect(namespace.name).toBe(DEFAULT_NAMESPACE); }); it('returns namespace with specified name', () => { const namespace = getNamespace('myNamespace'); expect(namespace !== undefined).toBe(true); expect(namespace.name).toBe('myNamespace'); }); it('returns existing instance if the name already exists', () => { const ns1 = getNamespace('myNamespace'); const ns2 = getNamespace('myNamespace'); expect(ns1).toBe(ns2); const ns3 = getNamespace(); const ns4 = getNamespace(); expect(ns3).toBe(ns4); }); }); describe('.getScale()', () => { it('returns a CategoricalColorScale from given scheme name', () => { const namespace = getNamespace('test-get-scale1'); const scale = namespace.getScale('testColors'); expect(scale).toBeDefined(); expect(scale.getColor('dog')).toBeDefined(); }); it('returns a scale when a schemeId is not specified and there is no default key', () => { getCategoricalSchemeRegistry().clearDefaultKey(); const namespace = getNamespace('new-space'); const scale = namespace.getScale(); expect(scale).toBeDefined(); getCategoricalSchemeRegistry().setDefaultKey('testColors'); }); }); describe('.setColor()', () => { it('overwrites color for all CategoricalColorScales in this namespace', () => { const namespace = getNamespace('test-set-scale1'); namespace.setColor('dog', 'black'); const scale = namespace.getScale('testColors'); expect(scale.getColor('dog')).toBe('black'); expect(scale.getColor('boy')).not.toBe('black'); }); it('can override forcedColors in each scale', () => { const namespace = getNamespace('test-set-scale2'); namespace.setColor('dog', 'black'); const scale = namespace.getScale('testColors'); scale.setColor('dog', 'pink'); expect(scale.getColor('dog')).toBe('black'); expect(scale.getColor('boy')).not.toBe('black'); }); it('does not affect scales in other namespaces', () => { const ns1 = getNamespace('test-set-scale3.1'); ns1.setColor('dog', 'black'); const scale1 = ns1.getScale('testColors'); const ns2 = getNamespace('test-set-scale3.2'); const scale2 = ns2.getScale('testColors'); expect(scale1.getColor('dog')).toBe('black'); expect(scale2.getColor('dog')).not.toBe('black'); }); it('returns the namespace instance', () => { const ns1 = getNamespace('test-set-scale3.1'); const ns2 = ns1.setColor('dog', 'black'); expect(ns1).toBe(ns2); }); it('should reset colors', () => { const ns1 = getNamespace('test-set-scale3.1'); ns1.setColor('dog', 'black'); ns1.resetColors(); expect(ns1.forcedItems).toMatchObject({}); }); }); describe('static getScale()', () => { it('getScale() returns a CategoricalColorScale with default scheme in default namespace', () => { const scale = getScale(); expect(scale).toBeDefined(); const scale2 = getNamespace().getScale(); expect(scale2).toBeDefined(); }); it('getScale(scheme) returns a CategoricalColorScale with specified scheme in default namespace', () => { const scale = getNamespace().getScale('testColors'); expect(scale).toBeDefined(); }); it('getScale(scheme, namespace) returns a CategoricalColorScale with specified scheme in specified namespace', () => { const scale = getNamespace('test-getScale').getScale('testColors'); expect(scale).toBeDefined(); }); }); describe('static getColor()', () => { it('getColor(value) returns a color from default scheme in default namespace', () => { const value = 'dog'; const color = getColor(value); const color2 = getNamespace().getScale().getColor(value); expect(color).toBe(color2); }); it('getColor(value, scheme) returns a color from specified scheme in default namespace', () => { const value = 'dog'; const scheme = 'testColors'; const color = getColor(value, scheme); const color2 = getNamespace().getScale(scheme).getColor(value); expect(color).toBe(color2); }); it('getColor(value, scheme, namespace) returns a color from specified scheme in specified namespace', () => { const value = 'dog'; const scheme = 'testColors'; const namespace = 'test-getColor'; const color = getColor(value, scheme, namespace); const color2 = getNamespace(namespace).getScale(scheme).getColor(value); expect(color).toBe(color2); }); }); });
5,499
0
petrpan-code/apache/superset/superset-frontend/packages/superset-ui-core/test
petrpan-code/apache/superset/superset-frontend/packages/superset-ui-core/test/color/CategoricalColorScale.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 { ScaleOrdinal } from 'd3-scale'; import { CategoricalColorScale, FeatureFlag, getSharedLabelColor, } from '@superset-ui/core'; describe('CategoricalColorScale', () => { it('exists', () => { expect(CategoricalColorScale !== undefined).toBe(true); }); describe('new CategoricalColorScale(colors, parentForcedColors)', () => { it('can create new scale when parentForcedColors is not given', () => { const scale = new CategoricalColorScale(['blue', 'red', 'green']); expect(scale).toBeInstanceOf(CategoricalColorScale); }); it('can create new scale when parentForcedColors is given', () => { const parentForcedColors = {}; const scale = new CategoricalColorScale( ['blue', 'red', 'green'], parentForcedColors, ); expect(scale).toBeInstanceOf(CategoricalColorScale); expect(scale.parentForcedColors).toBe(parentForcedColors); }); it('can refer to colors based on their index', () => { const parentForcedColors = { pig: 1, horse: 5 }; const scale = new CategoricalColorScale( ['blue', 'red', 'green'], parentForcedColors, ); expect(scale.getColor('pig')).toEqual('red'); expect(parentForcedColors.pig).toEqual('red'); // can loop around the scale expect(scale.getColor('horse')).toEqual('green'); expect(parentForcedColors.horse).toEqual('green'); }); }); describe('.getColor(value)', () => { it('returns same color for same value', () => { const scale = new CategoricalColorScale(['blue', 'red', 'green']); const c1 = scale.getColor('pig'); const c2 = scale.getColor('horse'); const c3 = scale.getColor('pig'); scale.getColor('cow'); const c5 = scale.getColor('horse'); expect(c1).toBe(c3); expect(c2).toBe(c5); }); it('returns different color for consecutive items', () => { const scale = new CategoricalColorScale(['blue', 'red', 'green']); const c1 = scale.getColor('pig'); const c2 = scale.getColor('horse'); const c3 = scale.getColor('cat'); expect(c1).not.toBe(c2); expect(c2).not.toBe(c3); expect(c3).not.toBe(c1); }); it('recycles colors when number of items exceed available colors', () => { window.featureFlags = { [FeatureFlag.USE_ANALAGOUS_COLORS]: false, }; const colorSet: { [key: string]: number } = {}; const scale = new CategoricalColorScale(['blue', 'red', 'green']); const colors = [ scale.getColor('pig'), scale.getColor('horse'), scale.getColor('cat'), scale.getColor('cow'), scale.getColor('donkey'), scale.getColor('goat'), ]; colors.forEach(color => { if (colorSet[color]) { colorSet[color] += 1; } else { colorSet[color] = 1; } }); expect(Object.keys(colorSet)).toHaveLength(3); ['blue', 'red', 'green'].forEach(color => { expect(colorSet[color]).toBe(2); }); }); it('get analogous colors when number of items exceed available colors', () => { window.featureFlags = { [FeatureFlag.USE_ANALAGOUS_COLORS]: true, }; const scale = new CategoricalColorScale(['blue', 'red', 'green']); scale.getColor('pig'); scale.getColor('horse'); scale.getColor('cat'); scale.getColor('cow'); scale.getColor('donkey'); scale.getColor('goat'); expect(scale.range()).toHaveLength(6); }); it('should remove shared color from range if avoid colors collision enabled', () => { window.featureFlags = { [FeatureFlag.AVOID_COLORS_COLLISION]: true, }; const scale = new CategoricalColorScale(['blue', 'red', 'green']); const color1 = scale.getColor('a', 1); expect(scale.range()).toHaveLength(3); const color2 = scale.getColor('a', 2); expect(color1).toBe(color2); scale.getColor('b', 2); expect(scale.range()).toHaveLength(2); scale.getColor('c', 2); expect(scale.range()).toHaveLength(1); }); window.featureFlags = { [FeatureFlag.AVOID_COLORS_COLLISION]: false, }; }); describe('.setColor(value, forcedColor)', () => { it('overrides default color', () => { const scale = new CategoricalColorScale(['blue', 'red', 'green']); scale.setColor('pig', 'pink'); expect(scale.getColor('pig')).toBe('pink'); }); it('does not override parentForcedColors', () => { const scale1 = new CategoricalColorScale(['blue', 'red', 'green']); scale1.setColor('pig', 'black'); const scale2 = new CategoricalColorScale( ['blue', 'red', 'green'], scale1.forcedColors, ); scale2.setColor('pig', 'pink'); expect(scale1.getColor('pig')).toBe('black'); expect(scale2.getColor('pig')).toBe('black'); }); it('returns the scale', () => { const scale = new CategoricalColorScale(['blue', 'red', 'green']); const output = scale.setColor('pig', 'pink'); expect(scale).toBe(output); }); }); describe('.getColorMap()', () => { it('returns correct mapping and parentForcedColors and forcedColors are specified', () => { const scale1 = new CategoricalColorScale(['blue', 'red', 'green']); scale1.setColor('cow', 'black'); const scale2 = new CategoricalColorScale( ['blue', 'red', 'green'], scale1.forcedColors, ); scale2.setColor('pig', 'pink'); scale2.getColor('cow'); scale2.getColor('pig'); scale2.getColor('horse'); expect(scale2.getColorMap()).toEqual({ cow: 'black', pig: 'pink', horse: 'green', }); }); }); describe('.copy()', () => { it('returns a copy', () => { const scale = new CategoricalColorScale(['blue', 'red', 'green']); const copy = scale.copy(); expect(copy).not.toBe(scale); expect(copy('cat')).toEqual(scale('cat')); expect(copy.domain()).toEqual(scale.domain()); expect(copy.range()).toEqual(scale.range()); expect(copy.unknown()).toEqual(scale.unknown()); }); }); describe('.domain()', () => { it('when called without argument, returns domain', () => { const scale = new CategoricalColorScale(['blue', 'red', 'green']); scale.getColor('pig'); expect(scale.domain()).toEqual(['pig']); }); it('when called with argument, sets domain', () => { const scale = new CategoricalColorScale(['blue', 'red', 'green']); scale.domain(['dog', 'pig', 'cat']); expect(scale('pig')).toEqual('red'); }); }); describe('.range()', () => { it('when called without argument, returns range', () => { const scale = new CategoricalColorScale(['blue', 'red', 'green']); expect(scale.range()).toEqual(['blue', 'red', 'green']); }); it('when called with argument, sets range', () => { const scale = new CategoricalColorScale(['blue', 'red', 'green']); scale.range(['pink', 'gray', 'yellow']); expect(scale.range()).toEqual(['pink', 'gray', 'yellow']); }); }); describe('.unknown()', () => { it('when called without argument, returns output for unknown value', () => { const scale = new CategoricalColorScale(['blue', 'red', 'green']); scale.unknown('#666'); expect(scale.unknown()).toEqual('#666'); }); it('when called with argument, sets output for unknown value', () => { const scale = new CategoricalColorScale(['blue', 'red', 'green']); scale.unknown('#222'); expect(scale.unknown()).toEqual('#222'); }); }); describe('a CategoricalColorScale instance is also a color function itself', () => { it('scale(value) returns color similar to calling scale.getColor(value)', () => { const scale = new CategoricalColorScale(['blue', 'red', 'green']); expect(scale.getColor('pig')).toBe(scale('pig')); expect(scale.getColor('cat')).toBe(scale('cat')); }); }); describe("is compatible with D3's ScaleOrdinal", () => { it('passes type check', () => { const scale: ScaleOrdinal<{ toString(): string }, string> = new CategoricalColorScale(['blue', 'red', 'green']); expect(scale('pig')).toBe('blue'); }); }); describe('.removeSharedLabelColorFromRange(colorMap, cleanedValue)', () => { it('should remove shared color from range', () => { const scale = new CategoricalColorScale(['blue', 'green', 'red']); expect(scale.range()).toEqual(['blue', 'green', 'red']); const sharedLabelColor = getSharedLabelColor(); sharedLabelColor.clear(); const colorMap = sharedLabelColor.getColorMap(); sharedLabelColor.addSlice('cow', 'blue', 1); scale.removeSharedLabelColorFromRange(colorMap, 'pig'); expect(scale.range()).toEqual(['green', 'red']); scale.removeSharedLabelColorFromRange(colorMap, 'cow'); expect(scale.range()).toEqual(['blue', 'green', 'red']); sharedLabelColor.clear(); }); it('recycles colors when all colors are in sharedLabelColor', () => { const scale = new CategoricalColorScale(['blue', 'green', 'red']); expect(scale.range()).toEqual(['blue', 'green', 'red']); const sharedLabelColor = getSharedLabelColor(); const colorMap = sharedLabelColor.getColorMap(); sharedLabelColor.addSlice('cow', 'blue', 1); sharedLabelColor.addSlice('pig', 'red', 1); sharedLabelColor.addSlice('horse', 'green', 1); scale.removeSharedLabelColorFromRange(colorMap, 'goat'); expect(scale.range()).toEqual(['blue', 'green', 'red']); sharedLabelColor.clear(); }); it('should remove parentForcedColors from range', () => { const parentForcedColors = { house: 'blue', cow: 'red' }; const scale = new CategoricalColorScale( ['blue', 'red', 'green'], parentForcedColors, ); const sharedLabelColor = getSharedLabelColor(); sharedLabelColor.clear(); const colorMap = sharedLabelColor.getColorMap(); scale.removeSharedLabelColorFromRange(colorMap, 'pig'); expect(scale.range()).toEqual(['green']); scale.removeSharedLabelColorFromRange(colorMap, 'cow'); expect(scale.range()).toEqual(['red', 'green']); sharedLabelColor.clear(); }); }); });
5,500
0
petrpan-code/apache/superset/superset-frontend/packages/superset-ui-core/test
petrpan-code/apache/superset/superset-frontend/packages/superset-ui-core/test/color/CategoricalSchemeRegistrySingleton.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 { CategoricalScheme, getCategoricalSchemeRegistry, } from '@superset-ui/core'; describe('CategoricalSchemeRegistry', () => { it('has default value out-of-the-box', () => { expect(getCategoricalSchemeRegistry().get()).toBeInstanceOf( CategoricalScheme, ); }); });
5,501
0
petrpan-code/apache/superset/superset-frontend/packages/superset-ui-core/test
petrpan-code/apache/superset/superset-frontend/packages/superset-ui-core/test/color/ColorScheme.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 ColorScheme from '../../src/color/ColorScheme'; describe('ColorScheme', () => { describe('new ColorScheme()', () => { it('returns an instance of ColorScheme', () => { const scheme = new ColorScheme({ id: 'test', colors: ['red', 'blue'] }); expect(scheme).toBeInstanceOf(ColorScheme); }); }); });
5,502
0
petrpan-code/apache/superset/superset-frontend/packages/superset-ui-core/test
petrpan-code/apache/superset/superset-frontend/packages/superset-ui-core/test/color/ColorSchemeRegistry.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 ColorSchemeRegistry from '../../src/color/ColorSchemeRegistry'; import schemes from '../../src/color/colorSchemes/categorical/d3'; import CategoricalScheme from '../../src/color/CategoricalScheme'; describe('ColorSchemeRegistry', () => { it('exists', () => { expect(ColorSchemeRegistry).toBeDefined(); expect(ColorSchemeRegistry).toBeInstanceOf(Function); }); it('returns undefined', () => { const registry = new ColorSchemeRegistry(); expect(registry.get('something')).toBeUndefined(); }); it('returns default', () => { const registry = new ColorSchemeRegistry(); registry.registerValue('SUPERSET_DEFAULT', schemes[0]); expect(registry.get('something')).toBeInstanceOf(CategoricalScheme); }); it('returns undefined in strict mode', () => { const registry = new ColorSchemeRegistry(); registry.registerValue('SUPERSET_DEFAULT', schemes[0]); expect(registry.get('something', true)).toBeUndefined(); }); });
5,503
0
petrpan-code/apache/superset/superset-frontend/packages/superset-ui-core/test
petrpan-code/apache/superset/superset-frontend/packages/superset-ui-core/test/color/SequentialScheme.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 { SequentialScheme } from '@superset-ui/core'; describe('SequentialScheme', () => { const scheme = new SequentialScheme({ id: 'white to black', colors: ['#fff', '#000'], }); it('exists', () => { expect(SequentialScheme).toBeDefined(); }); describe('new SequentialScheme()', () => { it('creates new instance', () => { const scheme2 = new SequentialScheme({ id: 'white to black', colors: ['#fff', '#000'], }); expect(scheme2).toBeInstanceOf(SequentialScheme); }); }); describe('.createLinearScale(domain, modifyRange)', () => { it('returns a piecewise scale', () => { const scale = scheme.createLinearScale([10, 100]); expect(scale.domain()).toHaveLength(scale.range().length); const scale2 = scheme.createLinearScale([0, 10, 100]); expect(scale2.domain()).toHaveLength(scale2.range().length); }); describe('domain', () => { it('returns a linear scale for the given domain', () => { const scale = scheme.createLinearScale([10, 100]); expect(scale(1)).toEqual('rgb(255, 255, 255)'); expect(scale(10)).toEqual('rgb(255, 255, 255)'); expect(scale(55)).toEqual('rgb(119, 119, 119)'); expect(scale(100)).toEqual('rgb(0, 0, 0)'); expect(scale(1000)).toEqual('rgb(0, 0, 0)'); }); it('uses [0, 1] as domain if not specified', () => { const scale = scheme.createLinearScale(); expect(scale(-1)).toEqual('rgb(255, 255, 255)'); expect(scale(0)).toEqual('rgb(255, 255, 255)'); expect(scale(0.5)).toEqual('rgb(119, 119, 119)'); expect(scale(1)).toEqual('rgb(0, 0, 0)'); expect(scale(2)).toEqual('rgb(0, 0, 0)'); }); }); describe('modifyRange', () => { const scheme3 = new SequentialScheme({ id: 'test-scheme3', colors: ['#fee087', '#fa5c2e', '#800026'], }); it('modifies domain by default', () => { const scale = scheme3.createLinearScale([0, 100]); expect(scale.domain()).toEqual([0, 50, 100]); expect(scale.range()).toEqual(['#fee087', '#fa5c2e', '#800026']); }); it('modifies range instead of domain if set to true', () => { const scale = scheme3.createLinearScale([0, 100], true); expect(scale.domain()).toEqual([0, 100]); expect(scale.range()).toEqual([ 'rgb(254, 224, 135)', 'rgb(128, 0, 38)', ]); }); }); }); describe('.getColors(numColors, extent)', () => { describe('numColors', () => { it('returns the original colors if numColors is not specified', () => { expect(scheme.getColors()).toEqual(['#fff', '#000']); }); it('returns the exact number of colors if numColors is specified', () => { expect(scheme.getColors(2)).toEqual(['#fff', '#000']); expect(scheme.getColors(3)).toEqual([ 'rgb(255, 255, 255)', 'rgb(119, 119, 119)', 'rgb(0, 0, 0)', ]); expect(scheme.getColors(4)).toEqual([ 'rgb(255, 255, 255)', 'rgb(162, 162, 162)', 'rgb(78, 78, 78)', 'rgb(0, 0, 0)', ]); }); }); describe('extent', () => { it('adjust the range if extent is specified', () => { expect(scheme.getColors(2, [0, 0.5])).toEqual([ 'rgb(255, 255, 255)', 'rgb(119, 119, 119)', ]); expect(scheme.getColors(2, [0.5, 1])).toEqual([ 'rgb(119, 119, 119)', 'rgb(0, 0, 0)', ]); }); }); }); });
5,504
0
petrpan-code/apache/superset/superset-frontend/packages/superset-ui-core/test
petrpan-code/apache/superset/superset-frontend/packages/superset-ui-core/test/color/SequentialSchemeRegistrySingleton.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 { SequentialScheme, getSequentialSchemeRegistry, } from '@superset-ui/core'; describe('SequentialSchemeRegistry', () => { it('has default value out-of-the-box', () => { expect(getSequentialSchemeRegistry().get()).toBeInstanceOf( SequentialScheme, ); }); });
5,505
0
petrpan-code/apache/superset/superset-frontend/packages/superset-ui-core/test
petrpan-code/apache/superset/superset-frontend/packages/superset-ui-core/test/color/SharedLabelColorSingleton.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 { CategoricalScheme, FeatureFlag, getCategoricalSchemeRegistry, getSharedLabelColor, SharedLabelColor, SharedLabelColorSource, } from '@superset-ui/core'; import { getAnalogousColors } from '../../src/color/utils'; jest.mock('../../src/color/utils', () => ({ getAnalogousColors: jest .fn() .mockImplementation(() => ['red', 'green', 'blue']), })); describe('SharedLabelColor', () => { beforeAll(() => { getCategoricalSchemeRegistry() .registerValue( 'testColors', new CategoricalScheme({ id: 'testColors', colors: ['red', 'green', 'blue'], }), ) .registerValue( 'testColors2', new CategoricalScheme({ id: 'testColors2', colors: ['yellow', 'green', 'blue'], }), ); }); beforeEach(() => { getSharedLabelColor().source = SharedLabelColorSource.dashboard; getSharedLabelColor().clear(); }); it('has default value out-of-the-box', () => { expect(getSharedLabelColor()).toBeInstanceOf(SharedLabelColor); }); describe('.addSlice(value, color, sliceId)', () => { it('should add to sliceLabelColorMap when first adding label', () => { const sharedLabelColor = getSharedLabelColor(); sharedLabelColor.addSlice('a', 'red', 1); expect(sharedLabelColor.sliceLabelMap.has(1)).toEqual(true); const labels = sharedLabelColor.sliceLabelMap.get(1); expect(labels?.includes('a')).toEqual(true); const colorMap = sharedLabelColor.getColorMap(); expect(Object.fromEntries(colorMap)).toEqual({ a: 'red' }); }); it('should add to sliceLabelColorMap when slice exist', () => { const sharedLabelColor = getSharedLabelColor(); sharedLabelColor.addSlice('a', 'red', 1); sharedLabelColor.addSlice('b', 'blue', 1); const labels = sharedLabelColor.sliceLabelMap.get(1); expect(labels?.includes('b')).toEqual(true); const colorMap = sharedLabelColor.getColorMap(); expect(Object.fromEntries(colorMap)).toEqual({ a: 'red', b: 'blue' }); }); it('should use last color if adding label repeatedly', () => { const sharedLabelColor = getSharedLabelColor(); sharedLabelColor.addSlice('b', 'blue', 1); sharedLabelColor.addSlice('b', 'green', 1); const labels = sharedLabelColor.sliceLabelMap.get(1); expect(labels?.includes('b')).toEqual(true); expect(labels?.length).toEqual(1); const colorMap = sharedLabelColor.getColorMap(); expect(Object.fromEntries(colorMap)).toEqual({ b: 'green' }); }); it('should do nothing when source is not dashboard', () => { const sharedLabelColor = getSharedLabelColor(); sharedLabelColor.source = SharedLabelColorSource.explore; sharedLabelColor.addSlice('a', 'red'); expect(Object.fromEntries(sharedLabelColor.sliceLabelMap)).toEqual({}); }); it('should do nothing when sliceId is undefined', () => { const sharedLabelColor = getSharedLabelColor(); sharedLabelColor.addSlice('a', 'red'); expect(Object.fromEntries(sharedLabelColor.sliceLabelMap)).toEqual({}); }); }); describe('.remove(sliceId)', () => { it('should remove sliceId', () => { const sharedLabelColor = getSharedLabelColor(); sharedLabelColor.addSlice('a', 'red', 1); sharedLabelColor.removeSlice(1); expect(sharedLabelColor.sliceLabelMap.has(1)).toEqual(false); }); it('should update colorMap', () => { const sharedLabelColor = getSharedLabelColor(); sharedLabelColor.addSlice('a', 'red', 1); sharedLabelColor.addSlice('b', 'blue', 2); sharedLabelColor.removeSlice(1); const colorMap = sharedLabelColor.getColorMap(); expect(Object.fromEntries(colorMap)).toEqual({ b: 'blue' }); }); it('should do nothing when source is not dashboard', () => { const sharedLabelColor = getSharedLabelColor(); sharedLabelColor.addSlice('a', 'red', 1); sharedLabelColor.source = SharedLabelColorSource.explore; sharedLabelColor.removeSlice(1); expect(sharedLabelColor.sliceLabelMap.has(1)).toEqual(true); }); }); describe('.updateColorMap(namespace, scheme)', () => { it('should update color map', () => { const sharedLabelColor = getSharedLabelColor(); sharedLabelColor.addSlice('a', 'red', 1); sharedLabelColor.addSlice('b', 'pink', 1); sharedLabelColor.addSlice('b', 'green', 2); sharedLabelColor.addSlice('c', 'blue', 2); sharedLabelColor.updateColorMap('', 'testColors2'); const colorMap = sharedLabelColor.getColorMap(); expect(Object.fromEntries(colorMap)).toEqual({ a: 'yellow', b: 'yellow', c: 'green', }); }); it('should use recycle colors', () => { window.featureFlags = { [FeatureFlag.USE_ANALAGOUS_COLORS]: false, }; const sharedLabelColor = getSharedLabelColor(); sharedLabelColor.addSlice('a', 'red', 1); sharedLabelColor.addSlice('b', 'blue', 2); sharedLabelColor.addSlice('c', 'green', 3); sharedLabelColor.addSlice('d', 'red', 4); sharedLabelColor.updateColorMap('', 'testColors'); const colorMap = sharedLabelColor.getColorMap(); expect(Object.fromEntries(colorMap)).not.toEqual({}); expect(getAnalogousColors).not.toBeCalled(); }); it('should use analagous colors', () => { window.featureFlags = { [FeatureFlag.USE_ANALAGOUS_COLORS]: true, }; const sharedLabelColor = getSharedLabelColor(); sharedLabelColor.addSlice('a', 'red', 1); sharedLabelColor.addSlice('b', 'blue', 1); sharedLabelColor.addSlice('c', 'green', 1); sharedLabelColor.addSlice('d', 'red', 1); sharedLabelColor.updateColorMap('', 'testColors'); const colorMap = sharedLabelColor.getColorMap(); expect(Object.fromEntries(colorMap)).not.toEqual({}); expect(getAnalogousColors).toBeCalled(); }); }); describe('.getColorMap()', () => { it('should get color map', () => { const sharedLabelColor = getSharedLabelColor(); sharedLabelColor.addSlice('a', 'red', 1); sharedLabelColor.addSlice('b', 'blue', 2); const colorMap = sharedLabelColor.getColorMap(); expect(Object.fromEntries(colorMap)).toEqual({ a: 'red', b: 'blue' }); }); }); describe('.reset()', () => { it('should reset color map', () => { const sharedLabelColor = getSharedLabelColor(); sharedLabelColor.addSlice('a', 'red', 1); sharedLabelColor.addSlice('b', 'blue', 2); sharedLabelColor.reset(); const colorMap = sharedLabelColor.getColorMap(); expect(Object.fromEntries(colorMap)).toEqual({ a: '', b: '' }); }); }); });
5,506
0
petrpan-code/apache/superset/superset-frontend/packages/superset-ui-core/test
petrpan-code/apache/superset/superset-frontend/packages/superset-ui-core/test/color/colorSchemes.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 { CategoricalAirbnb, CategoricalEcharts, CategoricalSuperset, CategoricalPreset, CategoricalD3, CategoricalGoogle, CategoricalLyft, SequentialCommon, SequentialD3, CategoricalScheme, SequentialScheme, } from '@superset-ui/core'; describe('Color Schemes', () => { describe('categorical', () => { it('returns an array of CategoricalScheme', () => { [ CategoricalAirbnb, CategoricalEcharts, CategoricalD3, CategoricalGoogle, CategoricalLyft, CategoricalSuperset, CategoricalPreset, ].forEach(group => { expect(group).toBeInstanceOf(Array); group.forEach(scheme => expect(scheme).toBeInstanceOf(CategoricalScheme), ); }); }); }); describe('sequential', () => { it('returns an array of SequentialScheme', () => { [SequentialCommon, SequentialD3].forEach(group => { expect(group).toBeInstanceOf(Array); group.forEach(scheme => expect(scheme).toBeInstanceOf(SequentialScheme), ); }); }); }); });
5,507
0
petrpan-code/apache/superset/superset-frontend/packages/superset-ui-core/test
petrpan-code/apache/superset/superset-frontend/packages/superset-ui-core/test/color/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 { BRAND_COLOR, CategoricalColorNamespace, CategoricalColorScale, CategoricalScheme, getCategoricalSchemeRegistry, getSequentialSchemeRegistry, SequentialScheme, } from '@superset-ui/core'; describe('index', () => { it('exports modules', () => { [ BRAND_COLOR, CategoricalColorNamespace, CategoricalColorScale, CategoricalScheme, getCategoricalSchemeRegistry, getSequentialSchemeRegistry, SequentialScheme, ].forEach(x => expect(x).toBeDefined()); }); });
5,508
0
petrpan-code/apache/superset/superset-frontend/packages/superset-ui-core/test
petrpan-code/apache/superset/superset-frontend/packages/superset-ui-core/test/color/utils.test.ts
/* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ import { getContrastingColor, addAlpha, hexToRgb, rgbToHex, } from '@superset-ui/core'; describe('color utils', () => { describe('getContrastingColor', () => { it('when called with 3-digit hex color', () => { const color = getContrastingColor('#000'); expect(color).toBe('#FFF'); }); it('when called with 6-digit hex color', () => { const color = getContrastingColor('#000000'); expect(color).toBe('#FFF'); }); it('when called with no # prefix hex color', () => { const color = getContrastingColor('000000'); expect(color).toBe('#FFF'); }); it('when called with rgb color', () => { const color = getContrastingColor('rgb(0, 0, 0)'); expect(color).toBe('#FFF'); }); it('when called with thresholds', () => { const color1 = getContrastingColor('rgb(255, 255, 255)'); const color2 = getContrastingColor('rgb(255, 255, 255)', 255); expect(color1).toBe('#000'); expect(color2).toBe('#FFF'); }); it('when called with rgba color, throw error', () => { expect(() => { getContrastingColor('rgba(0, 0, 0, 0.1)'); }).toThrow(); }); it('when called with invalid color, throw error', () => { expect(() => { getContrastingColor('#0000'); }).toThrow(); }); }); describe('addAlpha', () => { it('adds 20% opacity to black', () => { expect(addAlpha('#000000', 0.2)).toBe('#00000033'); }); it('adds 50% opacity to white', () => { expect(addAlpha('#FFFFFF', 0.5)).toBe('#FFFFFF80'); }); it('should apply transparent alpha', () => { expect(addAlpha('#000000', 0)).toBe('#00000000'); }); it('should apply fully opaque', () => { expect(addAlpha('#000000', 1)).toBe('#000000FF'); }); it('opacity should be between 0 and 1', () => { expect(() => { addAlpha('#000000', 2); }).toThrow(); expect(() => { addAlpha('#000000', -1); }).toThrow(); }); }); describe('hexToRgb', () => { it('convert 3 digits hex', () => { expect(hexToRgb('#fff')).toBe('rgb(255, 255, 255)'); }); it('convert 6 digits hex', () => { expect(hexToRgb('#ffffff')).toBe('rgb(255, 255, 255)'); }); it('convert invalid hex', () => { expect(hexToRgb('#ffffffffffffff')).toBe('rgb(0, 0, 0)'); }); }); describe('rgbToHex', () => { it('convert rgb to hex - white', () => { expect(rgbToHex(255, 255, 255)).toBe('#ffffff'); }); it('convert rgb to hex - black', () => { expect(rgbToHex(0, 0, 0)).toBe('#000000'); }); }); });
5,509
0
petrpan-code/apache/superset/superset-frontend/packages/superset-ui-core/test
petrpan-code/apache/superset/superset-frontend/packages/superset-ui-core/test/components/SafeMarkdown.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 { getOverrideHtmlSchema } from '../../src/components/SafeMarkdown'; describe('getOverrideHtmlSchema', () => { it('should append the override items', () => { const original = { attributes: { '*': ['size'], }, clobberPrefix: 'original-prefix', tagNames: ['h1', 'h2', 'h3'], }; const result = getOverrideHtmlSchema(original, { attributes: { '*': ['src'], h1: ['style'] }, clobberPrefix: 'custom-prefix', tagNames: ['iframe'], }); expect(result.clobberPrefix).toEqual('custom-prefix'); expect(result.attributes).toEqual({ '*': ['size', 'src'], h1: ['style'] }); expect(result.tagNames).toEqual(['h1', 'h2', 'h3', 'iframe']); }); });
5,510
0
petrpan-code/apache/superset/superset-frontend/packages/superset-ui-core/test
petrpan-code/apache/superset/superset-frontend/packages/superset-ui-core/test/connection/SupersetClient.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 { SupersetClient, SupersetClientClass } from '@superset-ui/core'; import { LOGIN_GLOB } from './fixtures/constants'; describe('SupersetClient', () => { beforeAll(() => { fetchMock.get(LOGIN_GLOB, { result: '' }); }); afterAll(fetchMock.restore); afterEach(SupersetClient.reset); it('exposes reset, configure, init, get, post, postForm, isAuthenticated, and reAuthenticate methods', () => { expect(typeof SupersetClient.configure).toBe('function'); expect(typeof SupersetClient.init).toBe('function'); expect(typeof SupersetClient.get).toBe('function'); expect(typeof SupersetClient.post).toBe('function'); expect(typeof SupersetClient.postForm).toBe('function'); expect(typeof SupersetClient.isAuthenticated).toBe('function'); expect(typeof SupersetClient.reAuthenticate).toBe('function'); expect(typeof SupersetClient.getGuestToken).toBe('function'); expect(typeof SupersetClient.request).toBe('function'); expect(typeof SupersetClient.reset).toBe('function'); }); it('throws if you call init, get, post, postForm, isAuthenticated, or reAuthenticate before configure', () => { expect(SupersetClient.init).toThrow(); expect(SupersetClient.get).toThrow(); expect(SupersetClient.post).toThrow(); expect(SupersetClient.postForm).toThrow(); expect(SupersetClient.isAuthenticated).toThrow(); expect(SupersetClient.reAuthenticate).toThrow(); expect(SupersetClient.request).toThrow(); expect(SupersetClient.configure).not.toThrow(); }); // this also tests that the ^above doesn't throw if configure is called appropriately it('calls appropriate SupersetClient methods when configured', async () => { expect.assertions(16); const mockGetUrl = '/mock/get/url'; const mockPostUrl = '/mock/post/url'; const mockRequestUrl = '/mock/request/url'; const mockPutUrl = '/mock/put/url'; const mockDeleteUrl = '/mock/delete/url'; const mockGetPayload = { get: 'payload' }; const mockPostPayload = { post: 'payload' }; const mockDeletePayload = { delete: 'ok' }; const mockPutPayload = { put: 'ok' }; fetchMock.get(mockGetUrl, mockGetPayload); fetchMock.post(mockPostUrl, mockPostPayload); fetchMock.delete(mockDeleteUrl, mockDeletePayload); fetchMock.put(mockPutUrl, mockPutPayload); fetchMock.get(mockRequestUrl, mockGetPayload); const initSpy = jest.spyOn(SupersetClientClass.prototype, 'init'); const getSpy = jest.spyOn(SupersetClientClass.prototype, 'get'); const postSpy = jest.spyOn(SupersetClientClass.prototype, 'post'); const putSpy = jest.spyOn(SupersetClientClass.prototype, 'put'); const deleteSpy = jest.spyOn(SupersetClientClass.prototype, 'delete'); const authenticatedSpy = jest.spyOn( SupersetClientClass.prototype, 'isAuthenticated', ); const csrfSpy = jest.spyOn(SupersetClientClass.prototype, 'getCSRFToken'); const requestSpy = jest.spyOn(SupersetClientClass.prototype, 'request'); const getGuestTokenSpy = jest.spyOn( SupersetClientClass.prototype, 'getGuestToken', ); SupersetClient.configure({}); await SupersetClient.init(); expect(initSpy).toHaveBeenCalledTimes(1); expect(authenticatedSpy).toHaveBeenCalledTimes(2); expect(csrfSpy).toHaveBeenCalledTimes(1); await SupersetClient.get({ url: mockGetUrl }); await SupersetClient.post({ url: mockPostUrl }); await SupersetClient.delete({ url: mockDeleteUrl }); await SupersetClient.put({ url: mockPutUrl }); await SupersetClient.request({ url: mockRequestUrl }); // Make sure network calls have Accept: 'application/json' in headers const networkCalls = [ mockGetUrl, mockPostUrl, mockRequestUrl, mockPutUrl, mockDeleteUrl, ]; networkCalls.map((url: string) => expect(fetchMock.calls(url)[0][1]?.headers).toStrictEqual({ Accept: 'application/json', 'X-CSRFToken': '', }), ); SupersetClient.isAuthenticated(); await SupersetClient.reAuthenticate(); SupersetClient.getGuestToken(); expect(getGuestTokenSpy).toHaveBeenCalledTimes(1); expect(initSpy).toHaveBeenCalledTimes(2); expect(deleteSpy).toHaveBeenCalledTimes(1); expect(putSpy).toHaveBeenCalledTimes(1); expect(getSpy).toHaveBeenCalledTimes(1); expect(postSpy).toHaveBeenCalledTimes(1); expect(requestSpy).toHaveBeenCalledTimes(5); // request rewires to get expect(csrfSpy).toHaveBeenCalledTimes(2); // from init() + reAuthenticate() initSpy.mockRestore(); getSpy.mockRestore(); putSpy.mockRestore(); deleteSpy.mockRestore(); requestSpy.mockRestore(); postSpy.mockRestore(); authenticatedSpy.mockRestore(); csrfSpy.mockRestore(); fetchMock.reset(); }); });
5,511
0
petrpan-code/apache/superset/superset-frontend/packages/superset-ui-core/test
petrpan-code/apache/superset/superset-frontend/packages/superset-ui-core/test/connection/SupersetClientClass.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 { SupersetClientClass, ClientConfig, CallApi } from '@superset-ui/core'; import { LOGIN_GLOB } from './fixtures/constants'; describe('SupersetClientClass', () => { beforeAll(() => { fetchMock.get(LOGIN_GLOB, { result: '' }); }); afterAll(fetchMock.restore); describe('new SupersetClientClass()', () => { it('fallback protocol to https when setting only host', () => { const client = new SupersetClientClass({ host: 'TEST-HOST' }); expect(client.baseUrl).toEqual('https://test-host'); }); }); describe('.getUrl()', () => { let client = new SupersetClientClass(); beforeEach(() => { client = new SupersetClientClass({ protocol: 'https:', host: 'CONFIG_HOST', }); }); it('uses url if passed', () => { expect( client.getUrl({ url: 'myUrl', endpoint: 'blah', host: 'blah' }), ).toBe('myUrl'); }); it('constructs a valid url from config.protocol + host + endpoint if passed', () => { expect(client.getUrl({ endpoint: '/test', host: 'myhost' })).toBe( 'https://myhost/test', ); expect(client.getUrl({ endpoint: '/test', host: 'myhost/' })).toBe( 'https://myhost/test', ); expect(client.getUrl({ endpoint: 'test', host: 'myhost' })).toBe( 'https://myhost/test', ); expect(client.getUrl({ endpoint: '/test/test//', host: 'myhost/' })).toBe( 'https://myhost/test/test//', ); }); it('constructs a valid url from config.host + endpoint if host is omitted', () => { expect(client.getUrl({ endpoint: '/test' })).toBe( 'https://config_host/test', ); }); it('does not throw if url, endpoint, and host are all empty', () => { client = new SupersetClientClass({ protocol: 'https:', host: '' }); expect(client.getUrl()).toBe('https://localhost/'); }); }); describe('.init()', () => { afterEach(() => { fetchMock.reset(); // reset fetchMock.get(LOGIN_GLOB, { result: 1234 }, { overwriteRoutes: true }); }); it('calls api/v1/security/csrf_token/ when init() is called if no CSRF token is passed', async () => { expect.assertions(1); await new SupersetClientClass().init(); expect(fetchMock.calls(LOGIN_GLOB)).toHaveLength(1); }); it('does NOT call api/v1/security/csrf_token/ when init() is called if a CSRF token is passed', async () => { expect.assertions(1); await new SupersetClientClass({ csrfToken: 'abc' }).init(); expect(fetchMock.calls(LOGIN_GLOB)).toHaveLength(0); }); it('calls api/v1/security/csrf_token/ when init(force=true) is called even if a CSRF token is passed', async () => { expect.assertions(4); const initialToken = 'initial_token'; const client = new SupersetClientClass({ csrfToken: initialToken }); await client.init(); expect(fetchMock.calls(LOGIN_GLOB)).toHaveLength(0); expect(client.csrfToken).toBe(initialToken); await client.init(true); expect(fetchMock.calls(LOGIN_GLOB)).toHaveLength(1); expect(client.csrfToken).not.toBe(initialToken); }); it('throws if api/v1/security/csrf_token/ returns an error', async () => { expect.assertions(1); const rejectError = { status: 403 }; fetchMock.get(LOGIN_GLOB, () => Promise.reject(rejectError), { overwriteRoutes: true, }); let error; try { await new SupersetClientClass({}).init(); } catch (err) { error = err; } finally { expect(error as typeof rejectError).toEqual(rejectError); } }); const invalidCsrfTokenError = { error: 'Failed to fetch CSRF token' }; it('throws if api/v1/security/csrf_token/ does not return a token', async () => { expect.assertions(1); fetchMock.get(LOGIN_GLOB, {}, { overwriteRoutes: true }); let error; try { await new SupersetClientClass({}).init(); } catch (err) { error = err; } finally { expect(error as typeof invalidCsrfTokenError).toEqual( invalidCsrfTokenError, ); } }); it('does not set csrfToken if response is not json', async () => { expect.assertions(1); fetchMock.get(LOGIN_GLOB, '123', { overwriteRoutes: true, }); let error; try { await new SupersetClientClass({}).init(); } catch (err) { error = err; } finally { expect(error as typeof invalidCsrfTokenError).toEqual( invalidCsrfTokenError, ); } }); }); describe('.isAuthenticated()', () => { afterEach(fetchMock.reset); it('returns true if there is a token and false if not', async () => { expect.assertions(2); const client = new SupersetClientClass({}); expect(client.isAuthenticated()).toBe(false); await client.init(); expect(client.isAuthenticated()).toBe(true); }); it('returns true if a token is passed at configuration', () => { expect.assertions(2); const clientWithoutToken = new SupersetClientClass({ csrfToken: undefined, }); const clientWithToken = new SupersetClientClass({ csrfToken: 'token' }); expect(clientWithoutToken.isAuthenticated()).toBe(false); expect(clientWithToken.isAuthenticated()).toBe(true); }); }); describe('.ensureAuth()', () => { it(`returns a promise that rejects if .init() has not been called`, async () => { expect.assertions(2); const client = new SupersetClientClass({}); let error; try { await client.ensureAuth(); } catch (err) { error = err; } finally { expect(error).toEqual({ error: expect.any(String) }); } expect(client.isAuthenticated()).toBe(false); }); it('returns a promise that resolves if .init() resolves successfully', async () => { expect.assertions(1); const client = new SupersetClientClass({}); await client.init(); await client.ensureAuth(); expect(client.isAuthenticated()).toBe(true); }); it(`returns a promise that rejects if .init() is unsuccessful`, async () => { expect.assertions(4); const rejectValue = { status: 403 }; fetchMock.get(LOGIN_GLOB, () => Promise.reject(rejectValue), { overwriteRoutes: true, }); const client = new SupersetClientClass({}); let error; let error2; try { await client.init(); } catch (err) { error = err; } finally { expect(error).toEqual(expect.objectContaining(rejectValue)); expect(client.isAuthenticated()).toBe(false); try { await client.ensureAuth(); } catch (err) { error2 = err; } finally { expect(error2).toEqual(expect.objectContaining(rejectValue)); expect(client.isAuthenticated()).toBe(false); } } // reset fetchMock.get( LOGIN_GLOB, { result: 1234 }, { overwriteRoutes: true, }, ); }); }); describe('requests', () => { afterEach(fetchMock.reset); const protocol = 'https:'; const host = 'host'; const mockGetEndpoint = '/get/url'; const mockRequestEndpoint = '/request/url'; const mockPostEndpoint = '/post/url'; const mockPutEndpoint = '/put/url'; const mockDeleteEndpoint = '/delete/url'; const mockTextEndpoint = '/text/endpoint'; const mockGetUrl = `${protocol}//${host}${mockGetEndpoint}`; const mockRequestUrl = `${protocol}//${host}${mockRequestEndpoint}`; const mockPostUrl = `${protocol}//${host}${mockPostEndpoint}`; const mockTextUrl = `${protocol}//${host}${mockTextEndpoint}`; const mockPutUrl = `${protocol}//${host}${mockPutEndpoint}`; const mockDeleteUrl = `${protocol}//${host}${mockDeleteEndpoint}`; const mockTextJsonResponse = '{ "value": 9223372036854775807 }'; const mockPayload = { json: () => Promise.resolve('payload') }; fetchMock.get(mockGetUrl, mockPayload); fetchMock.post(mockPostUrl, mockPayload); fetchMock.put(mockPutUrl, mockPayload); fetchMock.delete(mockDeleteUrl, mockPayload); fetchMock.delete(mockRequestUrl, mockPayload); fetchMock.get(mockTextUrl, mockTextJsonResponse); fetchMock.post(mockTextUrl, mockTextJsonResponse); it('checks for authentication before every get and post request', async () => { expect.assertions(6); const authSpy = jest.spyOn(SupersetClientClass.prototype, 'ensureAuth'); const client = new SupersetClientClass({ protocol, host }); await client.init(); await client.get({ url: mockGetUrl }); await client.post({ url: mockPostUrl }); await client.put({ url: mockPutUrl }); await client.delete({ url: mockDeleteUrl }); await client.request({ url: mockRequestUrl, method: 'DELETE' }); expect(fetchMock.calls(mockGetUrl)).toHaveLength(1); expect(fetchMock.calls(mockPostUrl)).toHaveLength(1); expect(fetchMock.calls(mockDeleteUrl)).toHaveLength(1); expect(fetchMock.calls(mockPutUrl)).toHaveLength(1); expect(fetchMock.calls(mockRequestUrl)).toHaveLength(1); expect(authSpy).toHaveBeenCalledTimes(5); authSpy.mockRestore(); }); it('sets protocol, host, headers, mode, and credentials from config', async () => { expect.assertions(3); const clientConfig: ClientConfig = { host, protocol, mode: 'cors', credentials: 'include', headers: { my: 'header' }, }; const client = new SupersetClientClass(clientConfig); await client.init(); await client.get({ url: mockGetUrl }); const fetchRequest = fetchMock.calls(mockGetUrl)[0][1] as CallApi; expect(fetchRequest.mode).toBe(clientConfig.mode); expect(fetchRequest.credentials).toBe(clientConfig.credentials); expect(fetchRequest.headers).toEqual( expect.objectContaining( clientConfig.headers, ) as typeof fetchRequest.headers, ); }); it('uses a guest token when provided', async () => { expect.assertions(2); const client = new SupersetClientClass({ protocol, host, guestToken: 'abc123', guestTokenHeaderName: 'guestTokenHeader', }); expect(client.getGuestToken()).toBe('abc123'); await client.init(); await client.get({ url: mockGetUrl }); const fetchRequest = fetchMock.calls(mockGetUrl)[0][1] as CallApi; expect(fetchRequest.headers).toEqual( expect.objectContaining({ guestTokenHeader: 'abc123', }), ); }); describe('.get()', () => { it('makes a request using url or endpoint', async () => { expect.assertions(2); const client = new SupersetClientClass({ protocol, host }); await client.init(); await client.get({ url: mockGetUrl }); expect(fetchMock.calls(mockGetUrl)).toHaveLength(1); await client.get({ endpoint: mockGetEndpoint }); expect(fetchMock.calls(mockGetUrl)).toHaveLength(2); }); it('supports parsing a response as text', async () => { expect.assertions(2); const client = new SupersetClientClass({ protocol, host }); await client.init(); const { text } = await client.get({ url: mockTextUrl, parseMethod: 'text', }); expect(fetchMock.calls(mockTextUrl)).toHaveLength(1); expect(text).toBe(mockTextJsonResponse); }); it('allows overriding host, headers, mode, and credentials per-request', async () => { expect.assertions(3); const clientConfig: ClientConfig = { host, protocol, mode: 'cors', credentials: 'include', headers: { my: 'header' }, }; const overrideConfig: ClientConfig = { host: 'override_host', mode: 'no-cors', credentials: 'omit', headers: { my: 'override', another: 'header' }, }; const client = new SupersetClientClass(clientConfig); await client.init(); await client.get({ url: mockGetUrl, ...overrideConfig }); const fetchRequest = fetchMock.calls(mockGetUrl)[0][1] as CallApi; expect(fetchRequest.mode).toBe(overrideConfig.mode); expect(fetchRequest.credentials).toBe(overrideConfig.credentials); expect(fetchRequest.headers).toEqual( expect.objectContaining( overrideConfig.headers, ) as typeof fetchRequest.headers, ); }); }); describe('.post()', () => { it('makes a request using url or endpoint', async () => { expect.assertions(2); const client = new SupersetClientClass({ protocol, host }); await client.init(); await client.post({ url: mockPostUrl }); expect(fetchMock.calls(mockPostUrl)).toHaveLength(1); await client.post({ endpoint: mockPostEndpoint }); expect(fetchMock.calls(mockPostUrl)).toHaveLength(2); }); it('allows overriding host, headers, mode, and credentials per-request', async () => { expect.assertions(3); const clientConfig: ClientConfig = { host, protocol, mode: 'cors', credentials: 'include', headers: { my: 'header' }, }; const overrideConfig: ClientConfig = { host: 'override_host', mode: 'no-cors', credentials: 'omit', headers: { my: 'override', another: 'header' }, }; const client = new SupersetClientClass(clientConfig); await client.init(); await client.post({ url: mockPostUrl, ...overrideConfig }); const fetchRequest = fetchMock.calls(mockPostUrl)[0][1] as CallApi; expect(fetchRequest.mode).toBe(overrideConfig.mode); expect(fetchRequest.credentials).toBe(overrideConfig.credentials); expect(fetchRequest.headers).toEqual( expect.objectContaining( overrideConfig.headers, ) as typeof fetchRequest.headers, ); }); it('supports parsing a response as text', async () => { expect.assertions(2); const client = new SupersetClientClass({ protocol, host }); await client.init(); const { text } = await client.post({ url: mockTextUrl, parseMethod: 'text', }); expect(fetchMock.calls(mockTextUrl)).toHaveLength(1); expect(text).toBe(mockTextJsonResponse); }); it('passes postPayload key,values in the body', async () => { expect.assertions(3); const postPayload = { number: 123, array: [1, 2, 3] }; const client = new SupersetClientClass({ protocol, host }); await client.init(); await client.post({ url: mockPostUrl, postPayload }); const fetchRequest = fetchMock.calls(mockPostUrl)[0][1] as CallApi; const formData = fetchRequest.body as FormData; expect(fetchMock.calls(mockPostUrl)).toHaveLength(1); Object.entries(postPayload).forEach(([key, value]) => { expect(formData.get(key)).toBe(JSON.stringify(value)); }); }); it('respects the stringify parameter for postPayload key,values', async () => { expect.assertions(3); const postPayload = { number: 123, array: [1, 2, 3] }; const client = new SupersetClientClass({ protocol, host }); await client.init(); await client.post({ url: mockPostUrl, postPayload, stringify: false }); const fetchRequest = fetchMock.calls(mockPostUrl)[0][1] as CallApi; const formData = fetchRequest.body as FormData; expect(fetchMock.calls(mockPostUrl)).toHaveLength(1); Object.entries(postPayload).forEach(([key, value]) => { expect(formData.get(key)).toBe(String(value)); }); }); }); }); describe('when unauthorized', () => { let originalLocation: any; let authSpy: jest.SpyInstance; const mockRequestUrl = 'https://host/get/url'; const mockRequestPath = '/get/url'; const mockRequestSearch = '?param=1&param=2'; const mockHref = mockRequestUrl + mockRequestSearch; beforeEach(() => { originalLocation = window.location; // @ts-ignore delete window.location; // @ts-ignore window.location = { pathname: mockRequestPath, search: mockRequestSearch, href: mockHref, }; authSpy = jest .spyOn(SupersetClientClass.prototype, 'ensureAuth') .mockImplementation(); const rejectValue = { status: 401 }; fetchMock.get(mockRequestUrl, () => Promise.reject(rejectValue), { overwriteRoutes: true, }); }); afterEach(() => { authSpy.mockReset(); window.location = originalLocation; }); it('should redirect', async () => { const client = new SupersetClientClass({}); let error; try { await client.request({ url: mockRequestUrl, method: 'GET' }); } catch (err) { error = err; } finally { const redirectURL = window.location.href; expect(redirectURL).toBe(`/login?next=${mockHref}`); expect(error.status).toBe(401); } }); it('should not redirect again if already on login page', async () => { const client = new SupersetClientClass({}); // @ts-expect-error window.location = { href: '/login?next=something', pathname: '/login', search: '?next=something', }; let error; try { await client.request({ url: mockRequestUrl, method: 'GET' }); } catch (err) { error = err; } finally { expect(window.location.href).toBe('/login?next=something'); expect(error.status).toBe(401); } }); it('does nothing if instructed to ignoreUnauthorized', async () => { const client = new SupersetClientClass({}); let error; try { await client.request({ url: mockRequestUrl, method: 'GET', ignoreUnauthorized: true, }); } catch (err) { error = err; } finally { // unchanged href, no redirect expect(window.location.href).toBe(mockHref); expect(error.status).toBe(401); } }); it('accepts an unauthorizedHandler to override redirect behavior', async () => { const unauthorizedHandler = jest.fn(); const client = new SupersetClientClass({ unauthorizedHandler }); let error; try { await client.request({ url: mockRequestUrl, method: 'GET', }); } catch (err) { error = err; } finally { // unchanged href, no redirect expect(window.location.href).toBe(mockHref); expect(error.status).toBe(401); expect(unauthorizedHandler).toHaveBeenCalledTimes(1); } }); }); describe('.postForm()', () => { const protocol = 'https:'; const host = 'host'; const mockPostFormEndpoint = '/post_form/url'; const mockPostFormUrl = `${protocol}//${host}${mockPostFormEndpoint}`; const guestToken = 'test-guest-token'; const postFormPayload = { number: 123, array: [1, 2, 3] }; let authSpy: jest.SpyInstance; let client: SupersetClientClass; let appendChild: any; let removeChild: any; let submit: any; let createElement: any; beforeEach(async () => { client = new SupersetClientClass({ protocol, host }); authSpy = jest.spyOn(SupersetClientClass.prototype, 'ensureAuth'); await client.init(); appendChild = jest.fn(); removeChild = jest.fn(); submit = jest.fn(); createElement = jest.fn(() => ({ appendChild: jest.fn(), submit, })); document.createElement = createElement as any; document.body.appendChild = appendChild; document.body.removeChild = removeChild; }); afterEach(() => { jest.restoreAllMocks(); }); it('makes postForm request', async () => { await client.postForm(mockPostFormUrl, {}); const hiddenForm = createElement.mock.results[0].value; const csrfTokenInput = createElement.mock.results[1].value; expect(createElement.mock.calls).toHaveLength(2); expect(hiddenForm.action).toBe(mockPostFormUrl); expect(hiddenForm.method).toBe('POST'); expect(hiddenForm.target).toBe('_blank'); expect(csrfTokenInput.type).toBe('hidden'); expect(csrfTokenInput.name).toBe('csrf_token'); expect(csrfTokenInput.value).toBe(1234); expect(appendChild.mock.calls).toHaveLength(1); expect(removeChild.mock.calls).toHaveLength(1); expect(authSpy).toHaveBeenCalledTimes(1); }); it('makes postForm request with guest token', async () => { client = new SupersetClientClass({ protocol, host, guestToken }); await client.init(); await client.postForm(mockPostFormUrl, {}); const guestTokenInput = createElement.mock.results[2].value; expect(createElement.mock.calls).toHaveLength(3); expect(guestTokenInput.type).toBe('hidden'); expect(guestTokenInput.name).toBe('guest_token'); expect(guestTokenInput.value).toBe(guestToken); expect(appendChild.mock.calls).toHaveLength(1); expect(removeChild.mock.calls).toHaveLength(1); expect(authSpy).toHaveBeenCalledTimes(1); }); it('makes postForm request with payload', async () => { await client.postForm(mockPostFormUrl, { form_data: postFormPayload }); const postFormPayloadInput = createElement.mock.results[1].value; expect(createElement.mock.calls).toHaveLength(3); expect(postFormPayloadInput.type).toBe('hidden'); expect(postFormPayloadInput.name).toBe('form_data'); expect(postFormPayloadInput.value).toBe(postFormPayload); expect(appendChild.mock.calls).toHaveLength(1); expect(removeChild.mock.calls).toHaveLength(1); expect(submit.mock.calls).toHaveLength(1); expect(authSpy).toHaveBeenCalledTimes(1); }); it('should do nothing when url is empty string', async () => { const result = await client.postForm('', {}); expect(result).toBeUndefined(); expect(createElement.mock.calls).toHaveLength(0); expect(appendChild.mock.calls).toHaveLength(0); expect(removeChild.mock.calls).toHaveLength(0); expect(authSpy).toHaveBeenCalledTimes(0); }); }); });
5,512
0
petrpan-code/apache/superset/superset-frontend/packages/superset-ui-core/test/connection
petrpan-code/apache/superset/superset-frontend/packages/superset-ui-core/test/connection/callApi/callApi.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 { CallApi, JsonObject } from '@superset-ui/core'; import * as constants from '../../../src/connection/constants'; import callApi from '../../../src/connection/callApi/callApi'; import { LOGIN_GLOB } from '../fixtures/constants'; // missing the toString function causing method to error out when casting to String class BadObject {} const corruptObject = new BadObject(); /* @ts-expect-error */ BadObject.prototype.toString = undefined; describe('callApi()', () => { beforeAll(() => { fetchMock.get(LOGIN_GLOB, { result: '1234' }); }); afterAll(fetchMock.restore); const mockGetUrl = '/mock/get/url'; const mockPostUrl = '/mock/post/url'; const mockPutUrl = '/mock/put/url'; const mockPatchUrl = '/mock/patch/url'; const mockCacheUrl = '/mock/cache/url'; const mockNotFound = '/mock/notfound'; const mockErrorUrl = '/mock/error/url'; const mock503 = '/mock/503'; const mockGetPayload = { get: 'payload' }; const mockPostPayload = { post: 'payload' }; const mockPutPayload = { post: 'payload' }; const mockPatchPayload = { post: 'payload' }; const mockCachePayload = { status: 200, body: 'BODY', headers: { Etag: 'etag' }, }; const mockErrorPayload = { status: 500, statusText: 'Internal error' }; fetchMock.get(mockGetUrl, mockGetPayload); fetchMock.post(mockPostUrl, mockPostPayload); fetchMock.put(mockPutUrl, mockPutPayload); fetchMock.patch(mockPatchUrl, mockPatchPayload); fetchMock.get(mockCacheUrl, mockCachePayload); fetchMock.get(mockNotFound, { status: 404 }); fetchMock.get(mock503, { status: 503 }); fetchMock.get(mockErrorUrl, () => Promise.reject(mockErrorPayload)); afterEach(fetchMock.reset); describe('request config', () => { it('calls the right url with the specified method', async () => { expect.assertions(4); await Promise.all([ callApi({ url: mockGetUrl, method: 'GET' }), callApi({ url: mockPostUrl, method: 'POST' }), callApi({ url: mockPutUrl, method: 'PUT' }), callApi({ url: mockPatchUrl, method: 'PATCH' }), ]); expect(fetchMock.calls(mockGetUrl)).toHaveLength(1); expect(fetchMock.calls(mockPostUrl)).toHaveLength(1); expect(fetchMock.calls(mockPutUrl)).toHaveLength(1); expect(fetchMock.calls(mockPatchUrl)).toHaveLength(1); }); it('passes along mode, cache, credentials, headers, body, signal, and redirect parameters in the request', async () => { expect.assertions(8); const mockRequest: CallApi = { url: mockGetUrl, mode: 'cors', cache: 'default', credentials: 'include', headers: { custom: 'header', }, redirect: 'follow', signal: undefined, body: 'BODY', }; await callApi(mockRequest); const calls = fetchMock.calls(mockGetUrl); const fetchParams = calls[0][1] as RequestInit; expect(calls).toHaveLength(1); expect(fetchParams.mode).toBe(mockRequest.mode); expect(fetchParams.cache).toBe(mockRequest.cache); expect(fetchParams.credentials).toBe(mockRequest.credentials); expect(fetchParams.headers).toEqual( expect.objectContaining( mockRequest.headers, ) as typeof fetchParams.headers, ); expect(fetchParams.redirect).toBe(mockRequest.redirect); expect(fetchParams.signal).toBe(mockRequest.signal); expect(fetchParams.body).toBe(mockRequest.body); }); }); describe('POST requests', () => { it('encodes key,value pairs from postPayload', async () => { expect.assertions(3); const postPayload = { key: 'value', anotherKey: 1237 }; await callApi({ url: mockPostUrl, method: 'POST', postPayload }); const calls = fetchMock.calls(mockPostUrl); expect(calls).toHaveLength(1); const fetchParams = calls[0][1] as RequestInit; const body = fetchParams.body as FormData; Object.entries(postPayload).forEach(([key, value]) => { expect(body.get(key)).toBe(JSON.stringify(value)); }); }); // the reason for this is to omit strings like 'undefined' from making their way to the backend it('omits key,value pairs from postPayload that have undefined values (POST)', async () => { expect.assertions(3); const postPayload = { key: 'value', noValue: undefined }; await callApi({ url: mockPostUrl, method: 'POST', postPayload }); const calls = fetchMock.calls(mockPostUrl); expect(calls).toHaveLength(1); const fetchParams = calls[0][1] as RequestInit; const body = fetchParams.body as FormData; expect(body.get('key')).toBe(JSON.stringify(postPayload.key)); expect(body.get('noValue')).toBeNull(); }); it('respects the stringify flag in POST requests', async () => { const postPayload = { string: 'value', number: 1237, array: [1, 2, 3], object: { a: 'a', 1: 1 }, null: null, emptyString: '', }; expect.assertions(1 + 3 * Object.keys(postPayload).length); await Promise.all([ callApi({ url: mockPostUrl, method: 'POST', postPayload }), callApi({ url: mockPostUrl, method: 'POST', postPayload, stringify: false, }), callApi({ url: mockPostUrl, method: 'POST', jsonPayload: postPayload }), ]); const calls = fetchMock.calls(mockPostUrl); expect(calls).toHaveLength(3); const stringified = (calls[0][1] as RequestInit).body as FormData; const unstringified = (calls[1][1] as RequestInit).body as FormData; const jsonRequestBody = JSON.parse( (calls[2][1] as RequestInit).body as string, ) as JsonObject; Object.entries(postPayload).forEach(([key, value]) => { expect(stringified.get(key)).toBe(JSON.stringify(value)); expect(unstringified.get(key)).toBe(String(value)); expect(jsonRequestBody[key]).toEqual(value); }); }); it('removes corrupt value when building formData with stringify = false', async () => { /* There has been a case when 'stringify' is false an object value on one of the attributes was missing a toString function making the cast to String() fail and causing entire method call to fail. The new logic skips corrupt values that fail cast to String() and allows all valid attributes to be added as key / value pairs to the formData instance. This test case replicates a corrupt object missing the .toString method representing a real bug report. */ const postPayload = { string: 'value', number: 1237, array: [1, 2, 3], object: { a: 'a', 1: 1 }, null: null, emptyString: '', // corruptObject has no toString method and will fail cast to String() corrupt: [corruptObject], }; jest.spyOn(console, 'error').mockImplementation(); await callApi({ url: mockPostUrl, method: 'POST', postPayload, stringify: false, }); const calls = fetchMock.calls(mockPostUrl); expect(calls).toHaveLength(1); const unstringified = (calls[0][1] as RequestInit).body as FormData; const hasCorruptKey = unstringified.has('corrupt'); expect(hasCorruptKey).toBeFalsy(); // When a corrupt attribute is encountred, a console.error call is made with info about the corrupt attribute // eslint-disable-next-line no-console expect(console.error).toHaveBeenCalledTimes(1); }); }); describe('PUT requests', () => { it('encodes key,value pairs from postPayload', async () => { expect.assertions(3); const postPayload = { key: 'value', anotherKey: 1237 }; await callApi({ url: mockPutUrl, method: 'PUT', postPayload }); const calls = fetchMock.calls(mockPutUrl); expect(calls).toHaveLength(1); const fetchParams = calls[0][1] as RequestInit; const body = fetchParams.body as FormData; Object.entries(postPayload).forEach(([key, value]) => { expect(body.get(key)).toBe(JSON.stringify(value)); }); }); // the reason for this is to omit strings like 'undefined' from making their way to the backend it('omits key,value pairs from postPayload that have undefined values (PUT)', async () => { expect.assertions(3); const postPayload = { key: 'value', noValue: undefined }; await callApi({ url: mockPutUrl, method: 'PUT', postPayload }); const calls = fetchMock.calls(mockPutUrl); expect(calls).toHaveLength(1); const fetchParams = calls[0][1] as RequestInit; const body = fetchParams.body as FormData; expect(body.get('key')).toBe(JSON.stringify(postPayload.key)); expect(body.get('noValue')).toBeNull(); }); it('respects the stringify flag in PUT requests', async () => { const postPayload = { string: 'value', number: 1237, array: [1, 2, 3], object: { a: 'a', 1: 1 }, null: null, emptyString: '', }; expect.assertions(1 + 2 * Object.keys(postPayload).length); await Promise.all([ callApi({ url: mockPutUrl, method: 'PUT', postPayload }), callApi({ url: mockPutUrl, method: 'PUT', postPayload, stringify: false, }), ]); const calls = fetchMock.calls(mockPutUrl); expect(calls).toHaveLength(2); const stringified = (calls[0][1] as RequestInit).body as FormData; const unstringified = (calls[1][1] as RequestInit).body as FormData; Object.entries(postPayload).forEach(([key, value]) => { expect(stringified.get(key)).toBe(JSON.stringify(value)); expect(unstringified.get(key)).toBe(String(value)); }); }); }); describe('PATCH requests', () => { it('encodes key,value pairs from postPayload', async () => { expect.assertions(3); const postPayload = { key: 'value', anotherKey: 1237 }; await callApi({ url: mockPatchUrl, method: 'PATCH', postPayload }); const calls = fetchMock.calls(mockPatchUrl); expect(calls).toHaveLength(1); const fetchParams = calls[0][1] as RequestInit; const body = fetchParams.body as FormData; Object.entries(postPayload).forEach(([key, value]) => { expect(body.get(key)).toBe(JSON.stringify(value)); }); }); // the reason for this is to omit strings like 'undefined' from making their way to the backend it('omits key,value pairs from postPayload that have undefined values (PATCH)', async () => { expect.assertions(3); const postPayload = { key: 'value', noValue: undefined }; await callApi({ url: mockPatchUrl, method: 'PATCH', postPayload }); const calls = fetchMock.calls(mockPatchUrl); expect(calls).toHaveLength(1); const fetchParams = calls[0][1] as RequestInit; const body = fetchParams.body as FormData; expect(body.get('key')).toBe(JSON.stringify(postPayload.key)); expect(body.get('noValue')).toBeNull(); }); it('respects the stringify flag in PATCH requests', async () => { const postPayload = { string: 'value', number: 1237, array: [1, 2, 3], object: { a: 'a', 1: 1 }, null: null, emptyString: '', }; expect.assertions(1 + 2 * Object.keys(postPayload).length); await Promise.all([ callApi({ url: mockPatchUrl, method: 'PATCH', postPayload }), callApi({ url: mockPatchUrl, method: 'PATCH', postPayload, stringify: false, }), ]); const calls = fetchMock.calls(mockPatchUrl); expect(calls).toHaveLength(2); const stringified = (calls[0][1] as RequestInit).body as FormData; const unstringified = (calls[1][1] as RequestInit).body as FormData; Object.entries(postPayload).forEach(([key, value]) => { expect(stringified.get(key)).toBe(JSON.stringify(value)); expect(unstringified.get(key)).toBe(String(value)); }); }); }); describe('caching', () => { const origLocation = window.location; beforeAll(() => { Object.defineProperty(window, 'location', { value: {} }); }); afterAll(() => { Object.defineProperty(window, 'location', { value: origLocation }); }); beforeEach(async () => { window.location.protocol = 'https:'; await caches.delete(constants.CACHE_KEY); }); it('caches requests with ETags', async () => { expect.assertions(2); await callApi({ url: mockCacheUrl, method: 'GET' }); const calls = fetchMock.calls(mockCacheUrl); expect(calls).toHaveLength(1); const supersetCache = await caches.open(constants.CACHE_KEY); const cachedResponse = await supersetCache.match(mockCacheUrl); expect(cachedResponse).toBeDefined(); }); it('will not use cache when running off an insecure connection', async () => { expect.assertions(2); window.location.protocol = 'http:'; await callApi({ url: mockCacheUrl, method: 'GET' }); const calls = fetchMock.calls(mockCacheUrl); expect(calls).toHaveLength(1); const supersetCache = await caches.open(constants.CACHE_KEY); const cachedResponse = await supersetCache.match(mockCacheUrl); expect(cachedResponse).toBeUndefined(); }); it('works when the Cache API is disabled', async () => { expect.assertions(5); // eslint-disable-next-line no-import-assign Object.defineProperty(constants, 'CACHE_AVAILABLE', { value: false }); const firstResponse = await callApi({ url: mockCacheUrl, method: 'GET' }); const calls = fetchMock.calls(mockCacheUrl); expect(calls).toHaveLength(1); const firstBody = await firstResponse.text(); expect(firstBody).toEqual('BODY'); const secondResponse = await callApi({ url: mockCacheUrl, method: 'GET', }); const fetchParams = calls[1][1] as RequestInit; expect(calls).toHaveLength(2); // second call should not have If-None-Match header expect(fetchParams.headers).toBeUndefined(); const secondBody = await secondResponse.text(); expect(secondBody).toEqual('BODY'); // eslint-disable-next-line no-import-assign Object.defineProperty(constants, 'CACHE_AVAILABLE', { value: true }); }); it('sends known ETags in the If-None-Match header', async () => { expect.assertions(3); // first call sets the cache await callApi({ url: mockCacheUrl, method: 'GET' }); const calls = fetchMock.calls(mockCacheUrl); expect(calls).toHaveLength(1); // second call sends the Etag in the If-None-Match header await callApi({ url: mockCacheUrl, method: 'GET' }); const fetchParams = calls[1][1] as RequestInit; const headers = { 'If-None-Match': 'etag' }; expect(calls).toHaveLength(2); expect(fetchParams.headers).toEqual( expect.objectContaining(headers) as typeof fetchParams.headers, ); }); it('reuses cached responses on 304 status', async () => { expect.assertions(3); // first call sets the cache await callApi({ url: mockCacheUrl, method: 'GET' }); const calls = fetchMock.calls(mockCacheUrl); expect(calls).toHaveLength(1); // second call reuses the cached payload on a 304 const mockCachedPayload = { status: 304 }; fetchMock.get(mockCacheUrl, mockCachedPayload, { overwriteRoutes: true }); const secondResponse = await callApi({ url: mockCacheUrl, method: 'GET', }); expect(calls).toHaveLength(2); const secondBody = await secondResponse.text(); expect(secondBody).toEqual('BODY'); }); it('throws error when cache fails on 304', async () => { expect.assertions(2); // this should never happen, since a 304 is only returned if we have // the cached response and sent the If-None-Match header const mockUncachedUrl = '/mock/uncached/url'; const mockCachedPayload = { status: 304 }; let error; fetchMock.get(mockUncachedUrl, mockCachedPayload); try { await callApi({ url: mockUncachedUrl, method: 'GET' }); } catch (err) { error = err; } finally { const calls = fetchMock.calls(mockUncachedUrl); expect(calls).toHaveLength(1); expect((error as { message: string }).message).toEqual( 'Received 304 but no content is cached!', ); } }); it('returns original response if no Etag', async () => { expect.assertions(3); const url = mockGetUrl; const response = await callApi({ url, method: 'GET' }); const calls = fetchMock.calls(url); expect(calls).toHaveLength(1); expect(response.status).toEqual(200); const body = await response.json(); expect(body as typeof mockGetPayload).toEqual(mockGetPayload); }); it('returns original response if status not 304 or 200', async () => { expect.assertions(2); const url = mockNotFound; const response = await callApi({ url, method: 'GET' }); const calls = fetchMock.calls(url); expect(calls).toHaveLength(1); expect(response.status).toEqual(404); }); }); it('rejects after retrying thrice if the request throws', async () => { expect.assertions(3); let error; try { await callApi({ fetchRetryOptions: constants.DEFAULT_FETCH_RETRY_OPTIONS, url: mockErrorUrl, method: 'GET', }); } catch (err) { error = err; } finally { const err = error as { status: number; statusText: string }; expect(fetchMock.calls(mockErrorUrl)).toHaveLength(4); expect(err.status).toBe(mockErrorPayload.status); expect(err.statusText).toBe(mockErrorPayload.statusText); } }); it('rejects without retries if the config is set to 0 retries', async () => { expect.assertions(3); let error; try { await callApi({ fetchRetryOptions: { retries: 0 }, url: mockErrorUrl, method: 'GET', }); } catch (err) { error = err as { status: number; statusText: string }; } finally { expect(fetchMock.calls(mockErrorUrl)).toHaveLength(1); expect(error?.status).toBe(mockErrorPayload.status); expect(error?.statusText).toBe(mockErrorPayload.statusText); } }); it('rejects after retrying thrice if the request returns a 503', async () => { expect.assertions(2); const url = mock503; const response = await callApi({ fetchRetryOptions: constants.DEFAULT_FETCH_RETRY_OPTIONS, url, method: 'GET', }); const calls = fetchMock.calls(url); expect(calls).toHaveLength(4); expect(response.status).toEqual(503); }); it('invalid json for postPayload should thrown error', async () => { expect.assertions(2); let error; try { await callApi({ url: mockPostUrl, method: 'POST', postPayload: 'haha', }); } catch (err) { error = err; } finally { expect(error).toBeInstanceOf(Error); expect(error.message).toEqual('Invalid payload:\n\nhaha'); } }); it('should accept search params object', async () => { expect.assertions(3); window.location.href = 'http://localhost'; fetchMock.get(`glob:*/get-search*`, { yes: 'ok' }); const response = await callApi({ url: '/get-search', searchParams: { abc: 1, }, method: 'GET', }); const result = await response.json(); expect(response.status).toEqual(200); expect(result).toEqual({ yes: 'ok' }); expect(fetchMock.lastUrl()).toEqual(`http://localhost/get-search?abc=1`); }); it('should accept URLSearchParams', async () => { expect.assertions(2); window.location.href = 'http://localhost'; fetchMock.post(`glob:*/post-search*`, { yes: 'ok' }); await callApi({ url: '/post-search', searchParams: new URLSearchParams({ abc: '1', }), method: 'POST', jsonPayload: { request: 'ok' }, }); expect(fetchMock.lastUrl()).toEqual(`http://localhost/post-search?abc=1`); expect(fetchMock.lastOptions()).toEqual( expect.objectContaining({ body: JSON.stringify({ request: 'ok' }), }), ); }); it('should throw when both payloads provided', async () => { expect.assertions(1); fetchMock.post('/post-both-payload', {}); let error; try { await callApi({ url: '/post-both-payload', method: 'POST', postPayload: { a: 1 }, jsonPayload: '{}', }); } catch (err) { error = err; } finally { expect((error as Error).message).toContain( 'provide only one of jsonPayload or postPayload', ); } }); it('should accept FormData as postPayload', async () => { expect.assertions(1); fetchMock.post('/post-formdata', {}); const payload = new FormData(); await callApi({ url: '/post-formdata', method: 'POST', postPayload: payload, }); expect(fetchMock.lastOptions()?.body).toBe(payload); }); it('should ignore "null" postPayload string', async () => { expect.assertions(1); fetchMock.post('/post-null-postpayload', {}); await callApi({ url: '/post-formdata', method: 'POST', postPayload: 'null', }); expect(fetchMock.lastOptions()?.body).toBeUndefined(); }); });
5,513
0
petrpan-code/apache/superset/superset-frontend/packages/superset-ui-core/test/connection
petrpan-code/apache/superset/superset-frontend/packages/superset-ui-core/test/connection/callApi/callApiAndParseWithTimeout.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 callApiAndParseWithTimeout from '../../../src/connection/callApi/callApiAndParseWithTimeout'; // we import these via * so that we can spy on the 'default' property of the object import * as callApi from '../../../src/connection/callApi/callApi'; import * as parseResponse from '../../../src/connection/callApi/parseResponse'; import * as rejectAfterTimeout from '../../../src/connection/callApi/rejectAfterTimeout'; import { LOGIN_GLOB } from '../fixtures/constants'; describe('callApiAndParseWithTimeout()', () => { beforeAll(() => { fetchMock.get(LOGIN_GLOB, { result: '1234' }); }); afterAll(fetchMock.restore); const mockGetUrl = '/mock/get/url'; const mockGetPayload = { get: 'payload' }; fetchMock.get(mockGetUrl, mockGetPayload); afterEach(() => { fetchMock.reset(); jest.useRealTimers(); }); describe('callApi', () => { it('calls callApi()', () => { const callApiSpy = jest.spyOn(callApi, 'default'); callApiAndParseWithTimeout({ url: mockGetUrl, method: 'GET' }); expect(callApiSpy).toHaveBeenCalledTimes(1); callApiSpy.mockClear(); }); }); describe('parseResponse', () => { it('calls parseResponse()', async () => { const parseSpy = jest.spyOn(parseResponse, 'default'); await callApiAndParseWithTimeout({ url: mockGetUrl, method: 'GET', }); expect(parseSpy).toHaveBeenCalledTimes(1); parseSpy.mockClear(); }); }); describe('timeout', () => { it('does not create a rejection timer if no timeout passed', () => { const rejectionSpy = jest.spyOn(rejectAfterTimeout, 'default'); callApiAndParseWithTimeout({ url: mockGetUrl, method: 'GET' }); expect(rejectionSpy).toHaveBeenCalledTimes(0); rejectionSpy.mockClear(); }); it('creates a rejection timer if a timeout passed', () => { jest.useFakeTimers(); // prevents the timeout from rejecting + failing test const rejectionSpy = jest.spyOn(rejectAfterTimeout, 'default'); callApiAndParseWithTimeout({ url: mockGetUrl, method: 'GET', timeout: 10, }); expect(rejectionSpy).toHaveBeenCalledTimes(1); rejectionSpy.mockClear(); }); it('rejects if the request exceeds the timeout', async () => { expect.assertions(2); jest.useFakeTimers(); const mockTimeoutUrl = '/mock/timeout/url'; const unresolvingPromise = new Promise(() => {}); let error; fetchMock.get(mockTimeoutUrl, () => unresolvingPromise); try { const promise = callApiAndParseWithTimeout({ url: mockTimeoutUrl, method: 'GET', timeout: 1, }); jest.advanceTimersByTime(2); await promise; } catch (err) { error = err; } finally { expect(fetchMock.calls(mockTimeoutUrl)).toHaveLength(1); expect(error).toEqual({ error: 'Request timed out', statusText: 'timeout', timeout: 1, }); } }); it('resolves if the request does not exceed the timeout', async () => { expect.assertions(1); const { json } = await callApiAndParseWithTimeout({ url: mockGetUrl, method: 'GET', timeout: 100, }); expect(json).toEqual(mockGetPayload); }); }); });
5,514
0
petrpan-code/apache/superset/superset-frontend/packages/superset-ui-core/test/connection
petrpan-code/apache/superset/superset-frontend/packages/superset-ui-core/test/connection/callApi/parseResponse.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 callApi from '../../../src/connection/callApi/callApi'; import parseResponse from '../../../src/connection/callApi/parseResponse'; import { LOGIN_GLOB } from '../fixtures/constants'; describe('parseResponse()', () => { beforeAll(() => { fetchMock.get(LOGIN_GLOB, { result: '1234' }); }); afterAll(fetchMock.restore); const mockGetUrl = '/mock/get/url'; const mockPostUrl = '/mock/post/url'; const mockErrorUrl = '/mock/error/url'; const mockNoParseUrl = '/mock/noparse/url'; const mockGetPayload = { get: 'payload' }; const mockPostPayload = { post: 'payload' }; const mockErrorPayload = { status: 500, statusText: 'Internal error' }; fetchMock.get(mockGetUrl, mockGetPayload); fetchMock.post(mockPostUrl, mockPostPayload); fetchMock.get(mockErrorUrl, () => Promise.reject(mockErrorPayload)); fetchMock.get(mockNoParseUrl, new Response('test response')); afterEach(fetchMock.reset); it('returns a Promise', () => { const apiPromise = callApi({ url: mockGetUrl, method: 'GET' }); const parsedResponsePromise = parseResponse(apiPromise); expect(parsedResponsePromise).toBeInstanceOf(Promise); }); it('resolves to { json, response } if the request succeeds', async () => { expect.assertions(4); const args = await parseResponse( callApi({ url: mockGetUrl, method: 'GET' }), ); expect(fetchMock.calls(mockGetUrl)).toHaveLength(1); const keys = Object.keys(args); expect(keys).toContain('response'); expect(keys).toContain('json'); expect(args.json).toEqual( expect.objectContaining(mockGetPayload) as typeof args.json, ); }); it('throws if `parseMethod=json` and .json() fails', async () => { expect.assertions(3); const mockTextUrl = '/mock/text/url'; const mockTextResponse = '<html><head></head><body>I could be a stack trace or something</body></html>'; fetchMock.get(mockTextUrl, mockTextResponse); let error; try { await parseResponse(callApi({ url: mockTextUrl, method: 'GET' })); } catch (err) { error = err as Error; } finally { expect(fetchMock.calls(mockTextUrl)).toHaveLength(1); expect(error?.stack).toBeDefined(); expect(error?.message).toContain('Unexpected token'); } }); it('resolves to { text, response } if the `parseMethod=text`', async () => { expect.assertions(4); // test with json + bigint to ensure that it was not first parsed as json const mockTextParseUrl = '/mock/textparse/url'; const mockTextJsonResponse = '{ "value": 9223372036854775807 }'; fetchMock.get(mockTextParseUrl, mockTextJsonResponse); const args = await parseResponse( callApi({ url: mockTextParseUrl, method: 'GET' }), 'text', ); expect(fetchMock.calls(mockTextParseUrl)).toHaveLength(1); const keys = Object.keys(args); expect(keys).toContain('response'); expect(keys).toContain('text'); expect(args.text).toBe(mockTextJsonResponse); }); it('throws if parseMethod is not null|json|text', async () => { expect.assertions(1); let error; try { await parseResponse( callApi({ url: mockNoParseUrl, method: 'GET' }), 'something-else' as never, ); } catch (err) { error = err; } finally { expect(error.message).toEqual( expect.stringContaining('Expected parseResponse=json'), ); } }); it('resolves to unmodified `Response` object if `parseMethod=null|raw`', async () => { expect.assertions(3); const responseNull = await parseResponse( callApi({ url: mockNoParseUrl, method: 'GET' }), null, ); const responseRaw = await parseResponse( callApi({ url: mockNoParseUrl, method: 'GET' }), 'raw', ); expect(fetchMock.calls(mockNoParseUrl)).toHaveLength(2); expect(responseNull.bodyUsed).toBe(false); expect(responseRaw.bodyUsed).toBe(false); }); it('resolves to big number value if `parseMethod=json-bigint`', async () => { const mockBigIntUrl = '/mock/get/bigInt'; const mockGetBigIntPayload = '{ "value": 9223372036854775807, "minus": { "value": -483729382918228373892, "str": "something" }, "number": 1234, "floatValue": { "plus": 0.3452211361231223, "minus": -0.3452211361231223 } }'; fetchMock.get(mockBigIntUrl, mockGetBigIntPayload); const responseBigNumber = await parseResponse( callApi({ url: mockBigIntUrl, method: 'GET' }), 'json-bigint', ); expect(`${responseBigNumber.json.value}`).toEqual('9223372036854775807'); expect(`${responseBigNumber.json.minus.value}`).toEqual( '-483729382918228373892', ); expect(responseBigNumber.json.number).toEqual(1234); expect(responseBigNumber.json.floatValue.plus).toEqual(0.3452211361231223); expect(responseBigNumber.json.floatValue.minus).toEqual( -0.3452211361231223, ); expect( responseBigNumber.json.floatValue.plus + responseBigNumber.json.floatValue.minus, ).toEqual(0); expect( responseBigNumber.json.floatValue.plus / responseBigNumber.json.floatValue.minus, ).toEqual(-1); expect(Math.min(responseBigNumber.json.floatValue.plus, 0)).toEqual(0); expect(Math.abs(responseBigNumber.json.floatValue.minus)).toEqual( responseBigNumber.json.floatValue.plus, ); }); it('rejects if request.ok=false', async () => { expect.assertions(3); const mockNotOkayUrl = '/mock/notokay/url'; fetchMock.get(mockNotOkayUrl, 404); // 404s result in not response.ok=false const apiPromise = callApi({ url: mockNotOkayUrl, method: 'GET' }); let error; try { await parseResponse(apiPromise); } catch (err) { error = err as { ok: boolean; status: number }; } finally { expect(fetchMock.calls(mockNotOkayUrl)).toHaveLength(1); expect(error?.ok).toBe(false); expect(error?.status).toBe(404); } }); });
5,515
0
petrpan-code/apache/superset/superset-frontend/packages/superset-ui-core/test/connection
petrpan-code/apache/superset/superset-frontend/packages/superset-ui-core/test/connection/callApi/rejectAfterTimeout.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 rejectAfterTimeout from '../../../src/connection/callApi/rejectAfterTimeout'; describe('rejectAfterTimeout()', () => { it('returns a promise that rejects after the specified timeout', async () => { expect.assertions(1); jest.useFakeTimers(); let error; try { const promise = rejectAfterTimeout(10); jest.advanceTimersByTime(11); await promise; } catch (err) { error = err; } finally { expect(error).toBeDefined(); } jest.useRealTimers(); }); });
5,517
0
petrpan-code/apache/superset/superset-frontend/packages/superset-ui-core/test
petrpan-code/apache/superset/superset-frontend/packages/superset-ui-core/test/currency-format/CurrencyFormatter.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 { CurrencyFormatter, getCurrencySymbol, NumberFormats, } from '@superset-ui/core'; it('getCurrencySymbol', () => { expect( getCurrencySymbol({ symbol: 'PLN', symbolPosition: 'prefix' }), ).toEqual('PLN'); expect( getCurrencySymbol({ symbol: 'USD', symbolPosition: 'prefix' }), ).toEqual('$'); expect(() => getCurrencySymbol({ symbol: 'INVALID_CODE', symbolPosition: 'prefix' }), ).toThrow(RangeError); }); it('CurrencyFormatter object fields', () => { const defaultCurrencyFormatter = new CurrencyFormatter({ currency: { symbol: 'USD', symbolPosition: 'prefix' }, }); expect(defaultCurrencyFormatter.d3Format).toEqual(NumberFormats.SMART_NUMBER); expect(defaultCurrencyFormatter.locale).toEqual('en-US'); expect(defaultCurrencyFormatter.currency).toEqual({ symbol: 'USD', symbolPosition: 'prefix', }); const currencyFormatter = new CurrencyFormatter({ currency: { symbol: 'PLN', symbolPosition: 'suffix' }, locale: 'pl-PL', d3Format: ',.1f', }); expect(currencyFormatter.d3Format).toEqual(',.1f'); expect(currencyFormatter.locale).toEqual('pl-PL'); expect(currencyFormatter.currency).toEqual({ symbol: 'PLN', symbolPosition: 'suffix', }); }); it('CurrencyFormatter:hasValidCurrency', () => { const currencyFormatter = new CurrencyFormatter({ currency: { symbol: 'USD', symbolPosition: 'prefix' }, }); expect(currencyFormatter.hasValidCurrency()).toBe(true); const currencyFormatterWithoutPosition = new CurrencyFormatter({ // @ts-ignore currency: { symbol: 'USD' }, }); expect(currencyFormatterWithoutPosition.hasValidCurrency()).toBe(true); const currencyFormatterWithoutSymbol = new CurrencyFormatter({ // @ts-ignore currency: { symbolPosition: 'prefix' }, }); expect(currencyFormatterWithoutSymbol.hasValidCurrency()).toBe(false); // @ts-ignore const currencyFormatterWithoutCurrency = new CurrencyFormatter({}); expect(currencyFormatterWithoutCurrency.hasValidCurrency()).toBe(false); }); it('CurrencyFormatter:getNormalizedD3Format', () => { const currencyFormatter = new CurrencyFormatter({ currency: { symbol: 'USD', symbolPosition: 'prefix' }, }); expect(currencyFormatter.getNormalizedD3Format()).toEqual( currencyFormatter.d3Format, ); const currencyFormatter2 = new CurrencyFormatter({ currency: { symbol: 'USD', symbolPosition: 'prefix' }, d3Format: ',.1f', }); expect(currencyFormatter2.getNormalizedD3Format()).toEqual( currencyFormatter2.d3Format, ); const currencyFormatter3 = new CurrencyFormatter({ currency: { symbol: 'USD', symbolPosition: 'prefix' }, d3Format: '$,.1f', }); expect(currencyFormatter3.getNormalizedD3Format()).toEqual(',.1f'); const currencyFormatter4 = new CurrencyFormatter({ currency: { symbol: 'USD', symbolPosition: 'prefix' }, d3Format: ',.1%', }); expect(currencyFormatter4.getNormalizedD3Format()).toEqual(',.1'); }); it('CurrencyFormatter:format', () => { const VALUE = 56100057; const currencyFormatterWithPrefix = new CurrencyFormatter({ currency: { symbol: 'USD', symbolPosition: 'prefix' }, }); expect(currencyFormatterWithPrefix(VALUE)).toEqual( currencyFormatterWithPrefix.format(VALUE), ); expect(currencyFormatterWithPrefix(VALUE)).toEqual('$ 56.1M'); const currencyFormatterWithSuffix = new CurrencyFormatter({ currency: { symbol: 'USD', symbolPosition: 'suffix' }, }); expect(currencyFormatterWithSuffix(VALUE)).toEqual('56.1M $'); const currencyFormatterWithoutPosition = new CurrencyFormatter({ // @ts-ignore currency: { symbol: 'USD' }, }); expect(currencyFormatterWithoutPosition(VALUE)).toEqual('56.1M $'); // @ts-ignore const currencyFormatterWithoutCurrency = new CurrencyFormatter({}); expect(currencyFormatterWithoutCurrency(VALUE)).toEqual('56.1M'); const currencyFormatterWithCustomD3 = new CurrencyFormatter({ currency: { symbol: 'USD', symbolPosition: 'prefix' }, d3Format: ',.1f', }); expect(currencyFormatterWithCustomD3(VALUE)).toEqual('$ 56,100,057.0'); const currencyFormatterWithPercentD3 = new CurrencyFormatter({ currency: { symbol: 'USD', symbolPosition: 'prefix' }, d3Format: ',.1f%', }); expect(currencyFormatterWithPercentD3(VALUE)).toEqual('$ 56,100,057.0'); const currencyFormatterWithCurrencyD3 = new CurrencyFormatter({ currency: { symbol: 'PLN', symbolPosition: 'suffix' }, d3Format: '$,.1f', }); expect(currencyFormatterWithCurrencyD3(VALUE)).toEqual('56,100,057.0 PLN'); });
5,518
0
petrpan-code/apache/superset/superset-frontend/packages/superset-ui-core/test
petrpan-code/apache/superset/superset-frontend/packages/superset-ui-core/test/currency-format/utils.test.ts
/* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ import { buildCustomFormatters, CurrencyFormatter, getCustomFormatter, getNumberFormatter, getValueFormatter, NumberFormatter, ValueFormatter, } from '@superset-ui/core'; test('buildCustomFormatters without saved metrics returns empty object', () => { expect( buildCustomFormatters( [ { expressionType: 'SIMPLE', aggregate: 'COUNT', column: { column_name: 'test' }, }, ], { sum__num: { symbol: 'USD', symbolPosition: 'prefix' }, }, {}, ',.1f', undefined, ), ).toEqual({}); expect( buildCustomFormatters( undefined, { sum__num: { symbol: 'USD', symbolPosition: 'prefix' }, }, {}, ',.1f', undefined, ), ).toEqual({}); }); test('buildCustomFormatters with saved metrics returns custom formatters object', () => { const customFormatters: Record<string, ValueFormatter> = buildCustomFormatters( [ { expressionType: 'SIMPLE', aggregate: 'COUNT', column: { column_name: 'test' }, }, 'sum__num', 'count', ], { sum__num: { symbol: 'USD', symbolPosition: 'prefix' }, }, { sum__num: ',.2' }, ',.1f', undefined, ); expect(customFormatters).toEqual({ sum__num: expect.any(Function), count: expect.any(Function), }); expect(customFormatters.sum__num).toBeInstanceOf(CurrencyFormatter); expect(customFormatters.count).toBeInstanceOf(NumberFormatter); expect((customFormatters.sum__num as CurrencyFormatter).d3Format).toEqual( ',.1f', ); }); test('buildCustomFormatters uses dataset d3 format if not provided in control panel', () => { const customFormatters: Record<string, ValueFormatter> = buildCustomFormatters( [ { expressionType: 'SIMPLE', aggregate: 'COUNT', column: { column_name: 'test' }, }, 'sum__num', 'count', ], { sum__num: { symbol: 'USD', symbolPosition: 'prefix' }, }, { sum__num: ',.2' }, undefined, undefined, ); expect((customFormatters.sum__num as CurrencyFormatter).d3Format).toEqual( ',.2', ); }); test('getCustomFormatter', () => { const customFormatters = { sum__num: new CurrencyFormatter({ currency: { symbol: 'USD', symbolPosition: 'prefix' }, }), count: getNumberFormatter(), }; expect(getCustomFormatter(customFormatters, 'count')).toEqual( customFormatters.count, ); expect( getCustomFormatter(customFormatters, ['count', 'sum__num'], 'count'), ).toEqual(customFormatters.count); expect(getCustomFormatter(customFormatters, ['count', 'sum__num'])).toEqual( undefined, ); }); test('getValueFormatter', () => { expect( getValueFormatter(['count', 'sum__num'], {}, {}, ',.1f', undefined), ).toBeInstanceOf(NumberFormatter); expect( getValueFormatter( ['count', 'sum__num'], {}, {}, ',.1f', undefined, 'count', ), ).toBeInstanceOf(NumberFormatter); expect( getValueFormatter( ['count', 'sum__num'], { count: { symbol: 'USD', symbolPosition: 'prefix' } }, {}, ',.1f', undefined, 'count', ), ).toBeInstanceOf(CurrencyFormatter); }); test('getValueFormatter with currency from control panel', () => { const countFormatter = getValueFormatter( ['count', 'sum__num'], { count: { symbol: 'USD', symbolPosition: 'prefix' } }, {}, ',.1f', { symbol: 'EUR', symbolPosition: 'suffix' }, 'count', ); expect(countFormatter).toBeInstanceOf(CurrencyFormatter); expect((countFormatter as CurrencyFormatter).currency).toEqual({ symbol: 'EUR', symbolPosition: 'suffix', }); }); test('getValueFormatter with currency from control panel when no saved currencies', () => { const formatter = getValueFormatter( ['count', 'sum__num'], {}, {}, ',.1f', { symbol: 'EUR', symbolPosition: 'suffix' }, undefined, ); expect(formatter).toBeInstanceOf(CurrencyFormatter); expect((formatter as CurrencyFormatter).currency).toEqual({ symbol: 'EUR', symbolPosition: 'suffix', }); }); test('getValueFormatter return NumberFormatter when no currency formatters', () => { const formatter = getValueFormatter( ['count', 'sum__num'], {}, {}, ',.1f', undefined, undefined, ); expect(formatter).toBeInstanceOf(NumberFormatter); });
5,519
0
petrpan-code/apache/superset/superset-frontend/packages/superset-ui-core/test
petrpan-code/apache/superset/superset-frontend/packages/superset-ui-core/test/dimension/computeMaxFontSize.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 { computeMaxFontSize } from '@superset-ui/core'; import { addDummyFill, removeDummyFill, SAMPLE_TEXT } from './getBBoxDummyFill'; describe('computeMaxFontSize(input)', () => { describe('returns dimension of the given text', () => { beforeEach(addDummyFill); afterEach(removeDummyFill); it('requires either idealFontSize or maxHeight', () => { expect(() => { computeMaxFontSize({ text: SAMPLE_TEXT[0], }); }).toThrow(); }); it('computes maximum font size for given maxWidth and maxHeight', () => { expect( computeMaxFontSize({ maxWidth: 400, maxHeight: 30, text: 'sample text', }), ).toEqual(30); }); it('computes maximum font size for given idealFontSize and maxHeight', () => { expect( computeMaxFontSize({ maxHeight: 20, idealFontSize: 40, text: SAMPLE_TEXT[0], }), ).toEqual(20); }); it('computes maximum font size for given maxWidth and idealFontSize', () => { expect( computeMaxFontSize({ maxWidth: 250, idealFontSize: 40, text: SAMPLE_TEXT[0], }), ).toEqual(25); }); it('ensure idealFontSize is used if the maximum font size calculation goes below zero', () => { expect( computeMaxFontSize({ maxWidth: 5, idealFontSize: 34, text: SAMPLE_TEXT[0], }), ).toEqual(34); }); }); });