Skip to content

Commit

Permalink
Fix tests, fix inconistent tests
Browse files Browse the repository at this point in the history
  • Loading branch information
mesudip committed Dec 3, 2024
1 parent a7e2234 commit c65b09c
Show file tree
Hide file tree
Showing 7 changed files with 185 additions and 78 deletions.
20 changes: 12 additions & 8 deletions integration_test/lib/fixtures/poll.ts
Original file line number Diff line number Diff line change
Expand Up @@ -94,15 +94,19 @@ export const test = base.extend<TestOptions & { pollId: number }>({
}

await use(pollId);

await Promise.all(
pages.map(async (userPage) => {
userPage.close();
})
);
try{
// cleanup
if (pollType !== 'NoAction' && pollType !== 'CreatePollWithoutTeardown') {
await organizerPollPage.deletePoll();
if (pollType !== 'NoAction' && pollType !== 'CreatePollWithoutTeardown') {
await organizerPollPage.deletePoll();
}
}catch(e){
console.warn("Unexpected error cleaning up:",e)
// just ignore the error
}
try{
await organizerPage.close()
}catch(e){
console.warn("Unexpected error cleaning up:",e)
}
},
});
122 changes: 102 additions & 20 deletions integration_test/lib/helpers/blockfrost.ts
Original file line number Diff line number Diff line change
Expand Up @@ -4,27 +4,24 @@ import environments from "@constants/environments";
const blockfrostApiUrl = 'https://cardano-'+(environments.networkId == 0? 'preview':'mainnet')+'.blockfrost.io/api/v0/txs/';
const blockfrostApiKey = environments.blockfrostApiKey;

async function fetchVoteMetadata (txHash:string): Promise<any> {
const url = `${blockfrostApiUrl}${txHash}/metadata`
console.log("Fetching:",url)
const response = await fetch(url, {
method: 'GET',
headers: {
'project_id': blockfrostApiKey,
},
});
const txData: any[] = await response.json();
const label27=txData.filter(x=>x.label==='27')[0].json_metadata
return label27;
};

export async function fetchPollSummaryMetadata(txHash: string):Promise<string[]>{
return await fetchVoteMetadata(txHash)
}
interface OnChainVoteData {
[delegate: string]: string[];
}

export type SummaryTxMetadata = {
votes: {
yes: number,
no: number,
abstain: number
}
eligibleVoters: number,
approvalPercent: number
voteTransactions: string[],
pollName: string,
constutionHash: string
}

