Skip to content

Commit

Permalink
wip: improve source code extraction
Browse files Browse the repository at this point in the history
  • Loading branch information
noomorph committed Jan 17, 2024
1 parent b161164 commit b28f829
Show file tree
Hide file tree
Showing 13 changed files with 77 additions and 92 deletions.
20 changes: 15 additions & 5 deletions index.d.ts
Original file line number Diff line number Diff line change
Expand Up @@ -430,24 +430,34 @@ declare module 'jest-allure2-reporter' {
extends GlobalExtractorContext<T>,
TestFileExtractorContextAugmentation {
filePath: string[];
docblock?: DocblockContext;
testFile: TestResult;
testFileDocblock?: DocblockContext;
testFileMetadata: AllureTestFileMetadata;
}

export interface TestCaseExtractorContext<T = unknown>
extends TestFileExtractorContext<T>,
TestCaseExtractorContextAugmentation {
testCase: TestCaseResult;
testCaseDocblock?: DocblockContext;
testCaseMetadata: AllureTestCaseMetadata;
}

export interface TestStepExtractorContext<T = unknown>
extends TestCaseExtractorContext<T>,
TestStepExtractorContextAugmentation {
testStepDocblock?: DocblockContext;
testStepMetadata: AllureTestStepMetadata;
}

export interface AllureTestItemSourceLocation {
fileName?: string;
lineNumber?: number;
columnNumber?: number;
}

export type AllureTestStepPath = string[];

export interface AllureTestItemMetadata {
/**
* File attachments to be added to the test case, test step or a test file.
Expand All @@ -458,15 +468,15 @@ declare module 'jest-allure2-reporter' {
* @see {steps}
* @example ['steps', '0']
*/
currentStep?: string[];
currentStep?: AllureTestStepPath;
/**
* Source code of the test case, test step or a hook.
*/
code?: string;
sourceCode?: string;
/**
* Position of the code snippet in the test file: [line, column?]
* Location (file, line, column) of the test case, test step or a hook.
*/
position?: [number, number?];
sourceLocation?: AllureTestItemSourceLocation;
/**
* Markdown description of the test case or test file, or plain text description of a test step.
*/
Expand Down
3 changes: 2 additions & 1 deletion package.json
Original file line number Diff line number Diff line change
Expand Up @@ -94,7 +94,7 @@
"eslint-config-prettier": "^9.0.0",
"eslint-plugin-ecmascript-compat": "^3.0.0",
"eslint-plugin-import": "^2.27.5",
"eslint-plugin-jsdoc": "^39.3.2",
"eslint-plugin-jsdoc": "^48.0.2",
"eslint-plugin-node": "^11.1.0",
"eslint-plugin-prefer-arrow": "^1.2.3",
"eslint-plugin-prettier": "^5.0.1",
Expand Down Expand Up @@ -127,6 +127,7 @@
"remark": "^15.0.1",
"remark-rehype": "^11.0.0",
"rimraf": "^4.3.1",
"stacktrace-js": "^2.0.2",
"strip-ansi": "^6.0.0"
},
"peerDependencies": {
Expand Down
2 changes: 1 addition & 1 deletion src/builtin-plugins/docblock.ts
Original file line number Diff line number Diff line change
Expand Up @@ -43,7 +43,7 @@ function createLabel(entry: [string, string | string[]]): Label | Label[] {
export const docblockPlugin: PluginConstructor = () => {
const plugin: Plugin = {
name: 'jest-allure2-reporter/plugins/docblock',
async beforeTestFileContext({ testFile: { testFilePath } }) {
async testFileContext({ testFile: { testFilePath } }) {
try {
const { parseWithComments } = await import('jest-docblock');
const testFileMetadata = state.getTestFileMetadata(testFilePath);
Expand Down
4 changes: 2 additions & 2 deletions src/builtin-plugins/prettier.ts
Original file line number Diff line number Diff line change
Expand Up @@ -21,9 +21,9 @@ export const prettierPlugin: PluginConstructor = (
};
},
async testCaseContext(context) {
const code = context.testCaseMetadata.code;
const code = context.testCaseMetadata.sourceCode;
if (code) {
context.testCaseMetadata.code = await prettier.format(
context.testCaseMetadata.sourceCode = await prettier.format(
code.trim(),
prettierConfig,
);
Expand Down
59 changes: 41 additions & 18 deletions src/environment/listener.ts
Original file line number Diff line number Diff line change
Expand Up @@ -9,6 +9,7 @@ import type {
TestEnvironmentCircusEvent,
TestEnvironmentSetupEvent,
} from 'jest-environment-emit';
import * as StackTrace from 'stacktrace-js';

import * as api from '../api';
import realm from '../realms';
Expand All @@ -31,33 +32,23 @@ const listener: EnvironmentListenerFn = (context) => {
)
.on('add_hook', function ({ event }) {
const code = event.fn.toString();
const hidden = code.includes(
"during setup, this cannot be null (and it's fine to explode if it is)",
);

const metadata = {
code,
} as Record<string, unknown>;

if (hidden) {
delete metadata.code;
metadata.hidden = true;
const MSG =
"during setup, this cannot be null (and it's fine to explode if it is)";
if (code.includes(MSG)) {
realm.runtimeContext.getCurrentMetadata().set('hidden', true);
}

realm.runtimeContext.getCurrentMetadata().assign(metadata);
})
.on('add_test', function ({ event }) {
realm.runtimeContext
.getCurrentMetadata()
.set('code', event.fn.toString());
})
.on('add_hook', addSourceLocation)
.on('add_test', addSourceLocation)
.on('test_start', executableStart)
.on('test_todo', testSkip)
.on('test_skip', testSkip)
.on('test_done', testDone)
.on('hook_start', addSourceCode)
.on('hook_start', executableStart)
.on('hook_failure', executableFailure)
.on('hook_success', executableSuccess)
.on('test_fn_start', addSourceCode)
.on('test_fn_start', executableStart)
.on('test_fn_success', executableSuccess)
.on('test_fn_failure', executableFailure)
Expand All @@ -66,6 +57,38 @@ const listener: EnvironmentListenerFn = (context) => {
});
};

function addSourceLocation({
event,
}: TestEnvironmentCircusEvent<
Circus.Event & { name: 'add_hook' | 'add_test' }
>) {
const metadata = realm.runtimeContext.getCurrentMetadata();
const task = StackTrace.fromError(event.asyncError).then(([frame]) => {
if (frame) {
metadata.set('sourceLocation', {
fileName: frame.fileName,
lineNumber: frame.lineNumber,
columnNumber: frame.columnNumber,
});
}
});

realm.runtimeContext.enqueueTask(task);
}

function addSourceCode({ event }: TestEnvironmentCircusEvent) {
let code = '';
if (event.name === 'hook_start') {
code = event.hook.fn.toString();
}
if (event.name === 'test_fn_start') {
code = event.test.fn.toString();
}
if (code) {
realm.runtimeContext.getCurrentMetadata().set('sourceCode', code);
}
}

// eslint-disable-next-line no-empty-pattern
function executableStart({}: TestEnvironmentCircusEvent) {
const metadata: AllureTestStepMetadata = {
Expand Down
1 change: 0 additions & 1 deletion src/metadata/index.ts
Original file line number Diff line number Diff line change
@@ -1,3 +1,2 @@
export * from './proxies';
export * from './MetadataSquasher';
export * from './StepExtractor';
4 changes: 2 additions & 2 deletions src/metadata/mergers.ts
Original file line number Diff line number Diff line change
Expand Up @@ -35,8 +35,8 @@ function mergeTestItemMetadata(
return {
attachments: mergeArrays(a.attachments, b.attachments),
currentStep: b.currentStep ?? a.currentStep,
code: b.code ?? a.code,
position: b.position ?? a.position,
sourceCode: b.sourceCode ?? a.sourceCode,
sourceLocation: b.sourceLocation ?? a.sourceLocation,
description: mergeArrays(a.description, b.description),
parameters: mergeArrays(a.parameters, b.parameters),
stage: b.stage ?? a.stage,
Expand Down
2 changes: 1 addition & 1 deletion src/metadata/proxies/AllureMetadataProxy.ts
Original file line number Diff line number Diff line change
Expand Up @@ -18,7 +18,7 @@ export class AllureMetadataProxy<T = unknown> {
return this.$metadata.get(fullPath, fallbackValue);
}

set(path: keyof T, value: T[keyof T]): this {
set<K extends keyof T>(path: K, value: T[K]): this {
const fullPath = this.$localPath(path);
this.$metadata.set(fullPath, value);
return this;
Expand Down
50 changes: 0 additions & 50 deletions src/metadata/types.ts

This file was deleted.

4 changes: 2 additions & 2 deletions src/options/default-options/testCase.ts
Original file line number Diff line number Diff line change
Expand Up @@ -30,8 +30,8 @@ export const testCase: ResolvedTestCaseCustomizer = {
fullName: ({ testCase }) => testCase.fullName,
description: ({ testCaseMetadata }) => {
const text = testCaseMetadata.description?.join('\n') ?? '';
const code = testCaseMetadata.code?.length
? '```javascript\n' + testCaseMetadata.code + '\n```'
const code = testCaseMetadata.sourceCode
? '```javascript\n' + testCaseMetadata.sourceCode + '\n```'
: '';
return [text, code].filter(Boolean).join('\n\n');
},
Expand Down
7 changes: 7 additions & 0 deletions src/runtime/AllureRuntimeContext.ts
Original file line number Diff line number Diff line change
Expand Up @@ -57,4 +57,11 @@ export class AllureRuntimeContext {
},
});
}

enqueueTask = (task: Promise<unknown> | (() => Promise<unknown>)): void => {
this.idle =
typeof task === 'function'
? this.idle.then(task)
: this.idle.then(() => task);
};
}
8 changes: 2 additions & 6 deletions src/runtime/modules/AttachmentsModule.ts
Original file line number Diff line number Diff line change
Expand Up @@ -132,9 +132,7 @@ export class FileAttachmentsModule extends AttachmentsModule<
const config = context.getReporterConfig();
return path.join(config.resultsDir, config.attachments.subDir);
},
waitFor: (promise) => {
context.idle = context.idle.then(() => promise);
},
waitFor: context.enqueueTask,
});
}

Expand Down Expand Up @@ -169,9 +167,7 @@ export class ContentAttachmentsModule extends AttachmentsModule<
const config = context.getReporterConfig();
return path.join(config.resultsDir, config.attachments.subDir);
},
waitFor: (promise) => {
context.idle = context.idle.then(() => promise);
},
waitFor: context.enqueueTask,
});
}

Expand Down
5 changes: 2 additions & 3 deletions src/runtime/modules/StepsModule.ts
Original file line number Diff line number Diff line change
Expand Up @@ -28,7 +28,7 @@ export class StepsModule {
}

step<T = unknown>(name: string, function_: () => T): T {
this.#startStep(name, function_);
this.#startStep(name);
const end = this.#stopStep;

let result: T;
Expand Down Expand Up @@ -57,11 +57,10 @@ export class StepsModule {
}
}

#startStep = (name: string, function_: Function) => {
#startStep = (name: string) => {
this.context.metadata.$startStep().assign({
stage: 'scheduled',
start: this.context.now,
code: function_.toString(),
description: [name],
});
};
Expand Down

0 comments on commit b28f829

Please sign in to comment.