Skip to content

Plugin E2E: Allow overriding grafanaAPICredentials #930

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 8 commits into from
May 30, 2024
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
10 changes: 10 additions & 0 deletions packages/plugin-e2e/playwright.config.ts
Original file line number Diff line number Diff line change
Expand Up @@ -25,6 +25,10 @@ export default defineConfig<PluginOptions>({

/* Collect trace when retrying the failed test. See https://playwright.dev/docs/trace-viewer */
trace: 'on-first-retry',
grafanaAPICredentials: {
user: 'admin',
password: 'admin',
},
httpCredentials: {
username: 'admin',
password: 'admin',
Expand All @@ -41,6 +45,12 @@ export default defineConfig<PluginOptions>({
name: 'authenticate',
testDir: './src/auth',
testMatch: [/.*auth\.setup\.ts/],
use: {
user: {
user: 'admin',
password: 'admin',
},
},
},
// Login to Grafana with new user with viewer role and store the cookie on disk for use in other tests
{
Expand Down
24 changes: 14 additions & 10 deletions packages/plugin-e2e/src/fixtures/commands/createUser.ts
Original file line number Diff line number Diff line change
@@ -1,22 +1,26 @@
import { APIRequestContext, expect, TestFixture } from '@playwright/test';
import { PlaywrightArgs } from '../../types';
import { PlaywrightArgs, User } from '../../types';

type CreateUserFixture = TestFixture<() => Promise<void>, PlaywrightArgs>;

const headers = {
Authorization: `Basic ${Buffer.from(`admin:admin`).toString('base64')}`,
};
const getHeaders = (user: User) => ({
Authorization: `Basic ${Buffer.from(`${user.user}:${user.password}`).toString('base64')}`,
});

const getUserIdByUsername = async (request: APIRequestContext, userName: string): Promise<number> => {
const getUserIdByUsername = async (
request: APIRequestContext,
userName: string,
grafanaAPIUser: User
): Promise<number> => {
const getUserIdByUserNameReq = await request.get(`/api/users/lookup?loginOrEmail=${userName}`, {
headers,
headers: getHeaders(grafanaAPIUser),
});
expect(getUserIdByUserNameReq.ok()).toBeTruthy();
const json = await getUserIdByUserNameReq.json();
return json.id;
};

export const createUser: CreateUserFixture = async ({ request, user }, use) => {
export const createUser: CreateUserFixture = async ({ request, user, grafanaAPICredentials }, use) => {
await use(async () => {
if (!user) {
throw new Error('Playwright option `User` was not provided');
Expand All @@ -28,7 +32,7 @@ export const createUser: CreateUserFixture = async ({ request, user }, use) => {
login: user?.user,
password: user?.password,
},
headers,
headers: getHeaders(grafanaAPICredentials),
});

let userId: number | undefined;
Expand All @@ -37,15 +41,15 @@ export const createUser: CreateUserFixture = async ({ request, user }, use) => {
userId = respJson.id;
} else if (createUserReq.status() === 412) {
// user already exists
userId = await getUserIdByUsername(request, user?.user);
userId = await getUserIdByUsername(request, user?.user, grafanaAPICredentials);
} else {
throw new Error(`Could not create user '${user?.user}': ${await createUserReq.text()}`);
}

if (user.role) {
const updateRoleReq = await request.patch(`/api/org/users/${userId}`, {
data: { role: user.role },
headers,
headers: getHeaders(grafanaAPICredentials),
});
const updateRoleReqText = await updateRoleReq.text();
expect(
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -5,15 +5,16 @@ import { DataSourceConfigPage } from '../../models/pages/DataSourceConfigPage';
type GotoDataSourceConfigPageFixture = TestFixture<(uid: string) => Promise<DataSourceConfigPage>, PlaywrightArgs>;

export const gotoDataSourceConfigPage: GotoDataSourceConfigPageFixture = async (
{ request, page, selectors, grafanaVersion },
{ request, page, selectors, grafanaVersion, grafanaAPICredentials },
use,
testInfo
) => {
await use(async (uid) => {
const response = await request.get(`/api/datasources/uid/${uid}`, {
headers: {
// here we call backend as admin user and not on behalf of the logged in user as it might not have required permissions
Authorization: `Basic ${Buffer.from(`admin:admin`).toString('base64')}`,
Authorization: `Basic ${Buffer.from(`${grafanaAPICredentials.user}:${grafanaAPICredentials.password}`).toString(
'base64'
)}`,
},
});
if (!response.ok()) {
Expand Down
7 changes: 2 additions & 5 deletions packages/plugin-e2e/src/fixtures/commands/login.ts
Original file line number Diff line number Diff line change
Expand Up @@ -4,14 +4,11 @@ import { PlaywrightArgs } from '../../types';

type LoginFixture = TestFixture<() => Promise<void>, PlaywrightArgs>;

const ADMIN_USER = { user: 'admin', password: 'admin' };

export const login: LoginFixture = async ({ request, user }, use) => {
await use(async () => {
const data = user ?? ADMIN_USER;
const loginReq = await request.post('/login', { data });
const loginReq = await request.post('/login', { data: user });
const text = await loginReq.text();
expect.soft(loginReq.ok(), `Could not log in to Grafana: ${text}`).toBeTruthy();
await request.storageState({ path: path.join(process.cwd(), `playwright/.auth/${data.user}.json`) });
await request.storageState({ path: path.join(process.cwd(), `playwright/.auth/${user?.user}.json`) });
});
};
7 changes: 5 additions & 2 deletions packages/plugin-e2e/src/options.ts
Original file line number Diff line number Diff line change
@@ -1,9 +1,12 @@
import path = require('path');
import { Fixtures } from '@playwright/test';
import { PluginOptions } from './types';
import { PluginOptions, User } from './types';

export const DEFAULT_ADMIN_USER: User = { user: 'admin', password: 'admin' };

export const options: Fixtures<{}, PluginOptions> = {
user: [undefined, { option: true, scope: 'worker' }],
featureToggles: [{}, { option: true, scope: 'worker' }],
provisioningRootDir: [path.join(process.cwd(), 'provisioning'), { option: true, scope: 'worker' }],
user: [DEFAULT_ADMIN_USER, { option: true, scope: 'worker' }],
grafanaAPICredentials: [DEFAULT_ADMIN_USER, { option: true, scope: 'worker' }],
};
24 changes: 16 additions & 8 deletions packages/plugin-e2e/src/types.ts
Original file line number Diff line number Diff line change
Expand Up @@ -62,7 +62,13 @@ export type PluginOptions = {
* You can use different users for different projects. See the fixture createUser for more information on how to create a user,
* and the fixture login for more information on how to authenticate. Also see https://grafana.com/developers/plugin-tools/e2e-test-a-plugin/use-authentication
*/
user?: CreateUserArgs;
user?: User;

/**
* The credentials to use when making requests to the Grafana API. For example when creating users, fetching data sources etc.
* If no credentials are provided, the server default admin:admin credentials will be used.
*/
grafanaAPICredentials: Credentials;
};

export type PluginFixture = {
Expand Down Expand Up @@ -301,19 +307,21 @@ export interface Dashboard {
title?: string;
}

export type CreateUserArgs = {
export type User = {
/**
* The username of the user to create. Needs to be unique
* The username of the user
*/
user: string;
/**
* The password of the user to create
*/
password: string;
role?: OrgRole;
};

export type Credentials = {
/**
* The role of the user to create
* The username of the user
*/
role?: OrgRole;
user: string;
password: string;
};

export type CreateDataSourceArgs<T = any> = {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -5,13 +5,16 @@ import { REDSHIFT_SCHEMAS } from '../mocks/resource';
test('should load resources and display them as options when clicking on an input', async ({
annotationEditPage,
page,
selectors,
readProvisionedDataSource,
}) => {
await annotationEditPage.mockResourceResponse('schemas', REDSHIFT_SCHEMAS);
const ds = await readProvisionedDataSource({ fileName: 'redshift.yaml' });
await annotationEditPage.datasource.set(ds.name);
await page.getByLabel('Schema').click();
await expect(annotationEditPage.getByGrafanaSelector('Select option')).toContainText(REDSHIFT_SCHEMAS);
await expect(annotationEditPage.getByGrafanaSelector(selectors.components.Select.option)).toContainText(
REDSHIFT_SCHEMAS
);
Copy link
Contributor Author

@sunker sunker May 28, 2024

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

This change (and the next file) is unrelated, but needed to get others tests to pass as this selector was recently changed in the main branch of Grafana.

});

test('should be able to add a new annotation when annotations already exist', async ({
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,7 @@ import { REDSHIFT_SCHEMAS, REDSHIFT_TABLES } from '../mocks/resource';
test('should load resources and display them as options when clicking on an input', async ({
variableEditPage,
page,
selectors,
readProvisionedDataSource,
}) => {
await variableEditPage.mockResourceResponse('schemas', REDSHIFT_SCHEMAS);
Expand All @@ -12,8 +13,12 @@ test('should load resources and display them as options when clicking on an inpu
await variableEditPage.setVariableType('Query');
await variableEditPage.datasource.set(ds.name);
await page.getByLabel('Schema').click();
await expect(variableEditPage.getByGrafanaSelector('Select option')).toContainText(REDSHIFT_SCHEMAS);
await expect(variableEditPage.getByGrafanaSelector(selectors.components.Select.option)).toContainText(
REDSHIFT_SCHEMAS
);
await page.keyboard.press('Enter');
await page.getByLabel('Table').click();
await expect(variableEditPage.getByGrafanaSelector('Select option')).toContainText(REDSHIFT_TABLES);
await expect(variableEditPage.getByGrafanaSelector(selectors.components.Select.option)).toContainText(
REDSHIFT_TABLES
);
});
Loading