Skip to content

Commit

Permalink
Merge pull request #182 from archfz/develop
Browse files Browse the repository at this point in the history
#180: Implement support for mochawesome integration.
  • Loading branch information
archfz authored Apr 2, 2023
2 parents 848f3d6 + 6c7d6db commit 5385c50
Show file tree
Hide file tree
Showing 13 changed files with 649 additions and 47 deletions.
1 change: 1 addition & 0 deletions .gitignore
Original file line number Diff line number Diff line change
Expand Up @@ -7,5 +7,6 @@ test/output/out.txt
test/output/not/existing/path/out.txt
test/output/out.cst
test/output_nested
test/cypress/reports
.idea
.vscode
30 changes: 27 additions & 3 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -7,7 +7,8 @@
[Limitations](#limitations-and-notes)
[Install](#install)
[Options](#options)
[Logging after/before all](#logging-after-all-and-before-all-hooks)
[Integrations](#integrations)
[After/before all](#logging-after-all-and-before-all-hooks)
[Logging to files](#logging-to-files)
[Development](#development)
[Release Notes](#release-notes)
Expand Down Expand Up @@ -38,8 +39,6 @@ Try it out by cloning [cypress-terminal-report-demo](https://github.com/archfz/c
- `console.log` usage was never meant to be used in the cypress test code. Using it will
not log anything with this plugin. Using it also goes against the queue nature of
cypress. Use `cy.log` instead. [See here for more details](https://github.com/archfz/cypress-terminal-report/issues/67).
- Using `cypress-fail-fast` and logging to files does not work out of the box. To enable support use
the [`logToFilesOnAfterRun`](#optionslogtofilesonafterrun) option.

## Install

Expand Down Expand Up @@ -200,6 +199,25 @@ tests are timing out.
// ...
```

## Integrations

### `cypress-fail-fast`

Logging to files does not work out of the box. To enable support use the
[`logToFilesOnAfterRun`](#optionslogtofilesonafterrun) option.

### `cypress-mochawesome-reporter`

The following example demonstrates adding logs to context for all tests (snippet from `e2e.js`):

```js
import 'cypress-mochawesome-reporter/register';
afterEach(() => {
cy.wait(50, {log: false}).then(() => cy.addTestContext(Cypress.TerminalReport.getLogs('txt')))
});
```
## Logging after all and before all hooks
Commands from before all and after all hooks are not logged by default. A new experimental feature introduces
Expand Down Expand Up @@ -332,6 +350,12 @@ directory. You should add `it.only` to the test case you are working on to speed
## Release Notes
#### 5.1.0
- Add global support side `Cypress.TerminalReport.getLogs()`.
- Add example on how to integrate with [`mochawesome`](#cypress-mochawesome-reporter). [issue](https://github.com/archfz/cypress-terminal-report/issues/180)
- Update cypress to 12.9.0 in tests to confirm support.
#### 5.0.2
- Fix existing log message not updating later. [issue](https://github.com/archfz/cypress-terminal-report/issues/173)
Expand Down
21 changes: 17 additions & 4 deletions src/installLogsCollector.d.ts
Original file line number Diff line number Diff line change
@@ -1,6 +1,5 @@
declare function installLogsCollector(config?: installLogsCollector.SupportOptions): void;
declare namespace installLogsCollector {

type Severity = '' | 'error' | 'warning';

type LogType = 'cons:log' |
Expand All @@ -16,6 +15,8 @@ declare namespace installLogsCollector {
'cy:command' |
'ctr:info';

type Log = [/* type: */ LogType, /* message: */ string, /* severity: */ Severity];

interface SupportOptions {
/**
* What types of logs to collect and print.
Expand All @@ -33,7 +34,7 @@ declare namespace installLogsCollector {
filterLog?:
| null
| NonNullable<SupportOptions['collectTypes']>[number]
| ((args: [/* type: */ LogType, /* message: */ string, /* severity: */ Severity]) => boolean);
| ((args: Log) => boolean);

/**
* Callback to process logs manually. The type is from the same list as for the collectTypes option.
Expand All @@ -43,15 +44,15 @@ declare namespace installLogsCollector {
processLog?:
| null
| NonNullable<SupportOptions['collectTypes']>[number]
| ((args: [/* type: */ LogType, /* message: */ string, /* severity: */ Severity]) => [LogType, string, Severity]);
| ((args: Log) => [LogType, string, Severity]);

/**
* Callback to collect each test case's logs after its run.
* @default undefined
*/
collectTestLogs?: (
context: {mochaRunnable: any, testState: string, testTitle: string, testLevel: number},
messages: [/* type: */ LogType, /* message: */ string, /* severity: */ Severity][]
messages: Log[]
) => void;

xhr?: {
Expand Down Expand Up @@ -89,4 +90,16 @@ declare namespace installLogsCollector {
debug?: boolean;
}
}

declare namespace Cypress {
interface TerminalReport {
getLogs<T extends 'txt' | 'json' | 'none' = 'none'>(format?: T): {
txt: string,
json: string,
none: installLogsCollector.Log[],
}[T];
}
const TerminalReport: TerminalReport;
}

export = installLogsCollector;
20 changes: 20 additions & 0 deletions src/installLogsCollector.js
Original file line number Diff line number Diff line change
Expand Up @@ -17,6 +17,8 @@ const LogCollectorState = require("./collector/LogCollectorState");
const LogCollectExtendedControl = require("./collector/LogCollectExtendedControl");
const LogCollectSimpleControl = require("./collector/LogCollectSimpleControl");

const logsTxtFormatter = require("./outputProcessor/logsTxtFormatter");

/**
* Installs the logs collector for cypress.
*
Expand All @@ -39,6 +41,8 @@ function installLogsCollector(config = {}) {
} else {
(new LogCollectSimpleControl(logCollectorState, config)).register();
}

registerGlobalApi(logCollectorState);
}

function registerLogCollectorTypes(logCollectorState, config) {
Expand All @@ -64,6 +68,22 @@ function registerLogCollectorTypes(logCollectorState, config) {
}
}

function registerGlobalApi(logCollectorState) {
Cypress.TerminalReport = {
getLogs: (format) => {
const logs = logCollectorState.getCurrentLogStack();

if (format === 'txt') {
return logsTxtFormatter(logs);
} else if (format === 'json') {
return JSON.stringify(logs, null, 2);
}

return logs;
},
};
}

function validateConfig(config) {
const result = tv4.validateMultiple(config, schema);

Expand Down
21 changes: 2 additions & 19 deletions src/outputProcessor/TextOutputProcessor.js
Original file line number Diff line number Diff line change
@@ -1,8 +1,7 @@
const BaseOutputProcessor = require('./BaseOutputProcessor');
const logsTxtFormatter = require('./logsTxtFormatter');

const CONSTANTS = require('../constants');
const PADDING = ' ';
const PADDING_LOGS = `${PADDING}`.repeat(6);
const {EOL} = require('os');

module.exports = class TextOutputProcessor extends BaseOutputProcessor {
Expand All @@ -12,29 +11,13 @@ module.exports = class TextOutputProcessor extends BaseOutputProcessor {
this.chunkSeparator = EOL + EOL;
}

severityToFont(severity) {
return {
[CONSTANTS.SEVERITY.ERROR]: 'X',
[CONSTANTS.SEVERITY.WARNING]: '!',
[CONSTANTS.SEVERITY.SUCCESS]: 'K',
}[severity];
}

padTypeText(text) {
return Array(Math.max(PADDING_LOGS.length - text.length + 1, 0)).join(' ')
+ text;
}

write(allMessages) {

Object.entries(allMessages).forEach(([spec, tests]) => {
let text = `${spec}:${EOL}`;
Object.entries(tests).forEach(([test, messages]) => {
text += `${PADDING}${test}${EOL}`;
messages.forEach(([type, message, severity]) => {
text += (this.padTypeText(`${type} (${this.severityToFont(severity)}): `) +
message.replace(/\n/g, `${EOL}${PADDING_LOGS}`) + EOL).replace(/\s+\n/, '\n');
});
text += logsTxtFormatter(messages, EOL);
text += EOL;
});

Expand Down
22 changes: 22 additions & 0 deletions src/outputProcessor/logsTxtFormatter.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,22 @@
const CONSTANTS = require("../constants");

const PADDING = ' ';
const PADDING_LOGS = `${PADDING}`.repeat(6);

const padTypeText = (text) => {
return Array(Math.max(PADDING_LOGS.length - text.length + 1, 0)).join(' ')
+ text;
}

function logsTxtFormatter(logs, EOL = '\n') {
return logs.map(([type, message, severity]) => {
return (padTypeText(`${type} (${{
[CONSTANTS.SEVERITY.ERROR]: 'X',
[CONSTANTS.SEVERITY.WARNING]: '!',
[CONSTANTS.SEVERITY.SUCCESS]: 'K',
}[severity]}): `) +
message.replace(/\n/g, `${EOL}${PADDING_LOGS}`) + EOL).replace(/\s+\n/, '\n');
}).join('');
}

module.exports = logsTxtFormatter;
5 changes: 5 additions & 0 deletions test/cypress.config.js
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,7 @@ module.exports = defineConfig({
"baseUrl": "https://example.cypress.io",
"video": false,
"screenshotOnRunFailure": false,
reporter: 'cypress-mochawesome-reporter',
specPattern: 'cypress/integration/**/*.spec.{js,jsx,ts,tsx}',
async setupNodeEvents(on, config) {
let options = {
Expand Down Expand Up @@ -134,6 +135,10 @@ module.exports = defineConfig({
require("cypress-fail-fast/plugin")(on, config);
}

if (config.env.mochawesome == '1') {
require('cypress-mochawesome-reporter/plugin')(on);
}

require('../src/installLogsPrinter')(on, options);

return config;
Expand Down
11 changes: 11 additions & 0 deletions test/cypress/support/e2e.js
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
import './commands';
import registerCypressGrep from "cypress-grep";
import 'cypress-mochawesome-reporter/register';

const env = Cypress.env();
let config = {};
Expand Down Expand Up @@ -91,6 +92,16 @@ if (env.enableContinuousLogging == '1') {
config.enableContinuousLogging = true;
}

if (env.mochawesome == '1') {
afterEach(() => {
cy.wait(50, {log: false}).then(() => {
const logs = Cypress.TerminalReport.getLogs('txt');
cy.addTestContext(logs);
cy.log('Global API logs: ' + logs);
})
});
}

require('../../../src/installLogsCollector')(config);

enableFetchWorkaround();
Expand Down
Loading

0 comments on commit 5385c50

Please sign in to comment.