E2E: migrate to playwright (#107241)

* separate playwright into its own folder

* better separation

* add login scenario, add tags

* remove ui option

* update CODEOWNERS

* add a panels suite test

* migrate queries test to playwright

* rename + add dashlist test

* add panelEdit_base

* add geomap map controls test

* add geomap-layer-types

* add geomap-spatial-operations tests

* add frontend-sandbox-panel tests

* add smoke-tests-suite

* add comment about adding datasource

* add dashboard-browse-nested

* add dashboard-browse

* add dashboard-export-json

* add dashboard-keybindings test

* remove @wip tag

* turn on screenshots and add comment for why this test fails

* add dashboard-links-without-slug test

* try adding permissions in the test as well

* add dashboard-live-streaming

* context in the test doesn't work - sad

* create dashboard-public-templating

* add dashboard-public-create and make live streaming more resilient

* add share externally test

* add dashboard-share-internally

* add share-snapshot-create test

* add dashboard-templating

* add timepicker tests

* add embedded-dashboard test

* add general_dashboards test

* add import-dashboard test

* add load-options-from-url test

* add new-constant-variable test

* add custom-variable test

* add new-datasource-variable test

* add new-interval-variable test

* add text-box-variable test

* add new-query-variable test

* add horizontal repeat test

* add panel-vertical-repeat test

* add empty-row-repeat test

* add set-options-from-ui test

* add snapshot-create test

* add templating test

* add textbox-variables test

* add cloud-plugins-suite

* add storybook verification tests

* add playwright storybook verification workflow

* add playwright browsers

* update CODEOWNERS

* test change to trigger storybook verification workflows

* try container instead

* get the version right...

* go back to installing - less chance of forgetting to update

* Basic Github Actions

Squashed commit of the following:

commit f84c650a71
Author: joshhunt <josh.hunt@grafana.com>
Date:   Tue Jul 1 13:23:46 2025 +0100

    add arg for sharding, but not using it yet

commit 7bcf0512c6
Author: joshhunt <josh.hunt@grafana.com>
Date:   Tue Jul 1 12:30:30 2025 +0100

    less newline

commit b643911882
Author: joshhunt <josh.hunt@grafana.com>
Date:   Tue Jul 1 12:24:31 2025 +0100

    less logs

commit 38f871e9c2
Author: joshhunt <josh.hunt@grafana.com>
Date:   Tue Jul 1 10:00:26 2025 +0100

    fix yaml

commit db9a773136
Author: joshhunt <josh.hunt@grafana.com>
Date:   Tue Jul 1 09:57:47 2025 +0100

    clean up files

commit c0525f41fa
Author: joshhunt <josh.hunt@grafana.com>
Date:   Tue Jul 1 09:44:56 2025 +0100

    gha workflow

commit 895bea7c52
Author: joshhunt <josh.hunt@grafana.com>
Date:   Mon Jun 30 19:33:08 2025 +0100

    working dagger

commit cea1f84437
Author: joshhunt <josh.hunt@grafana.com>
Date:   Mon Jun 30 16:17:46 2025 +0100

    wip

* shard gha

* some tidy up

* add flags for exporting results, and a gha step to merge runs

* fix shard gha

* add dashboard-duplicate-panel test

* add dashboard-outline test

* add dashboards-add-panel

* remove some commented out code

* add dashboards-title-description test

* add dashboards-remove-panel

* don't install cypress

* gha: check playwright results

* add dashboards-edit-adhoc-variables test

* fix check-jobs

* add dagger cloud token

* add dagger cloud token

* add edit-datasource-variable test

* update CODEOWNERS

* add dashboards-edit-group-by-variables (skipped for now)

* add dashboards-edit-panel-title-description test

* add dashboards-edit-transparent-bg test

* add dashboards-edit-query-variables test

* run with 8 shards

* add dashboards-edit-variables

* tidy up gha

* add dashboard-group-panels

* fix action

* try to cache the grafana build

* fix missing action becuase no checkout, use builtin continue-on-error instead

* fix missing id

* cat out.txt

* debug build cache

* fix debug build cache

* add dashboards-panel-layouts test

* tidy up

* no more debug

* fix grafana dir

* add dashboards-move-panel test

* skip some failing tests

* mark up plugins tests with @plugins tag, only run @plugins tests in drone

* Hackathon/Playwright Conversion - Various Suite (#107516)

* Playwright Migration: Various Suite tests

* skipping bad tests

* fix some tests that can fail

* fix uid

* separate user for the verify-i18n test

* build test plugins for grafana server

* properly blur input fields

* login manually

* get dashboardPage from goto

* ignore a couple of type assertions

* remove a couple of timeouts

* remove timeouts on dashboard-share-internally

* use toBeHidden

* make dashboard-share-internally more stable

* remove TEMP_DAGGER_TOKEN

* clean up visaulization-suggestions

* unskip gauge test

* unskip trace-view-scrolling

* attempt to make create variable utils stable

* unskip loki tests

* make go linter happy

* unskip edit-group-by-variables test

* unskip move panel tests

* isolate dashboard-timepicker tests with separate user

* create data source as part of smoke test

* make sure we're awaiting in dashboard-edit-adhoc-variables

* make dashboards-edit-variables test more robust

* Hackathon Playwright: Dashboards Search (#107580)

* Hackathon Playwright: Dashboards Search

* Feedback changes

* make trace-view-scrolling more stable

* add json report and bench step

* fix bench version

* move fail step to after the playwright report so we can report test failures

* fix output file name

* fix typo

* try wrap in expect.poll

* stability

* bit more tidy up

* fix dashboard-new-layouts tests

* move test-plugins to e2e-playwright

* fix go code for drone e2e run

* move loki plugin-e2e test

* make v2 dashboards work again

---------

Co-authored-by: joshhunt <josh.hunt@grafana.com>
Co-authored-by: Josh Hunt <joshhunt@users.noreply.github.com>
Co-authored-by: Collin Fingar <collin.fingar@grafana.com>
Co-authored-by: Jeff Levin <jeff@levinology.com>
This commit is contained in:
Ashley Harrison
2025-07-11 10:31:33 +01:00
committed by GitHub
co-authored by joshhunt Josh Hunt Collin Fingar Jeff Levin
parent ea0ddb3fc9
commit b6580ccb10
250 changed files with 22677 additions and 1038 deletions
@@ -1,8 +0,0 @@
import { test, expect } from '@grafana/plugin-e2e';
test('Smoke test: decoupled frontend plugin loads', async ({ createDataSourceConfigPage, page }) => {
await createDataSourceConfigPage({ type: 'grafana-azure-monitor-datasource' });
await expect(await page.getByText('Type: Azure Monitor', { exact: true })).toBeVisible();
await expect(await page.getByRole('heading', { name: 'Authentication', exact: true })).toBeVisible();
});
@@ -1,8 +0,0 @@
import { test, expect } from '@grafana/plugin-e2e';
test('Smoke test: decoupled frontend plugin loads', async ({ createDataSourceConfigPage, page }) => {
await createDataSourceConfigPage({ type: 'stackdriver' });
await expect(await page.getByText('Type: Google Cloud Monitoring', { exact: true })).toBeVisible();
await expect(await page.getByText('Google JWT File', { exact: true })).toBeVisible();
});
@@ -1,8 +0,0 @@
import { test, expect } from '@grafana/plugin-e2e';
test('Smoke test: decoupled frontend plugin loads', async ({ createDataSourceConfigPage, page }) => {
await createDataSourceConfigPage({ type: 'cloudwatch' });
await expect(await page.getByText('Type: CloudWatch', { exact: true })).toBeVisible();
await expect(await page.getByRole('heading', { name: 'Connection Details', exact: true })).toBeVisible();
});
@@ -1,8 +0,0 @@
import { test, expect } from '@grafana/plugin-e2e';
test('Smoke test: decoupled frontend plugin loads', async ({ createDataSourceConfigPage, page }) => {
await createDataSourceConfigPage({ type: 'elasticsearch' });
await expect(await page.getByText('Type: Elasticsearch', { exact: true })).toBeVisible();
await expect(await page.getByRole('heading', { name: 'Connection', exact: true })).toBeVisible();
});
-8
View File
@@ -1,8 +0,0 @@
import { test, expect } from '@grafana/plugin-e2e';
test('Smoke test: decoupled frontend plugin loads', async ({ createDataSourceConfigPage, page }) => {
await createDataSourceConfigPage({ type: 'graphite' });
await expect(await page.getByText('Type: Graphite', { exact: true })).toBeVisible();
await expect(await page.getByRole('heading', { name: 'HTTP', exact: true })).toBeVisible();
});
-8
View File
@@ -1,8 +0,0 @@
import { test, expect } from '@grafana/plugin-e2e';
test('Smoke test: decoupled frontend plugin loads', async ({ createDataSourceConfigPage, page }) => {
await createDataSourceConfigPage({ type: 'influxdb' });
await expect(await page.getByText('Type: InfluxDB', { exact: true })).toBeVisible();
await expect(await page.getByRole('heading', { name: 'HTTP', exact: true })).toBeVisible();
});
-8
View File
@@ -1,8 +0,0 @@
import { test, expect } from '@grafana/plugin-e2e';
test('Smoke test: plugin loads', async ({ createDataSourceConfigPage, page }) => {
await createDataSourceConfigPage({ type: 'jaeger' });
await expect(await page.getByText('Type: Jaeger', { exact: true })).toBeVisible();
await expect(await page.getByRole('heading', { name: 'Connection', exact: true })).toBeVisible();
});
-8
View File
@@ -1,8 +0,0 @@
import { test, expect } from '@grafana/plugin-e2e';
test('Smoke test: decoupled frontend plugin loads', async ({ createDataSourceConfigPage, page }) => {
await createDataSourceConfigPage({ type: 'loki' });
await expect(await page.getByText('Type: Loki', { exact: true })).toBeVisible();
await expect(await page.getByRole('heading', { name: 'Connection', exact: true })).toBeVisible();
});
-8
View File
@@ -1,8 +0,0 @@
import { test, expect } from '@grafana/plugin-e2e';
test('Smoke test: decoupled frontend plugin loads', async ({ createDataSourceConfigPage, page }) => {
await createDataSourceConfigPage({ type: 'mssql' });
await expect(await page.getByText('Type: Microsoft SQL Server', { exact: true })).toBeVisible();
await expect(await page.getByRole('heading', { name: 'Connection', exact: true })).toBeVisible();
});
-72
View File
@@ -1,72 +0,0 @@
export const normalTableName = 'normalTable';
export const tableNameWithSpecialCharacter = 'table-name';
export const tablesResponse = {
results: {
tables: {
status: 200,
frames: [
{
schema: {
refId: 'tables',
meta: {
executedQueryString:
"SELECT table_name FROM information_schema.tables WHERE table_schema = 'DataMaker' ORDER BY table_name",
},
fields: [{ name: 'TABLE_NAME', type: 'string', typeInfo: { frame: 'string', nullable: true } }],
},
data: { values: [[normalTableName, tableNameWithSpecialCharacter]] },
},
],
},
},
};
export const fieldsResponse = (refId: string) => ({
results: {
[refId]: {
status: 200,
frames: [
{
schema: {
refId,
meta: {
executedQueryString:
"SELECT column_name, data_type FROM information_schema.columns WHERE table_schema = 'DataMaker' AND table_name = 'RandomIntsWithTimes' ORDER BY column_name",
},
fields: [
{ name: 'COLUMN_NAME', type: 'string', typeInfo: { frame: 'string', nullable: true } },
{ name: 'DATA_TYPE', type: 'string', typeInfo: { frame: 'string', nullable: true } },
],
},
data: {
values: [
['createdAt', 'id', 'time', 'updatedAt', 'bigint', 'name'],
['datetime', 'int', 'datetime', 'datetime', 'int', 'string'],
],
},
},
],
},
},
});
export const datasetResponse = {
results: {
datasets: {
status: 200,
frames: [
{
schema: {
refId: 'datasets',
meta: {
executedQueryString:
"SELECT DISTINCT TABLE_SCHEMA from information_schema.TABLES where TABLE_TYPE != 'SYSTEM VIEW' ORDER BY TABLE_SCHEMA",
},
fields: [{ name: 'TABLE_SCHEMA', type: 'string', typeInfo: { frame: 'string', nullable: true } }],
},
data: { values: [['DataMaker', 'mysql', 'performance_schema', 'sys']] },
},
],
},
},
};
-25
View File
@@ -1,25 +0,0 @@
import { expect, test } from '@grafana/plugin-e2e';
import { tableNameWithSpecialCharacter } from './mocks/mysql.mocks';
import { mockDataSourceRequest } from './utils';
test.beforeEach(mockDataSourceRequest);
test('code editor autocomplete should handle table name escaping/quoting', async ({ explorePage, selectors, page }) => {
await page.getByLabel('Code').check();
const editor = explorePage.getByGrafanaSelector(selectors.components.CodeEditor.container).getByRole('textbox');
await editor.fill('S');
await page.getByLabel('SELECT <column> FROM <table>').locator('a').click();
await expect(page.getByLabel(tableNameWithSpecialCharacter)).toBeVisible();
await page.keyboard.press('Enter');
await expect(editor).toHaveValue(`SELECT FROM grafana.\`${tableNameWithSpecialCharacter}\``);
for (let i = 0; i < tableNameWithSpecialCharacter.length + 2; i++) {
await page.keyboard.press('Backspace');
}
await page.keyboard.press('Control+I');
await expect(page.getByLabel(tableNameWithSpecialCharacter)).toBeVisible();
});
-23
View File
@@ -1,23 +0,0 @@
import { PlaywrightTestArgs } from '@playwright/test';
import { PluginFixture } from '@grafana/plugin-e2e';
import { datasetResponse, fieldsResponse, tablesResponse } from './mocks/mysql.mocks';
export async function mockDataSourceRequest({ context, explorePage, selectors }: PlaywrightTestArgs & PluginFixture) {
await explorePage.datasource.set('gdev-mysql');
await context.route(selectors.apis.DataSource.queryPattern, async (route, request) => {
const refId = request.postDataJSON().queries[0].refId;
if (/fields-.*/g.test(refId)) {
return route.fulfill({ json: fieldsResponse(refId), status: 200 });
}
switch (refId) {
case 'tables':
return route.fulfill({ json: tablesResponse, status: 200 });
case 'datasets':
return route.fulfill({ json: datasetResponse, status: 200 });
default:
return route.continue();
}
});
}
@@ -1,164 +0,0 @@
import { selectors } from '@grafana/e2e-selectors';
import { test, expect } from '@grafana/plugin-e2e';
import { normalTableName } from './mocks/mysql.mocks';
import { mockDataSourceRequest } from './utils';
test.beforeEach(mockDataSourceRequest);
test('visual query builder should handle macros', async ({ explorePage, page }) => {
await explorePage.getByGrafanaSelector(selectors.components.SQLQueryEditor.headerTableSelector).click();
await page.getByText(normalTableName, { exact: true }).click();
// Open Data operations
await explorePage.getByGrafanaSelector(selectors.components.SQLQueryEditor.selectAggregation).click();
const select = page.getByLabel('Select options menu');
await select.locator(page.getByText('$__timeGroupAlias')).click();
// Open column selector
await explorePage.getByGrafanaSelector(selectors.components.SQLQueryEditor.selectFunctionParameter('Column')).click();
await select.locator(page.getByText('createdAt')).click();
// Open Interval selector
await explorePage
.getByGrafanaSelector(selectors.components.SQLQueryEditor.selectFunctionParameter('Interval'))
.click();
await select.locator(page.getByText('$__interval')).click();
await page.getByRole('button', { name: 'Add column' }).click();
await explorePage.getByGrafanaSelector(selectors.components.SQLQueryEditor.selectAggregation).nth(1).click();
await select.locator(page.getByText('AVG')).click();
await explorePage
.getByGrafanaSelector(selectors.components.SQLQueryEditor.selectFunctionParameter('Column'))
.nth(1)
.click();
await select.locator(page.getByText('bigint')).click();
// Validate the query
await expect(
explorePage.getByGrafanaSelector(selectors.components.CodeEditor.container).getByRole('textbox')
).toHaveValue(
`SELECT\n $__timeGroupAlias(createdAt, $__interval),\n AVG(\`bigint\`)\nFROM\n DataMaker.normalTable\nLIMIT\n 50`
);
});
test('visual query builder should handle time filter macro', async ({ explorePage, page }) => {
await explorePage.getByGrafanaSelector(selectors.components.SQLQueryEditor.headerTableSelector).click();
await page.getByText(normalTableName, { exact: true }).click();
// Open column selector
await explorePage.getByGrafanaSelector(selectors.components.SQLQueryEditor.selectColumn).click();
const select = page.getByLabel('Select options menu');
await select.locator(page.getByText('createdAt')).click();
// Toggle where row
await page.getByLabel('Filter').last().click();
// Click add filter button
await page.getByRole('button', { name: 'Add filter' }).click();
await page.getByRole('button', { name: 'Add filter' }).click(); // For some reason we need to click twice
// Open field selector
await explorePage.getByGrafanaSelector(selectors.components.SQLQueryEditor.filterField).click();
await select.locator(page.getByText('createdAt')).click();
// Open operator selector
await explorePage.getByGrafanaSelector(selectors.components.SQLQueryEditor.filterOperator).click();
await select.locator(page.getByText('Macros')).click();
// Open macros value selector
await explorePage.getByGrafanaSelector('Macros value selector').click();
await select.locator(page.getByText('timeFilter', { exact: true })).click();
// Validate that the timeFilter macro was added
await expect(
explorePage.getByGrafanaSelector(selectors.components.CodeEditor.container).getByRole('textbox')
).toHaveValue(`SELECT\n createdAt\nFROM\n DataMaker.normalTable\nWHERE\n $__timeFilter(createdAt)\nLIMIT\n 50`);
// Validate that the timeFilter macro was removed when changed to equals operator
await explorePage.getByGrafanaSelector(selectors.components.SQLQueryEditor.filterOperator).click();
await select.locator(page.getByText('==')).click();
await explorePage.getByGrafanaSelector(selectors.components.DateTimePicker.input).click();
await explorePage.getByGrafanaSelector(selectors.components.DateTimePicker.input).blur();
await expect(
explorePage.getByGrafanaSelector(selectors.components.CodeEditor.container).getByRole('textbox')
).not.toHaveValue(`SELECT\n createdAt\nFROM\n DataMaker.normalTable\nWHERE\n createdAt = NULL\nLIMIT\n 50`);
});
test('visual query builder should not crash when filter is set to select_any_in', async ({ explorePage, page }) => {
const queryParams = new URLSearchParams();
queryParams.set('schemaVersion', '1');
queryParams.set('orgId', '1');
const panes = {
mmm: {
datasource: 'P4FDCC188E688367F',
queries: [
{
refId: 'A',
datasource: {
type: 'mysql',
uid: 'P4FDCC188E688367F',
},
format: 'table',
rawSql: "SELECT * FROM DataMaker.normalTable WHERE name IN ('a') LIMIT 50 ",
editorMode: 'builder',
sql: {
columns: [
{
type: 'function',
parameters: [
{
type: 'functionParameter',
name: '*',
},
],
},
],
groupBy: [
{
type: 'groupBy',
property: {
type: 'string',
},
},
],
limit: 50,
whereJsonTree: {
id: 'baa99aa9-0123-4456-b89a-b195d1dcfc6a',
type: 'group',
children1: [
{
type: 'rule',
id: 'bb9a8bba-89ab-4cde-b012-3195d1dd2c91',
properties: {
fieldSrc: 'field',
field: 'name',
operator: 'select_any_in',
value: ['a'],
valueSrc: ['value'],
valueType: ['text'],
},
},
],
},
whereString: "name IN ('a')",
},
dataset: 'DataMaker',
table: 'normalTable',
},
],
},
};
queryParams.set('panes', JSON.stringify(panes));
await explorePage.goto({ queryParams });
// Validate the query
await expect(
explorePage.getByGrafanaSelector(selectors.components.CodeEditor.container).getByRole('textbox')
).toHaveValue(`SELECT\n *\nFROM\n DataMaker.normalTable\nWHERE\n name IN ('a')\nLIMIT\n 50`);
});
-8
View File
@@ -1,8 +0,0 @@
import { test, expect } from '@grafana/plugin-e2e';
test('Smoke test: decoupled frontend plugin loads', async ({ createDataSourceConfigPage, page }) => {
await createDataSourceConfigPage({ type: 'opentsdb' });
await expect(await page.getByText('Type: OpenTSDB', { exact: true })).toBeVisible();
await expect(await page.getByRole('heading', { name: 'HTTP', exact: true })).toBeVisible();
});
@@ -1,3 +0,0 @@
# @grafana/plugin-e2e API tests
The purpose of the E2E tests in this directory is not to test the plugins per se - it's to verify that the fixtures, models and expect matchers provided by the [`@grafana/plugin-e2e`](https://github.com/grafana/plugin-tools/tree/main/packages/plugin-e2e) package are compatible with the latest version of Grafana. If you find that any of these tests are failing, it's likely because you have made changes in the Grafana UI that breaks the end-to-end testing APIs in plugin-e2e. For information on how to address this, follow the instructions in the [contributing guidelines](https://github.com/grafana/plugin-tools/blob/main/packages/plugin-e2e/CONTRIBUTING.md#how-to-fix-broken-test-scenarios-after-changes-in-grafana) for the @grafana/plugin-e2e package in the plugin-tools repository.
@@ -1,28 +0,0 @@
import * as e2e from '@grafana/e2e-selectors';
import { expect, test } from '@grafana/plugin-e2e';
// let's disable the feature toggles for now, otherwise the getAlertRuleQueryRow fails and I don't see any other way to get the query row
test.use({ featureToggles: { alertingQueryAndExpressionsStepMode: false, alertingNotificationsStepMode: false } });
test('should evaluate to false if entire request returns 200 but partial query result is invalid', async ({
page,
alertRuleEditPage,
}) => {
await alertRuleEditPage.alertRuleNameField.fill('Test Alert Rule');
//add working query
const queryA = alertRuleEditPage.getAlertRuleQueryRow('A');
await queryA.datasource.set('gdev-prometheus');
await queryA.locator.getByLabel('Code').click();
await page.waitForFunction(() => window.monaco);
await queryA.getByGrafanaSelector(e2e.selectors.components.QueryField.container).click();
await page.keyboard.insertText('topk(5, max(scrape_duration_seconds) by (job))');
//add broken query
const newQuery = await alertRuleEditPage.clickAddQueryRow();
await newQuery.datasource.set('gdev-prometheus');
await newQuery.locator.getByLabel('Code').click();
await newQuery.getByGrafanaSelector(e2e.selectors.components.QueryField.container).click();
await page.keyboard.insertText('topk(5,');
await expect(alertRuleEditPage.evaluate()).not.toBeOK();
});
@@ -1,53 +0,0 @@
import { expect, test } from '@grafana/plugin-e2e';
import { AlertVariant } from '@grafana/ui';
import {
successfulAnnotationQueryWithData,
failedAnnotationQueryWithMultipleErrors,
successfulAnnotationQueryWithoutData,
failedAnnotationQuery,
} from '../mocks/queries';
interface Scenario {
name: string;
mock: object;
text: string;
severity: AlertVariant;
status: number;
}
const scenarios: Scenario[] = [
{ name: 'error', severity: 'error', mock: failedAnnotationQuery, text: 'Google API Error 400', status: 400 },
{
name: 'multiple errors',
severity: 'error',
mock: failedAnnotationQueryWithMultipleErrors,
text: 'Google API Error 400Google API Error 401',
status: 400,
},
{
name: 'data',
severity: 'success',
mock: successfulAnnotationQueryWithData,
text: '2 events (from 2 fields)',
status: 200,
},
{
name: 'empty result',
severity: 'warning',
mock: successfulAnnotationQueryWithoutData,
text: 'No events found',
status: 200,
},
];
for (const scenario of scenarios) {
test(`annotation query data with ${scenario.name}`, async ({ annotationEditPage, page }) => {
annotationEditPage.mockQueryDataResponse(scenario.mock, scenario.status);
await annotationEditPage.datasource.set('gdev-testdata');
await page.getByLabel('Scenario').last().fill('CSV Content');
await page.keyboard.press('Tab');
await annotationEditPage.runQuery();
await expect(annotationEditPage).toHaveAlert(scenario.severity, { hasText: scenario.text });
});
}
@@ -1,15 +0,0 @@
import { expect, test } from '@grafana/plugin-e2e';
const REACT_TABLE_DASHBOARD = { uid: 'U_bZIMRMk' };
test('add panel in already existing dashboard', async ({ gotoDashboardPage, page }) => {
const dashboardPage = await gotoDashboardPage(REACT_TABLE_DASHBOARD);
await dashboardPage.addPanel();
await expect(page.url()).toContain('editPanel');
});
test('add panel in new dashboard', async ({ dashboardPage, page }) => {
const panelEditPage = await dashboardPage.addPanel();
await expect(panelEditPage.panel.locator).toBeVisible();
await expect(page.url()).toContain('editPanel');
});
@@ -1,37 +0,0 @@
import { expect, test } from '@grafana/plugin-e2e';
import { formatExpectError } from '../errors';
test.describe('test createDataSourceConfigPage fixture, saveAndTest and toBeOK matcher', () => {
test('invalid credentials should return an error', async ({ createDataSourceConfigPage, page }) => {
const configPage = await createDataSourceConfigPage({ type: 'prometheus' });
await page.getByPlaceholder('http://localhost:9090').fill('http://localhost:9090');
await expect(
configPage.saveAndTest(),
formatExpectError('Expected save data source config to fail when Prometheus server is not running')
).not.toBeOK();
});
test('valid credentials should return a 200 status code', async ({ createDataSourceConfigPage, page }) => {
const configPage = await createDataSourceConfigPage({ type: 'prometheus' });
configPage.mockHealthCheckResponse({ status: 200 });
await page.getByPlaceholder('http://localhost:9090').fill('http://localhost:9090');
await expect(
configPage.saveAndTest(),
formatExpectError('Expected data source config to be successfully saved')
).toBeOK();
});
});
test.describe('test data source with frontend only health check', () => {
test('valid credentials should display a success alert on the page', async ({ createDataSourceConfigPage, page }) => {
const configPage = await createDataSourceConfigPage({ type: 'zipkin' });
configPage.mockHealthCheckResponse({ message: 'Data source is working', status: 'OK' }, 200);
await page.getByPlaceholder('http://localhost:9411').fill('http://localhost:9411');
await expect(configPage.saveAndTest()).toBeOK();
await expect(
configPage,
formatExpectError('Expected data source config to display success alert after save')
).toHaveAlert('success', { hasNotText: 'Datasource updated' });
});
});
@@ -1,8 +0,0 @@
import { expect, test } from '@grafana/plugin-e2e';
import { formatExpectError } from '../errors';
test('query data response should be OK when query is valid', async ({ explorePage }) => {
await explorePage.datasource.set('gdev-testdata');
await expect(explorePage.runQuery(), formatExpectError('Expected Explore query to execute successfully')).toBeOK();
});
@@ -1,17 +0,0 @@
import { expect, test } from '@grafana/plugin-e2e';
const TRUTHY_CUSTOM_TOGGLE = 'custom_toggle1';
const FALSY_CUSTOM_TOGGLE = 'custom_toggle2';
// override the feature toggles defined in playwright.config.ts only for tests in this file
test.use({
featureToggles: {
[TRUTHY_CUSTOM_TOGGLE]: true,
[FALSY_CUSTOM_TOGGLE]: false,
},
});
test('should set and check feature toggles correctly', async ({ isFeatureToggleEnabled }) => {
expect(await isFeatureToggleEnabled(TRUTHY_CUSTOM_TOGGLE)).toBeTruthy();
expect(await isFeatureToggleEnabled(FALSY_CUSTOM_TOGGLE)).toBeFalsy();
});
@@ -1,87 +0,0 @@
import * as e2e from '@grafana/e2e-selectors';
import { expect, test } from '@grafana/plugin-e2e';
test.describe('Loki editor', () => {
test('Autocomplete features should work as expected.', async ({ page }) => {
// Go to loki datasource in explore
await page.goto(
'/explore?schemaVersion=1&panes=%7B%22iap%22:%7B%22datasource%22:%22gdev-loki%22,%22queries%22:%5B%7B%22refId%22:%22A%22,%22expr%22:%22%22,%22queryType%22:%22range%22,%22datasource%22:%7B%22type%22:%22loki%22,%22uid%22:%22gdev-loki%22%7D,%22editorMode%22:%22builder%22%7D%5D,%22range%22:%7B%22from%22:%22now-1h%22,%22to%22:%22now%22%7D%7D%7D&orgId=1'
);
const queryEditor = page.getByTestId(e2e.selectors.components.QueryField.container);
const queryEditorRows = page.getByTestId('query-editor-rows');
async function assertQueryEditorEmpty() {
const queryEditorEmptyText = /^Enter to Rename.+/;
await expect(queryEditor).toHaveText(queryEditorEmptyText);
}
async function clearInput() {
// Clear focused input
// Monaco appears to need some time to init keybindings after a change, adding this timeout to prevent flake
await page.waitForTimeout(100);
await page.keyboard.press('ControlOrMeta+A');
await page.keyboard.press('Backspace');
}
// assert that the query builder is shown by default
await expect(page.getByText('Label filters')).toHaveCount(1);
// switch to code editor
await page.getByLabel('Code').click();
await page.waitForFunction(() => window.monaco);
await expect(queryEditor).toHaveCount(1);
await assertQueryEditorEmpty();
// assert editor automatically adds close paren
await queryEditor.click();
await page.keyboard.type('time(');
await expect(queryEditor).toContainText('time()');
// removes closing brace when opening brace is removed
await clearInput();
await assertQueryEditorEmpty();
await page.keyboard.type('avg_over_time(');
await expect(queryEditor).toContainText('avg_over_time()');
await page.keyboard.press('Backspace');
await expect(queryEditor).not.toContainText('avg_over_time()');
await expect(queryEditor).toContainText('avg_over_time');
// keeps closing brace when opening brace is removed and inner values exist
await clearInput();
await assertQueryEditorEmpty();
await page.keyboard.type('time(test');
await page.keyboard.press('ArrowLeft');
await page.keyboard.press('ArrowLeft');
await page.keyboard.press('ArrowLeft');
await page.keyboard.press('ArrowLeft');
await page.keyboard.press('Backspace');
await expect(queryEditor).toContainText('timetest');
// overrides an automatically inserted paren
await clearInput();
await assertQueryEditorEmpty();
await page.keyboard.type('time()');
await expect(queryEditor).toContainText('time()');
// does not override manually inserted braces
await clearInput();
await assertQueryEditorEmpty();
await page.keyboard.type('))');
await expect(queryEditor).toContainText('))');
// Should execute the query when enter with shift is pressed
await clearInput();
await assertQueryEditorEmpty();
await page.keyboard.press('Shift+Enter');
await expect(page.getByTestId('explore-no-data')).toHaveCount(1);
// Suggestions plugin
await clearInput();
await assertQueryEditorEmpty();
await page.keyboard.type('av');
await expect(queryEditorRows.getByLabel(/avg, docs:/)).toHaveCount(1);
await expect(queryEditorRows.getByLabel(/avg_over_time, docs:/)).toHaveCount(1);
});
});
@@ -1,101 +0,0 @@
import { expect, test } from '@grafana/plugin-e2e';
import { formatExpectError } from '../errors';
import { successfulDataQuery } from '../mocks/queries';
const REACT_TABLE_DASHBOARD = { uid: 'U_bZIMRMk' };
test.describe('panel edit page', () => {
test('table panel data assertions with provisioned dashboard', async ({ gotoPanelEditPage }) => {
const panelEditPage = await gotoPanelEditPage({ dashboard: REACT_TABLE_DASHBOARD, id: '4' });
await expect(
panelEditPage.panel.locator,
formatExpectError('Could not locate panel in panel edit page')
).toBeVisible();
await expect(
panelEditPage.panel.fieldNames,
formatExpectError('Could not locate header elements in table panel')
).toContainText(['Field', 'Max', 'Mean', 'Last']);
});
test('table panel data assertions', async ({ panelEditPage }) => {
await panelEditPage.mockQueryDataResponse(successfulDataQuery, 200);
await panelEditPage.datasource.set('gdev-testdata');
await panelEditPage.setVisualization('Table');
await panelEditPage.refreshPanel();
await expect(
panelEditPage.panel.locator,
formatExpectError('Could not locate panel in panel edit page')
).toBeVisible();
await expect(
panelEditPage.panel.fieldNames,
formatExpectError('Could not locate header elements in table panel')
).toContainText(['col1', 'col2']);
await expect(panelEditPage.panel.data, formatExpectError('Could not locate headers in table panel')).toContainText([
'val1',
'val2',
'val3',
'val4',
]);
});
test('timeseries panel - table view assertions', async ({ panelEditPage }) => {
await panelEditPage.mockQueryDataResponse(successfulDataQuery, 200);
await panelEditPage.datasource.set('gdev-testdata');
await panelEditPage.setVisualization('Time series');
await panelEditPage.refreshPanel();
await panelEditPage.toggleTableView();
await expect(
panelEditPage.panel.locator,
formatExpectError('Could not locate panel in panel edit page')
).toBeVisible();
await expect(
panelEditPage.panel.fieldNames,
formatExpectError('Could not locate header elements in table panel')
).toContainText(['col1', 'col2']);
await expect(
panelEditPage.panel.data,
formatExpectError('Could not locate data elements in table panel')
).toContainText(['val1', 'val2', 'val3', 'val4']);
});
});
test.describe('dashboard page', () => {
test('getting panel by title', async ({ gotoDashboardPage }) => {
const dashboardPage = await gotoDashboardPage(REACT_TABLE_DASHBOARD);
await dashboardPage.goto();
const panel = await dashboardPage.getPanelByTitle('Colored background');
await expect(panel.fieldNames).toContainText(['Field', 'Max', 'Mean', 'Last']);
});
test('getting panel by id', async ({ gotoDashboardPage }) => {
const dashboardPage = await gotoDashboardPage(REACT_TABLE_DASHBOARD);
await dashboardPage.goto();
const panel = await dashboardPage.getPanelByTitle('Colored background');
await expect(panel.fieldNames, formatExpectError('Could not locate header elements in table panel')).toContainText([
'Field',
'Max',
'Mean',
'Last',
]);
});
});
test.describe('explore page', () => {
test('table panel', async ({ explorePage }) => {
const url =
'left=%7B"datasource":"grafana","queries":%5B%7B"queryType":"randomWalk","refId":"A","datasource":%7B"type":"datasource","uid":"grafana"%7D%7D%5D,"range":%7B"from":"1547161200000","to":"1576364400000"%7D%7D&orgId=1';
await explorePage.goto({
queryParams: new URLSearchParams(url),
});
await expect(
explorePage.timeSeriesPanel.locator,
formatExpectError('Could not locate time series panel in explore page')
).toBeVisible();
await expect(
explorePage.tablePanel.locator,
formatExpectError('Could not locate table panel in explore page')
).toBeVisible();
await expect(explorePage.tablePanel.fieldNames).toContainText(['time', 'A-series']);
});
});
@@ -1,206 +0,0 @@
import { expect, test } from '@grafana/plugin-e2e';
import { formatExpectError } from '../errors';
import { successfulDataQuery } from '../mocks/queries';
import { scenarios } from '../mocks/resources';
const PANEL_TITLE = 'Table panel E2E test';
const TABLE_VIZ_NAME = 'Table';
const TIME_SERIES_VIZ_NAME = 'Time series';
const STANDARD_OTIONS_CATEGORY = 'Standard options';
const DISPLAY_NAME_LABEL = 'Display name';
const REACT_TABLE_DASHBOARD = { uid: 'U_bZIMRMk' };
test.describe('query editor query data', () => {
test('query data response should be OK when query is valid', async ({ panelEditPage }) => {
await panelEditPage.datasource.set('gdev-testdata');
await expect(
panelEditPage.refreshPanel(),
formatExpectError('Expected panel query to execute successfully')
).toBeOK();
});
test('query data response should not be OK and panel error should be displayed when query is invalid', async ({
panelEditPage,
}) => {
await panelEditPage.datasource.set('gdev-testdata');
const queryEditorRow = await panelEditPage.getQueryEditorRow('A');
await queryEditorRow.getByLabel('Labels').fill('invalid-label-format');
await expect(panelEditPage.refreshPanel(), formatExpectError('Expected panel query to fail')).not.toBeOK();
await expect(
panelEditPage.panel.getErrorIcon(),
formatExpectError('Expected panel error to be displayed after query execution')
).toBeVisible();
});
});
test.describe('query editor with mocked responses', () => {
test('and resource `scenarios` is mocked', async ({ selectors, dashboardPage }) => {
await dashboardPage.mockResourceResponse('scenarios', scenarios);
const panelEditPage = await dashboardPage.addPanel();
await panelEditPage.datasource.set('gdev-testdata');
const queryEditorRow = await panelEditPage.getQueryEditorRow('A');
await queryEditorRow.getByLabel('Scenario').last().click();
await expect(
panelEditPage.getByGrafanaSelector(selectors.components.Select.option),
formatExpectError('Expected certain select options to be displayed after clicking on the select input')
).toHaveText(scenarios.map((s) => s.name));
});
test('mocked query data response', async ({ panelEditPage, selectors }) => {
await panelEditPage.mockQueryDataResponse(successfulDataQuery, 200);
await panelEditPage.datasource.set('gdev-testdata');
await panelEditPage.setVisualization(TABLE_VIZ_NAME);
await panelEditPage.refreshPanel();
await expect(
panelEditPage.panel.getErrorIcon(),
formatExpectError('Did not expect panel error to be displayed after query execution')
).not.toBeVisible();
await expect(
panelEditPage.getByGrafanaSelector(selectors.components.Panels.Visualization.Table.body),
formatExpectError('Expected certain select options to be displayed after clicking on the select input')
).toHaveText('val1val2val3val4');
});
});
test.describe('edit panel plugin settings', () => {
test('change viz to table panel, set panel title and collapse section', async ({
panelEditPage,
selectors,
page,
}) => {
await panelEditPage.setVisualization(TABLE_VIZ_NAME);
await expect(
panelEditPage.getByGrafanaSelector(selectors.components.PanelEditor.toggleVizPicker),
formatExpectError('Expected panel visualization to be set to table')
).toHaveText(TABLE_VIZ_NAME);
await panelEditPage.setPanelTitle(PANEL_TITLE);
await expect(
panelEditPage.getByGrafanaSelector(selectors.components.Panels.Panel.title(PANEL_TITLE)),
formatExpectError('Expected panel title to be updated')
).toBeVisible();
await panelEditPage.collapseSection(STANDARD_OTIONS_CATEGORY);
await expect(
page.getByText(DISPLAY_NAME_LABEL),
formatExpectError('Expected section to be collapsed')
).toBeVisible();
});
test('Select time zone in timezone picker', async ({ panelEditPage }) => {
await panelEditPage.setVisualization(TIME_SERIES_VIZ_NAME);
const axisOptions = await panelEditPage.getCustomOptions('Axis');
const timeZonePicker = axisOptions.getSelect('Time zone');
await timeZonePicker.selectOption('Europe/Stockholm');
await expect(timeZonePicker).toHaveSelected('Europe/Stockholm');
});
test('select unit in unit picker', async ({ panelEditPage }) => {
await panelEditPage.setVisualization(TIME_SERIES_VIZ_NAME);
const standardOptions = panelEditPage.getStandardOptions();
const unitPicker = standardOptions.getUnitPicker('Unit');
await unitPicker.selectOption('Misc > Pixels');
await expect(unitPicker).toHaveSelected('Pixels');
});
test('enter value in number input', async ({ panelEditPage }) => {
await panelEditPage.setVisualization(TIME_SERIES_VIZ_NAME);
const axisOptions = panelEditPage.getCustomOptions('Axis');
const lineWith = axisOptions.getNumberInput('Soft min');
await lineWith.fill('10');
await expect(lineWith).toHaveValue('10');
});
test('enter value in slider', async ({ panelEditPage }) => {
await panelEditPage.setVisualization(TIME_SERIES_VIZ_NAME);
const graphOptions = panelEditPage.getCustomOptions('Graph styles');
const lineWidth = graphOptions.getSliderInput('Line width');
await lineWidth.fill('10');
await expect(lineWidth).toHaveValue('10');
});
test('select value in single value select', async ({ panelEditPage }) => {
await panelEditPage.setVisualization(TIME_SERIES_VIZ_NAME);
const standardOptions = panelEditPage.getStandardOptions();
const colorSchemeSelect = standardOptions.getSelect('Color scheme');
await colorSchemeSelect.selectOption('Classic palette');
await expect(colorSchemeSelect).toHaveSelected('Classic palette');
});
test('clear input', async ({ panelEditPage }) => {
await panelEditPage.setVisualization(TIME_SERIES_VIZ_NAME);
const panelOptions = panelEditPage.getPanelOptions();
const title = panelOptions.getTextInput('Title');
await expect(title).toHaveValue('New panel');
await title.clear();
await expect(title).toHaveValue('');
});
test('enter value in input', async ({ panelEditPage }) => {
await panelEditPage.setVisualization(TIME_SERIES_VIZ_NAME);
const panelOptions = panelEditPage.getPanelOptions();
const description = panelOptions.getTextInput('Description');
await expect(description).toHaveValue('');
await description.fill('This is a panel');
await expect(description).toHaveValue('This is a panel');
});
test('unchecking switch', async ({ panelEditPage }) => {
await panelEditPage.setVisualization(TIME_SERIES_VIZ_NAME);
const axisOptions = panelEditPage.getCustomOptions('Axis');
const showBorder = axisOptions.getSwitch('Show border');
await expect(showBorder).toBeChecked({ checked: false });
await showBorder.check();
await expect(showBorder).toBeChecked();
await showBorder.uncheck();
await expect(showBorder).toBeChecked({ checked: false });
});
test('checking switch', async ({ panelEditPage }) => {
await panelEditPage.setVisualization(TIME_SERIES_VIZ_NAME);
const axisOptions = panelEditPage.getCustomOptions('Axis');
const showBorder = axisOptions.getSwitch('Show border');
await expect(showBorder).toBeChecked({ checked: false });
await showBorder.check();
await expect(showBorder).toBeChecked();
});
test('re-selecting value in radio button group', async ({ panelEditPage }) => {
await panelEditPage.setVisualization(TIME_SERIES_VIZ_NAME);
const axisOptions = panelEditPage.getCustomOptions('Axis');
const placement = axisOptions.getRadioGroup('Placement');
await placement.check('Right');
await expect(placement).toHaveChecked('Right');
await placement.check('Auto');
await expect(placement).toHaveChecked('Auto');
});
test('selecting value in radio button group', async ({ panelEditPage }) => {
await panelEditPage.setVisualization(TIME_SERIES_VIZ_NAME);
const axisOptions = panelEditPage.getCustomOptions('Axis');
const placement = axisOptions.getRadioGroup('Placement');
await placement.check('Right');
await expect(placement).toHaveChecked('Right');
});
});
test('backToDashboard method should navigate to dashboard page', async ({ gotoPanelEditPage, page }) => {
const panelEditPage = await gotoPanelEditPage({ dashboard: REACT_TABLE_DASHBOARD, id: '4' });
await panelEditPage.backToDashboard();
await expect(page.url()).not.toContain('editPanel');
});
@@ -1,17 +0,0 @@
import { expect, test } from '@grafana/plugin-e2e';
import { formatExpectError } from '../errors';
import { prometheusLabels } from '../mocks/resources';
test('variable query with mocked response', async ({ variableEditPage, page }) => {
variableEditPage.mockResourceResponse('api/v1/labels?*', prometheusLabels);
variableEditPage.mockResourceResponse('suggestions*', prometheusLabels);
await variableEditPage.datasource.set('gdev-prometheus');
await variableEditPage.getByGrafanaSelector('Query type').fill('Label names');
await page.keyboard.press('Tab');
await variableEditPage.runQuery();
await expect(
variableEditPage,
formatExpectError('Expected variable edit page to display certain label names after query execution')
).toDisplayPreviews(prometheusLabels.data);
});
@@ -1,16 +0,0 @@
import { expect, test } from '@grafana/plugin-e2e';
test('should redirect to start page when permissions to navigate to page is missing', async ({ page }) => {
await page.goto('/');
const homePageURL = new URL(page.url());
await page.goto('/datasources', { waitUntil: 'networkidle' });
const redirectedPageURL = new URL(page.url());
expect(homePageURL.pathname).toEqual(redirectedPageURL.pathname);
});
test('current user should have viewer role', async ({ page, request }) => {
await page.goto('/');
const response = await request.get('/api/user/orgs');
await expect(response).toBeOK();
await expect(await response.json()).toContainEqual(expect.objectContaining({ role: 'Viewer' }));
});
@@ -1,4 +0,0 @@
export const formatExpectError = (message: string) => {
return `Error while verifying @grafana/plugin-e2e scenarios: ${message}.
See https://github.com/grafana/grafana/blob/main/plugin-e2e/plugin-e2e-api-tests/README.md for more information.`;
};
@@ -1,138 +0,0 @@
export const successfulDataQuery = {
results: {
A: {
status: 200,
frames: [
{
schema: {
refId: 'A',
fields: [
{
name: 'col1',
type: 'string',
typeInfo: {
frame: 'string',
nullable: true,
},
},
{
name: 'col2',
type: 'string',
typeInfo: {
frame: 'string',
nullable: true,
},
},
],
},
data: {
values: [
['val1', 'val3'],
['val2', 'val4'],
],
},
},
],
},
},
};
export const failedAnnotationQuery: object = {
results: {
Anno: {
error: 'Google API Error 400',
errorSource: '',
status: 500,
},
},
};
export const failedAnnotationQueryWithMultipleErrors: object = {
results: {
Anno1: {
error: 'Google API Error 400',
errorSource: '',
status: 400,
},
Anno2: {
error: 'Google API Error 401',
errorSource: '',
status: 401,
},
},
};
export const successfulAnnotationQueryWithData: object = {
results: {
Anno: {
status: 200,
frames: [
{
schema: {
refId: 'Anno',
fields: [
{
name: 'time',
type: 'time',
typeInfo: {
frame: 'time.Time',
nullable: true,
},
},
{
name: 'col2',
type: 'string',
typeInfo: {
frame: 'string',
nullable: true,
},
},
],
},
data: {
values: [
[1702973084093, 1702973084099],
['val1', 'val2'],
],
},
},
],
},
},
};
export const successfulAnnotationQueryWithoutData: object = {
results: {
Anno: {
status: 200,
frames: [
{
schema: {
refId: 'Anno',
fields: [
{
name: 'time',
type: 'time',
typeInfo: {
frame: 'time.Time',
nullable: true,
},
},
{
name: 'col2',
type: 'string',
typeInfo: {
frame: 'string',
nullable: true,
},
},
],
},
data: {
values: [],
},
},
],
},
},
};
@@ -1,19 +0,0 @@
export const scenarios = [
{
description: '',
id: 'annotations',
name: 'Annotations',
stringInput: '',
},
{
description: '',
id: 'arrow',
name: 'Load Apache Arrow Data',
stringInput: '',
},
];
export const prometheusLabels = {
status: 'success',
data: ['__name__', 'action', 'active', 'address'],
};
-8
View File
@@ -1,8 +0,0 @@
import { test, expect } from '@grafana/plugin-e2e';
test('Smoke test: plugin loads', async ({ createDataSourceConfigPage, page }) => {
await createDataSourceConfigPage({ type: 'grafana-postgresql-datasource' });
await expect(await page.getByText('Type: PostgreSQL', { exact: true })).toBeVisible();
await expect(await page.getByRole('heading', { name: 'Connection', exact: true })).toBeVisible();
});
-23
View File
@@ -1,23 +0,0 @@
#!/bin/bash
. scripts/grafana-server/variables
LICENSE_PATH=""
if [ "$1" = "enterprise" ]; then
if [ "$2" != "dev" ] && [ "$2" != "debug" ]; then
LICENSE_PATH=$2/license.jwt
else
LICENSE_PATH=$3/license.jwt
fi
fi
if [ "$BASE_URL" != "" ]; then
echo -e "BASE_URL set, skipping starting server"
else
# Start it in the background
./scripts/grafana-server/start-server $LICENSE_PATH 2>&1 > scripts/grafana-server/server.log &
./scripts/grafana-server/wait-for-grafana
fi
PORT=3001 HOST=localhost yarn playwright test
-8
View File
@@ -1,8 +0,0 @@
import { test, expect } from '@grafana/plugin-e2e';
test('Smoke test: plugin loads', async ({ createDataSourceConfigPage, page }) => {
await createDataSourceConfigPage({ type: 'zipkin' });
await expect(await page.getByText('Type: Zipkin', { exact: true })).toBeVisible();
await expect(await page.getByRole('heading', { name: 'Connection', exact: true })).toBeVisible();
});
-33
View File
@@ -1,33 +0,0 @@
# Test plugins
The [e2e test server](https://github.com/grafana/grafana/blob/main/scripts/grafana-server/start-server) automatically scans and looks for plugins in this directory.
### To add a new test plugin:
1. If provisioning is required you may update the YAML config file in [`/devenv`](https://github.com/grafana/grafana/tree/main/devenv).
2. Add the plugin ID to the `allow_loading_unsigned_plugins` setting in the test server's [configuration file](https://github.com/grafana/grafana/blob/main/scripts/grafana-server/custom.ini).
### Building a test plugin with webpack
If you wish to build a test plugin with webpack, you may take a look at how the [grafana-extensionstest-app](./grafana-extensionstest-app/) is wired. A few things to keep in mind:
- the package name needs to be prefixed with `@test-plugins/`
- extend the webpack config from [`@grafana/plugin-configs`](../../packages/grafana-plugin-configs/) and use custom webpack config to only copy the necessary files (see example [here](./grafana-extensionstest-app/webpack.config.ts))
- keep dependency versions in sync with what's in core
#### Local development
1: Install frontend dependencies:
`yarn install --immutable`
2: Build and watch the core frontend
`yarn start`
3: Build and watch the test plugins
`yarn e2e:plugin:build:dev`
4: Build the backend
`make build-go`
5: Start the Grafana e2e test server with the provisioned test plugin
`PORT=3000 ./scripts/grafana-server/start-server`
@@ -1 +0,0 @@
<?xml version="1.0" encoding="UTF-8"?><svg xmlns="http://www.w3.org/2000/svg" width="1" height="1"/>

Before

Width:  |  Height:  |  Size: 100 B

@@ -1,41 +0,0 @@
/*
* This is a dummy plugin to test the frontend sandbox
* It is not meant to be used in any other way
* This file doesn't require any compilation
*/
define(['react', '@grafana/data', 'react-router-dom'], function (React, grafanaData, ReactRouterDom) {
const { AppPlugin } = grafanaData;
const { Switch, Route } = ReactRouterDom;
function PageOne() {
return React.createElement(
'div',
{
'data-testid': 'sandbox-app-test-page-one',
},
'This is a page one'
);
}
function App() {
return React.createElement(Switch, null, React.createElement(Route, { component: PageOne }));
}
function AppConfig() {
return React.createElement(
'div',
{
'data-testid': 'sandbox-app-test-config-page',
},
'This is a config page'
);
}
const plugin = new AppPlugin().setRootPage(App).addConfigPage({
title: 'Configuration',
icon: 'cog',
body: AppConfig,
id: 'configuration',
});
return { plugin };
});
@@ -1,35 +0,0 @@
{
"$schema": "https://raw.githubusercontent.com/grafana/grafana/master/docs/sources/developers/plugins/plugin.schema.json",
"type": "app",
"name": "Sandbox app test plugin",
"id": "sandbox-app-test",
"info": {
"keywords": ["app", "sandbox"],
"description": "",
"author": {
"name": "Grafana"
},
"logos": {
"small": "img/logo.svg",
"large": "img/logo.svg"
},
"links": [],
"screenshots": [],
"version": "1.0.0",
"updated": "2023-06-27"
},
"includes": [
{
"type": "page",
"icon": "cog",
"name": "Sandbox App Page",
"path": "/plugins/sandbox-app-test",
"role": "Admin",
"addToNav": true
}
],
"dependencies": {
"grafanaDependency": ">=10.0",
"plugins": []
}
}
@@ -1 +0,0 @@
<?xml version="1.0" encoding="UTF-8"?><svg xmlns="http://www.w3.org/2000/svg" width="1" height="1"/>

Before

Width:  |  Height:  |  Size: 100 B

@@ -1,115 +0,0 @@
/*
* This is a dummy plugin to test the frontend sandbox
* It is not meant to be used in any other way
* This file doesn't require any compilation
*/
define(['react', '@grafana/data'], function (React, grafanaData) {
const { DataSourcePlugin, DataSourceApi, MutableDataFrame, FieldType } = grafanaData;
const { useState } = React;
const QueryEditor = (props) => {
const [value, setValue] = useState('');
const handleChange = (event) => {
setValue(event.target.value);
props.onChange({
...props.query,
testValue: event.target.value,
});
props.onRunQuery();
};
return React.createElement(
'div',
null,
React.createElement('label', { htmlFor: 'inputField' }, 'Dummy input field'),
React.createElement('input', {
type: 'text',
id: 'inputField',
'data-testid': 'sandbox-query-editor-query-input',
value: value,
onChange: handleChange,
})
);
};
const ConfigEditor = (props) => {
const { onOptionsChange, options } = props;
const value = options.jsonData.input || '';
const handleChange = (event) => {
onOptionsChange({
...options,
jsonData: {
input: event.target.value,
},
});
};
return React.createElement(
'div',
null,
React.createElement('label', { htmlFor: 'inputField' }, 'Test Config field'),
React.createElement('input', {
type: 'text',
id: 'inputField',
'data-testid': 'sandbox-config-editor-query-input',
value: value,
onChange: handleChange,
})
);
};
class BasicDataSource extends DataSourceApi {
constructor(instanceSettings) {
super(instanceSettings);
}
// this is a test query it'll generate a logarithmic series starting now-1h
async query(options) {
const promises = options.targets.map(async (target) => {
const query = target;
const timestamps = [];
const values = [];
const endTime = Date.now();
const startTime = endTime - 3600000; // 1 hour in milliseconds
// Define the logarithmic base and increment factor
const base = 2;
const increment = 0.1;
// Generate the data points
for (let i = 0; i < 50; i++) {
// Calculate the timestamp
const timestamp = startTime + ((endTime - startTime) / 50) * i;
timestamps.push(timestamp);
// Calculate the value using logarithmic increase
const value = Math.pow(base, increment * i);
values.push(value);
}
return new MutableDataFrame({
refId: query.refId,
fields: [
{ name: 'Time', type: FieldType.time, values: timestamps },
{ name: 'Value', type: FieldType.number, values: values },
],
});
});
return Promise.all(promises).then((data) => ({ data }));
}
async testDatasource() {
return {
status: 'success',
message: 'Sandbox Success',
};
}
}
const plugin = new DataSourcePlugin(BasicDataSource).setConfigEditor(ConfigEditor).setQueryEditor(QueryEditor);
return { plugin };
});
@@ -1,26 +0,0 @@
{
"$schema": "https://raw.githubusercontent.com/grafana/grafana/master/docs/sources/developers/plugins/plugin.schema.json",
"type": "datasource",
"name": "Sandbox datasource test plugin",
"id": "sandbox-test-datasource",
"metrics": true,
"info": {
"keywords": ["explore", "datasource"],
"description": "",
"author": {
"name": "Grafana"
},
"logos": {
"small": "img/logo.svg",
"large": "img/logo.svg"
},
"links": [],
"screenshots": [],
"version": "1.0.0",
"updated": "2023-06-27"
},
"dependencies": {
"grafanaDependency": ">=10.0",
"plugins": []
}
}
@@ -1 +0,0 @@
<?xml version="1.0" encoding="UTF-8"?><svg xmlns="http://www.w3.org/2000/svg" width="1" height="1"/>

Before

Width:  |  Height:  |  Size: 100 B

@@ -1,188 +0,0 @@
/*
* This is a dummy plugin to test the frontend sandbox
* It is not meant to be used in any other way
* This file doesn't require any compilation
*/
define(['react', '@grafana/data'], function (React, grafanaData) {
// This would be a custom editor component
function Editor() {
const onChangeInternal = (event) => {
const outsideEl =
event.target.parentElement.parentElement.parentElement.parentElement.parentElement.parentElement.parentElement
.parentElement.parentElement;
outsideEl.dataset.sandboxTest = 'panel-editor';
};
return React.createElement('input', {
type: 'text',
onChange: onChangeInternal,
'data-testid': 'panel-editor-custom-editor-input',
});
}
const PanelComponent = () => {
const [testedGlobals, setTestedGlobals] = React.useState([]);
const createIframe = () => {
// direct iframe creation
const iframe = document.createElement('iframe');
iframe.src = 'about:blank';
iframe.id = 'createElementIframe';
iframe.style.width = '10%';
iframe.style.height = '10%';
iframe.style.border = 'none';
document.body.appendChild(iframe);
// via innerHTML
const div = document.createElement('div');
document.body.appendChild(div);
div.innerHTML =
'<iframe src="about:blank" id="innerHTMLIframe" style="width: 10%; height: 10%; border: none;"></iframe>';
// via append
const appendIframe = document.createElement('iframe');
appendIframe.src = 'about:blank';
appendIframe.id = 'appendIframe';
appendIframe.style.width = '10%';
appendIframe.style.height = '10%';
appendIframe.style.border = 'none';
document.body.append(appendIframe);
// via prepend
const prependIframe = document.createElement('iframe');
prependIframe.src = 'about:blank';
prependIframe.id = 'prependIframe';
prependIframe.style.width = '10%';
prependIframe.style.height = '10%';
prependIframe.style.border = 'none';
document.body.prepend(prependIframe);
// via after
const referenceElementAfter = document.createElement('div');
document.body.appendChild(referenceElementAfter);
const afterIframe = document.createElement('iframe');
afterIframe.src = 'about:blank';
afterIframe.id = 'afterIframe';
afterIframe.style.width = '10%';
afterIframe.style.height = '10%';
afterIframe.style.border = 'none';
referenceElementAfter.after(afterIframe);
// via before
const referenceElementBefore = document.createElement('div');
document.body.appendChild(referenceElementBefore);
const beforeIframe = document.createElement('iframe');
beforeIframe.src = 'about:blank';
beforeIframe.id = 'beforeIframe';
beforeIframe.style.width = '10%';
beforeIframe.style.height = '10%';
beforeIframe.style.border = 'none';
referenceElementBefore.before(beforeIframe);
// via outerHTML
const outerHTMLIframe = document.createElement('iframe');
outerHTMLIframe.src = 'about:blank';
outerHTMLIframe.id = 'outerHTMLIframeTemp';
outerHTMLIframe.style.width = '10%';
outerHTMLIframe.style.height = '10%';
outerHTMLIframe.style.border = 'none';
document.body.appendChild(outerHTMLIframe);
outerHTMLIframe.outerHTML =
'<iframe src="about:blank" id="outerHTMLIframe" style="width: 10%; height: 10%; border: none;"></iframe>';
// via parseFromString
const iframeString =
'<iframe src="about:blank" id="parseFromStringIframe" style="width: 10%; height: 10%; border: none;"></iframe>';
const parser = new DOMParser();
const parsedDoc = parser.parseFromString(iframeString, 'text/html');
document.body.appendChild(parsedDoc.body.firstChild);
// via insertBefore
const referenceForInsertBefore = document.createElement('div');
document.body.appendChild(referenceForInsertBefore);
const insertBeforeIframe = document.createElement('iframe');
insertBeforeIframe.src = 'about:blank';
insertBeforeIframe.id = 'insertBeforeIframe';
insertBeforeIframe.style.width = '10%';
insertBeforeIframe.style.height = '10%';
insertBeforeIframe.style.border = 'none';
document.body.insertBefore(insertBeforeIframe, referenceForInsertBefore);
// via replaceChild
const replaceChildDiv = document.createElement('div');
document.body.appendChild(replaceChildDiv);
const replaceChildIframe = document.createElement('iframe');
replaceChildIframe.src = 'about:blank';
replaceChildIframe.id = 'replaceChildIframe';
replaceChildIframe.style.width = '10%';
replaceChildIframe.style.height = '10%';
replaceChildIframe.style.border = 'none';
document.body.replaceChild(replaceChildIframe, replaceChildDiv);
};
const reachOut = (e) => {
const outsideEl = e.target.parentElement.parentElement.parentElement.parentElement.parentElement;
outsideEl.dataset.sandboxTest = 'true';
};
// a function for each global we want to test
const globalTests = [
function () {
try {
console.log(window.Prism.languages);
return 'Prism';
} catch (e) {}
},
function () {
try {
console.log(window.jQuery.fn.jquery);
console.log(window.$.fn.jquery);
return 'jQuery';
} catch (e) {}
},
function () {
try {
console.log(window.locationSandbox);
return 'location';
} catch (e) {}
},
];
// it'll assign a variable with one attribute of the Globals
// and create a new element with the name of the global.
const testGlobals = () => {
const results = globalTests.map((test) => test());
setTestedGlobals(results);
};
const elements = testedGlobals.map((item) => {
const attributes = { 'data-sandbox-global': `${item}` };
return React.createElement('div', attributes, item);
});
return React.createElement(
'div',
{ className: 'frontend-sandbox-test' },
React.createElement(
'button',
{ onClick: createIframe, 'data-testid': 'button-create-iframes' },
'Create iframes'
),
React.createElement('button', { onClick: reachOut, 'data-testid': 'button-reach-out' }, 'Reach out'),
React.createElement('button', { onClick: testGlobals, 'data-testid': 'button-test-globals' }, 'Test Globals'),
React.createElement('div', null, elements)
);
};
const plugin = new grafanaData.PanelPlugin(PanelComponent);
plugin.setPanelOptions((builder) => {
builder.addCustomEditor({
id: 'buttons',
path: 'buttons',
name: 'Button Configuration',
defaultValue: [{ text: '', datasource: '', query: '' }],
editor: (props) => React.createElement(Editor, { onChange: props.onChange }),
});
});
return { plugin };
});
@@ -1,25 +0,0 @@
{
"$schema": "https://raw.githubusercontent.com/grafana/grafana/master/docs/sources/developers/plugins/plugin.schema.json",
"type": "panel",
"name": "Sandbox test plugin",
"id": "sandbox-test-panel",
"info": {
"keywords": ["panel"],
"description": "",
"author": {
"name": "Grafana"
},
"logos": {
"small": "img/logo.svg",
"large": "img/logo.svg"
},
"links": [],
"screenshots": [],
"version": "1.0.0",
"updated": "2023-06-27"
},
"dependencies": {
"grafanaDependency": ">=10.0",
"plugins": []
}
}
@@ -1,39 +0,0 @@
# Logs
logs
*.log
npm-debug.log*
yarn-debug.log*
yarn-error.log*
.pnpm-debug.log*
node_modules/
# Runtime data
pids
*.pid
*.seed
*.pid.lock
# Directory for instrumented libs generated by jscoverage/JSCover
lib-cov
# Coverage directory used by tools like istanbul
coverage
# Compiled binary addons (https://nodejs.org/api/addons.html)
dist/
artifacts/
work/
ci/
# e2e test directories
/test-results/
/playwright-report/
/blob-report/
/playwright/.cache/
/playwright/.auth/
# Editor
.idea
.eslintcache
@@ -1 +0,0 @@
# Changelog
@@ -1,35 +0,0 @@
# Extensions test plugins
This is an app plugin containing nested app plugins that are used for testing the plugins ui extensions APIs.
Further reading:
- [Plugin Ui Extensions docs](https://grafana.com/developers/plugin-tools/how-to-guides/ui-extensions/)
- [Plugin E2e testing docs](https://grafana.com/developers/plugin-tools/e2e-test-a-plugin/introduction)
## Build
To build this plugin run `yarn e2e:plugin:build`.
## Development
1: Install frontend dependencies:
`yarn install --immutable`
2: Build and watch the core frontend
`yarn start`
3: Build and watch the test plugins
`yarn e2e:plugin:build:dev`
4: Build the backend
`make build-go`
5: Start the Grafana e2e test server with the provisioned test plugin
`PORT=3000 ./scripts/grafana-server/start-server`
Note that this plugin extends the `@grafana/plugin-configs` configs which is why it has no src directory and uses a custom webpack config to copy necessary files.
## Run Playwright tests
- `yarn playwright test --project extensions-test-app`
@@ -1,100 +0,0 @@
import { PluginExtension, PluginExtensionLink, SelectableValue, locationUtil } from '@grafana/data';
import { isPluginExtensionLink, locationService } from '@grafana/runtime';
import { Button, ButtonGroup, ButtonSelect, Modal, Stack, ToolbarButton } from '@grafana/ui';
import { testIds } from '../../testIds';
import { ReactElement, useMemo, useState } from 'react';
type Props = {
extensions: PluginExtension[];
};
export function ActionButton(props: Props): ReactElement {
const options = useExtensionsAsOptions(props.extensions);
const [extension, setExtension] = useState<PluginExtensionLink | undefined>();
if (options.length === 0) {
return <Button>Run default action</Button>;
}
return (
<>
<ButtonGroup>
<ToolbarButton key="default-action" variant="canvas" onClick={() => alert('You triggered the default action')}>
Run default action
</ToolbarButton>
<ButtonSelect
data-testid={testIds.actions.button}
key="select-extension"
variant="canvas"
options={options}
onChange={(option) => {
const extension = option.value;
if (isPluginExtensionLink(extension)) {
if (extension.path) {
return setExtension(extension);
}
if (extension.onClick) {
return extension.onClick();
}
}
}}
/>
</ButtonGroup>
{extension && extension?.path && (
<LinkModal title={extension.title} path={extension.path} onDismiss={() => setExtension(undefined)} />
)}
</>
);
}
function useExtensionsAsOptions(extensions: PluginExtension[]): Array<SelectableValue<PluginExtension>> {
return useMemo(() => {
return extensions.reduce((options: Array<SelectableValue<PluginExtension>>, extension) => {
if (isPluginExtensionLink(extension)) {
options.push({
label: extension.title,
title: extension.title,
value: extension,
});
}
return options;
}, []);
}, [extensions]);
}
type LinkModelProps = {
onDismiss: () => void;
title: string;
path: string;
};
export function LinkModal(props: LinkModelProps): ReactElement {
const { onDismiss, title, path } = props;
const openInNewTab = () => {
global.open(locationUtil.assureBaseUrl(path), '_blank');
onDismiss();
};
const openInCurrentTab = () => locationService.push(path);
return (
<Modal data-testid={testIds.modal.container} title={title} isOpen onDismiss={onDismiss}>
<Stack direction={'column'}>
<p>Do you want to proceed in the current tab or open a new tab?</p>
</Stack>
<Modal.ButtonRow>
<Button onClick={onDismiss} fill="outline" variant="secondary">
Cancel
</Button>
<Button type="submit" variant="secondary" onClick={openInNewTab} icon="external-link-alt">
Open in new tab
</Button>
<Button data-testid={testIds.modal.open} type="submit" variant="primary" onClick={openInCurrentTab} icon="apps">
Open
</Button>
</Modal.ButtonRow>
</Modal>
);
}
@@ -1 +0,0 @@
export { ActionButton } from './ActionButton';
@@ -1,21 +0,0 @@
import { Route, Routes } from 'react-router-dom';
import { AppRootProps } from '@grafana/data';
import { ROUTES } from '../../constants';
import { AddedComponents, AddedLinks, ExposedComponents } from '../../pages';
import { testIds } from '../../testIds';
export function App(props: AppRootProps) {
return (
<div data-testid={testIds.container} style={{ marginTop: '5%' }}>
<Routes>
<Route path={ROUTES.ExposedComponents} element={<ExposedComponents />} />
<Route path={ROUTES.AddedComponents} element={<AddedComponents />} />
<Route path={ROUTES.AddedLinks} element={<AddedLinks />} />
<Route path={'*'} element={<ExposedComponents />} />
</Routes>
</div>
);
}
@@ -1 +0,0 @@
export * from './App';
@@ -1,45 +0,0 @@
import { DataQuery } from '@grafana/data';
import { Button, FilterPill, Modal, Stack } from '@grafana/ui';
import { testIds } from '../../testIds';
import { ReactElement, useState } from 'react';
import { selectQuery } from '../../utils/utils';
type Props = {
targets: DataQuery[] | undefined;
onDismiss?: () => void;
};
export function QueryModal(props: Props): ReactElement {
const { targets = [], onDismiss } = props;
const [selected, setSelected] = useState(targets[0]);
return (
<div data-testid={testIds.modal.container}>
<p>Please select the query you would like to use to create &quot;something&quot; in the plugin.</p>
<Stack>
{targets.map((query) => (
<FilterPill
key={query.refId}
label={query.refId}
selected={query.refId === selected?.refId}
onClick={() => setSelected(query)}
/>
))}
</Stack>
<Modal.ButtonRow>
<Button variant="secondary" fill="outline" onClick={onDismiss}>
Cancel
</Button>
<Button
disabled={!Boolean(selected)}
onClick={() => {
onDismiss?.();
selectQuery(selected);
}}
>
OK
</Button>
</Modal.ButtonRow>
</div>
);
}
@@ -1 +0,0 @@
export { QueryModal } from './QueryModal';
@@ -1,11 +0,0 @@
import pluginJson from './plugin.json';
export const PLUGIN_BASE_URL = `/a/${pluginJson.id}`;
export enum ROUTES {
LegacyGetters = 'legacy-getters',
LegacyHooks = 'legacy-hooks',
ExposedComponents = 'exposed-components',
AddedComponents = 'added-components',
AddedLinks = 'added-links',
}
@@ -1 +0,0 @@
<svg xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" viewBox="0 0 81.9 71.52"><defs><style>.cls-1{fill:#84aff1;}.cls-2{fill:#3865ab;}.cls-3{fill:url(#linear-gradient);}</style><linearGradient id="linear-gradient" x1="42.95" y1="16.88" x2="81.9" y2="16.88" gradientUnits="userSpaceOnUse"><stop offset="0" stop-color="#f2cc0c"/><stop offset="1" stop-color="#ff9830"/></linearGradient></defs><g id="Layer_2" data-name="Layer 2"><g id="Layer_1-2" data-name="Layer 1"><path class="cls-1" d="M55.46,62.43A2,2,0,0,1,54.07,59l4.72-4.54a2,2,0,0,1,2.2-.39l3.65,1.63,3.68-3.64a2,2,0,1,1,2.81,2.84l-4.64,4.6a2,2,0,0,1-2.22.41L60.6,58.26l-3.76,3.61A2,2,0,0,1,55.46,62.43Z"/><path class="cls-2" d="M37,0H2A2,2,0,0,0,0,2V31.76a2,2,0,0,0,2,2H37a2,2,0,0,0,2-2V2A2,2,0,0,0,37,0ZM4,29.76V8.84H35V29.76Z"/><path class="cls-3" d="M79.9,0H45a2,2,0,0,0-2,2V31.76a2,2,0,0,0,2,2h35a2,2,0,0,0,2-2V2A2,2,0,0,0,79.9,0ZM47,29.76V8.84h31V29.76Z"/><path class="cls-2" d="M37,37.76H2a2,2,0,0,0-2,2V69.52a2,2,0,0,0,2,2H37a2,2,0,0,0,2-2V39.76A2,2,0,0,0,37,37.76ZM4,67.52V46.6H35V67.52Z"/><path class="cls-2" d="M79.9,37.76H45a2,2,0,0,0-2,2V69.52a2,2,0,0,0,2,2h35a2,2,0,0,0,2-2V39.76A2,2,0,0,0,79.9,37.76ZM47,67.52V46.6h31V67.52Z"/><rect class="cls-1" x="10.48" y="56.95" width="4" height="5.79"/><rect class="cls-1" x="17.43" y="53.95" width="4" height="8.79"/><rect class="cls-1" x="24.47" y="50.95" width="4" height="11.79"/><path class="cls-1" d="M19.47,25.8a6.93,6.93,0,1,1,6.93-6.92A6.93,6.93,0,0,1,19.47,25.8Zm0-9.85a2.93,2.93,0,1,0,2.93,2.93A2.93,2.93,0,0,0,19.47,16Z"/></g></g></svg>

Before

Width:  |  Height:  |  Size: 1.5 KiB

@@ -1,86 +0,0 @@
import { AppPlugin, PluginExtensionPanelContext, PluginExtensionPoints } from '@grafana/data';
import { App } from './components/App';
import { QueryModal } from './components/QueryModal';
import { selectQuery } from './utils/utils';
import pluginJson from './plugin.json';
export const plugin = new AppPlugin<{}>()
.setRootPage(App)
.addLink<PluginExtensionPanelContext>({
title: 'Open from time series or pie charts (path)',
description: 'This link will only be visible on time series and pie charts',
targets: PluginExtensionPoints.DashboardPanelMenu,
path: `/a/${pluginJson.id}/`,
configure: (context) => {
// Will only be visible for the Link Extensions dashboard
if (context?.dashboard?.title !== 'Link Extensions (path)') {
return undefined;
}
switch (context?.pluginId) {
case 'timeseries':
return {}; // Does not apply any overrides
case 'piechart':
return {
title: `Open from ${context.pluginId}`,
};
default:
// By returning undefined the extension will be hidden
return undefined;
}
},
})
.addLink<PluginExtensionPanelContext>({
title: 'Open from time series or pie charts (onClick)',
description: 'This link will only be visible on time series and pie charts',
targets: PluginExtensionPoints.DashboardPanelMenu,
onClick: (_, { openModal, context }) => {
const targets = context?.targets ?? [];
const title = context?.title;
if (!isSupported(context)) {
return;
}
// Show a modal to display a UI for selecting between the available queries (targets)
// in case there are more available.
if (targets.length > 1) {
return openModal({
title: `Select query from "${title}"`,
body: (props) => <QueryModal {...props} targets={targets} />,
});
}
const [target] = targets;
selectQuery(target);
},
configure: (context) => {
// Will only be visible for the Command Extensions dashboard
if (context?.dashboard?.title !== 'Link Extensions (onClick)') {
return undefined;
}
if (!isSupported(context)) {
return;
}
switch (context?.pluginId) {
case 'timeseries':
return {}; // Does not apply any overrides
case 'piechart':
return {
title: `Open from ${context.pluginId}`,
};
default:
// By returning undefined the extension will be hidden
return undefined;
}
},
});
function isSupported(context?: PluginExtensionPanelContext): boolean {
const targets = context?.targets ?? [];
return targets.length > 0;
}
@@ -1,46 +0,0 @@
{
"name": "@test-plugins/extensions-test-app",
"version": "12.1.0-pre",
"private": true,
"scripts": {
"build": "NODE_OPTIONS='--experimental-strip-types --no-warnings=ExperimentalWarning' webpack -c ./webpack.config.ts --env production",
"dev": "NODE_OPTIONS='--experimental-strip-types --no-warnings=ExperimentalWarning' webpack -w -c ./webpack.config.ts --env development",
"typecheck": "tsc --noEmit",
"lint": "eslint --cache --ignore-path ./.gitignore --ext .js,.jsx,.ts,.tsx ."
},
"author": "Grafana Labs",
"license": "Apache-2.0",
"devDependencies": {
"@grafana/plugin-configs": "workspace:*",
"@types/lodash": "4.17.7",
"@types/node": "22.15.0",
"@types/prismjs": "1.26.4",
"@types/react": "18.3.18",
"@types/react-dom": "18.3.5",
"@types/semver": "7.5.8",
"@types/uuid": "9.0.8",
"glob": "10.4.1",
"ts-node": "10.9.2",
"typescript": "5.5.4",
"webpack": "5.95.0",
"webpack-merge": "5.10.0"
},
"engines": {
"node": ">=20"
},
"dependencies": {
"@emotion/css": "11.11.2",
"@grafana/data": "workspace:*",
"@grafana/runtime": "workspace:*",
"@grafana/schema": "workspace:*",
"@grafana/ui": "workspace:*",
"react": "18.3.1",
"react-dom": "18.3.1",
"react-router-dom": "^6.22.0",
"rxjs": "7.8.1",
"tslib": "2.6.3"
},
"peerDependencies": {
"@grafana/runtime": "*"
}
}
@@ -1,27 +0,0 @@
import { PluginPage, usePluginComponents } from '@grafana/runtime';
import { Stack } from '@grafana/ui';
import { testIds } from '../testIds';
type ReusableComponentProps = {
name: string;
};
export function AddedComponents() {
const { components } = usePluginComponents<ReusableComponentProps>({
extensionPointId: 'plugins/grafana-extensionstest-app/addComponent/v1',
});
return (
<PluginPage>
<Stack direction={'column'} gap={4} data-testid={testIds.addedComponentsPage.container}>
<article>
<h3>Component extensions defined with addComponent and retrived with usePluginComponents hook</h3>
{components.map((Component, i) => {
return <Component key={i} name="World" />;
})}
</article>
</Stack>
</PluginPage>
);
}
@@ -1,22 +0,0 @@
import { PluginPage, usePluginLinks } from '@grafana/runtime';
import { Stack } from '@grafana/ui';
import { ActionButton } from '../components/ActionButton';
import { testIds } from '../testIds';
export const LINKS_EXTENSION_POINT_ID = 'plugins/grafana-extensionstest-app/use-plugin-links/v1';
export function AddedLinks() {
const { links } = usePluginLinks({ extensionPointId: LINKS_EXTENSION_POINT_ID });
return (
<PluginPage>
<Stack direction={'column'} gap={4} data-testid={testIds.addedLinksPage.container}>
<section data-testid={testIds.addedLinksPage.section1}>
<h3>Link extensions defined with addLink and retrieved using usePluginLinks</h3>
<ActionButton extensions={links} />
</section>
</Stack>
</PluginPage>
);
}
@@ -1,25 +0,0 @@
import { PluginPage, usePluginComponent } from '@grafana/runtime';
import { testIds } from '../testIds';
type ReusableComponentProps = {
name: string;
};
export function ExposedComponents() {
const { component: ReusableComponent } = usePluginComponent<ReusableComponentProps>(
'grafana-extensionexample1-app/reusable-component/v1'
);
if (!ReusableComponent) {
return null;
}
return (
<PluginPage>
<div data-testid={testIds.exposedComponentsPage.container}>
<ReusableComponent name={'World'} />
</div>
</PluginPage>
);
}
@@ -1,3 +0,0 @@
export { ExposedComponents } from './ExposedComponents';
export { AddedComponents } from './AddedComponents';
export { AddedLinks } from './AddedLinks';
@@ -1,86 +0,0 @@
{
"$schema": "https://raw.githubusercontent.com/grafana/grafana/main/docs/sources/developers/plugins/plugin.schema.json",
"type": "app",
"name": "Extensions test app",
"preload": true,
"id": "grafana-extensionstest-app",
"info": {
"keywords": ["app"],
"description": "",
"author": {
"name": "Grafana"
},
"logos": {
"small": "img/logo.svg",
"large": "img/logo.svg"
},
"screenshots": [],
"version": "%VERSION%",
"updated": "%TODAY%"
},
"includes": [
{
"type": "page",
"name": "Exposed components",
"path": "/a/grafana-extensionstest-app/exposed-components",
"role": "Admin",
"addToNav": true,
"defaultNav": false
},
{
"type": "page",
"name": "Added components",
"path": "/a/grafana-extensionstest-app/added-components",
"role": "Admin",
"addToNav": true,
"defaultNav": false
},
{
"type": "page",
"name": "Added links",
"path": "/a/grafana-extensionstest-app/added-links",
"role": "Admin",
"addToNav": true,
"defaultNav": false
}
],
"extensions": {
"addedLinks": [
{
"targets": ["grafana/dashboard/panel/menu"],
"title": "Open from time series or pie charts (path)",
"description": "This link will only be visible on time series and pie charts"
},
{
"targets": ["grafana/dashboard/panel/menu"],
"title": "Open from time series or pie charts (onClick)",
"description": "This link will only be visible on time series and pie charts"
}
],
"extensionPoints": [
{
"id": "plugins/grafana-extensionstest-app/use-plugin-links/v1",
"title": "Extension point - links"
},
{
"id": "plugins/grafana-extensionstest-app/addComponent/v1",
"title": "Extension point - components"
},
{
"id": "plugins/grafana-extensionstest-app/actions",
"title": "Legacy extension point - usePluginExtensions() and usePluginLinkExtensions()"
},
{
"id": "plugins/grafana-extensionstest-app/configure-extension-component/v1",
"title": "Legacy extension point - usePluginComponentExtensions()"
}
]
},
"dependencies": {
"grafanaDependency": ">=10.4.0",
"plugins": [],
"extensions": {
"exposedComponents": ["grafana-extensionexample1-app/reusable-component/v1"]
}
}
}
@@ -1,13 +0,0 @@
import * as React from 'react';
import { AppRootProps } from '@grafana/data';
import { testIds } from '../../../../testIds';
export class App extends React.PureComponent<AppRootProps> {
render() {
return (
<div data-testid={testIds.appA.container} className="page-container">
Hello Grafana!!!!!
</div>
);
}
}
@@ -1 +0,0 @@
<svg xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" viewBox="0 0 81.9 71.52"><defs><style>.cls-1{fill:#84aff1;}.cls-2{fill:#3865ab;}.cls-3{fill:url(#linear-gradient);}</style><linearGradient id="linear-gradient" x1="42.95" y1="16.88" x2="81.9" y2="16.88" gradientUnits="userSpaceOnUse"><stop offset="0" stop-color="#f2cc0c"/><stop offset="1" stop-color="#ff9830"/></linearGradient></defs><g id="Layer_2" data-name="Layer 2"><g id="Layer_1-2" data-name="Layer 1"><path class="cls-1" d="M55.46,62.43A2,2,0,0,1,54.07,59l4.72-4.54a2,2,0,0,1,2.2-.39l3.65,1.63,3.68-3.64a2,2,0,1,1,2.81,2.84l-4.64,4.6a2,2,0,0,1-2.22.41L60.6,58.26l-3.76,3.61A2,2,0,0,1,55.46,62.43Z"/><path class="cls-2" d="M37,0H2A2,2,0,0,0,0,2V31.76a2,2,0,0,0,2,2H37a2,2,0,0,0,2-2V2A2,2,0,0,0,37,0ZM4,29.76V8.84H35V29.76Z"/><path class="cls-3" d="M79.9,0H45a2,2,0,0,0-2,2V31.76a2,2,0,0,0,2,2h35a2,2,0,0,0,2-2V2A2,2,0,0,0,79.9,0ZM47,29.76V8.84h31V29.76Z"/><path class="cls-2" d="M37,37.76H2a2,2,0,0,0-2,2V69.52a2,2,0,0,0,2,2H37a2,2,0,0,0,2-2V39.76A2,2,0,0,0,37,37.76ZM4,67.52V46.6H35V67.52Z"/><path class="cls-2" d="M79.9,37.76H45a2,2,0,0,0-2,2V69.52a2,2,0,0,0,2,2h35a2,2,0,0,0,2-2V39.76A2,2,0,0,0,79.9,37.76ZM47,67.52V46.6h31V67.52Z"/><rect class="cls-1" x="10.48" y="56.95" width="4" height="5.79"/><rect class="cls-1" x="17.43" y="53.95" width="4" height="8.79"/><rect class="cls-1" x="24.47" y="50.95" width="4" height="11.79"/><path class="cls-1" d="M19.47,25.8a6.93,6.93,0,1,1,6.93-6.92A6.93,6.93,0,0,1,19.47,25.8Zm0-9.85a2.93,2.93,0,1,0,2.93,2.93A2.93,2.93,0,0,0,19.47,16Z"/></g></g></svg>

Before

Width:  |  Height:  |  Size: 1.5 KiB

@@ -1,27 +0,0 @@
import { AppPlugin } from '@grafana/data';
import { LINKS_EXTENSION_POINT_ID } from '../../pages/AddedLinks';
import { testIds } from '../../testIds';
import { App } from './components/App';
export const plugin = new AppPlugin<{}>()
.setRootPage(App)
.exposeComponent({
id: 'grafana-extensionexample1-app/reusable-component/v1',
title: 'Exposed component',
description: 'A component that can be reused by other app plugins.',
component: ({ name }: { name: string }) => <div data-testid={testIds.appB.exposedComponent}>Hello {name}!</div>,
})
.addLink({
title: 'Basic link',
description: '...',
targets: [LINKS_EXTENSION_POINT_ID],
path: '/a/grafana-extensionexample1-app/',
})
.addLink({
title: 'Go to A',
description: 'Navigating to pluging A',
targets: [LINKS_EXTENSION_POINT_ID],
path: '/a/grafana-extensionexample1-app/',
});
@@ -1,59 +0,0 @@
{
"$schema": "https://raw.githubusercontent.com/grafana/grafana/main/docs/sources/developers/plugins/plugin.schema.json",
"type": "app",
"name": "C App",
"id": "grafana-extensionexample1-app",
"preload": true,
"info": {
"keywords": ["app"],
"description": "Will extend root app with ui extensions",
"author": {
"name": "Myorg"
},
"logos": {
"small": "img/logo.svg",
"large": "img/logo.svg"
},
"screenshots": [],
"version": "%VERSION%",
"updated": "%TODAY%"
},
"includes": [
{
"type": "page",
"name": "Default",
"path": "/a/grafana-extensionexample1-app",
"role": "Admin",
"addToNav": false,
"defaultNav": false
}
],
"extensions": {
"exposedComponents": [
{
"id": "grafana-extensionexample1-app/reusable-component/v1",
"title": "Exposed component",
"description": "A component that can be reused by other app plugins."
}
],
"addedLinks": [
{
"targets": [
"plugins/grafana-extensionstest-app/actions",
"plugins/grafana-extensionstest-app/use-plugin-links/v1"
],
"title": "Go to A",
"description": "Navigating to pluging A"
},
{
"targets": ["plugins/grafana-extensionstest-app/use-plugin-links/v1"],
"title": "Basic link",
"description": "..."
}
]
},
"dependencies": {
"grafanaDependency": ">=10.3.3",
"plugins": []
}
}
@@ -1,8 +0,0 @@
import * as React from 'react';
import { AppRootProps } from '@grafana/data';
export class App extends React.PureComponent<AppRootProps> {
render() {
return <div className="page-container">Hello Grafana!</div>;
}
}
@@ -1 +0,0 @@
<svg xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" viewBox="0 0 81.9 71.52"><defs><style>.cls-1{fill:#84aff1;}.cls-2{fill:#3865ab;}.cls-3{fill:url(#linear-gradient);}</style><linearGradient id="linear-gradient" x1="42.95" y1="16.88" x2="81.9" y2="16.88" gradientUnits="userSpaceOnUse"><stop offset="0" stop-color="#f2cc0c"/><stop offset="1" stop-color="#ff9830"/></linearGradient></defs><g id="Layer_2" data-name="Layer 2"><g id="Layer_1-2" data-name="Layer 1"><path class="cls-1" d="M55.46,62.43A2,2,0,0,1,54.07,59l4.72-4.54a2,2,0,0,1,2.2-.39l3.65,1.63,3.68-3.64a2,2,0,1,1,2.81,2.84l-4.64,4.6a2,2,0,0,1-2.22.41L60.6,58.26l-3.76,3.61A2,2,0,0,1,55.46,62.43Z"/><path class="cls-2" d="M37,0H2A2,2,0,0,0,0,2V31.76a2,2,0,0,0,2,2H37a2,2,0,0,0,2-2V2A2,2,0,0,0,37,0ZM4,29.76V8.84H35V29.76Z"/><path class="cls-3" d="M79.9,0H45a2,2,0,0,0-2,2V31.76a2,2,0,0,0,2,2h35a2,2,0,0,0,2-2V2A2,2,0,0,0,79.9,0ZM47,29.76V8.84h31V29.76Z"/><path class="cls-2" d="M37,37.76H2a2,2,0,0,0-2,2V69.52a2,2,0,0,0,2,2H37a2,2,0,0,0,2-2V39.76A2,2,0,0,0,37,37.76ZM4,67.52V46.6H35V67.52Z"/><path class="cls-2" d="M79.9,37.76H45a2,2,0,0,0-2,2V69.52a2,2,0,0,0,2,2h35a2,2,0,0,0,2-2V39.76A2,2,0,0,0,79.9,37.76ZM47,67.52V46.6h31V67.52Z"/><rect class="cls-1" x="10.48" y="56.95" width="4" height="5.79"/><rect class="cls-1" x="17.43" y="53.95" width="4" height="8.79"/><rect class="cls-1" x="24.47" y="50.95" width="4" height="11.79"/><path class="cls-1" d="M19.47,25.8a6.93,6.93,0,1,1,6.93-6.92A6.93,6.93,0,0,1,19.47,25.8Zm0-9.85a2.93,2.93,0,1,0,2.93,2.93A2.93,2.93,0,0,0,19.47,16Z"/></g></g></svg>

Before

Width:  |  Height:  |  Size: 1.5 KiB

@@ -1,28 +0,0 @@
import { AppPlugin } from '@grafana/data';
import { LINKS_EXTENSION_POINT_ID } from '../../pages/AddedLinks';
import { testIds } from '../../testIds';
import { App } from './components/App';
export const plugin = new AppPlugin<{}>()
.setRootPage(App)
.addComponent<{ name: string }>({
targets: 'plugins/grafana-extensionstest-app/addComponent/v1',
title: 'Added component from B',
description: 'A component that can be reused by other app plugins. Shared using addComponent api',
component: ({ name }: { name: string }) => (
<div data-testid={testIds.appB.reusableAddedComponent}>Hello {name}!</div>
),
})
.addLink({
title: 'Open from B',
description: 'Open a modal from plugin B',
targets: [LINKS_EXTENSION_POINT_ID],
onClick: (_, { openModal }) => {
openModal({
title: 'Modal from app B',
body: () => <div data-testid={testIds.appB.modal}>From plugin B</div>,
});
},
});
@@ -1,59 +0,0 @@
{
"$schema": "https://raw.githubusercontent.com/grafana/grafana/main/docs/sources/developers/plugins/plugin.schema.json",
"type": "app",
"name": "D App",
"id": "grafana-extensionexample2-app",
"preload": true,
"info": {
"keywords": ["app"],
"description": "Will extend root app with ui extensions",
"author": {
"name": "grafana"
},
"logos": {
"small": "img/logo.svg",
"large": "img/logo.svg"
},
"screenshots": [],
"version": "%VERSION%",
"updated": "%TODAY%"
},
"extensions": {
"addedLinks": [
{
"targets": [
"plugins/grafana-extensionstest-app/actions",
"plugins/grafana-extensionstest-app/use-plugin-links/v1"
],
"title": "Open from B",
"description": "Open a modal from plugin B"
}
],
"addedComponents": [
{
"targets": ["plugins/grafana-extensionstest-app/configure-extension-component/v1"],
"title": "Configure extension component from B",
"description": "A component that can be reused by other app plugins. Shared using configureExtensionComponent api"
},
{
"targets": ["plugins/grafana-extensionstest-app/addComponent/v1"],
"title": "Added component from B",
"description": "A component that can be reused by other app plugins. Shared using addComponent api"
}
]
},
"includes": [
{
"type": "page",
"name": "Default",
"path": "/a/grafana-extensionexample2-app",
"role": "Admin",
"addToNav": false,
"defaultNav": false
}
],
"dependencies": {
"grafanaDependency": ">=10.3.3",
"plugins": []
}
}
@@ -1,18 +0,0 @@
import { usePluginLinks } from '@grafana/runtime';
import { Stack } from '@grafana/ui';
import { testIds } from '../../../../testIds';
import { ActionButton } from '../../../../components/ActionButton';
export const LINKS_EXTENSION_POINT_ID = 'plugins/grafana-extensionstest-app/use-plugin-links/v1';
export function AddedLinks() {
const { links } = usePluginLinks({ extensionPointId: LINKS_EXTENSION_POINT_ID });
return (
<Stack direction={'column'} gap={4}>
<section data-testid={testIds.appC.section1}>
<h3>Link extensions defined with addLink and retrieved using usePluginLinks</h3>
<ActionButton extensions={links} />
</section>
</Stack>
);
}
@@ -1,15 +0,0 @@
import * as React from 'react';
import { AppRootProps } from '@grafana/data';
import { AddedLinks } from './AddedLinks';
import { testIds } from '../../../../testIds';
export class App extends React.PureComponent<AppRootProps> {
render() {
return (
<div data-testid={testIds.appC.container} className="page-container">
Hello Grafana!
<AddedLinks></AddedLinks>
</div>
);
}
}
@@ -1 +0,0 @@
<svg xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" viewBox="0 0 81.9 71.52"><defs><style>.cls-1{fill:#84aff1;}.cls-2{fill:#3865ab;}.cls-3{fill:url(#linear-gradient);}</style><linearGradient id="linear-gradient" x1="42.95" y1="16.88" x2="81.9" y2="16.88" gradientUnits="userSpaceOnUse"><stop offset="0" stop-color="#f2cc0c"/><stop offset="1" stop-color="#ff9830"/></linearGradient></defs><g id="Layer_2" data-name="Layer 2"><g id="Layer_1-2" data-name="Layer 1"><path class="cls-1" d="M55.46,62.43A2,2,0,0,1,54.07,59l4.72-4.54a2,2,0,0,1,2.2-.39l3.65,1.63,3.68-3.64a2,2,0,1,1,2.81,2.84l-4.64,4.6a2,2,0,0,1-2.22.41L60.6,58.26l-3.76,3.61A2,2,0,0,1,55.46,62.43Z"/><path class="cls-2" d="M37,0H2A2,2,0,0,0,0,2V31.76a2,2,0,0,0,2,2H37a2,2,0,0,0,2-2V2A2,2,0,0,0,37,0ZM4,29.76V8.84H35V29.76Z"/><path class="cls-3" d="M79.9,0H45a2,2,0,0,0-2,2V31.76a2,2,0,0,0,2,2h35a2,2,0,0,0,2-2V2A2,2,0,0,0,79.9,0ZM47,29.76V8.84h31V29.76Z"/><path class="cls-2" d="M37,37.76H2a2,2,0,0,0-2,2V69.52a2,2,0,0,0,2,2H37a2,2,0,0,0,2-2V39.76A2,2,0,0,0,37,37.76ZM4,67.52V46.6H35V67.52Z"/><path class="cls-2" d="M79.9,37.76H45a2,2,0,0,0-2,2V69.52a2,2,0,0,0,2,2h35a2,2,0,0,0,2-2V39.76A2,2,0,0,0,79.9,37.76ZM47,67.52V46.6h31V67.52Z"/><rect class="cls-1" x="10.48" y="56.95" width="4" height="5.79"/><rect class="cls-1" x="17.43" y="53.95" width="4" height="8.79"/><rect class="cls-1" x="24.47" y="50.95" width="4" height="11.79"/><path class="cls-1" d="M19.47,25.8a6.93,6.93,0,1,1,6.93-6.92A6.93,6.93,0,0,1,19.47,25.8Zm0-9.85a2.93,2.93,0,1,0,2.93,2.93A2.93,2.93,0,0,0,19.47,16Z"/></g></g></svg>

Before

Width:  |  Height:  |  Size: 1.5 KiB

@@ -1,27 +0,0 @@
import { AppPlugin } from '@grafana/data';
import { LINKS_EXTENSION_POINT_ID } from '../../pages/AddedLinks';
import { testIds } from '../../testIds';
import { App } from '../../components/App';
export const plugin = new AppPlugin<{}>()
.setRootPage(App)
.addComponent<{ name: string }>({
targets: ['plugins/grafana-extensionstest-app/addComponent/v1'],
title: 'Added component (where meta data is missing)',
description: '.',
component: ({ name }: { name: string }) => (
<div data-testid={testIds.appB.reusableAddedComponent}>Hello {name}!</div>
),
})
.addLink({
title: 'Added link (where meta data is missing)',
description: '.',
targets: [LINKS_EXTENSION_POINT_ID],
onClick: (_, { openModal }) => {
openModal({
title: 'Modal from app C',
body: () => <div data-testid={testIds.appB.modal}>From plugin B</div>,
});
},
});
@@ -1,35 +0,0 @@
{
"$schema": "https://raw.githubusercontent.com/grafana/grafana/main/docs/sources/developers/plugins/plugin.schema.json",
"type": "app",
"name": "D App",
"id": "grafana-extensionexample3-app",
"preload": true,
"info": {
"keywords": ["app"],
"description": "Will extend root app with ui extensions",
"author": {
"name": "grafana"
},
"logos": {
"small": "img/logo.svg",
"large": "img/logo.svg"
},
"screenshots": [],
"version": "%VERSION%",
"updated": "%TODAY%"
},
"includes": [
{
"type": "page",
"name": "Default",
"path": "/a/grafana-extensionexample3-app",
"role": "Admin",
"addToNav": false,
"defaultNav": false
}
],
"dependencies": {
"grafanaDependency": ">=10.3.3",
"plugins": []
}
}
@@ -1,46 +0,0 @@
export const testIds = {
container: 'main-app-body',
actions: {
button: 'action-button',
},
modal: {
container: 'container',
open: 'open-link',
},
appA: {
container: 'a-app-body',
},
appB: {
modal: 'b-app-modal',
reusableComponent: 'b-app-configure-extension-component',
reusableAddedComponent: 'b-app-add-component',
exposedComponent: 'b-app-exposed-component',
},
appC: {
container: 'c-app-body',
section1: 'use-plugin-links',
section2: 'use-plugin-extensions',
},
legacyGettersPage: {
container: 'data-testid pg-legacy-getters-container',
section1: 'get-plugin-extensions',
section2: 'configure-extension-link-get-plugin-link-extensions',
section3: 'configure-extension-component-get-plugin-component-extensions',
},
legacyHooksPage: {
container: 'data-testid pg-legacy-hooks-container',
section1: 'use-plugin-extensions',
section2: 'configure-extension-link-use-plugin-link-extensions',
section3: 'configure-extension-component-use-plugin-component-extensions',
},
exposedComponentsPage: {
container: 'data-testid pg-exposed-components-container',
},
addedComponentsPage: {
container: 'data-testid pg-added-components-container',
},
addedLinksPage: {
container: 'data-testid pg-added-links-container',
section1: 'use-plugin-links',
},
};
@@ -1,8 +0,0 @@
import { test, expect } from '@grafana/plugin-e2e';
import { testIds } from '../testIds';
import pluginJson from '../plugin.json';
test('should display component exposed by another app', async ({ page }) => {
await page.goto(`/a/${pluginJson.id}/exposed-components`);
await expect(page.getByTestId(testIds.appB.exposedComponent)).toHaveText('Hello World!');
});
@@ -1,11 +0,0 @@
import { test, expect } from '@grafana/plugin-e2e';
import pluginJson from '../plugin.json';
import { testIds } from '../testIds';
test('should render component with usePluginComponents hook', async ({ page }) => {
await page.goto(`/a/${pluginJson.id}/added-components`);
await expect(
page.getByTestId(testIds.addedComponentsPage.container).getByTestId(testIds.appB.reusableAddedComponent)
).toHaveText('Hello World!');
});
@@ -1,71 +0,0 @@
import { test, expect } from '@grafana/plugin-e2e';
import pluginJson from '../plugin.json';
import testApp3pluginJson from '../plugins/grafana-extensionexample3-app/plugin.json';
import { testIds } from '../testIds';
test('should extend the actions menu with a link to a-app plugin', async ({ page }) => {
await page.goto(`/a/${pluginJson.id}/added-links`);
const section = await page.getByTestId(testIds.addedLinksPage.section1);
await section.getByTestId(testIds.actions.button).click();
await page.getByTestId(testIds.container).getByText('Go to A').click();
await page.getByTestId(testIds.modal.open).click();
await expect(page.getByTestId(testIds.appA.container)).toBeVisible();
});
test('should extend main app with link extension from app B', async ({ page }) => {
await page.goto(`/a/${pluginJson.id}/added-links`);
const section = await page.getByTestId(testIds.addedLinksPage.section1);
await section.getByTestId(testIds.actions.button).click();
await page.getByTestId(testIds.container).getByText('Open from B').click();
await expect(page.getByTestId(testIds.appB.modal)).toBeVisible();
});
test('should extend main app with basic link extension from app A', async ({ page }) => {
await page.goto(`/a/${pluginJson.id}/added-links`);
const section = await page.getByTestId(testIds.addedLinksPage.section1);
await section.getByTestId(testIds.actions.button).click();
await page.getByTestId(testIds.container).getByText('Basic link').click();
await page.getByTestId(testIds.modal.open).click();
await expect(page.getByTestId(testIds.appA.container)).toBeVisible();
});
test('should not display any extensions when extension point is not declared in plugin json when in development mode', async ({
page,
}) => {
await page.goto(`/a/${testApp3pluginJson.id}`);
const container = await page.getByTestId(testIds.appC.section1);
await expect(container.getByTestId(testIds.actions.button)).not.toBeVisible();
});
const panelTitle = 'Link with defaults';
const extensionTitle = 'Open from time series...';
const linkOnClickDashboardUid = 'dbfb47c5-e5e5-4d28-8ac7-35f349b95946';
const linkPathDashboardUid = 'd1fbb077-cd44-4738-8c8a-d4e66748b719';
test('configureExtensionLink - should add link extension (path) with defaults to time series panel.', async ({
gotoDashboardPage,
page,
}) => {
const dashboardPage = await gotoDashboardPage({ uid: linkPathDashboardUid });
const panel = await dashboardPage.getPanelByTitle(panelTitle);
await panel.clickOnMenuItem(extensionTitle, { parentItem: 'Extensions' });
await expect(page.getByRole('heading', { name: 'Extensions test app' })).toBeVisible();
});
test('should add link extension (onclick) with defaults to time series panel', async ({ gotoDashboardPage, page }) => {
const dashboardPage = await gotoDashboardPage({ uid: linkOnClickDashboardUid });
const panel = await dashboardPage.getPanelByTitle(panelTitle);
await panel.clickOnMenuItem(extensionTitle, { parentItem: 'Extensions' });
await expect(page.getByRole('dialog')).toContainText('Select query from "Link with defaults"');
});
test('should add link extension (onclick) with new title to pie chart panel', async ({ gotoDashboardPage, page }) => {
const panelTitle = 'Link with new name';
const extensionTitle = 'Open from piechart';
const dashboardPage = await gotoDashboardPage({ uid: linkOnClickDashboardUid });
const panel = await dashboardPage.getPanelByTitle(panelTitle);
await panel.clickOnMenuItem(extensionTitle, { parentItem: 'Extensions' });
await expect(page.getByRole('dialog')).toContainText('Select query from "Link with new name"');
});
@@ -1,10 +0,0 @@
import { Page } from '@playwright/test';
import { selectors } from '@grafana/e2e-selectors';
export async function ensureExtensionRegistryIsPopulated(page: Page) {
// Due to these plugins using the old getter extensions api we need to force a refresh by navigating home then back
// to guarantee the extensions are available to the plugin before we interact with the page.
await page.getByTestId(selectors.components.Breadcrumbs.breadcrumb('Home')).click();
await page.goBack();
}
@@ -1,8 +0,0 @@
{
"compilerOptions": {
"jsx": "react-jsx",
"types": ["node", "jest", "@testing-library/jest-dom"]
},
"extends": "@grafana/plugin-configs/tsconfig.json",
"include": ["."]
}
@@ -1,6 +0,0 @@
import { PLUGIN_BASE_URL } from '../constants';
// Prefixes the route with the base URL of the plugin
export function prefixRoute(route: string): string {
return `${PLUGIN_BASE_URL}/${route}`;
}
@@ -1,5 +0,0 @@
import { DataQuery } from '@grafana/data';
export function selectQuery(target: DataQuery): void {
alert(`You selected query "${target.refId}"`);
}
@@ -1,44 +0,0 @@
import CopyWebpackPlugin from 'copy-webpack-plugin';
import grafanaConfig, { type Env } from '@grafana/plugin-configs/webpack.config.ts';
import { mergeWithCustomize, unique } from 'webpack-merge';
import { type Configuration } from 'webpack';
function skipFiles(f: string): boolean {
if (f.includes('/dist/')) {
// avoid copying files already in dist
return false;
}
if (f.includes('/node_modules/')) {
// avoid copying tsconfig.json
return false;
}
if (f.includes('/package.json')) {
// avoid copying package.json
return false;
}
return true;
}
const config = async (env: Env): Promise<Configuration> => {
const baseConfig = await grafanaConfig(env);
const customConfig = {
plugins: [
new CopyWebpackPlugin({
patterns: [
// To `compiler.options.output`
{ from: 'README.md', to: '.', force: true },
{ from: 'plugin.json', to: '.' },
{ from: 'CHANGELOG.md', to: '.', force: true },
{ from: '**/*.json', to: '.', filter: skipFiles },
{ from: '**/*.svg', to: '.', noErrorOnMissing: true, filter: skipFiles }, // Optional
],
}),
],
};
return mergeWithCustomize({
customizeArray: unique('plugins', ['CopyPlugin'], (plugin) => plugin.constructor && plugin.constructor.name),
})(baseConfig, customConfig);
};
export default config;
@@ -1 +0,0 @@
# Changelog
@@ -1,96 +0,0 @@
import { ChangeEvent } from 'react';
import { Checkbox, InlineField, InlineSwitch, Input, SecretInput, Select } from '@grafana/ui';
import { DataSourcePluginOptionsEditorProps, SelectableValue, toOption } from '@grafana/data';
import { MyDataSourceOptions, MySecureJsonData } from '../types';
interface Props extends DataSourcePluginOptionsEditorProps<MyDataSourceOptions, MySecureJsonData> {}
export function ConfigEditor(props: Props) {
const { onOptionsChange, options } = props;
const { jsonData, secureJsonFields, secureJsonData } = options;
const onJsonDataChange = (key: string, value: string | number | boolean) => {
onOptionsChange({
...options,
jsonData: {
...jsonData,
[key]: value,
},
});
};
// Secure field (only sent to the backend)
const onSecureJsonDataChange = (key: string, value: string | number) => {
onOptionsChange({
...options,
secureJsonData: {
[key]: value,
},
});
};
const onResetAPIKey = () => {
onOptionsChange({
...options,
secureJsonFields: {
...options.secureJsonFields,
apiKey: false,
},
secureJsonData: {
...options.secureJsonData,
apiKey: '',
},
});
};
return (
<>
<InlineField label="Path" labelWidth={14} interactive tooltip={'Json field returned to frontend'}>
<Input
id="config-editor-path"
onChange={(e: ChangeEvent<HTMLInputElement>) => onJsonDataChange('path', e.target.value)}
value={jsonData.path}
placeholder="Enter the path, e.g. /api/v1"
width={40}
/>
</InlineField>
<InlineField label="API Key" labelWidth={14} interactive tooltip={'Secure json field (backend only)'}>
<SecretInput
required
id="config-editor-api-key"
isConfigured={secureJsonFields.apiKey}
value={secureJsonData?.apiKey}
placeholder="Enter your API key"
width={40}
onReset={onResetAPIKey}
onChange={(e: ChangeEvent<HTMLInputElement>) => onSecureJsonDataChange('path', e.target.value)}
/>
</InlineField>
<InlineField label="Switch Enabled">
<InlineSwitch
width={40}
label="Switch Enabled"
value={jsonData.switchEnabled ?? false}
onChange={(e: ChangeEvent<HTMLInputElement>) => onJsonDataChange('switchEnabled', e.target.checked)}
/>
</InlineField>
<InlineField label="Checkbox Enabled">
<Checkbox
width={40}
id="config-checkbox-enabled"
value={jsonData.checkboxEnabled}
onChange={(e: ChangeEvent<HTMLInputElement>) => onJsonDataChange('checkboxEnabled', e.target.checked)}
/>
</InlineField>
<InlineField label="Auth type">
<Select
width={40}
inputId="config-auth-type"
value={jsonData.authType ?? 'keys'}
options={['keys', 'credentials'].map(toOption)}
onChange={(e: SelectableValue<string>) => onJsonDataChange('authType', e.value!)}
/>
</InlineField>
</>
);
}
@@ -1,45 +0,0 @@
import { ChangeEvent } from 'react';
import { InlineField, Input, Stack } from '@grafana/ui';
import { QueryEditorProps } from '@grafana/data';
import { DataSource } from '../datasource';
import { MyDataSourceOptions, MyQuery } from '../types';
type Props = QueryEditorProps<DataSource, MyQuery, MyDataSourceOptions>;
export function QueryEditor({ query, onChange, onRunQuery }: Props) {
const onQueryTextChange = (event: ChangeEvent<HTMLInputElement>) => {
onChange({ ...query, queryText: event.target.value });
};
const onConstantChange = (event: ChangeEvent<HTMLInputElement>) => {
onChange({ ...query, constant: parseFloat(event.target.value) });
// executes the query
onRunQuery();
};
const { queryText, constant } = query;
return (
<Stack gap={0}>
<InlineField label="Constant">
<Input
id="query-editor-constant"
onChange={onConstantChange}
value={constant}
width={8}
type="number"
step="0.1"
/>
</InlineField>
<InlineField label="Query Text" labelWidth={16} tooltip="Not used yet">
<Input
id="query-editor-query-text"
onChange={onQueryTextChange}
value={queryText || ''}
required
placeholder="Enter a query"
/>
</InlineField>
</Stack>
);
}
@@ -1,94 +0,0 @@
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';
import { VariableSupport } from './variables';
export class DataSource extends DataSourceApi<MyQuery, MyDataSourceOptions> {
baseUrl: string;
constructor(instanceSettings: DataSourceInstanceSettings<MyDataSourceOptions>) {
super(instanceSettings);
this.baseUrl = instanceSettings.url!;
this.variables = new VariableSupport();
}
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 {
data: [
createDataFrame({
refId: 'A',
fields: [
{ name: 'Time', values: [from, to], type: FieldType.time },
{ name: 'Value', values: ['A', 'B'], type: FieldType.string },
],
}),
],
};
}
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,
};
}
}
}
@@ -1 +0,0 @@
<svg xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" viewBox="0 0 81.9 71.52"><defs><style>.cls-1{fill:#84aff1;}.cls-2{fill:#3865ab;}.cls-3{fill:url(#linear-gradient);}</style><linearGradient id="linear-gradient" x1="42.95" y1="16.88" x2="81.9" y2="16.88" gradientUnits="userSpaceOnUse"><stop offset="0" stop-color="#f2cc0c"/><stop offset="1" stop-color="#ff9830"/></linearGradient></defs><g id="Layer_2" data-name="Layer 2"><g id="Layer_1-2" data-name="Layer 1"><path class="cls-1" d="M55.46,62.43A2,2,0,0,1,54.07,59l4.72-4.54a2,2,0,0,1,2.2-.39l3.65,1.63,3.68-3.64a2,2,0,1,1,2.81,2.84l-4.64,4.6a2,2,0,0,1-2.22.41L60.6,58.26l-3.76,3.61A2,2,0,0,1,55.46,62.43Z"/><path class="cls-2" d="M37,0H2A2,2,0,0,0,0,2V31.76a2,2,0,0,0,2,2H37a2,2,0,0,0,2-2V2A2,2,0,0,0,37,0ZM4,29.76V8.84H35V29.76Z"/><path class="cls-3" d="M79.9,0H45a2,2,0,0,0-2,2V31.76a2,2,0,0,0,2,2h35a2,2,0,0,0,2-2V2A2,2,0,0,0,79.9,0ZM47,29.76V8.84h31V29.76Z"/><path class="cls-2" d="M37,37.76H2a2,2,0,0,0-2,2V69.52a2,2,0,0,0,2,2H37a2,2,0,0,0,2-2V39.76A2,2,0,0,0,37,37.76ZM4,67.52V46.6H35V67.52Z"/><path class="cls-2" d="M79.9,37.76H45a2,2,0,0,0-2,2V69.52a2,2,0,0,0,2,2h35a2,2,0,0,0,2-2V39.76A2,2,0,0,0,79.9,37.76ZM47,67.52V46.6h31V67.52Z"/><rect class="cls-1" x="10.48" y="56.95" width="4" height="5.79"/><rect class="cls-1" x="17.43" y="53.95" width="4" height="8.79"/><rect class="cls-1" x="24.47" y="50.95" width="4" height="11.79"/><path class="cls-1" d="M19.47,25.8a6.93,6.93,0,1,1,6.93-6.92A6.93,6.93,0,0,1,19.47,25.8Zm0-9.85a2.93,2.93,0,1,0,2.93,2.93A2.93,2.93,0,0,0,19.47,16Z"/></g></g></svg>

Before

Width:  |  Height:  |  Size: 1.5 KiB

@@ -1,9 +0,0 @@
import { DataSourcePlugin } from '@grafana/data';
import { DataSource } from './datasource';
import { ConfigEditor } from './components/ConfigEditor';
import { QueryEditor } from './components/QueryEditor';
import { MyQuery, MyDataSourceOptions } from './types';
export const plugin = new DataSourcePlugin<DataSource, MyQuery, MyDataSourceOptions>(DataSource)
.setConfigEditor(ConfigEditor)
.setQueryEditor(QueryEditor);
@@ -1,47 +0,0 @@
{
"name": "@test-plugins/grafana-e2etest-datasource",
"version": "12.1.0-pre",
"private": true,
"scripts": {
"build": "NODE_OPTIONS='--experimental-strip-types --no-warnings=ExperimentalWarning' webpack -c ./webpack.config.ts --env production",
"dev": "NODE_OPTIONS='--experimental-strip-types --no-warnings=ExperimentalWarning' webpack -w -c ./webpack.config.ts --env development",
"typecheck": "tsc --noEmit",
"lint": "eslint --cache --ignore-path ./.gitignore --ext .js,.jsx,.ts,.tsx ."
},
"author": "Grafana",
"license": "Apache-2.0",
"devDependencies": {
"@grafana/plugin-configs": "workspace:*",
"@types/lodash": "4.17.7",
"@types/node": "22.15.0",
"@types/prismjs": "1.26.4",
"@types/react": "18.3.18",
"@types/react-dom": "18.3.5",
"@types/semver": "7.5.8",
"@types/uuid": "9.0.8",
"glob": "10.4.1",
"ts-node": "10.9.2",
"typescript": "5.5.4",
"webpack": "5.95.0",
"webpack-merge": "5.10.0"
},
"engines": {
"node": ">=20"
},
"dependencies": {
"@emotion/css": "11.11.2",
"@grafana/data": "workspace:*",
"@grafana/runtime": "workspace:*",
"@grafana/schema": "workspace:*",
"@grafana/ui": "workspace:*",
"react": "18.3.1",
"react-dom": "18.3.1",
"react-router-dom": "^6.22.0",
"rxjs": "7.8.1",
"tslib": "2.6.3"
},
"peerDependencies": {
"@grafana/runtime": "*"
},
"packageManager": "yarn@4.4.0"
}
@@ -1,26 +0,0 @@
{
"$schema": "https://raw.githubusercontent.com/grafana/grafana/main/docs/sources/developers/plugins/plugin.schema.json",
"type": "datasource",
"name": "Test",
"id": "grafana-e2etest-datasource",
"metrics": true,
"info": {
"description": "",
"author": {
"name": "Grafana"
},
"keywords": ["datasource"],
"logos": {
"small": "img/logo.svg",
"large": "img/logo.svg"
},
"links": [],
"screenshots": [],
"version": "%VERSION%",
"updated": "%TODAY%"
},
"dependencies": {
"grafanaDependency": ">=10.4.0",
"plugins": []
}
}
@@ -1,39 +0,0 @@
import { test, expect, DataSourceConfigPage } from '@grafana/plugin-e2e';
// The following tests verify that label and input field association is working correctly.
// If these tests break, e2e tests in external plugins will break too.
test.describe('config editor ', () => {
let configPage: DataSourceConfigPage;
test.beforeEach(async ({ createDataSourceConfigPage }) => {
configPage = await createDataSourceConfigPage({ type: 'grafana-e2etest-datasource' });
});
test('text input field', async ({ page }) => {
const field = page.getByRole('textbox', { name: 'API key' });
await expect(field).toBeEmpty();
await field.fill('test text');
await expect(field).toHaveValue('test text');
});
test('switch field', async ({ page }) => {
const field = page.getByLabel('Switch Enabled');
await expect(field).not.toBeChecked();
await field.check();
await expect(field).toBeChecked();
});
test('checkbox field', async ({ page }) => {
const field = page.getByRole('checkbox', { name: 'Checkbox Enabled' });
await expect(field).not.toBeChecked();
await field.check({ force: true });
await expect(field).toBeChecked();
});
test('select field', async ({ page, selectors }) => {
const field = page.getByRole('combobox', { name: 'Auth type' });
await field.click();
const option = selectors.components.Select.option;
await expect(configPage.getByGrafanaSelector(option)).toHaveText(['keys', 'credentials']);
});
});
@@ -1,13 +0,0 @@
import { test, expect } from '@grafana/plugin-e2e';
test('should render variable editor', async ({ variableEditPage, page }) => {
await variableEditPage.datasource.set('gdev-e2etestdatasource');
await expect(page.getByRole('textbox', { name: 'Query Text' })).toBeVisible();
});
test('create new, successful variable query', async ({ variableEditPage, page }) => {
await variableEditPage.datasource.set('gdev-e2etestdatasource');
await page.getByRole('textbox', { name: 'Query Text' }).fill('variableQuery');
await variableEditPage.runQuery();
await expect(variableEditPage).toDisplayPreviews(['A', 'B']);
});
@@ -1,8 +0,0 @@
{
"compilerOptions": {
"jsx": "react-jsx",
"types": ["node", "jest", "@testing-library/jest-dom"]
},
"extends": "@grafana/plugin-configs/tsconfig.json",
"include": ["."]
}
@@ -1,37 +0,0 @@
import { DataSourceJsonData } from '@grafana/data';
import { DataQuery } from '@grafana/schema';
export interface MyQuery extends DataQuery {
queryText?: string;
constant: number;
}
export const DEFAULT_QUERY: Partial<MyQuery> = {
constant: 6.5,
};
export interface DataPoint {
Time: number;
Value: number;
}
export interface DataSourceResponse {
datapoints: DataPoint[];
}
/**
* These are options configured for each DataSource instance
*/
export interface MyDataSourceOptions extends DataSourceJsonData {
switchEnabled: boolean;
checkboxEnabled: boolean;
authType: string;
path?: string;
}
/**
* Value that is used in the backend, but never sent over HTTP to the frontend
*/
export interface MySecureJsonData {
apiKey?: string;
}
@@ -1,13 +0,0 @@
import { VariableSupportBase, VariableSupportType } from '@grafana/data';
import { DEFAULT_QUERY, MyQuery } from './types';
import { DataSource } from './datasource';
export class VariableSupport extends VariableSupportBase<DataSource> {
getType(): VariableSupportType {
return VariableSupportType.Datasource;
}
getDefaultQuery(): Partial<MyQuery> {
return DEFAULT_QUERY;
}
}
@@ -1,44 +0,0 @@
import CopyWebpackPlugin from 'copy-webpack-plugin';
import grafanaConfig, { type Env } from '@grafana/plugin-configs/webpack.config.ts';
import { mergeWithCustomize, unique } from 'webpack-merge';
import { type Configuration } from 'webpack';
function skipFiles(f: string): boolean {
if (f.includes('/dist/')) {
// avoid copying files already in dist
return false;
}
if (f.includes('/node_modules/')) {
// avoid copying tsconfig.json
return false;
}
if (f.includes('/package.json')) {
// avoid copying package.json
return false;
}
return true;
}
const config = async (env: Env): Promise<Configuration> => {
const baseConfig = await grafanaConfig(env);
const customConfig = {
plugins: [
new CopyWebpackPlugin({
patterns: [
// To `compiler.options.output`
{ from: 'README.md', to: '.', force: true },
{ from: 'plugin.json', to: '.' },
{ from: 'CHANGELOG.md', to: '.', force: true },
{ from: '**/*.json', to: '.', filter: skipFiles },
{ from: '**/*.svg', to: '.', noErrorOnMissing: true, filter: skipFiles }, // Optional
],
}),
],
};
return mergeWithCustomize({
customizeArray: unique('plugins', ['CopyPlugin'], (plugin) => plugin.constructor && plugin.constructor.name),
})(baseConfig, customConfig);
};
export default config;