Test plugins: Add datasource test plugin with field tests (#95472)

* add new test plugin

* add some field validation tests

* update lockfile

* fix bad test file name
This commit is contained in:
Erik Sundell
2024-11-01 08:25:27 +01:00
committed by GitHub
parent f3bdf4455c
commit c29ed503db
19 changed files with 500 additions and 1 deletions

View File

@ -0,0 +1,93 @@
import { getBackendSrv, isFetchError } from '@grafana/runtime';
import {
CoreApp,
DataQueryRequest,
DataQueryResponse,
DataSourceApi,
DataSourceInstanceSettings,
createDataFrame,
FieldType,
} from '@grafana/data';
import { MyQuery, MyDataSourceOptions, DEFAULT_QUERY, DataSourceResponse } from './types';
import { lastValueFrom } from 'rxjs';
export class DataSource extends DataSourceApi<MyQuery, MyDataSourceOptions> {
baseUrl: string;
constructor(instanceSettings: DataSourceInstanceSettings<MyDataSourceOptions>) {
super(instanceSettings);
this.baseUrl = instanceSettings.url!;
}
getDefaultQuery(_: CoreApp): Partial<MyQuery> {
return DEFAULT_QUERY;
}
filterQuery(query: MyQuery): boolean {
// if no query has been provided, prevent the query from being executed
return !!query.queryText;
}
async query(options: DataQueryRequest<MyQuery>): Promise<DataQueryResponse> {
const { range } = options;
const from = range!.from.valueOf();
const to = range!.to.valueOf();
// Return a constant for each query.
const data = options.targets.map((target) => {
return createDataFrame({
refId: target.refId,
fields: [
{ name: 'Time', values: [from, to], type: FieldType.time },
{ name: 'Value', values: [target.constant, target.constant], type: FieldType.number },
],
});
});
return { data };
}
async request(url: string, params?: string) {
const response = getBackendSrv().fetch<DataSourceResponse>({
url: `${this.baseUrl}${url}${params?.length ? `?${params}` : ''}`,
});
return lastValueFrom(response);
}
/**
* Checks whether we can connect to the API.
*/
async testDatasource() {
const defaultErrorMessage = 'Cannot connect to API';
try {
const response = await this.request('/health');
if (response.status === 200) {
return {
status: 'success',
message: 'Success',
};
} else {
return {
status: 'error',
message: response.statusText ? response.statusText : defaultErrorMessage,
};
}
} catch (err) {
let message = '';
if (typeof err === 'string') {
message = err;
} else if (isFetchError(err)) {
message = 'Fetch error: ' + (err.statusText ? err.statusText : defaultErrorMessage);
if (err.data && err.data.error && err.data.error.code) {
message += ': ' + err.data.error.code + '. ' + err.data.error.message;
}
}
return {
status: 'error',
message,
};
}
}
}