export type Vote = VotePayload & {
voterName: string
cosesign1: string
Expand All @@ -39,6 +36,91 @@ export interface VotePayload{
vote: 'yes'| 'no' | 'abstain'
challenge: string
}


async function fetchVoteMetadata (txHash:string): Promise<any> {
const url = `${blockfrostApiUrl}${txHash}/metadata`
console.log("Fetching:",url)
const response = await fetch(url, {
method: 'GET',
headers: {
'project_id': blockfrostApiKey,
},
});
const txData: any[] = await response.json();
const label27=txData.filter(x=>x.label==='27')[0].json_metadata
return label27;
};

export async function fetchPollSummaryMetadata(txHash: string):Promise<SummaryTxMetadata>{
const strings: string[]= await fetchVoteMetadata(txHash)
let txHashes=[]
const delegateIndex = strings.indexOf("Delegate Signature Transaction Hashes:");

// If the index is found, slice the array and filter out the hashes
if (delegateIndex !== -1) {
txHashes= strings.slice(delegateIndex + 1).filter(item => /^[a-f0-9]{64}$/.test(item));
}

// Initialize variables to store the metadata
let pollName = "";
let constutionHash = "";
let yesVotes = 0;
let noVotes = 0;
let abstainVotes = 0;
let eligibleVoters = 0;
let approvalPercent = 0;


strings.slice(0,delegateIndex).forEach((line, index) => {
// Extract poll name
if (line.startsWith("Poll: ")) {
pollName = line.replace("Poll: ", "").trim();
}

// Extract constitution hash
if (line.startsWith("Text Hash:")) {
constutionHash = strings[index+1].trim();
}

// Extract Yes, No, Abstain votes
if (line.startsWith("Yes Votes: ")) {
yesVotes = parseInt(line.replace("Yes Votes: ", "").trim(), 10);
}
if (line.startsWith("No Votes: ")) {
noVotes = parseInt(line.replace("No Votes: ", "").trim(), 10);
}
if (line.startsWith("Abstain Votes: ")) {
abstainVotes = parseInt(line.replace("Abstain Votes: ", "").trim(), 10);
}

// Extract total eligible voters
if (line.startsWith("Total Eligible Voters: ")) {
eligibleVoters = parseInt(line.replace("Total Eligible Voters: ", "").trim(), 10);
}

// Extract approval percentage
if (line.startsWith("Approval Result: ")) {
const approvalResult = line.replace("Approval Result: ", "").trim();
approvalPercent = parseFloat(approvalResult.replace("%", ""));
}
});

// Return the structured metadata
return {
votes: {
yes: yesVotes,
no: noVotes,
abstain: abstainVotes
},
eligibleVoters,
approvalPercent,
voteTransactions: txHashes,
pollName,
constutionHash
};
};

export async function fetchVoteTxMetadata(txHash: string):Promise<Vote[]>{
const voteData: OnChainVoteData[] = await fetchVoteMetadata(txHash)
return voteData.map(v=>{
Expand Down Expand Up @@ -90,8 +172,9 @@ function extractVoteData(data:string): Vote {
};
}

///Wallet: stake_test1uqp28kgg6cafhzuf74eyh8trpa4fh5w50776wk5xh5npv8gx0zh92,
//Poll: Rustic Plastic Chips, Hashed Constitution Text: 16885f03dd0368dbcaaf80ea0ebc5c2e81b46dd082ec628662d69968af096f8d,
// Sample content to be parsed
// Wallet: stake_test1uqp28kgg6cafhzuf74eyh8trpa4fh5w50776wk5xh5npv8gx0zh92,
// Poll: Rustic Plastic Chips, Hashed Constitution Text: 16885f03dd0368dbcaaf80ea0ebc5c2e81b46dd082ec628662d69968af096f8d,
// Link to Constitution Text: https://proud-publication.info/, Vote: no,
// Timestamp: 12/2/2024, 11:14:32 PM, Challenge: fa2c6340ddfbb809735bd51217f0cbcbd3bd2b487654549f054e74ac5e8c9d87
export function decodeOnChainPayload(data: string): VotePayload {
Expand Down Expand Up @@ -126,5 +209,4 @@ function extractVoteData(data:string): Vote {
challenge: challengeMatch ? challengeMatch[1] : '',
vote: voteMatch ? validateVote(voteMatch[1]) : 'abstain',
};
}

}
6 changes: 3 additions & 3 deletions integration_test/lib/helpers/userRoles.ts
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,7 @@ import {
newOrganizer1Page,
} from '@helpers/page';

import { Page } from '@playwright/test';
import { Browser, BrowserContext, Page } from '@playwright/test';

type UserRole =
| 'Delegate'
Expand Down Expand Up @@ -38,12 +38,12 @@ export function getUserPages(browser, userRole?: UserRole): Promise<Page[]> {
export function forEachUser(
handler: (user: {
role: string;
loader: (browser: unknown) => Promise<Page>;
loader: (browser: Browser|BrowserContext) => Promise<Page>;
}) => unknown
) {
const users: {
role: string;
handler: (browser: unknown) => Promise<Page>;
handler: (browser: Browser|BrowserContext) => Promise<Page>;
}[] = [
{
role: 'Alternate',
Expand Down
9 changes: 5 additions & 4 deletions integration_test/lib/pages/pollPage.ts
Original file line number Diff line number Diff line change
Expand Up @@ -26,17 +26,18 @@ export default class PollPage {

constructor(private readonly page: Page) {}

async goto(pollId: number): Promise<void> {
this.page.goto(`/polls/${pollId}`);
async goto(pollId: number): Promise<any> {
return await this.page.goto(`/polls/${pollId}`);
}

async deletePoll(): Promise<void> {
await this.deletePollBtn.click();
await this.deletePollConfirm.click();
await this.page.waitForURL('/', {
timeout: 10_000,
timeout: 15_000,
}).finally(()=>{
console.log("PageUrl after wait :",this.page.url())
});

}
async endVoting() {
await this.endVotingBtn.click();
Expand Down
55 changes: 33 additions & 22 deletions integration_test/tests/0-common/comon.spec.ts
Original file line number Diff line number Diff line change
Expand Up @@ -57,6 +57,7 @@ test.describe('Polls', () => {
}
})
);
await Promise.all(pages.map(page=>page.close()))
});

forEachUser((user) => {
Expand All @@ -74,6 +75,7 @@ test.describe('Polls', () => {

const statusText = await pollPageStatusChip.textContent();
expect(['Concluded', 'Pending', 'Voting']).toContain(statusText);
await page.close()
});
});

Expand Down Expand Up @@ -121,6 +123,7 @@ test.describe('Polls', () => {
expect(votes).toEqual('1 vote');
})
);
await Promise.all(pages.map(page=>page.close()));
});
});

