Skip to content

Instantly share code, notes, and snippets.

@futantan
Created June 21, 2019 09:07
Show Gist options
  • Save futantan/a3b08535c6a4814feab82800954768b3 to your computer and use it in GitHub Desktop.
Save futantan/a3b08535c6a4814feab82800954768b3 to your computer and use it in GitHub Desktop.
//import TestRail from './TestRail';
'use strict';
Object.defineProperty(exports, '__esModule', {
value: true
});
var request = require('request');
var qs = require('querystring');
var Promise = require('bluebird');
require('babel-core/register');
require('babel-polyfill');
/* #region Testrail */
// ----- API Reference: http://docs.gurock.com/testrail-api2/start -----
function TestRail(options) {
this.host = options.host;
this.user = options.user;
this.password = options.password;
this.uri = '/index.php?/api/v2/';
}
TestRail.prototype.apiGet = function (apiMethod, queryVariables, callback) {
var url = this.host + this.uri + apiMethod;
if (typeof queryVariables == 'function') {
callback = queryVariables;
queryVariables = null;
}
return this._callAPI('get', url, queryVariables, null, callback);
};
TestRail.prototype.apiPost = function (apiMethod, body, queryVariables, callback) {
var url = this.host + this.uri + apiMethod;
if (typeof body == 'function') {
callback = body;
queryVariables = body = null;
} else if (typeof queryVariables == 'function') {
callback = queryVariables;
queryVariables = null;
}
return this._callAPI('post', url, queryVariables, body, callback);
};
TestRail.prototype._callAPI = function (method, url, queryVariables, body, callback) {
if (queryVariables != null) {
url += '&' + qs.stringify(queryVariables);
}
var requestArguments = {
uri: url,
headers: {
'content-type': 'application/json',
'accept': 'application/json'
},
rejectUnauthorized: false
};
if (body != null) {
requestArguments.body = body;
}
var bool = false;
if (typeof callback === 'function') {
var data = request[method](requestArguments, function (err, res, body) {
bool = true;
if (err) {
return callback(err);
}
var responseBody = body === '' ? JSON.stringify({}) : body;
if (res.statusCode != 200) {
var errData = body;
try {
errData = JSON.parse(body);
} catch (err) {
return callback(err.message || err);
}
return callback(errData, res);
}
return callback(null, res, JSON.parse(responseBody));
}).auth(this.user, this.password, true);
require('deasync').loopWhile(function () {
return !bool;
});
return data;
} else {
return new Promise((function (resolve, reject) {
return request[method](requestArguments, function (err, res, body) {
if (err) {
return reject(err);
}
var responseBody = body === '' ? JSON.stringify({}) : body;
if (res.statusCode != 200) {
var errData = body;
try {
errData = JSON.parse(body);
} catch (err) {
return callback(err.message || err);
}
return reject({ message: errData, response: res });
}
return resolve({ response: res, body: JSON.parse(responseBody) });
}).auth(this.user, this.password, true);
}).bind(this));
}
};
// ----- Cases -----
TestRail.prototype.getCase = function (id, callback) {
return this.apiGet('get_case/' + id, callback);
};
TestRail.prototype.getCases = function (project_id, filters, callback) {
var uri = 'get_cases/' + project_id;
if (typeof filters == 'function') {
callback = filters;
return this.apiGet(uri, callback);
} else {
return this.apiGet(uri, filters, callback);
}
};
TestRail.prototype.addCase = function (section_id, data, callback) {
return this.apiPost('add_case/' + section_id, JSON.stringify(data), callback);
};
TestRail.prototype.updateCase = function (case_id, data, callback) {
return this.apiPost('update_case/' + case_id, JSON.stringify(data), callback);
};
TestRail.prototype.deleteCase = function (case_id, callback) {
return this.apiPost('delete_case/' + case_id, callback);
};
// ----- Case Fields -----
TestRail.prototype.getCaseFields = function (callback) {
return this.apiGet('get_case_fields', callback);
};
// ----- Case Types -----
TestRail.prototype.getCaseTypes = function (callback) {
return this.apiGet('get_case_types', callback);
};
// ----- Configurations -----
TestRail.prototype.getConfigs = function (project_id, callback) {
return this.apiGet('get_configs/' + project_id, callback);
};
TestRail.prototype.addConfigGroup = function (project_id, data, callback) {
return this.apiPost('add_config_group/' + project_id, JSON.stringify(data), callback);
};
TestRail.prototype.addConfig = function (config_group_id, data, callback) {
return this.apiPost('add_config/' + config_group_id, JSON.stringify(data), callback);
};
TestRail.prototype.updateConfigGroup = function (config_group_id, data, callback) {
return this.apiPost('update_config_group/' + config_group_id, JSON.stringify(data), callback);
};
TestRail.prototype.updateConfig = function (config_id, data, callback) {
return this.apiPost('update_config/' + config_id, JSON.stringify(data), callback);
};
TestRail.prototype.deleteConfigGroup = function (config_group_id, callback) {
return this.apiPost('delete_config_group/' + config_group_id, callback);
};
TestRail.prototype.deleteConfig = function (config_id, callback) {
return this.apiPost('delete_config/' + config_id, callback);
};
// ----- Milestones -----
TestRail.prototype.getMilestone = function (id, callback) {
return this.apiGet('get_milestone/' + id, callback);
};
TestRail.prototype.getMilestones = function (project_id, filters, callback) {
var uri = 'get_milestones/' + project_id;
if (typeof filters == 'function') {
callback = filters;
return this.apiGet(uri, callback);
} else {
return this.apiGet(uri, filters, callback);
}
};
TestRail.prototype.addMilestone = function (project_id, data, callback) {
return this.apiPost('add_milestone/' + project_id, JSON.stringify(data), callback);
};
TestRail.prototype.updateMilestone = function (milestone_id, data, callback) {
return this.apiPost('update_milestone/' + milestone_id, JSON.stringify(data), callback);
};
TestRail.prototype.deleteMilestone = function (milestone_id, callback) {
return this.apiPost('delete_milestone/' + milestone_id, callback);
};
// ----- Plans -----
TestRail.prototype.getPlan = function (id, callback) {
return this.apiGet('get_plan/' + id, callback);
};
TestRail.prototype.getPlans = function (project_id, filters, callback) {
var uri = 'get_plans/' + project_id;
if (typeof filters == 'function') {
callback = filters;
return this.apiGet(uri, callback);
} else {
return this.apiGet(uri, filters, callback);
}
};
TestRail.prototype.addPlan = function (project_id, data, callback) {
return this.apiPost('add_plan/' + project_id, JSON.stringify(data), callback);
};
TestRail.prototype.addPlanEntry = function (plan_id, data, callback) {
return this.apiPost('add_plan_entry/' + plan_id, JSON.stringify(data), callback);
};
TestRail.prototype.updatePlan = function (plan_id, data, callback) {
return this.apiPost('update_plan/' + plan_id, JSON.stringify(data), callback);
};
TestRail.prototype.updatePlanEntry = function (plan_id, entry_id, data, callback) {
return this.apiPost('update_plan_entry/' + plan_id + '/' + entry_id, JSON.stringify(data), callback);
};
TestRail.prototype.closePlan = function (plan_id, callback) {
return this.apiPost('close_plan/' + plan_id, callback);
};
TestRail.prototype.deletePlan = function (plan_id, callback) {
return this.apiPost('delete_plan/' + plan_id, callback);
};
TestRail.prototype.deletePlanEntry = function (plan_id, entry_id, callback) {
return this.apiPost('delete_plan_entry/' + plan_id + '/' + entry_id, callback);
};
// ----- Priorities -----
TestRail.prototype.getPriorities = function (callback) {
return this.apiGet('get_priorities', callback);
};
// ----- Projects -----
TestRail.prototype.getProject = function (id, callback) {
return this.apiGet('get_project/' + id, callback);
};
TestRail.prototype.getProjects = function (filters, callback) {
var uri = 'get_projects';
if (typeof filters == 'function') {
callback = filters;
return this.apiGet(uri, callback);
} else {
return this.apiGet(uri, filters, callback);
}
};
TestRail.prototype.addProject = function (data, callback) {
return this.apiPost('add_project', JSON.stringify(data), callback);
};
TestRail.prototype.updateProject = function (project_id, data, callback) {
return this.apiPost('update_project/' + project_id, JSON.stringify(data), callback);
};
TestRail.prototype.deleteProject = function (project_id, callback) {
return this.apiPost('delete_project/' + project_id, callback);
};
// ----- Results -----
TestRail.prototype.getResults = function (test_id, filters, callback) {
var uri = 'get_results/' + test_id;
if (typeof filters == 'function') {
callback = filters;
return this.apiGet(uri, callback);
} else {
return this.apiGet(uri, filters, callback);
}
};
TestRail.prototype.getResultsForCase = function (run_id, case_id, filters, callback) {
var uri = 'get_results_for_case/' + run_id + '/' + case_id;
if (typeof filters == 'function') {
callback = filters;
return this.apiGet(uri, callback);
} else {
return this.apiGet(uri, filters, callback);
}
};
TestRail.prototype.getResultsForRun = function (run_id, filters, callback) {
var uri = 'get_results_for_run/' + run_id;
if (typeof filters == 'function') {
callback = filters;
return this.apiGet(uri, callback);
} else {
return this.apiGet(uri, filters, callback);
}
};
TestRail.prototype.addResult = function (test_id, data, callback) {
return this.apiPost('add_result/' + test_id, JSON.stringify(data), callback);
};
TestRail.prototype.addResultForCase = function (run_id, case_id, data, callback) {
return this.apiPost('add_result_for_case/' + run_id + '/' + case_id, JSON.stringify(data), callback);
};
TestRail.prototype.addResults = function (run_id, data, callback) {
return this.apiPost('add_results/' + run_id, JSON.stringify(data), callback);
};
TestRail.prototype.addResultsForCases = function (run_id, data, callback) {
return this.apiPost('add_results_for_cases/' + run_id, JSON.stringify(data), callback);
};
// ----- Result Fields -----
TestRail.prototype.getResultFields = function (callback) {
return this.apiGet('get_result_fields', callback);
};
// ----- Runs -----
TestRail.prototype.getRun = function (id, callback) {
return this.apiGet('get_run/' + id, callback);
};
TestRail.prototype.getRuns = function (project_id, filters, callback) {
var uri = 'get_runs/' + project_id;
if (typeof filters == 'function') {
callback = filters;
return this.apiGet(uri, callback);
} else {
return this.apiGet(uri, filters, callback);
}
};
TestRail.prototype.addRun = function (project_id, data, callback) {
return this.apiPost('add_run/' + project_id, JSON.stringify(data), callback);
};
TestRail.prototype.updateRun = function (run_id, data, callback) {
return this.apiPost('update_run/' + run_id, JSON.stringify(data), callback);
};
TestRail.prototype.closeRun = function (run_id, callback) {
return this.apiPost('close_run/' + run_id, callback);
};
TestRail.prototype.deleteRun = function (run_id, callback) {
return this.apiPost('delete_run/' + run_id, callback);
};
// ----- Sections -----
TestRail.prototype.getSection = function (id, callback) {
return this.apiGet('get_section/' + id, callback);
};
TestRail.prototype.getSections = function (project_id, filters, callback) {
var uri = 'get_sections/' + project_id;
if (typeof filters == 'function') {
callback = filters;
return this.apiGet(uri, callback);
} else {
return this.apiGet(uri, filters, callback);
}
};
TestRail.prototype.addSection = function (project_id, data, callback) {
return this.apiPost('add_section/' + project_id, JSON.stringify(data), callback);
};
TestRail.prototype.updateSection = function (section_id, data, callback) {
return this.apiPost('update_section/' + section_id, JSON.stringify(data), callback);
};
TestRail.prototype.deleteSection = function (section_id, callback) {
return this.apiPost('delete_section/' + section_id, callback);
};
// ----- Statuses -----
TestRail.prototype.getStatuses = function (callback) {
return this.apiGet('get_statuses', callback);
};
// ----- Suites -----
TestRail.prototype.getSuite = function (id, callback) {
return this.apiGet('get_suite/' + id, callback);
};
TestRail.prototype.getSuites = function (project_id, callback) {
return this.apiGet('get_suites/' + project_id, callback);
};
TestRail.prototype.addSuite = function (project_id, data, callback) {
return this.apiPost('add_suite/' + project_id, JSON.stringify(data), callback);
};
TestRail.prototype.updateSuite = function (suite_id, data, callback) {
return this.apiPost('update_suite/' + suite_id, JSON.stringify(data), callback);
};
TestRail.prototype.deleteSuite = function (suite_id, callback) {
return this.apiPost('delete_suite/' + suite_id, callback);
};
// ----- Templates -----
TestRail.prototype.getTemplates = function (project_id, callback) {
return this.apiGet('get_templates/' + project_id, callback);
};
// ----- Tests -----
TestRail.prototype.getTest = function (id, callback) {
return this.apiGet('get_test/' + id, callback);
};
TestRail.prototype.getTests = function (run_id, filters, callback) {
var uri = 'get_tests/' + run_id;
if (typeof filters == 'function') {
callback = filters;
return this.apiGet(uri, callback);
} else return this.apiGet(uri, filters, callback);
};
// ----- Users -----
TestRail.prototype.getUser = function (id, callback) {
return this.apiGet('get_user/' + id, callback);
};
TestRail.prototype.getUserByEmail = function (email, callback) {
return this.apiGet('get_user_by_email', { email: email }, callback);
};
TestRail.prototype.getUsers = function (callback) {
return this.apiGet('get_users', callback);
};
/* #endregion */
exports['default'] = function () {
return {
noColors: false,
startTime: null,
afterErrList: false,
currentFixtureName: null,
testCount: 0,
skipped: 0,
output: '',
testResult: [],
agents: '',
passed: '',
failed: '',
testStartTime: '',
testEndTime: '',
totalTaskTime: '',
errorTestData: [],
creationDate: '',
PlanName: '',
PlanID: 0,
SuiteID: 0,
SuiteName: '',
EnableTestrail: false,
ProjectID: 0,
ProjectName: '',
RunName: '',
TestrailUser: null,
TestrailPass: null,
TestrailHost: null,
ConfigID: [],
OpenBugData: [],
PassCount: 0,
FailCount: 0,
SkipCount: 0,
OpenCount: 0,
FailureTestCases: [],
KnownFailureCount: 0,
ListKnownFailureTestcases: '',
KnownTestFailureTestCases: [],
OpenBugFailureTestCases: [],
// for XML
report_XML: '',
startTime_XML: null,
uaList_XML: null,
currentFixtureName_XML: null,
testCount_XML: 0,
skipped_XML: 0,
reportTaskStart: function reportTaskStart(startTime, userAgents, testCount) {
return regeneratorRuntime.async(function reportTaskStart$(context$2$0) {
while (1) switch (context$2$0.prev = context$2$0.next) {
case 0:
context$2$0.prev = 0;
this.startTime = new Date(); // set first test start time
this.testCount = testCount;
// for xml report
this.startTime_XML = startTime;
this.uaList_XML = userAgents.join(', ');
this.testCount_XML = testCount;
// end xml report
this.setIndent(2).useWordWrap(true).write('--------------------------------------------------------------------').newline().write('| Running tests in:').write(this.chalk.blue(userAgents)).write('|').newline().write('--------------------------------------------------------------------').newline();
this.agents = userAgents;
this.testStartTime = new Date();
this.ProjectName = process.env.PROJECT_NAME;
this.EnableTestrail = process.env.TESTRAIL_ENABLE == 'true';
this.TestrailHost = process.env.TESTRAIL_HOST;
this.TestrailPass = process.env.TESTRAIL_PASS;
this.TestrailUser = process.env.TESTRAIL_USER;
this.SuiteName = process.env.SUITE_NAME || null;
this.RunName = process.env.RUN_NAME;
this.IsAdvancedReporter = String(process.env.BUG_REPORT_ENABLE || 'false').toUpperCase() == 'TRUE' || false;
this.BugURL = process.env.APPLICATION_BUGS_URL || null;
this.KnownFailureURL = process.env.KNOWN_FAILURES_FILE_PATH || null;
if (this.EnableTestrail) {
if (!this.ProjectName || !this.TestrailHost || !this.TestrailPass || !this.TestrailUser) {
this.newline().write(this.chalk.red.bold('Error: TESTRAIL_HOST, TESTRAIL_USER, TESTRAIL_PASS and PROJECT_NAME must be set as environment variables for the reporter plugin to push the result to the Testrail'));
process.exit(1);
}
}
this.PlanName = process.env.PLAN_NAME || 'TestAutomation_1';
if (!(this.IsAdvancedReporter && this.BugURL !== null)) {
context$2$0.next = 31;
break;
}
context$2$0.next = 24;
return regeneratorRuntime.awrap(this.fetchListofBug());
case 24:
this.OpenBugData = context$2$0.sent;
if (!(this.KnownFailureURL !== null)) {
context$2$0.next = 29;
break;
}
context$2$0.next = 28;
return regeneratorRuntime.awrap(this.fetchListofScriptFailureTestcases());
case 28:
this.ListKnownFailureTestcases = context$2$0.sent;
case 29:
context$2$0.next = 32;
break;
case 31:
if (this.BugURL === null && this.IsAdvancedReporter) {
console.log('WARNING!!!! Please set APPLICATION_BUGS_URL as environment variable to generate bug report');
this.IsAdvancedReporter = false;
}
case 32:
context$2$0.next = 37;
break;
case 34:
context$2$0.prev = 34;
context$2$0.t0 = context$2$0['catch'](0);
console.log(context$2$0.t0);
case 37:
case 'end':
return context$2$0.stop();
}
}, null, this, [[0, 34]]);
},
reportFixtureStart: function reportFixtureStart(name) {
this.currentFixtureName = name;
//for xml report
this.currentFixtureName_XML = this.escapeHtml(name);
},
reportTestDone: function reportTestDone(name, testRunInfo) {
var _this = this;
this.testEndTime = new Date(); // set test end time
var hasErr = testRunInfo.errs.length;
var testOutput = {};
this.testStartTime = new Date(); // set net test start time
var testStatus = '';
var namef = this.currentFixtureName + ' - ' + name;
/* #region evaluting Test status */
if (testRunInfo.skipped) testStatus = 'Skipped';else if (hasErr === 0) testStatus = 'Passed';else if (this.IsAdvancedReporter) {
// if test get fail we check if there is Open bug for that
if (String(name).includes('PREAPPS')) {
var BlockLength = name.split('\|').length;
var AssociateBug = String(name.split('\|')[BlockLength - 1]).trim();
if (typeof this.OpenBugData[AssociateBug] != 'undefined' && this.OpenBugData[AssociateBug] !== 'CLOSED') testStatus = 'Application Bug';else testStatus = 'Failed';
} else {
testStatus = 'Failed';
}
if (testStatus === 'Failed' && this.KnownFailureURL !== null && this.ListKnownFailureTestcases.includes(String(namef).toUpperCase())) {
testStatus = 'Known Failure';
}
} else {
testStatus = 'Failed';
}
/* #endregion */
/* #region Console output */
var result = null;
if (testStatus === 'Passed') {
result = this.chalk.green(testStatus);
this.PassCount += 1;
this.reportTestDone_XML(name, testRunInfo, false);
} else if (testStatus === 'Skipped') {
result = this.chalk.gray(testStatus);
this.SkipCount += 1;
this.reportTestDone_XML(name, testRunInfo, false);
} else if (testStatus === 'Failed') {
result = this.chalk.red(testStatus);
this.FailureTestCases.push(result + ' > ' + namef);
this.FailCount += 1;
this.reportTestDone_XML(name, testRunInfo);
} else if (testStatus === 'Known Failure') {
result = this.chalk.bold.cyan(testStatus);
this.KnownTestFailureTestCases.push(result + ' > ' + namef);
this.KnownFailureCount += 1;
this.reportTestDone_XML(name, testRunInfo, false);
} else {
result = this.chalk.magenta(testStatus);
this.OpenBugFailureTestCases.push(result + ' > ' + namef);
this.OpenCount += 1;
this.reportTestDone_XML(name, testRunInfo, false);
}
var title = result + ' > ' + namef;
this.write(title).newline();
/* #endregion */
testOutput[0] = this.currentFixtureName;
testOutput[1] = name;
testOutput[2] = testStatus;
testOutput[3] = this.moment.duration(testRunInfo.durationMs).format('h[h] mm[m] ss[s]');
var error = {};
if (testRunInfo.skipped) this.skipped++;
if (hasErr > 0) {
error[0] = this.currentFixtureName;
error[1] = name;
error[2] = '';
testOutput[4] = '';
this._renderErrors(testRunInfo.errs);
testRunInfo.errs.forEach(function (err, idx) {
error[2] += _this.formatError(err, idx + 1 + ') ').replace(/(?:\r\n|\r|\n)/g, '<br />').replace(/[\u001b\u009b][[()#;?]*(?:[0-9]{1,4}(?:;[0-9]{0,4})*)?[0-9A-ORZcf-nqry=><]/g, '');
testOutput[4] += _this.formatError(err, idx + 1 + ') ').replace(/[\u001b\u009b][[()#;?]*(?:[0-9]{1,4}(?:;[0-9]{0,4})*)?[0-9A-ORZcf-nqry=><]/g, '');
});
this.errorTestData.push(error);
}
this.testResult.push(testOutput);
},
reportTaskDone: function reportTaskDone(endTime, passed, warnings) {
var durationMs = endTime - this.startTime;
var durationStr = this.moment.duration(durationMs).format('h[h] mm[m] ss[s]');
this.totalTaskTime = durationStr;
var footer = '';
if (!this.IsAdvancedReporter) {
footer = passed === this.testCount ? this.testCount + ' Passed' : this.testCount - passed + '/' + this.testCount + ' Failed';
footer += ' (Duration: ' + durationStr + ')';
}
if (this.IsAdvancedReporter) {
if (this.OpenBugFailureTestCases.length > 0) {
footer += '\n--------------- Open Application Bug Failed Tests --------------\n';
this.OpenBugFailureTestCases.forEach(function (test) {
footer += test + '\n';
});
footer += '----------------------------------------------------------------\n';
}
if (this.KnownTestFailureTestCases.length > 0) {
footer += '\n---------------------- Known Test Failures ---------------------\n';
this.KnownTestFailureTestCases.forEach(function (test) {
footer += test + '\n';
});
footer += '----------------------------------------------------------------\n';
}
if (this.FailureTestCases.length > 0) {
footer += '\n------------------------- Failed Tests -------------------------\n';
this.FailureTestCases.forEach(function (test) {
footer += test + '\n';
});
footer += '----------------------------------------------------------------\n';
}
footer += '\n----------------------------------------------------------------\nTotal Tests: ' + this.testCount + '\nTotal Passed: ' + this.PassCount + '\nTotal Failed: ' + this.FailCount + '\nTotal Skipped: ' + this.SkipCount + '\n\nTotal Failed due to Known Test Failures: ' + this.KnownFailureCount + '\nTotal Failed due to Open Application Bugs: ' + this.OpenCount + '\n(Duration: ' + durationStr + ')\n----------------------------------------------------------------\n ';
} else if (this.skipped > 0) {
this.write(this.chalk.gray(this.skipped + ' Skipped')).newline();
}
this.passed = passed;
this.failed = this.testCount - passed;
this.write(footer).newline();
var d = new Date();
this.creationDate = d.getDate() + '_' + (d.getMonth() + 1) + '_' + d.getFullYear() + '_' + d.getHours() + '_' + d.getMinutes() + '_' + d.getSeconds();
var reportName = 'Report_' + this.creationDate;
this.generateReport(reportName);
if (this.IsAdvancedReporter) {
this.reportTaskDone_XML(endTime, passed, warnings, reportName, this.FailureTestCases.length);
}
if (this.EnableTestrail) {
this.publishResultToTestrail();
}
},
_renderErrors: function _renderErrors(errs) {
var _this2 = this;
this.setIndent(3).newline();
errs.forEach(function (err, idx) {
var prefix = _this2.chalk.red(idx + 1 + ') ');
_this2.newline().write(_this2.formatError(err, prefix)).newline().newline();
});
},
fetchListofBug: function fetchListofBug() {
var _this3 = this;
try {
var _fetch = require('node-fetch');
return _fetch(this.BugURL).then(function (resp) {
return resp.text();
}).then(function callee$2$0(body) {
var arr, bugList, bug;
return regeneratorRuntime.async(function callee$2$0$(context$3$0) {
while (1) switch (context$3$0.prev = context$3$0.next) {
case 0:
arr = {};
arr = body.split('\n');
bugList = {};
bug = undefined;
arr.forEach(function (element) {
if (String(element).includes('PREAPPS')) {
bug = element.replace(/\s/g, ' ').split(' ');
bugList[bug[0]] = String(bug[1]).toUpperCase(); // bugList[4102] = 'CLOSED';
}
});
return context$3$0.abrupt('return', bugList);
case 6:
case 'end':
return context$3$0.stop();
}
}, null, _this3);
})['catch'](function (ex) {
console.error('Error while fetching bug details', ex);
});
} catch (error) {
console.log(error);
}
},
fetchListofScriptFailureTestcases: function fetchListofScriptFailureTestcases() {
return regeneratorRuntime.async(function fetchListofScriptFailureTestcases$(context$2$0) {
var _this4 = this;
while (1) switch (context$2$0.prev = context$2$0.next) {
case 0:
context$2$0.prev = 0;
context$2$0.next = 3;
return regeneratorRuntime.awrap(require('fs').readFile(require('path').join(__dirname, '../../../' + this.KnownFailureURL), 'utf8', function (err, data) {
if (err) {
console.log('Error while reading ' + require('path').join(__dirname, '../../../' + _this4.KnownFailureURL));
console.log('Error: ', err);
}
_this4.ListKnownFailureTestcases = String(data.split(/\r|\n/).join(',')).toUpperCase();
return String(data.split(/\r|\n/).join(',')).toUpperCase();
}));
case 3:
return context$2$0.abrupt('return', context$2$0.sent);
case 6:
context$2$0.prev = 6;
context$2$0.t0 = context$2$0['catch'](0);
console.log(context$2$0.t0);
case 9:
case 'end':
return context$2$0.stop();
}
}, null, this, [[0, 6]]);
},
publishResultToTestrail: function publishResultToTestrail() {
var resultsTestcases, caseidList, index, testDesc, caseID, _status, comment, Testresult, api, AgentDetails, rundetails, runId, result;
return regeneratorRuntime.async(function publishResultToTestrail$(context$2$0) {
var _this5 = this;
while (1) switch (context$2$0.prev = context$2$0.next) {
case 0:
resultsTestcases = [];
caseidList = [];
this.newline().write('------------------------------------------------------').newline().write(this.chalk.green('Publishing the result to testrail...'));
context$2$0.t0 = regeneratorRuntime.keys(this.testResult);
case 4:
if ((context$2$0.t1 = context$2$0.t0()).done) {
context$2$0.next = 26;
break;
}
index = context$2$0.t1.value;
testDesc = this.testResult[index][1].split('\|');
caseID = null;
if (!(typeof testDesc[2] === 'undefined')) {
context$2$0.next = 11;
break;
}
// verify that Case_ID of test is present or not
this.newline().write(this.chalk.red.bold(this.symbols.err)).write('Warning: Test: ' + this.testResult[index][1] + ' missing the Testrail ID');
return context$2$0.abrupt('continue', 4);
case 11:
caseID = String(testDesc[2]).toUpperCase().replace('C', ''); // remove the prefix C from CaseID
//to check that caseID is valid ID using isnumber function
if (!isNaN(caseID)) {
context$2$0.next = 15;
break;
}
this.newline().write(this.chalk.red.bold(this.symbols.err)).write('Warning: Test: ' + this.testResult[index][1] + ' contains invalid Test rail Case id');
return context$2$0.abrupt('continue', 4);
case 15:
_status = this.testResult[index][2];
comment = null;
if (_status === 'Skipped') {
_status = 6;
comment = 'Test Skipped';
} else if (_status === 'Passed') {
_status = 1;
comment = 'Test passed';
} else {
_status = 5;
comment = this.testResult[index][4]; // if error found for the Test, It will populated in the comment
}
Testresult = {};
Testresult['case_id'] = caseID.trim();
Testresult['status_id'] = _status;
Testresult['comment'] = comment;
resultsTestcases.push(Testresult);
caseidList.push(caseID.trim());
context$2$0.next = 4;
break;
case 26:
if (!(caseidList.length == 0)) {
context$2$0.next = 29;
break;
}
this.newline().write(this.chalk.red.bold(this.symbols.err)).write('No test case data found to publish');
return context$2$0.abrupt('return');
case 29:
api = new TestRail({
host: this.TestrailHost,
user: this.TestrailUser,
password: this.TestrailPass
});
context$2$0.next = 32;
return regeneratorRuntime.awrap(this.getProject(api));
case 32:
this.ProjectID = context$2$0.sent;
if (!(String(this.ProjectID) === '0')) {
context$2$0.next = 35;
break;
}
return context$2$0.abrupt('return');
case 35:
context$2$0.next = 37;
return regeneratorRuntime.awrap(this.getPlanID(api));
case 37:
this.PlanID = context$2$0.sent;
if (!(String(this.PlanID) === '0')) {
context$2$0.next = 40;
break;
}
return context$2$0.abrupt('return');
case 40:
context$2$0.next = 42;
return regeneratorRuntime.awrap(this.getSuiteID(api));
case 42:
this.SuiteID = context$2$0.sent;
if (!(this.SuiteID === 0)) {
context$2$0.next = 45;
break;
}
return context$2$0.abrupt('return');
case 45:
AgentDetails = this.agents[0].split('/');
rundetails = {
'suite_id': this.SuiteID,
'include_all': false,
'case_ids': caseidList,
'name': this.RunName ? this.RunName + AgentDetails[0] : 'Run_' + this.creationDate + '(' + AgentDetails[0] + '_' + AgentDetails[1] + ')'
};
runId = null;
result = null;
api.addPlanEntry(this.PlanID, rundetails, function (err, run) {
var data = JSON.parse(run.body);
if (err !== 'null') {
runId = data.runs[0].id;
_this5.newline().write('------------------------------------------------------').newline().write(_this5.chalk.green('Run added successfully.')).newline().write(_this5.chalk.blue.bold('Run name ')).write(_this5.chalk.yellow(_this5.RunName ? _this5.RunName + AgentDetails[0] : 'Run_' + _this5.creationDate + '(' + AgentDetails[0] + '_' + AgentDetails[1] + ')'));
result = {
results: resultsTestcases
};
api.addResultsForCases(runId, result, function (err1, results) {
if (err1 === 'null') {
_this5.newline().write(_this5.chalk.blue('---------Error at Add result -----')).newline().write(err1);
} else if (results.length == 0) {
_this5.newline().write(_this5.chalk.red('No Data has been published to Testrail.')).newline().write(err1);
} else {
_this5.newline().write('------------------------------------------------------').newline().write(_this5.chalk.green('Result added to the testrail successfully'));
}
});
} else {
_this5.newline().write(_this5.chalk.blue('-------------Error at AddPlanEntry ----------------')).newline().write(err);
}
});
case 50:
case 'end':
return context$2$0.stop();
}
}, null, this);
},
getProject: function getProject(api) {
var _this6 = this;
return api.getProjects({}).then(function (project) {
var projectID = 0;
if (typeof project !== 'undefined') {
project.body.forEach(function (project) {
if (String(project.name) === String(_this6.ProjectName)) {
_this6.newline().write(_this6.chalk.blue.bold('Project name(id) ')).write(_this6.chalk.yellow(_this6.ProjectName + '(' + project.id + ')'));
projectID = project.id;
}
});
} else {
_this6.newline().write(_this6.chalk.blue('project is undefined')).newline();
projectID = 0;
}
return projectID;
})['catch'](function (err) {
_this6.newline().write(_this6.chalk.blue('-------------Error at Get Projects ----------------')).write(err).newline();
return 0;
});
},
getPlanID: function getPlanID(api) {
var _this7 = this;
return api.getPlans(this.ProjectID).then(function callee$2$0(result) {
var planid, plan, planFound, index;
return regeneratorRuntime.async(function callee$2$0$(context$3$0) {
while (1) switch (context$3$0.prev = context$3$0.next) {
case 0:
planid = result;
plan = result.body;
planFound = false;
context$3$0.t0 = regeneratorRuntime.keys(plan);
case 4:
if ((context$3$0.t1 = context$3$0.t0()).done) {
context$3$0.next = 13;
break;
}
index = context$3$0.t1.value;
if (!(plan[index].name === this.PlanName)) {
context$3$0.next = 11;
break;
}
this.newline().write(this.chalk.blue.bold('Plan name(id) ')).write(this.chalk.yellow(plan[index].name + '(' + plan[index].id + ')'));
planid = plan[index].id;
planFound = true;
return context$3$0.abrupt('break', 13);
case 11:
context$3$0.next = 4;
break;
case 13:
if (!(!planFound || planid === '')) {
context$3$0.next = 17;
break;
}
context$3$0.next = 16;
return regeneratorRuntime.awrap(this.addNewPlan(api));
case 16:
planid = context$3$0.sent;
case 17:
return context$3$0.abrupt('return', planid);
case 18:
case 'end':
return context$3$0.stop();
}
}, null, _this7);
})['catch'](function (error) {
console.log('in error');
_this7.newline().write(_this7.chalk.blue('-------------Error at Get Plans ----------------')).newline();
console.log(error);
return 0;
});
},
addNewPlan: function addNewPlan(api) {
var _this8 = this;
return api.addPlan(this.ProjectID, { name: this.PlanName, desription: 'Added From Automation reporter plugin' }).then(function (plan) {
var splanID = 0;
if (typeof plan.body.id === 'undefined') {
_this8.newline().write(_this8.chalk.red('Plan Id found as undefined'));
splanID = 0;
} else {
_this8.newline().write(_this8.chalk.green('New plan created.')).newline().write(_this8.chalk.blue.bold('Plan name(id) ')).write(_this8.chalk.yellow(plan.body.name + '(' + plan.body.id + ')'));
splanID = plan.body.id;
}
return splanID;
})['catch'](function (error) {
_this8.newline().write(_this8.chalk.blue('-------------Error at Add New Plan ----------------')).newline();
console.log(error);
return 0;
});
},
getSuiteID: function getSuiteID(api) {
var _this9 = this;
return api.getSuites(this.ProjectID).then(function (suites) {
var id = 0;
var suite = suites.body;
var suiteName;
if (suites.length === 0) {
_this9.newline().write(_this9.chalk.red('The project doesnt contain any suite'));
id = 0;
} else {
if (_this9.SuiteName !== null) {
for (var index in suite) {
if (String(suite[index].name).trim().toUpperCase() === String(_this9.SuiteName).trim().toUpperCase()) {
suiteName = suite[index].name;
id = suite[index].id;
break;
}
}
}
_this9.newline().write(_this9.chalk.blue.bold('Suite name(id) ')).write(_this9.chalk.yellow(suiteName + '(' + id + ')'));
}
return id;
})['catch'](function (error) {
_this9.newline().write(_this9.chalk.blue('-------------Error at Get Suites ----------------')).newline();
console.log(error);
return 0;
});
},
generateReport: function generateReport(reportName) {
this.output += '<!DOCTYPE html>\n\t\t\t\t\t\t\t<html>\n <head>\n <title>TestCafe HTML Report</title>\n <script src=\'https://cdnjs.cloudflare.com/ajax/libs/Chart.js/2.7.2/Chart.min.js\'></script>\n <meta name=\'viewport\' content=\'width=device-width, initial-scale=1\'>\n <link rel=\'stylesheet\' href=\'https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css\'>\n <script src=\'https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js\'></script>\n <script>\n var config = { type: \'pie\', data: { datasets: [{ data: [ \'' + this.PassCount + '\',\'' + this.FailCount + '\' ], backgroundColor: [ \'Green\', \'Red\' ] }], labels: [ \'Pass\', \'Failed\' ] }, options: { responsive: true } }; window.onload = function() { var ctx = document.getElementById(\'myChart\').getContext(\'2d\'); window.myPie = new Chart(ctx, config); };\n </script>\n </head>\n <body>\n <div class=\'container-fluid\'>\n <div class="row">\n <div class="col-sm-8">\n <div>\n <canvas id=\'myChart\' height=\'80\' ></canvas>\n </div>\n </div>\n <div class="col-sm-2" style=" padding-top:80px">\n <table class=\'table table-bordered\' >\n <tr>\n <td><b>Passed</b></td>\n <td> ' + this.PassCount + ' </td>\n </tr>\n <tr>\n <td> <b>Failed </b></td>\n <td> ' + this.FailCount + ' </td>\n </tr>\n <tr>\n <td> <b>Skipped </b></td>\n <td> ' + this.SkipCount + ' </td>\n </tr>';
if (this.KnownFailureURL !== null) {
this.output += '<tr>\n <td> <b>Known Tests Failed </b></td>\n <td> ' + this.KnownFailureCount + ' </td>\n </tr>';
}
// If advanced Reporter then shows Open Application bug count
if (this.IsAdvancedReporter) {
this.output += '<tr>\n <td> <b>Application Bug Failed </b></td>\n <td> ' + this.OpenCount + ' </td>\n </tr>';
}
this.output += '<tr class=\'info\'>\n <td> <b>Total </b></td>\n <td> ' + (this.PassCount + this.FailCount + this.skipped + this.OpenCount + this.KnownFailureCount) + ' </td>\n </tr>\n </table>\n </div>\n </div>\n <hr/>\n\n\n <h4>Running tests in: <b>' + this.agents + '</b> <span> Total Time: ' + this.totalTaskTime + '</span></h4>\n <hr/><br/>\n <h3 style=\'font-color:red\'> Test details</h3>\n <hr />';
var InitialTable = ' <table class=\'table table-bordered table-hover\'>\n <thead>\n <tr>\n <th> Fixture Name </th>\n <th> Test Name </th>\n <th> Status </th>\n <th> Time </th>\n </tr> </thead><tbody>';
var FailedList = '<h4> Failed Tests </h4>' + InitialTable;
var PassedList = '<h4> Passed Tests </h4>' + InitialTable;
var OpenBugFailedList = '<h4> Open Application Bug Failed Tests </h4>' + InitialTable;
var SkippedList = '<h4> Skipped Tests </h4>' + InitialTable;
var KnownFailureList = '<h4> Failed due to Known Test Failures </h4>' + InitialTable;
var OldVersion = InitialTable;
for (var index in this.testResult) {
var status = this.testResult[index][2];
var testOutput = '';
if (status === 'Skipped') status = '<td style=\'background-color:gray\' >Skipped</td>';else if (status === 'Passed') status = '<td style=\'background-color:green\' >Passed</td>';else if (status === 'Failed') status = '<td style=\'background-color:red\' >Failed</td>';else if (status === 'Known Failure') status = '<td style=\'background-color:cyan\' >Failed</td>';else status = '<td style=\'background-color:magenta\' >Failed</td>';
testOutput = '<tr>\n <td>' + this.testResult[index][0] + '</td>\n <td>' + this.testResult[index][1] + '</td>\n ' + status + '\n <td style=\'padding-right:0px;border-right:0px;\'>' + this.testResult[index][3] + '</td>\n </tr>';
status = this.testResult[index][2];
if (this.IsAdvancedReporter) {
if (status === 'Skipped') SkippedList += testOutput;else if (status === 'Passed') PassedList += testOutput;else if (status === 'Failed') FailedList += testOutput;else if (status === 'Known Failure') KnownFailureList += testOutput;else OpenBugFailedList += testOutput;
} else {
OldVersion += testOutput;
}
}
var CompleteTable = '</tbody></table><hr />';
OldVersion += CompleteTable;
if (this.IsAdvancedReporter) {
FailedList += CompleteTable;
PassedList += CompleteTable;
OpenBugFailedList += CompleteTable;
KnownFailureList += CompleteTable;
SkippedList += CompleteTable;
if (this.FailCount > 0) {
this.output += FailedList;
}
if (this.PassCount > 0) {
this.output += PassedList;
}
if (this.SkipCount > 0) {
this.output += SkippedList;
}
if (this.KnownFailureCount > 0) {
this.output += KnownFailureList;
}
if (this.OpenCount > 0) {
this.output += OpenBugFailedList;
}
} else {
this.output += OldVersion;
}
if (this.errorTestData.length > 0) {
this.output += '<h3 style=\'font-color:red\'> Error details</h3><br /><table class=\'table table-bordered table-hover\'><thead>\n <tr>\n <th> Fixture Name </th>\n <th> Test Name </th>\n <th> Error </th>\n </tr></thead><tbody>';
}
for (var i in this.errorTestData) {
this.output += '<tr id=\'' + String(this.errorTestData[i][1]).split('\|')[2].trim() + '\'>\n <td>' + this.errorTestData[i][0] + '</td>\n <td>' + this.errorTestData[i][1] + '</td>\n <td>' + this.errorTestData[i][2] + '</td>\n </tr>';
}
this.output += '</tbody></table>\n </body>\n </html>';
var fs = require('fs');
var dir = process.env.HTML_REPORT_PATH || __dirname + '../../../../test-reports';
if (!fs.existsSync(dir)) {
var dirName = '';
var filePathSplit = dir.split('/');
for (var _index = 0; _index < filePathSplit.length; _index++) {
dirName += filePathSplit[_index] + '/';
if (!fs.existsSync(dirName)) fs.mkdirSync(dirName);
}
}
var filename = reportName + '.html'; //`Report_${this.creationDate}.html`;
if (typeof process.env.HTML_REPORT_NAME !== 'undefined') {
filename = process.env.HTML_REPORT_NAME + '.html';
}
var file = dir + '/' + filename;
if (typeof process.env.HTML_REPORT_PATH !== 'undefined') {
file = process.env.HTML_REPORT_PATH + ('/' + filename);
}
var isError = false;
fs.writeFile(file, this.output, function (err) {
if (err) {
isError = true;
return console.log(err);
}
});
if (!isError) {
if (!this.IsAdvancedReporter) {
this.newline().write('----------------------------------------------------------------').newline().write(this.chalk.green('The file was saved at')).write(this.chalk.yellow(file));
} else {
this.write(this.chalk.green('The file was saved at')).write(this.chalk.yellow(file));
}
}
},
/* #region XML report functions*/
_renderErrors_XML: function _renderErrors_XML(errs) {
var _this10 = this;
this.report_XML += this.indentString('<failure>\n', 4);
this.report_XML += this.indentString('<![CDATA[', 4);
errs.forEach(function (err, idx) {
err = _this10.formatError(err, idx + 1 + ') ').replace(/[\u001b\u009b][[()#;?]*(?:[0-9]{1,4}(?:;[0-9]{0,4})*)?[0-9A-ORZcf-nqry=><]/g, '');
_this10.report_XML += '\n';
_this10.report_XML += _this10.indentString(err, 6);
_this10.report_XML += '\n';
});
this.report_XML += this.indentString(']]>\n', 4);
this.report_XML += this.indentString('</failure>\n', 4);
},
reportTestDone_XML: function reportTestDone_XML(name, testRunInfo) {
var isFailed = arguments.length <= 2 || arguments[2] === undefined ? true : arguments[2];
var hasErr = !!testRunInfo.errs.length;
if (testRunInfo.unstable) name += ' (unstable)';
if (testRunInfo.screenshotPath) name += ' (screenshots: ' + testRunInfo.screenshotPath + ')';
name = this.escapeHtml(name);
var openTag = '<testcase classname="" ' + ('name="' + this.currentFixtureName + ' - ' + name + '" time="' + testRunInfo.durationMs / 1000 + '">\n');
this.report_XML += this.indentString(openTag, 2);
if (testRunInfo.skipped) {
this.skipped_XML++;
this.report_XML += this.indentString('<skipped/>\n', 4);
} else if (hasErr) {
if (isFailed) this._renderErrors_XML(testRunInfo.errs);
}
this.report_XML += this.indentString('</testcase>\n', 2);
},
_renderWarnings_XML: function _renderWarnings_XML(warnings) {
var _this11 = this;
this.setIndent(2).write('<system-out>').newline().write('<![CDATA[').newline().setIndent(4).write('Warnings (' + warnings.length + '):').newline();
warnings.forEach(function (msg) {
_this11.setIndent(4).write('--').newline().setIndent(0).write(_this11.indentString(msg, 6)).newline();
});
this.setIndent(2).write(']]>').newline().write('</system-out>').newline();
},
reportTaskDone_XML: function reportTaskDone_XML(endTime, passed, warnings, reportName, actualFailureCount) {
var name = 'TestCafe Tests: ' + this.escapeHtml(this.uaList_XML);
var failures = actualFailureCount;
var time = (endTime - this.startTime_XML) / 1000;
var FullXMLData = '';
FullXMLData += '<?xml version="1.0" encoding="UTF-8" ?>\n <testsuite name="' + name + '" tests="' + this.testCount_XML + '" failures="' + failures + '" skipped="' + this.skipped_XML + '"' + (' errors="' + failures + '" time="' + time + '" timestamp="' + endTime.toUTCString() + '" >\n ' + this.report_XML + '\n </testsuite>');
/* if (warnings.length)
FullXMLData += this._renderWarnings_XML(warnings); */
var fs = require('fs');
var dir = process.env.HTML_REPORT_PATH || __dirname + '../../../../test-reports';
if (!fs.existsSync(dir)) {
var dirName = '';
var filePathSplit = dir.split('/');
for (var index = 0; index < filePathSplit.length; index++) {
dirName += filePathSplit[index] + '/';
if (!fs.existsSync(dirName)) fs.mkdirSync(dirName);
}
}
var filename = reportName + '.xml';
var file = dir + '/' + filename;
/* if (typeof process.env.HTML_REPORT_PATH !== 'undefined') {
file = process.env.HTML_REPORT_PATH + `/${filename}`;
} */
fs.writeFile(file, FullXMLData, function (err) {
if (err) {
this.newline().write(this.chalk.red('Error on saving xml file ' + err));
return console.log(err);
}
});
}
/* #region XML functions*/
};
};
module.exports = exports['default'];
/* const fetch = require('node-fetch');
if(String(this.KnownFailureURL).indexOf('http') === 0 ){
return fetch(this.KnownFailureURL)
.then(resp => resp.text())
.then(body => {
let arr = {};
arr = body.split('\n');
const TestCaseList = [];
arr.forEach(element => TestCaseList.push(element));
return String(TestCaseList.join(',')).toUpperCase();
}).catch(ex => {
console.error('Error while fetching Testcases details', ex);
});
} else { */
//} //else
// split the Test Description
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment