Skip to content

Commit

Permalink
Merge pull request #1033 from IntersectMBO/feat/extended-tests
Browse files Browse the repository at this point in the history
Feat/extended tests
  • Loading branch information
mesudip authored May 16, 2024
2 parents 7242721 + d516bd6 commit 899edbe
Show file tree
Hide file tree
Showing 37 changed files with 599 additions and 137 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -22,7 +22,7 @@ export async function createTempDRepAuth(page: Page, wallet: ShelleyWallet) {

export async function createTempAdaHolderAuth(
page: Page,
wallet: ShelleyWallet
wallet: ShelleyWallet,
) {
await importWallet(page, wallet.json());

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -7,7 +7,7 @@ import { Page } from "@playwright/test";

export default async function createWallet(
page: Page,
config?: CardanoTestWalletConfig
config?: CardanoTestWalletConfig,
) {
const wallet = (await ShelleyWallet.generate()).json();

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,7 @@ import { StaticWallet } from "@types";

export async function importWallet(
page: Page,
wallet: StaticWallet | CardanoTestWallet
wallet: StaticWallet | CardanoTestWallet,
) {
await page.addInitScript((wallet) => {
// @ts-ignore
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -6,11 +6,11 @@ import path = require("path");

export default async function loadDemosExtension(
page: Page,
enableStakeSigning = false
enableStakeSigning = false,
) {
const demosBundleScriptPath = path.resolve(
__dirname,
"../../node_modules/@cardanoapi/cardano-test-wallet/script.js"
"../../node_modules/@cardanoapi/cardano-test-wallet/script.js",
);
let walletConfig: CardanoTestWalletConfig = {
enableStakeSigning,
Expand Down
5 changes: 5 additions & 0 deletions tests/govtool-frontend/playwright/lib/helpers/cardano.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
export function lovelaceToAda(lovelace: number) {
if (lovelace === 0) return 0;

return lovelace / 1e6;
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,29 @@
const monthNames = [
"Jan",
"Feb",
"Mar",
"Apr",
"May",
"Jun",
"Jul",
"Aug",
"Sep",
"Oct",
"Nov",
"Dec",
];

export default function extractExpiryDateFromText(text: string): Date | null {
const regex = /(\d{1,2})th ([\w]{3}) (\d{4})/;
const match = text.match(regex);

if (match) {
const day = parseInt(match[1]);
const month = match[2];
const year = parseInt(match[3]);

return new Date(year, monthNames.indexOf(month), day);
} else {
return null;
}
}
13 changes: 13 additions & 0 deletions tests/govtool-frontend/playwright/lib/helpers/logger.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,13 @@
export class Logger {
static success(msg: string) {
console.debug(`\x1b[32m✔ ${msg}\x1b[0m`); // Green color
}

static fail(msg) {
console.debug(`\x1b[33m✖ ${msg}\x1b[0m`); // Orange color
}

static info(msg: string) {
console.debug(`\x1b[36mℹ ${msg}\x1b[0m`); // Cyan color
}
}
13 changes: 13 additions & 0 deletions tests/govtool-frontend/playwright/lib/helpers/metadata.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,13 @@
import { Download } from "@playwright/test";
import * as fs from "fs";

export async function downloadMetadata(download: Download): Promise<{
name: string;
data: JSON;
}> {
const path = `.download/${download.suggestedFilename()}`;
await download.saveAs(path);
const fileContent = fs.readFileSync(path, "utf-8");
const jsonData = JSON.parse(fileContent);
return { name: download.suggestedFilename(), data: jsonData };
}
2 changes: 1 addition & 1 deletion tests/govtool-frontend/playwright/lib/helpers/page.ts
Original file line number Diff line number Diff line change
Expand Up @@ -11,7 +11,7 @@ interface BrowserConfig {

export async function createNewPageWithWallet(
browser: Browser,
{ storageState, wallet, enableStakeSigning }: BrowserConfig
{ storageState, wallet, enableStakeSigning }: BrowserConfig,
): Promise<Page> {
const context = await browser.newContext({
storageState: storageState,
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -15,7 +15,7 @@ export default async function setupWallets(wallets: ShelleyWallet[]) {
const { txId, address } = await kuberService.initializeWallets(
faucetWallet.address,
signingKey,
wallets
wallets,
);
await pollTransaction(txId, address);

Expand Down
21 changes: 16 additions & 5 deletions tests/govtool-frontend/playwright/lib/helpers/transaction.ts
Original file line number Diff line number Diff line change
Expand Up @@ -10,7 +10,7 @@ import { Logger } from "../../../cypress/lib/logger/logger";
*/
export async function pollTransaction(
txHash: string,
lockInfo?: LockInterceptorInfo
lockInfo?: LockInterceptorInfo,
) {
try {
Logger.info(`Waiting for tx completion: ${txHash}`);
Expand All @@ -23,7 +23,7 @@ export async function pollTransaction(
},
{
timeout: environments.txTimeOut,
}
},
)
.toBeGreaterThan(0);

Expand All @@ -34,7 +34,7 @@ export async function pollTransaction(
await LockInterceptor.releaseLockForAddress(
lockInfo.address,
lockInfo.lockId,
`Task completed for:${lockInfo.lockId}`
`Task completed for:${lockInfo.lockId}`,
);
} catch (err) {
if (lockInfo) {
Expand All @@ -43,20 +43,31 @@ export async function pollTransaction(
await LockInterceptor.releaseLockForAddress(
lockInfo.address,
lockInfo.lockId,
`Task failure: \n${JSON.stringify(errorMessage)}`
`Task failure: \n${JSON.stringify(errorMessage)}`,
);
}

throw err;
}
}

export async function waitForTxConfirmation(page: Page) {
export async function waitForTxConfirmation(
page: Page,
triggerCallback?: () => Promise<void>,
) {
let transactionHash: string | undefined;
const transactionStatusPromise = page.waitForRequest((request) => {
return request.url().includes("/transaction/status/");
});

await triggerCallback?.call(this);
await expect(
page
.getByTestId("alert-warning")
.getByText("Transaction in progress", { exact: false }),
).toBeVisible({
timeout: 10000,
});
const url = (await transactionStatusPromise).url();
const regex = /\/transaction\/status\/([^\/]+)$/;
const match = url.match(regex);
Expand Down
28 changes: 10 additions & 18 deletions tests/govtool-frontend/playwright/lib/lockInterceptor.ts
Original file line number Diff line number Diff line change
Expand Up @@ -10,24 +10,16 @@ export interface LockInterceptorInfo {
address: string;
}

abstract class BaseLock {
abstract acquireLock(key: string, id?: string): Promise<boolean>;

abstract releaseLock(key: string, id?: string): Promise<boolean>;

abstract checkLock(key: string): Promise<boolean>;
}

export class LockInterceptor {
private static async acquireLock(
address: string,
lockId: string
lockId: string,
): Promise<void> {
const lockFilePath = path.resolve(__dirname, `../.lock-pool/${address}`);

try {
await log(
`Initiator: ${address} \n---------------------> acquiring lock for:${lockId}`
`Initiator: ${address} \n---------------------> acquiring lock for:${lockId}`,
);
await new Promise<void>((resolve, reject) => {
lockfile.lock(lockFilePath, (err) => {
Expand All @@ -39,7 +31,7 @@ export class LockInterceptor {
});
});
await log(
`Initiator: ${address} \n---------------------> acquired lock for:${lockId}`
`Initiator: ${address} \n---------------------> acquired lock for:${lockId}`,
);
} catch (err) {
throw err;
Expand All @@ -48,13 +40,13 @@ export class LockInterceptor {

private static async releaseLock(
address: string,
lockId: string
lockId: string,
): Promise<void> {
const lockFilePath = path.resolve(__dirname, `../.lock-pool/${address}`);

try {
await log(
`Initiator: ${address} \n---------------------> releasing lock for:${lockId}`
`Initiator: ${address} \n---------------------> releasing lock for:${lockId}`,
);
await new Promise<void>((resolve, reject) => {
lockfile.unlock(lockFilePath, async (err) => {
Expand All @@ -66,7 +58,7 @@ export class LockInterceptor {
});
});
await log(
`Initiator: ${address} \n---------------------> released lock for:${lockId}\n`
`Initiator: ${address} \n---------------------> released lock for:${lockId}\n`,
);
} catch (err) {
throw err;
Expand All @@ -75,13 +67,13 @@ export class LockInterceptor {

private static async waitForReleaseLock(
address: string,
lockId: string
lockId: string,
): Promise<void> {
const pollInterval = 4000; // 4 secs

try {
await log(
`Initiator: ${address} \n ---------------------> waiting lock for:${lockId}`
`Initiator: ${address} \n ---------------------> waiting lock for:${lockId}`,
);
return new Promise<void>((resolve, reject) => {
const pollFn = () => {
Expand All @@ -108,7 +100,7 @@ export class LockInterceptor {
address: string,
callbackFn: () => Promise<TxSubmitResponse>,
lockId: string,
provider: "local" | "server" = "local"
provider: "local" | "server" = "local",
): Promise<TxSubmitResponse> {
while (true) {
const isAddressLocked = checkAddressLock(address);
Expand Down Expand Up @@ -142,7 +134,7 @@ export class LockInterceptor {
static async releaseLockForAddress(
address: string,
lockId: string,
message?: string
message?: string,
) {
try {
message && (await log(message));
Expand Down
Original file line number Diff line number Diff line change
@@ -1,4 +1,6 @@
import { Page } from "@playwright/test";
import { downloadMetadata } from "@helpers/metadata";
import { Download, Page } from "@playwright/test";
import metadataBucketService from "@services/metadataBucketService";
import { IDRepInfo } from "@types";
import environments from "lib/constants/environments";

Expand All @@ -7,7 +9,7 @@ export default class DRepRegistrationPage {
readonly skipBtn = this.page.getByTestId("skip-button");
readonly confirmBtn = this.page.getByTestId("confirm-modal-button");
readonly registrationSuccessModal = this.page.getByTestId(
"governance-action-submitted-modal"
"governance-action-submitted-modal",
);
readonly continueBtn = this.page.getByTestId("retire-button"); // BUG testId -> continue-button
readonly addLinkBtn = this.page.getByRole("button", { name: "+ Add link" }); // BUG: testId -> add-link-button
Expand All @@ -25,7 +27,7 @@ export default class DRepRegistrationPage {
await this.continueBtn.click(); // BUG: testId -> continue-register-button
}

async register(dRepInfo: IDRepInfo) {
async register(dRepInfo: IDRepInfo = { name: "Test_dRep" }) {
await this.nameInput.fill(dRepInfo.name);

if (dRepInfo.email != null) {
Expand All @@ -40,13 +42,24 @@ export default class DRepRegistrationPage {
}
}

this.page
.getByRole("button", { name: "download Vote_Context.jsonld" })
.click();
const dRepMetadata = await this.downloadVoteMetadata();
const url = await metadataBucketService.uploadMetadata(
dRepMetadata.name,
dRepMetadata.data,
);
await this.continueBtn.click(); // BUG: testId -> submit-button
await this.page.getByRole("checkbox").click();
await this.continueBtn.click(); // BUG: testId -> submit-button

await this.page
.getByPlaceholder("URL")
.fill(`${environments.metadataBucketUrl}/Test_dRep`);
await this.page.getByPlaceholder("URL").fill(url);
await this.continueBtn.click();
}

async downloadVoteMetadata() {
const download: Download = await this.page.waitForEvent("download");
return downloadMetadata(download);
}
}
18 changes: 11 additions & 7 deletions tests/govtool-frontend/playwright/lib/pages/delegationPage.ts
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
import { Page } from "@playwright/test";
import { Page, expect } from "@playwright/test";
import environments from "lib/constants/environments";
import { withTxConfirmation } from "lib/transaction.decorator";

export default class DelegationPage {
readonly otherOptionsBtn = this.page.getByText("Other options");
Expand All @@ -18,27 +19,30 @@ export default class DelegationPage {
.filter({ hasText: "Signal No Confidence on Every" })
.nth(2); // BUG: testId -> signal-no-confidence-card
readonly abstainDelegationCard = this.page.getByText(
"Abstain from Every VoteSelect this to vote ABSTAIN to every vote.Voting Power₳"
);// BUG: testId -> abstain-delegation-card
"Abstain from Every VoteSelect this to vote ABSTAIN to every vote.Voting Power₳",
); // BUG: testId -> abstain-delegation-card

readonly delegationErrorModal = this.page.getByTestId(
"delegation-transaction-error-modal"
"delegation-transaction-error-modal",
);

readonly delegateBtns = this.page.locator(
'[data-testid$="-delegate-button"]'
);
'[data-testid$="-delegate-button"]',
);

constructor(private readonly page: Page) {}

async goto() {
await this.page.goto(
`${environments.frontendUrl}/connected/dRep_directory`
`${environments.frontendUrl}/connected/dRep_directory`,
);
}

@withTxConfirmation
async delegateToDRep(dRepId: string) {
await this.searchInput.fill(dRepId);
const delegateBtn = this.page.getByTestId(`${dRepId}-delegate-button`);
await expect(delegateBtn).toBeVisible();
await this.page.getByTestId(`${dRepId}-delegate-button`).click();
}

Expand Down
Loading

0 comments on commit 899edbe

Please sign in to comment.