Expand Down Expand Up @@ -173,6 +176,8 @@ test.describe('Polls', () => {
await expect(abstainCount).toHaveText('1');
})
);
await Promise.all(pages.map(page=>page.close()));

});

/**
Expand Down Expand Up @@ -201,6 +206,7 @@ test.describe('Polls', () => {
expect(acceptancePercentage).toEqual('2%');
})
);
await Promise.all(pages.map(page=>page.close()));
});
});

Expand Down Expand Up @@ -261,6 +267,7 @@ test.describe('User profile', () => {
await votingTable.getByTestId('user-votes-' + pollId).isVisible();
})
);
await Promise.all(pages.map(page=>page.close()));
});

/**
Expand Down Expand Up @@ -374,35 +381,37 @@ test.describe('CSV File', () => {
fs.unlinkSync(filePath);
})
);
await Promise.all(pages.map(page=>page.close()));
});

});

test.describe('Constitution Poll Hash', () => {
test.use({ pollType: 'CreatePollWithCustomHash' });

test.describe('Pending Poll', () => {
test.use({ pollType: 'CreatePollWithCustomHash' });
test('0-4A-1 Observers should be able to view custom hash of pending poll', async ({
pollId,
browser,
}) => {
test.slow();
const pages = await getUserPages(browser);
await Promise.all(
pages.map(async (page) => {
const pollPage = new PollPage(page);
await pollPage.goto(pollId);
forEachUser(user=>{
test('0-4A-1 '+user.role+' should be able to view custom hash of pending poll', async ({
pollId,
browser,
}) => {
test.slow()
const page= await user.loader(browser)
const pollPage = new PollPage(page);
await pollPage.goto(pollId);

// fetch hash value
const pollPageHash = page.getByTestId('constitution-poll-hash');
await expect(pollPageHash.first()).toBeVisible({ timeout: 20_000 });
const pollPageHashContent = await pollPageHash.innerText();
// fetch hash value
const pollPageHash = page.getByTestId('constitution-poll-hash');
await expect(pollPageHash.first()).toBeVisible({ timeout: 20_000 });
const pollPageHashContent = await pollPageHash.innerText();

// assert hash value
expect(pollPageHashContent).toContain(
'1111111111111111111111111111111111111111111111111111111111111112'
);
})
);
});
// assert hash value
expect(pollPageHashContent).toContain(
'1111111111111111111111111111111111111111111111111111111111111112'
);
await page.close()
});
})
});

test.describe('On Going Poll', () => {
Expand All @@ -429,6 +438,7 @@ test.describe('Constitution Poll Hash', () => {
);
})
);
await Promise.all(pages.map(page=>page.close()));
});
});

Expand Down Expand Up @@ -456,6 +466,7 @@ test.describe('Constitution Poll Hash', () => {
);
})
);
await Promise.all(pages.map(page=>page.close()));
});
});
});
Expand Down
Loading

0 comments on commit c65b09c

Please sign in to comment.