跳至主要内容

配置必要资源

介绍

在许多情况下,您需要在 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 工具提供了夹具 (fixtures),使您能够读取放置在 provisioning 文件夹中的文件。

readProvisionedDataSource 夹具

readProvisionedDataSource 夹具允许您从插件的 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 夹具

readProvisionedDashboard 夹具允许您从 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 夹具

readProvisionedAlertRule 夹具允许您从插件的 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();
});