mirror of
https://github.com/apache/superset.git
synced 2026-04-22 01:24:43 +00:00
test: DatabaseSelector (#13581)
* Moving DatabaseSelector to a folder * Tests for DatabaseSelector * Using factory for props * Update superset-frontend/src/components/DatabaseSelector/DatabaseSelector.test.tsx Co-authored-by: Michael S. Molina <70410625+michael-s-molina@users.noreply.github.com> * Update superset-frontend/src/components/DatabaseSelector/DatabaseSelector.test.tsx Co-authored-by: Michael S. Molina <70410625+michael-s-molina@users.noreply.github.com> * Update superset-frontend/src/components/DatabaseSelector/DatabaseSelector.test.tsx Co-authored-by: Michael S. Molina <70410625+michael-s-molina@users.noreply.github.com> * apply waitFor and remove act Co-authored-by: Michael S. Molina <70410625+michael-s-molina@users.noreply.github.com>
This commit is contained in:
@@ -0,0 +1,202 @@
|
||||
/**
|
||||
* Licensed to the Apache Software Foundation (ASF) under one
|
||||
* or more contributor license agreements. See the NOTICE file
|
||||
* distributed with this work for additional information
|
||||
* regarding copyright ownership. The ASF licenses this file
|
||||
* to you under the Apache License, Version 2.0 (the
|
||||
* "License"); you may not use this file except in compliance
|
||||
* with the License. You may obtain a copy of the License at
|
||||
*
|
||||
* http://www.apache.org/licenses/LICENSE-2.0
|
||||
*
|
||||
* Unless required by applicable law or agreed to in writing,
|
||||
* software distributed under the License is distributed on an
|
||||
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
|
||||
* KIND, either express or implied. See the License for the
|
||||
* specific language governing permissions and limitations
|
||||
* under the License.
|
||||
*/
|
||||
|
||||
import React from 'react';
|
||||
import { render, screen, waitFor } from 'spec/helpers/testing-library';
|
||||
import { SupersetClient } from '@superset-ui/core';
|
||||
import userEvent from '@testing-library/user-event';
|
||||
import DatabaseSelector from '.';
|
||||
|
||||
const SupersetClientGet = jest.spyOn(SupersetClient, 'get');
|
||||
|
||||
const createProps = () => ({
|
||||
dbId: 1,
|
||||
formMode: false,
|
||||
isDatabaseSelectEnabled: true,
|
||||
readOnly: false,
|
||||
schema: 'public',
|
||||
sqlLabMode: true,
|
||||
getDbList: jest.fn(),
|
||||
getTableList: jest.fn(),
|
||||
handleError: jest.fn(),
|
||||
onDbChange: jest.fn(),
|
||||
onSchemaChange: jest.fn(),
|
||||
onSchemasLoad: jest.fn(),
|
||||
onChange: jest.fn(),
|
||||
});
|
||||
|
||||
beforeEach(() => {
|
||||
jest.resetAllMocks();
|
||||
SupersetClientGet.mockImplementation(
|
||||
async ({ endpoint }: { endpoint: string }) => {
|
||||
if (endpoint.includes('schemas')) {
|
||||
return {
|
||||
json: { result: ['information_schema', 'public'] },
|
||||
} as any;
|
||||
}
|
||||
if (endpoint.includes('/function_names')) {
|
||||
return {
|
||||
json: { function_names: [] },
|
||||
} as any;
|
||||
}
|
||||
return {
|
||||
json: {
|
||||
count: 1,
|
||||
description_columns: {},
|
||||
ids: [1],
|
||||
label_columns: {
|
||||
allow_csv_upload: 'Allow Csv Upload',
|
||||
allow_ctas: 'Allow Ctas',
|
||||
allow_cvas: 'Allow Cvas',
|
||||
allow_dml: 'Allow Dml',
|
||||
allow_multi_schema_metadata_fetch:
|
||||
'Allow Multi Schema Metadata Fetch',
|
||||
allow_run_async: 'Allow Run Async',
|
||||
allows_cost_estimate: 'Allows Cost Estimate',
|
||||
allows_subquery: 'Allows Subquery',
|
||||
allows_virtual_table_explore: 'Allows Virtual Table Explore',
|
||||
backend: 'Backend',
|
||||
changed_on: 'Changed On',
|
||||
changed_on_delta_humanized: 'Changed On Delta Humanized',
|
||||
'created_by.first_name': 'Created By First Name',
|
||||
'created_by.last_name': 'Created By Last Name',
|
||||
database_name: 'Database Name',
|
||||
explore_database_id: 'Explore Database Id',
|
||||
expose_in_sqllab: 'Expose In Sqllab',
|
||||
force_ctas_schema: 'Force Ctas Schema',
|
||||
id: 'Id',
|
||||
},
|
||||
list_columns: [
|
||||
'allow_csv_upload',
|
||||
'allow_ctas',
|
||||
'allow_cvas',
|
||||
'allow_dml',
|
||||
'allow_multi_schema_metadata_fetch',
|
||||
'allow_run_async',
|
||||
'allows_cost_estimate',
|
||||
'allows_subquery',
|
||||
'allows_virtual_table_explore',
|
||||
'backend',
|
||||
'changed_on',
|
||||
'changed_on_delta_humanized',
|
||||
'created_by.first_name',
|
||||
'created_by.last_name',
|
||||
'database_name',
|
||||
'explore_database_id',
|
||||
'expose_in_sqllab',
|
||||
'force_ctas_schema',
|
||||
'id',
|
||||
],
|
||||
list_title: 'List Database',
|
||||
order_columns: [
|
||||
'allow_csv_upload',
|
||||
'allow_dml',
|
||||
'allow_run_async',
|
||||
'changed_on',
|
||||
'changed_on_delta_humanized',
|
||||
'created_by.first_name',
|
||||
'database_name',
|
||||
'expose_in_sqllab',
|
||||
],
|
||||
result: [
|
||||
{
|
||||
allow_csv_upload: false,
|
||||
allow_ctas: false,
|
||||
allow_cvas: false,
|
||||
allow_dml: false,
|
||||
allow_multi_schema_metadata_fetch: false,
|
||||
allow_run_async: false,
|
||||
allows_cost_estimate: null,
|
||||
allows_subquery: true,
|
||||
allows_virtual_table_explore: true,
|
||||
backend: 'postgresql',
|
||||
changed_on: '2021-03-09T19:02:07.141095',
|
||||
changed_on_delta_humanized: 'a day ago',
|
||||
created_by: null,
|
||||
database_name: 'examples',
|
||||
explore_database_id: 1,
|
||||
expose_in_sqllab: true,
|
||||
force_ctas_schema: null,
|
||||
id: 1,
|
||||
},
|
||||
],
|
||||
},
|
||||
} as any;
|
||||
},
|
||||
);
|
||||
});
|
||||
|
||||
test('Should render', async () => {
|
||||
const props = createProps();
|
||||
render(<DatabaseSelector {...props} />);
|
||||
expect(await screen.findByTestId('DatabaseSelector')).toBeInTheDocument();
|
||||
});
|
||||
|
||||
test('Refresh should work', async () => {
|
||||
const props = createProps();
|
||||
|
||||
render(<DatabaseSelector {...props} />);
|
||||
|
||||
await waitFor(() => {
|
||||
expect(SupersetClientGet).toBeCalledTimes(2);
|
||||
expect(props.getDbList).toBeCalledTimes(1);
|
||||
expect(props.getTableList).toBeCalledTimes(0);
|
||||
expect(props.handleError).toBeCalledTimes(0);
|
||||
expect(props.onDbChange).toBeCalledTimes(0);
|
||||
expect(props.onSchemaChange).toBeCalledTimes(0);
|
||||
expect(props.onSchemasLoad).toBeCalledTimes(1);
|
||||
expect(props.onChange).toBeCalledTimes(0);
|
||||
});
|
||||
|
||||
userEvent.click(screen.getByRole('button'));
|
||||
|
||||
await waitFor(() => {
|
||||
expect(SupersetClientGet).toBeCalledTimes(3);
|
||||
expect(props.getDbList).toBeCalledTimes(1);
|
||||
expect(props.getTableList).toBeCalledTimes(0);
|
||||
expect(props.handleError).toBeCalledTimes(0);
|
||||
expect(props.onDbChange).toBeCalledTimes(1);
|
||||
expect(props.onSchemaChange).toBeCalledTimes(1);
|
||||
expect(props.onSchemasLoad).toBeCalledTimes(2);
|
||||
expect(props.onChange).toBeCalledTimes(1);
|
||||
});
|
||||
});
|
||||
|
||||
test('Should database select display options', async () => {
|
||||
const props = createProps();
|
||||
render(<DatabaseSelector {...props} />);
|
||||
const selector = await screen.findByText('Database:');
|
||||
expect(selector).toBeInTheDocument();
|
||||
expect(selector.parentElement).toHaveTextContent(
|
||||
'Database:postgresql examples',
|
||||
);
|
||||
});
|
||||
|
||||
test('Should schema select display options', async () => {
|
||||
const props = createProps();
|
||||
render(<DatabaseSelector {...props} />);
|
||||
|
||||
const selector = await screen.findByText('Schema:');
|
||||
expect(selector).toBeInTheDocument();
|
||||
expect(selector.parentElement).toHaveTextContent('Schema: public');
|
||||
|
||||
userEvent.click(screen.getByRole('button'));
|
||||
|
||||
expect(await screen.findByText('Select a schema (2)')).toBeInTheDocument();
|
||||
});
|
||||
290
superset-frontend/src/components/DatabaseSelector/index.tsx
Normal file
290
superset-frontend/src/components/DatabaseSelector/index.tsx
Normal file
@@ -0,0 +1,290 @@
|
||||
/**
|
||||
* Licensed to the Apache Software Foundation (ASF) under one
|
||||
* or more contributor license agreements. See the NOTICE file
|
||||
* distributed with this work for additional information
|
||||
* regarding copyright ownership. The ASF licenses this file
|
||||
* to you under the Apache License, Version 2.0 (the
|
||||
* "License"); you may not use this file except in compliance
|
||||
* with the License. You may obtain a copy of the License at
|
||||
*
|
||||
* http://www.apache.org/licenses/LICENSE-2.0
|
||||
*
|
||||
* Unless required by applicable law or agreed to in writing,
|
||||
* software distributed under the License is distributed on an
|
||||
* "AS IS" BASIS, WITHOUT WARRANTIES 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, { ReactNode, useEffect, useState } from 'react';
|
||||
import { styled, SupersetClient, t } from '@superset-ui/core';
|
||||
import rison from 'rison';
|
||||
import { Select } from 'src/components/Select';
|
||||
import Label from 'src/components/Label';
|
||||
import RefreshLabel from 'src/components/RefreshLabel';
|
||||
import SupersetAsyncSelect from 'src/components/AsyncSelect';
|
||||
|
||||
const FieldTitle = styled.p`
|
||||
color: ${({ theme }) => theme.colors.secondary.light2};
|
||||
font-size: ${({ theme }) => theme.typography.sizes.s}px;
|
||||
margin: 20px 0 10px 0;
|
||||
text-transform: uppercase;
|
||||
`;
|
||||
|
||||
const DatabaseSelectorWrapper = styled.div`
|
||||
.fa-refresh {
|
||||
padding-left: 9px;
|
||||
}
|
||||
|
||||
.refresh-col {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
width: 30px;
|
||||
margin-left: ${({ theme }) => theme.gridUnit}px;
|
||||
}
|
||||
|
||||
.section {
|
||||
padding-bottom: 5px;
|
||||
display: flex;
|
||||
flex-direction: row;
|
||||
}
|
||||
|
||||
.select {
|
||||
flex-grow: 1;
|
||||
}
|
||||
`;
|
||||
|
||||
const DatabaseOption = styled.span`
|
||||
display: inline-flex;
|
||||
align-items: center;
|
||||
`;
|
||||
|
||||
interface DatabaseSelectorProps {
|
||||
dbId: number;
|
||||
formMode?: boolean;
|
||||
getDbList?: (arg0: any) => {};
|
||||
getTableList?: (dbId: number, schema: string, force: boolean) => {};
|
||||
handleError: (msg: string) => void;
|
||||
isDatabaseSelectEnabled?: boolean;
|
||||
onDbChange?: (db: any) => void;
|
||||
onSchemaChange?: (arg0?: any) => {};
|
||||
onSchemasLoad?: (schemas: Array<object>) => void;
|
||||
readOnly?: boolean;
|
||||
schema?: string;
|
||||
sqlLabMode?: boolean;
|
||||
onChange?: ({
|
||||
dbId,
|
||||
schema,
|
||||
}: {
|
||||
dbId: number;
|
||||
schema?: string;
|
||||
tableName?: string;
|
||||
}) => void;
|
||||
}
|
||||
|
||||
export default function DatabaseSelector({
|
||||
dbId,
|
||||
formMode = false,
|
||||
getDbList,
|
||||
getTableList,
|
||||
handleError,
|
||||
isDatabaseSelectEnabled = true,
|
||||
onChange,
|
||||
onDbChange,
|
||||
onSchemaChange,
|
||||
onSchemasLoad,
|
||||
readOnly = false,
|
||||
schema,
|
||||
sqlLabMode = false,
|
||||
}: DatabaseSelectorProps) {
|
||||
const [currentDbId, setCurrentDbId] = useState(dbId);
|
||||
const [currentSchema, setCurrentSchema] = useState<string | undefined>(
|
||||
schema,
|
||||
);
|
||||
const [schemaLoading, setSchemaLoading] = useState(false);
|
||||
const [schemaOptions, setSchemaOptions] = useState([]);
|
||||
|
||||
function fetchSchemas(databaseId: number, forceRefresh = false) {
|
||||
const actualDbId = databaseId || dbId;
|
||||
if (actualDbId) {
|
||||
setSchemaLoading(true);
|
||||
const queryParams = rison.encode({
|
||||
force: Boolean(forceRefresh),
|
||||
});
|
||||
const endpoint = `/api/v1/database/${actualDbId}/schemas/?q=${queryParams}`;
|
||||
return SupersetClient.get({ endpoint })
|
||||
.then(({ json }) => {
|
||||
const options = json.result.map((s: string) => ({
|
||||
value: s,
|
||||
label: s,
|
||||
title: s,
|
||||
}));
|
||||
setSchemaOptions(options);
|
||||
setSchemaLoading(false);
|
||||
if (onSchemasLoad) {
|
||||
onSchemasLoad(options);
|
||||
}
|
||||
})
|
||||
.catch(() => {
|
||||
setSchemaOptions([]);
|
||||
setSchemaLoading(false);
|
||||
handleError(t('Error while fetching schema list'));
|
||||
});
|
||||
}
|
||||
return Promise.resolve();
|
||||
}
|
||||
|
||||
useEffect(() => {
|
||||
if (currentDbId) {
|
||||
fetchSchemas(currentDbId);
|
||||
}
|
||||
}, [currentDbId]);
|
||||
|
||||
function onSelectChange({ dbId, schema }: { dbId: number; schema?: string }) {
|
||||
setCurrentDbId(dbId);
|
||||
setCurrentSchema(schema);
|
||||
if (onChange) {
|
||||
onChange({ dbId, schema, tableName: undefined });
|
||||
}
|
||||
}
|
||||
|
||||
function dbMutator(data: any) {
|
||||
if (getDbList) {
|
||||
getDbList(data.result);
|
||||
}
|
||||
if (data.result.length === 0) {
|
||||
handleError(t("It seems you don't have access to any database"));
|
||||
}
|
||||
return data.result.map((row: any) => ({
|
||||
...row,
|
||||
// label is used for the typeahead
|
||||
label: `${row.backend} ${row.database_name}`,
|
||||
}));
|
||||
}
|
||||
|
||||
function changeDataBase(db: any, force = false) {
|
||||
const dbId = db ? db.id : null;
|
||||
setSchemaOptions([]);
|
||||
if (onSchemaChange) {
|
||||
onSchemaChange(null);
|
||||
}
|
||||
if (onDbChange) {
|
||||
onDbChange(db);
|
||||
}
|
||||
fetchSchemas(dbId, force);
|
||||
onSelectChange({ dbId, schema: undefined });
|
||||
}
|
||||
|
||||
function changeSchema(schemaOpt: any, force = false) {
|
||||
const schema = schemaOpt ? schemaOpt.value : null;
|
||||
if (onSchemaChange) {
|
||||
onSchemaChange(schema);
|
||||
}
|
||||
setCurrentSchema(schema);
|
||||
onSelectChange({ dbId: currentDbId, schema });
|
||||
if (getTableList) {
|
||||
getTableList(currentDbId, schema, force);
|
||||
}
|
||||
}
|
||||
|
||||
function renderDatabaseOption(db: any) {
|
||||
return (
|
||||
<DatabaseOption title={db.database_name}>
|
||||
<Label type="default">{db.backend}</Label> {db.database_name}
|
||||
</DatabaseOption>
|
||||
);
|
||||
}
|
||||
|
||||
function renderSelectRow(select: ReactNode, refreshBtn: ReactNode) {
|
||||
return (
|
||||
<div className="section">
|
||||
<span className="select">{select}</span>
|
||||
<span className="refresh-col">{refreshBtn}</span>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
function renderDatabaseSelect() {
|
||||
const queryParams = rison.encode({
|
||||
order_columns: 'database_name',
|
||||
order_direction: 'asc',
|
||||
page: 0,
|
||||
page_size: -1,
|
||||
...(formMode || !sqlLabMode
|
||||
? {}
|
||||
: {
|
||||
filters: [
|
||||
{
|
||||
col: 'expose_in_sqllab',
|
||||
opr: 'eq',
|
||||
value: true,
|
||||
},
|
||||
],
|
||||
}),
|
||||
});
|
||||
|
||||
return renderSelectRow(
|
||||
<SupersetAsyncSelect
|
||||
data-test="select-database"
|
||||
dataEndpoint={`/api/v1/database/?q=${queryParams}`}
|
||||
onChange={(db: any) => changeDataBase(db)}
|
||||
onAsyncError={() =>
|
||||
handleError(t('Error while fetching database list'))
|
||||
}
|
||||
clearable={false}
|
||||
value={currentDbId}
|
||||
valueKey="id"
|
||||
valueRenderer={(db: any) => (
|
||||
<div>
|
||||
<span className="text-muted m-r-5">{t('Database:')}</span>
|
||||
{renderDatabaseOption(db)}
|
||||
</div>
|
||||
)}
|
||||
optionRenderer={renderDatabaseOption}
|
||||
mutator={dbMutator}
|
||||
placeholder={t('Select a database')}
|
||||
autoSelect
|
||||
isDisabled={!isDatabaseSelectEnabled || readOnly}
|
||||
/>,
|
||||
null,
|
||||
);
|
||||
}
|
||||
|
||||
function renderSchemaSelect() {
|
||||
const value = schemaOptions.filter(({ value }) => currentSchema === value);
|
||||
const refresh = !formMode && !readOnly && (
|
||||
<RefreshLabel
|
||||
onClick={() => changeDataBase({ id: dbId }, true)}
|
||||
tooltipContent={t('Force refresh schema list')}
|
||||
/>
|
||||
);
|
||||
|
||||
return renderSelectRow(
|
||||
<Select
|
||||
name="select-schema"
|
||||
placeholder={t('Select a schema (%s)', schemaOptions.length)}
|
||||
options={schemaOptions}
|
||||
value={value}
|
||||
valueRenderer={o => (
|
||||
<div>
|
||||
<span className="text-muted">{t('Schema:')}</span> {o.label}
|
||||
</div>
|
||||
)}
|
||||
isLoading={schemaLoading}
|
||||
autosize={false}
|
||||
onChange={item => changeSchema(item)}
|
||||
isDisabled={readOnly}
|
||||
/>,
|
||||
refresh,
|
||||
);
|
||||
}
|
||||
|
||||
return (
|
||||
<DatabaseSelectorWrapper data-test="DatabaseSelector">
|
||||
{formMode && <FieldTitle>{t('datasource')}</FieldTitle>}
|
||||
{renderDatabaseSelect()}
|
||||
{formMode && <FieldTitle>{t('schema')}</FieldTitle>}
|
||||
{renderSchemaSelect()}
|
||||
</DatabaseSelectorWrapper>
|
||||
);
|
||||
}
|
||||
Reference in New Issue
Block a user