@testomatio/reporter
Version:
Testomatio Reporter Client
237 lines (235 loc) • 10.3 kB
JavaScript
;
var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
if (k2 === undefined) k2 = k;
var desc = Object.getOwnPropertyDescriptor(m, k);
if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
desc = { enumerable: true, get: function() { return m[k]; } };
}
Object.defineProperty(o, k2, desc);
}) : (function(o, m, k, k2) {
if (k2 === undefined) k2 = k;
o[k2] = m[k];
}));
var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {
Object.defineProperty(o, "default", { enumerable: true, value: v });
}) : function(o, v) {
o["default"] = v;
});
var __importStar = (this && this.__importStar) || (function () {
var ownKeys = function(o) {
ownKeys = Object.getOwnPropertyNames || function (o) {
var ar = [];
for (var k in o) if (Object.prototype.hasOwnProperty.call(o, k)) ar[ar.length] = k;
return ar;
};
return ownKeys(o);
};
return function (mod) {
if (mod && mod.__esModule) return mod;
var result = {};
if (mod != null) for (var k = ownKeys(mod), i = 0; i < k.length; i++) if (k[i] !== "default") __createBinding(result, mod, k[i]);
__setModuleDefault(result, mod);
return result;
};
})();
var __importDefault = (this && this.__importDefault) || function (mod) {
return (mod && mod.__esModule) ? mod : { "default": mod };
};
Object.defineProperty(exports, "__esModule", { value: true });
const debug_1 = __importDefault(require("debug"));
const path_1 = __importDefault(require("path"));
const picocolors_1 = __importDefault(require("picocolors"));
const humanize_duration_1 = __importDefault(require("humanize-duration"));
const lodash_merge_1 = __importDefault(require("lodash.merge"));
const constants_js_1 = require("../constants.js");
const utils_js_1 = require("../utils/utils.js");
const pipe_utils_js_1 = require("../utils/pipe_utils.js");
const debug = (0, debug_1.default)('@testomatio/reporter:pipe:github');
/**
* @typedef {import('../../types/types.js').Pipe} Pipe
* @typedef {import('../../types/types.js').TestData} TestData
* @class GitHubPipe
* @implements {Pipe}
*/
class GitHubPipe {
constructor(params, store = {}) {
this.isEnabled = false;
this.store = store;
this.tests = [];
this.token = params.GH_PAT || process.env.GH_PAT;
this.ref = process.env.GITHUB_REF;
this.repo = process.env.GITHUB_REPOSITORY;
this.jobKey = `${process.env.GITHUB_WORKFLOW || ''} / ${process.env.GITHUB_JOB || ''}`;
this.hiddenCommentData = `<!--- testomat.io report ${this.jobKey} -->`;
debug('GitHub Pipe: ', this.token ? 'TOKEN' : '*no token*', 'Ref:', this.ref, 'Repo:', this.repo);
if (!this.token || !this.ref || !this.repo)
return;
this.isEnabled = true;
const matchedIssue = this.ref.match(/refs\/pull\/(\d+)\/merge/);
if (!matchedIssue)
return;
this.issue = parseInt(matchedIssue[1], 10);
this.start = new Date();
debug('GitHub Pipe: Enabled');
}
// TODO: to using SET opts as argument => prepareRun(opts)
async prepareRun() { }
async createRun() { }
addTest(test) {
if (!this.isEnabled)
return;
debug('Adding test:', test);
const index = this.tests.findIndex(t => (0, utils_js_1.isSameTest)(t, test));
// update if they were already added
if (index >= 0) {
this.tests[index] = (0, lodash_merge_1.default)(this.tests[index], test);
return;
}
this.tests.push(test);
}
async finishRun(runParams) {
if (!this.isEnabled)
return;
if (!this.issue)
return;
if (runParams.tests)
runParams.tests.forEach(t => this.addTest(t));
const { Octokit } = await Promise.resolve().then(() => __importStar(require('@octokit/rest')));
this.octokit = new Octokit({
auth: this.token,
});
const [owner, repo] = (this.repo || '').split('/');
if (!(owner || repo))
return;
// ... create a comment on GitHub
const passedCount = this.tests.filter(t => t.status === 'passed').length;
const failedCount = this.tests.filter(t => t.status === 'failed').length;
const skippedCount = this.tests.filter(t => t.status === 'skipped').length;
let summary = `${this.hiddenCommentData}
| [](https://testomat.io) | ${(0, pipe_utils_js_1.statusEmoji)(runParams.status)} ${`${process.env.GITHUB_JOB} ${runParams.status}`.toUpperCase()} |
| --- | --- |
| Tests | ✔️ **${this.tests.length}** tests run |
| Summary | ${failedCount ? `${(0, pipe_utils_js_1.statusEmoji)('failed')} **${failedCount}** failed; ` : ''} ${(0, pipe_utils_js_1.statusEmoji)('passed')} **${passedCount}** passed; **${(0, pipe_utils_js_1.statusEmoji)('skipped')}** ${skippedCount} skipped |
| Duration | 🕐 **${(0, humanize_duration_1.default)(parseInt(this.tests.reduce((a, t) => a + (t.run_time || 0), 0), 10), {
maxDecimalPoints: 0,
})}** |`;
if (this.store.runUrl) {
summary += `\n| Testomat.io Report | 📊 [Run #${this.store.runId}](${this.store.runUrl}) | `;
}
if (process.env.GITHUB_WORKFLOW) {
summary += `\n| Job | 🗂️ [${this.jobKey}](${process.env.GITHUB_SERVER_URL || 'https://github.com'}/${this.repo}/actions/runs/${process.env.GITHUB_RUN_ID}) | `;
}
if (process.env.RUNNER_OS) {
summary += `\n| Operating System | 🖥️ \`${process.env.RUNNER_OS}\` ${process.env.RUNNER_ARCH || ''} | `;
}
const failures = this.tests
.filter(t => t.status === 'failed')
.slice(0, 20)
.map(t => {
let text = `#### ${(0, pipe_utils_js_1.statusEmoji)('failed')} ${(0, pipe_utils_js_1.fullName)(t)} `;
text += '\n\n';
if (t.message)
text += `> ${t.message
.replace(/[^\x20-\x7E]/g, '')
.replace((0, utils_js_1.ansiRegExp)(), '')
.trim()}\n`;
if (t.stack)
text += `\`\`\`diff\n${t.stack.replace((0, utils_js_1.ansiRegExp)(), '').trim()}\n\`\`\`\n`;
if (t.artifacts && t.artifacts.length && !process.env.TESTOMATIO_PRIVATE_ARTIFACTS) {
t.artifacts
.filter(f => !!f)
.filter(f => f.endsWith('.png'))
.forEach(f => {
if (f.endsWith('.png')) {
text += `\n`;
return text;
}
text += `[📄 ${path_1.default.basename(f)}](${f})\n`;
return text;
});
}
text += '\n---\n';
return text;
});
let body = summary;
if (failures.length) {
body += `\n<details>\n<summary><h3>🟥 Failures (${failures.length})</h4></summary>\n\n${failures.join('\n')}\n`;
if (failures.length > 20) {
body += '\n> Notice\n> Only first 20 failures shown*';
}
body += '\n\n</details>';
}
if (this.tests.length > 0) {
body += '\n<details>\n<summary><h3>🐢 Slowest Tests</h3></summary>\n\n';
body += this.tests
.sort((a, b) => b?.run_time - a?.run_time)
.slice(0, 5)
.map(t => `* ${(0, pipe_utils_js_1.fullName)(t)} (${(0, humanize_duration_1.default)(parseFloat(t.run_time))})`)
.join('\n');
body += '\n</details>';
}
await deletePreviousReport(this.octokit, owner, repo, this.issue, this.hiddenCommentData);
// add report as comment
try {
debug('Adding comment\n', body);
const resp = await this.octokit.rest.issues.createComment({
owner,
repo,
issue_number: this.issue,
body,
});
const url = resp.data?.html_url;
debug('Comment URL:', url);
this.store.githubUrl = url;
console.log(constants_js_1.APP_PREFIX, picocolors_1.default.yellow('GitHub'), `Report created: ${picocolors_1.default.magenta(url)}`);
}
catch (err) {
console.log(constants_js_1.APP_PREFIX, picocolors_1.default.yellow('GitHub'), `Couldn't create GitHub report ${err}`);
}
}
toString() {
return 'GitHub Reporter';
}
}
async function deletePreviousReport(octokit, owner, repo, issue, hiddenCommentData) {
if (process.env.GH_KEEP_OUTDATED_REPORTS)
return;
// get comments
let comments = [];
try {
const response = await octokit.rest.issues.listComments({
owner,
repo,
issue_number: issue,
});
comments = response.data;
}
catch (e) {
console.error('Error while attempt to retrieve comments on GitHub Pull Request:\n', e);
}
if (!comments.length)
return;
for (const comment of comments) {
// if comment was left by the same workflow
if (comment.body.includes(hiddenCommentData)) {
try {
// delete previous comment
await octokit.rest.issues.deleteComment({
owner,
repo,
issue_number: issue,
comment_id: comment.id,
});
}
catch (e) {
console.warn(`Can't delete previously added comment with testomat.io report. Ignore.`);
}
// pass next env var if need to clear all previous reports;
// only the last one is removed by default
if (!process.env.GITHUB_REMOVE_ALL_OUTDATED_REPORTS)
break;
// TODO: in case of many reports should implement pagination
}
}
}
module.exports = GitHubPipe;