Skip to content

Commit

Permalink
feat: add discord reporter
Browse files Browse the repository at this point in the history
  • Loading branch information
Vorobeyko committed Jan 23, 2025
1 parent c7d3365 commit ef68a68
Show file tree
Hide file tree
Showing 7 changed files with 267 additions and 1 deletion.
2 changes: 1 addition & 1 deletion package.json
Original file line number Diff line number Diff line change
Expand Up @@ -44,7 +44,7 @@
"branches": [
"main",
{
"name": "develop",
"name": "feat/add-discord-report",
"channel": "alpha",
"prerelease": "alpha"
}
Expand Down
21 changes: 21 additions & 0 deletions packages/discord-reporter/LICENSE.txt
Original file line number Diff line number Diff line change
@@ -0,0 +1,21 @@
MIT License

Copyright (c) 2021 Lido

Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
15 changes: 15 additions & 0 deletions packages/discord-reporter/README.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,15 @@
# Wallets Module

Module with report for playwright which sending message to discord

## Install

```bash
yarn add @lidofinance/discord-reporter
```

## Usage

```ts

```
35 changes: 35 additions & 0 deletions packages/discord-reporter/package.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,35 @@
{
"name": "@lidofinance/discord-reporter",
"version": "0.0.0",
"main": "dist/src/index.js",
"types": "dist/src/index.d.ts",
"license": "MIT",
"homepage": "https://github.com/lidofinance/wallets-testing-modules",
"repository": {
"type": "git",
"url": "https://github.com/lidofinance/wallets-testing-modules.git",
"directory": "packages/discord-reporter"
},
"bugs": {
"url": "https://github.com/lidofinance/wallets-testing-modules/issues"
},
"sideEffects": false,
"scripts": {
"build": "tsc --build"
},
"keywords": [
"lido",
"lidofinance"
],
"files": [
"dist"
],
"publishConfig": {
"registry": "https://registry.npmjs.org/",
"access": "public"
},
"dependencies": {
"@playwright/test": "^1.44.1",
"axios": "^1.7.9"
}
}
166 changes: 166 additions & 0 deletions packages/discord-reporter/src/discord-reporter.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,166 @@
import {
FullResult,
Reporter,
TestCase,
TestResult,
} from '@playwright/test/reporter';
import axios from 'axios';

interface EmbedField {
name: string;
value: string;
inline?: boolean;
}

interface Embed {
title: string;
description: string;
color: number;
fields: EmbedField[];
url?: string;
}

interface WebhookPayload {
embeds: Embed[];
}

const testStatusToEmoji = {
passed: '✅',
failed: '❌',
timedOut: '❌',
skipped: '⏸️',
interrupted: '❌',
};

const GREEN = 47872;
const RED = 13959168;

const resultToStatus = {
passed: { color: GREEN, title: '🎉 Testing Completed!' },
failed: { color: RED, title: `${testStatusToEmoji.failed} Testing Failed!` },
timedout: {
color: RED,
title: `${testStatusToEmoji.failed} Testing Failed!`,
},
interrupted: {
color: RED,
title: `${testStatusToEmoji.failed} Testing Failed!`,
},
};

interface ReporterOptions {
enabled: string;
}

class DiscordReporter implements Reporter {
private enabled: boolean;

private webhookUrl: string;
private passedTestCount = 0;
private failedTestCount = 0;
private skippedTestCount = 0;

constructor(options: ReporterOptions) {
this.enabled = options.enabled?.toLowerCase() === 'true';
if (!this.enabled) return;

const webhook = process.env.DISCORD_WEBHOOK_URL;
if (!webhook) {
throw new Error(
'DISCORD_WEBHOOK_URL is not defined in environment variables',
);
}
this.webhookUrl = webhook;
}

async sendDiscordWebhook(payload: WebhookPayload) {
try {
console.log(JSON.stringify(payload));
const response = await axios.post(this.webhookUrl, payload, {
headers: {
'Content-Type': 'application/json',
},
});
console.log('Webhook успешно отправлен:', response.status);
} catch (error: any) {
console.error('Ошибка при отправке вебхука:', error?.message);
}
}

onTestEnd(test: TestCase, result: TestResult) {
if (!this.enabled) return;
switch (result.status) {
case 'passed':
this.passedTestCount++;
break;
case 'failed':
case 'timedOut':
case 'interrupted': {
this.failedTestCount++;
break;
}
case 'skipped':
this.skippedTestCount++;
break;
}
}

async onEnd(result: FullResult) {
if (!this.enabled) return;
const duration = this.formatDuration(result.duration);
const githubRunUrl = `${process.env.GITHUB_SERVER_URL}/${process.env.GITHUB_REPOSITORY}/actions/runs/${process.env.GITHUB_RUN_ID}`;

const payload: WebhookPayload = {
embeds: [
{
title: resultToStatus[result.status].title,
description: 'Here are the test run results:',
color: resultToStatus[result.status].color,
fields: [
{
name: `${testStatusToEmoji.passed} Passed`,
value: `${this.passedTestCount}`,
inline: true,
},
{
name: `${testStatusToEmoji.failed} Failed`,
value: `${this.failedTestCount}`,
inline: true,
},
{
name: `${testStatusToEmoji.skipped} Skipped`,
value: `${this.skippedTestCount}`,
inline: true,
},
{
name: '⏳ Run Time',
value: `${duration}`,
inline: false,
},
{
name: '🔗 GitHub Run',
value: process.env.CI
? `[View GitHub Run](${githubRunUrl})`
: 'Local run',
inline: true,
},
],
url: process.env.CI ? githubRunUrl : undefined,
},
],
};

await this.sendDiscordWebhook(payload);
}

private formatDuration(durationMs: number): string {
const totalSeconds = Math.floor(durationMs / 1000);
const hours = Math.floor(totalSeconds / 3600);
const minutes = Math.floor((totalSeconds % 3600) / 60);
const seconds = totalSeconds % 60;

return `${hours} hours ${minutes} minutes ${seconds} seconds`;
}
}

export default DiscordReporter;
1 change: 1 addition & 0 deletions packages/discord-reporter/src/index.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
export * from './discord-reporter';
28 changes: 28 additions & 0 deletions packages/discord-reporter/tsconfig.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,28 @@
{
"compilerOptions": {
"skipLibCheck": true,
"alwaysStrict": true,
"strict": true,
"esModuleInterop": true,
"emitDecoratorMetadata": true,
"experimentalDecorators": true,
"strictNullChecks": false,
"noImplicitReturns": true,
"noImplicitThis": true,
"noImplicitAny": false,
"declaration": true,
"declarationMap": true,
"incremental": true,
"forceConsistentCasingInFileNames": true,
"moduleResolution": "node",
"module": "commonjs",
"target": "ES2020",
"resolveJsonModule": true,
"composite": true,
"sourceMap": true,
"lib": ["ES2020"],
"outDir": "./dist",
"rootDir": "."
},
"references": []
}

0 comments on commit ef68a68

Please sign in to comment.