Skip to content
Merged
Show file tree
Hide file tree
Changes from 5 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
11 changes: 11 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',
grafanaAPIUser: {
Copy link
Collaborator

Choose a reason for hiding this comment

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

nit: Besides a user account are there other ways to auth with the API? Maybe grafanaAPIAuth or grafanaAPICredentials would work rather than mentioning user?

Copy link
Contributor Author

Choose a reason for hiding this comment

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

yep, 100% agree

user: 'admin',
password: 'admin',
},
httpCredentials: {
username: 'admin',
password: 'admin',
Expand All @@ -41,6 +45,13 @@ export default defineConfig<PluginOptions>({
name: 'authenticate',
testDir: './src/auth',
testMatch: [/.*auth\.setup\.ts/],
use: {
user: {
user: 'admin',
password: 'admin',
skipCreateUser: true,
},
},
},
// Login to Grafana with new user with viewer role and store the cookie on disk for use in other tests
{
Expand Down
2 changes: 1 addition & 1 deletion packages/plugin-e2e/src/auth/auth.setup.ts
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
import { test as setup } from '../';

setup('authenticate', async ({ login, createUser, user }) => {
if (user) {
if (user && !user.skipCreateUser) {
Copy link
Collaborator

Choose a reason for hiding this comment

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

Not sure I'm understanding the skipCreateUser. Doesn't createUser already handle cases where the user already exists?

Copy link
Contributor Author

Choose a reason for hiding this comment

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

No that's right, user is only created if it doesn't exist, so this is not entirely necessary. I guess I thought this would make this more clear from an end-user standpoint, but that's not the case so I'll remote this prop. Thanks for feedback.

await createUser();
}
await login();
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, grafanaAPIUser }, 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(grafanaAPIUser),
});

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, grafanaAPIUser);
} 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(grafanaAPIUser),
});
const updateRoleReqText = await updateRoleReq.text();
expect(
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -5,15 +5,14 @@ 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, grafanaAPIUser },
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(`${grafanaAPIUser.user}:${grafanaAPIUser.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' }],
grafanaAPIUser: [DEFAULT_ADMIN_USER, { option: true, scope: 'worker' }],
};
21 changes: 17 additions & 4 deletions packages/plugin-e2e/src/types.ts
Original file line number Diff line number Diff line change
Expand Up @@ -62,7 +62,18 @@ 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 & {
/**
* Set this to true if the user already exist in the database. If omitted or set to false, the user will be created.
*/
skipCreateUser?: boolean;
Copy link
Contributor Author

Choose a reason for hiding this comment

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

This prop name is a bit weird - would have been better to reverse the condition and call this createUser, but that would have been a breaking change.

};

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

export type PluginFixture = {
Expand Down Expand Up @@ -301,15 +312,17 @@ 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
* The passwords
*/
password: string;

/**
* The role of the user to create
*/
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
);
});