Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

fix: logging in DEBUG mode #78

Merged
merged 1 commit into from
Apr 29, 2024
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 1 addition & 1 deletion debug.mjs
Original file line number Diff line number Diff line change
@@ -1 +1 @@
export * from './dist/debug.js';
export * from './dist/debug/index.js';
3 changes: 2 additions & 1 deletion package-e2e/test.cjs
Original file line number Diff line number Diff line change
Expand Up @@ -10,9 +10,10 @@ assert(typeof $Assign === 'function', 'jest-metadata should export $Assign funct
assert(typeof $Defaults === 'function', 'jest-metadata should export $Defaults function as a named export');
assert(typeof $Unshift === 'function', 'jest-metadata should export $Unshift function as a named export');

const { events, metadataRegistryEvents } = require('jest-metadata/debug');
const { events, metadataRegistryEvents, visualize } = require('jest-metadata/debug');
assert(typeof events === 'object', 'jest-metadata/debug should export `events` object');
assert(typeof metadataRegistryEvents === 'object', 'jest-metadata/debug should export `metadataRegistryEvents` object');
assert(typeof visualize === 'function', 'jest-metadata/debug should export `visualize` function as a named export');

const environmentListener = require('jest-metadata/environment-listener');
assert(typeof environmentListener === 'function', 'jest-metadata/environment-listener should export a class as its default export');
Expand Down
3 changes: 2 additions & 1 deletion package-e2e/test.mjs
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
import assert from 'assert';
import { $Set, $Push, $Merge, $Assign, $Defaults, $Unshift, state, metadata } from 'jest-metadata';
import { events, metadataRegistryEvents } from 'jest-metadata/debug';
import { events, metadataRegistryEvents, visualize } from 'jest-metadata/debug';
import JsdomTestEnvironment from 'jest-metadata/environment-jsdom';
import NodeTestEnvironment from 'jest-metadata/environment-node';
import environmentListener from 'jest-metadata/environment-listener';
Expand All @@ -17,6 +17,7 @@ assert(typeof $Unshift === 'function', 'jest-metadata should export `$Unshift` f

assert(typeof events === 'object', 'jest-metadata/debug should export `events` object');
assert(typeof metadataRegistryEvents === 'object', 'jest-metadata/debug should export `metadataRegistryEvents` object');
assert(typeof visualize === 'function', 'jest-metadata/debug should export `visualize` function as a named export');

assert(typeof environmentListener === 'function', 'jest-metadata/environment-listener should export a function as its default export');

Expand Down
7 changes: 6 additions & 1 deletion package-e2e/test.ts
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
import { $Set, $Push, $Merge, $Assign, $Defaults, $Unshift, state, metadata } from 'jest-metadata';
import { events, metadataRegistryEvents } from 'jest-metadata/debug';
import { events, metadataRegistryEvents, visualize } from 'jest-metadata/debug';
import type { GlobalMetadata, Metadata } from 'jest-metadata';
import JestMetadataReporter, { query, JestMetadataReporter as JestMetadataReporterNamed } from 'jest-metadata/reporter';
import JsdomTestEnvironment from 'jest-metadata/environment-jsdom';
Expand Down Expand Up @@ -74,3 +74,8 @@ assertType<Function>(JsdomTestEnvironment);
assertType<Function>(NodeTestEnvironment);

assertType<Function>(environmentListener);

assertType<Function>(() => {
assertType<Promise<string>>(visualize('/path/to/bunyamin.log'));
assertType<Promise<string>>(visualize([{ type: 'setup', testFilePath: 'test.ts' }]));
});
6 changes: 2 additions & 4 deletions package.json
Original file line number Diff line number Diff line change
Expand Up @@ -93,6 +93,7 @@
"funpermaproxy": "^1.1.0",
"jest-environment-emit": "^1.0.6",
"lodash.merge": "^4.6.2",
"lodash.snakecase": "^4.1.1",
"node-ipc": "9.2.1",
"strip-ansi": "^6.0.0",
"tslib": "^2.5.3"
Expand Down Expand Up @@ -135,11 +136,8 @@
"@types/bunyan": "^1.8.8",
"@types/jest": "^29.2.5",
"@types/lodash": "^4.14.191",
"@types/lodash.get": "^4.4.7",
"@types/lodash.memoize": "^4.1.7",
"@types/lodash.merge": "^4.6.7",
"@types/lodash.once": "^4.1.7",
"@types/lodash.set": "^4.3.7",
"@types/lodash.snakecase": "^4.1.9",
"@types/node": "^18.11.18",
"@types/node-ipc": "^9.2.0",
"@types/rimraf": "^3.0.2",
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -9,7 +9,7 @@ import type {
TestEntryMetadata,
TestFnInvocationMetadata,
TestInvocationMetadata,
} from '../index';
} from '../metadata';

export abstract class MetadataVisitor {
constructor(protected readonly checker: MetadataChecker) {}
Expand Down
6 changes: 4 additions & 2 deletions src/debug.ts → src/debug/index.ts
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
import { ParentProcessRealm, realm } from './realms';
import { ParentProcessRealm, realm } from '../realms';

export { Shallow } from './jest-reporter';
export { Shallow } from '../jest-reporter';

export function isFallback() {
return realm.type === 'parent_process'
Expand All @@ -11,3 +11,5 @@ export function isFallback() {
export const events = realm.events;

export const metadataRegistryEvents = realm.metadataRegistry.events;

export * from './visualize';
Original file line number Diff line number Diff line change
@@ -1,6 +1,4 @@
import { isEmpty, omitBy } from 'lodash';

import type { Metadata } from '../../index';
import type { Metadata } from '../../metadata';
import { PlantObject } from './PlantObject';

const COLORS: Record<string, string> = {
Expand All @@ -21,13 +19,25 @@ export class MetadataPlantObject extends PlantObject {
id: metadata.id,
name,
color: COLORS[name],
properties: omitBy(
{
id: metadata.id.split(':').pop(),
data: metadata.get(),
},
isEmpty,
),
properties: getProperties(metadata),
});
}
}

function getProperties(metadata: Metadata): Record<string, unknown> {
const [fileId, childId] = metadata.id.split(':');
const result: Record<string, unknown> = {
id: childId || fileId,
data: metadata.get(),
};

if (!result.id) {
delete result.id;
}

if (!result.data || Object.keys(result.data).length === 0) {
delete result.data;
}

return result;
}
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
import { snakeCase } from 'lodash';
import snakeCase from 'lodash.snakecase';

export class PlantLink {
constructor(
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -8,7 +8,7 @@ import type {
TestEntryMetadata,
TestFnInvocationMetadata,
TestInvocationMetadata,
} from '../../index';
} from '../../metadata';
import { MetadataVisitor } from '../MetadataVisitor';
import { MetadataPlantObject } from './MetadataPlantObject';
import { PlantLink } from './PlantLink';
Expand Down
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
import { snakeCase } from 'lodash';
import snakeCase from 'lodash.snakecase';

export type PlantObjectConfig = {
id: string;
Expand Down
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
import type { GlobalMetadataRegistry, MetadataChecker } from '../../index';
import type { GlobalMetadataRegistry, MetadataChecker } from '../../metadata';
import { PlantMetadataVisitor } from './PlantMetadataVisitor';

export const PlantSerializer = {
Expand Down
File renamed without changes.
50 changes: 50 additions & 0 deletions src/debug/visualize.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,50 @@
import fs from 'node:fs/promises';
import {
GlobalMetadataRegistry,
type MetadataEvent,
MetadataEventHandler,
MetadataFactoryImpl,
type WriteMetadataEventEmitter,
} from '../metadata';
import { SerialEmitter } from '../utils';
import { PlantSerializer } from './plant';

export async function visualize(traceJsonFile: string | MetadataEvent[]) {
const events: MetadataEvent[] = Array.isArray(traceJsonFile)
? traceJsonFile
: await readEvents(traceJsonFile);

return replayEvents(events);
}

async function readEvents(traceJsonFile: string): Promise<MetadataEvent[]> {
const raw = await fs.readFile(traceJsonFile, 'utf8');
const json = JSON.parse(raw) as any[];
const mainPID = json[0].pid;
const events: MetadataEvent[] = [];
for (const event of json) {
const { cat, pid, args } = event;
if (pid === mainPID && args?.event?.type && cat?.includes('emitter-events')) {
events.push(args.event as MetadataEvent);
}
}

return events;
}

function replayEvents(events: MetadataEvent[]) {
const emitter: WriteMetadataEventEmitter = new SerialEmitter('set');
const metadataRegistry = new GlobalMetadataRegistry();
const metadataFactory = new MetadataFactoryImpl(metadataRegistry, emitter);
const globalMetadata = metadataFactory.createGlobalMetadata();
const eventHandler = new MetadataEventHandler({
globalMetadata,
metadataRegistry,
});

for (const event of events) {
eventHandler.handle(event);
}

return PlantSerializer.serialize(metadataFactory.checker, metadataRegistry);
}
2 changes: 1 addition & 1 deletion src/environment-listener.ts
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,7 @@ import { detectDuplicateRealms, injectRealmIntoSandbox, realm } from './realms';
import { jestUtils, logger } from './utils';

const listener: EnvironmentListenerFn = (context) => {
const log = logger.child({ cat: 'environment', tid: 'environment' });
const log = logger.child({ cat: 'jest-metadata-environment', tid: 'jest-metadata' });
const jestEnvironment = context.env;
const jestEnvironmentConfig = context.config;
const environmentContext = context.context;
Expand Down
4 changes: 2 additions & 2 deletions src/ipc/IPCClient.ts
Original file line number Diff line number Diff line change
Expand Up @@ -4,11 +4,11 @@ import stripAnsi from 'strip-ansi';
import { JestMetadataError } from '../errors';
import type { GlobalMetadata, MetadataEvent } from '../metadata';
import { internal } from '../metadata';
import { logger, optimizeTracing } from '../utils';
import { diagnostics, optimizeTracing } from '../utils';
import type { BatchMessage } from './BatchMessage';
import { sendAsyncMessage } from './sendAsyncMessage';

const log = logger.child({ cat: 'ipc', tid: 'ipc-client' });
const log = diagnostics.child({ cat: ['ipc', 'ipc-client'], tid: 'jest-metadata-ipc' });

type IPC = Omit<typeof node_ipc, 'IPC'>;
type IPCConnection = (typeof node_ipc)['of'][string];
Expand Down
7 changes: 5 additions & 2 deletions src/ipc/IPCServer.ts
Original file line number Diff line number Diff line change
Expand Up @@ -4,10 +4,13 @@ import node_ipc from 'node-ipc';
import stripAnsi from 'strip-ansi';

import type { Metadata, MetadataEventEmitter } from '../metadata';
import { Deferred, logger, makeDeferred, optimizeTracing } from '../utils';
import { Deferred, diagnostics, makeDeferred, optimizeTracing } from '../utils';
import type { BatchMessage } from './BatchMessage';

const log = logger.child({ cat: 'ipc', tid: 'ipc-server' });
const log = diagnostics.child({
cat: ['ipc', 'ipc-server'],
tid: 'jest-metadata-ipc',
});

type IPC = Omit<typeof node_ipc, 'IPC'>;

Expand Down
17 changes: 13 additions & 4 deletions src/jest-reporter/ReporterServer.ts
Original file line number Diff line number Diff line change
@@ -1,38 +1,47 @@
import path from 'node:path';

/* eslint-disable @typescript-eslint/no-empty-function,unicorn/no-for-loop */
import type { TestCaseResult, TestResult } from '@jest/reporters';
// eslint-disable-next-line import/no-internal-modules
import { aggregateLogs } from 'jest-environment-emit/debug';
import type { IPCServer } from '../ipc';
import { logger, memoizeArg1, memoizeLast, optimizeTracing } from '../utils';
import { diagnostics, memoizeArg1, memoizeLast, optimizeTracing } from '../utils';
import type { AssociateMetadata } from './AssociateMetadata';
import type { FallbackAPI } from './FallbackAPI';

export type ReporterServerConfig = {
ipc: IPCServer;
fallbackAPI: FallbackAPI;
associate: AssociateMetadata;
rootDir: string;
};

const __REPORTER = optimizeTracing((testFilePath: string, data?: unknown) => {
return {
tid: ['reporter', testFilePath],
tid: ['jest-metadata-reporter', testFilePath],
data,
};
});

const __FILE = optimizeTracing((cwd: string, testFilePath: string) => {
return path.relative(cwd, testFilePath);
});

/**
* @implements {import('@jest/reporters').Reporter}
*/
export class ReporterServer {
#log = logger.child({ cat: 'reporter', tid: 'reporter' });
#log = diagnostics.child({ cat: 'reporter', tid: 'jest-metadata-reporter' });
#associate: AssociateMetadata;
#fallbackAPI: FallbackAPI;
#ipc: IPCServer;
#rootDir: string;

constructor(config: ReporterServerConfig) {
this.#associate = config.associate;
this.#fallbackAPI = config.fallbackAPI;
this.#ipc = config.ipc;
this.#rootDir = config.rootDir;

// We are memoizing all methods because there might be
// multiple reporters based on jest-metadata, so we need to
Expand Down Expand Up @@ -67,7 +76,7 @@ export class ReporterServer {
}

onTestFileStart(testPath: string): void {
this.#log.debug.begin(__REPORTER(testPath), testPath);
this.#log.debug.begin(__REPORTER(testPath), __FILE(this.#rootDir, testPath));
const testFileMetadata = this.#fallbackAPI.reportTestFile(testPath);
this.#associate.filePath(testPath, testFileMetadata);
}
Expand Down
1 change: 1 addition & 0 deletions src/jest-reporter/__tests__/fallback-api.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -40,6 +40,7 @@ describe('Fallback API', () => {
const fallbackAPI = new FallbackAPI(globalMetadata, emitter);
server = new ReporterServer({
associate,
rootDir: process.cwd(),
fallbackAPI,
ipc,
});
Expand Down
Loading
Loading