跳到主要内容

配置必要的资源

简介

在许多情况下,您需要在 Grafana 中配置某些资源,然后才能运行端到端测试。例如,要测试面板插件如何显示数据,您需要配置一个数据源来查询和返回该数据。本指南介绍如何通过配置来设置这些资源。

测试隔离

测试隔离 是 Playwright 测试的核心部分。关于这一点,我们建议独立测试插件功能,而不是通过高级流程运行它们,因为在高级流程中,某些步骤依赖于之前的步骤。

一个具体的例子

假设您想在数据源插件中测试模板变量插值。为了在 DataSource 文件中进行任何插值,需要定义一个模板变量。由于目标是测试变量插值,我们不想在测试代码中创建模板变量。相反,我们将使用一个已配置的仪表板,该仪表板在我们的测试中已经定义了一个模板变量。

在以下示例中,我们导航到一个已配置的仪表板。该仪表板有一个多值模板变量 env,其值为 testprod。我们添加一个新的面板,并设置一个引用 env 变量的 SQL 查询。然后,我们监视查询数据请求,断言它被调用时带有与模板变量关联的扩展值。

test('should expand multi-valued variable before calling backend', async ({
gotoDashboardPage,
readProvisionedDashboard,
}) => {
const dashboard = await readProvisionedDashboard({ fileName: 'variable.json' });
const dashboardPage = await gotoDashboardPage(dashboard);
const panelEditPage = await dashboardPage.addPanel();
const queryDataSpy = panelEditPage.waitForQueryDataRequest((request) =>
(request.postData() ?? '').includes(`select * from dataset where env in ('test', 'prod')"`)
);
await page.getByLabel('Query').fill('select * from dataset where env in (${env:singlequote})');
await panelEditPage.refreshPanel();
await expect(await queryDataSpy).toBeTruthy();
});

配置必要的资源

您可以使用配置来配置诸如仪表板和数据源之类的资源。

注意

如果在 CI 中运行端到端测试需要配置,您可能需要从插件的 .gitignore 文件中删除 provisioning 文件夹。

危险

注意不要将机密信息提交到公共存储库。对于敏感数据,请使用环境变量插值

读取已配置的文件

@grafana/plugin-e2e 工具提供了 fixture,使您能够读取放置在 provisioning 文件夹中的文件。

readProvisionedDataSource fixture

readProvisionedDataSource fixture 允许您从插件的 provisioning/datasources 文件夹中读取文件。这为您提供了类型,并且还允许您将数据源配置保存在一个地方。

configEditor.spec.ts
const datasource = readProvisionedDataSource<JsonData, SecureJsonData>({ fileName: 'datasources.yml' });
await page.getByLabel('API Key').fill(datasource.secureJsonData.apiKey);
queryEditor.spec.ts
const datasource = readProvisionedDataSource({ fileName: 'datasources.yml' });
await panelEditPage.datasource.set(datasource.name);

readProvisionedDashboard fixture

readProvisionedDashboard fixture 允许您从 provisioning/dashboards 文件夹中读取仪表板 JSON 文件的内容。当您不想硬编码仪表板 UID 而导航到已配置的仪表板时,它可能很有用。

variableEditPage.spec.ts
const dashboard = await readProvisionedDashboard({ fileName: 'dashboard.json' });
const variableEditPage = new VariableEditPage(
{ request, page, selectors, grafanaVersion, testInfo },
{ dashboard, id: '2' }
);
await variableEditPage.goto();

readProvisionedAlertRule fixture

readProvisionedAlertRule fixture 允许您从插件的 provisioning/alerting 文件夹中读取文件。

alerting.spec.ts
test('should evaluate to true when loading a provisioned query that is valid', async ({
gotoAlertRuleEditPage,
readProvisionedAlertRule,
}) => {
const alertRule = await readProvisionedAlertRule({ fileName: 'alerts.yml' });
const alertRuleEditPage = await gotoAlertRuleEditPage(alertRule);
await expect(alertRuleEditPage.evaluate()).toBeOK();
});