Skip to content

Commit

Permalink
test: migrate logger tests to vitest (#6220)
Browse files Browse the repository at this point in the history
* Migrate logger tests to vitest

* Remove lint comment
  • Loading branch information
nazarhussain authored Dec 26, 2023
1 parent 21851b2 commit 1200c59
Show file tree
Hide file tree
Showing 20 changed files with 137 additions and 129 deletions.
5 changes: 0 additions & 5 deletions packages/logger/.mocharc.yml

This file was deleted.

9 changes: 0 additions & 9 deletions packages/logger/karma.config.cjs

This file was deleted.

10 changes: 7 additions & 3 deletions packages/logger/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -56,9 +56,12 @@
"lint": "eslint --color --ext .ts src/ test/",
"lint:fix": "yarn run lint --fix",
"pretest": "yarn run check-types",
"test:unit": "mocha 'test/unit/**/*.test.ts'",
"test:browsers": "yarn karma start karma.config.cjs",
"test:e2e": "LODESTAR_PRESET=minimal mocha 'test/e2e/**/*.test.ts'",
"test:unit": "vitest --run --dir test/unit/ --coverage",
"test:browsers": "yarn test:browsers:chrome && yarn test:browsers:firefox && yarn test:browsers:electron",
"test:browsers:chrome": "vitest --run --browser chrome --config ./vitest.browser.config.ts --dir test/unit",
"test:browsers:firefox": "vitest --run --browser firefox --config ./vitest.browser.config.ts --dir test/unit",
"test:browsers:electron": "echo 'Electron tests will be introduced back in the future as soon vitest supports electron.'",
"test:e2e": "LODESTAR_PRESET=minimal vitest --run --dir test/e2e",
"check-readme": "typescript-docs-verifier"
},
"types": "lib/index.d.ts",
Expand All @@ -69,6 +72,7 @@
"winston-transport": "^4.5.0"
},
"devDependencies": {
"@chainsafe/threads": "^1.11.1",
"@lodestar/test-utils": "^1.13.0",
"@types/triple-beam": "^1.3.2",
"rimraf": "^4.4.1",
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,7 @@ import worker from "node:worker_threads";
import {expose} from "@chainsafe/threads/worker";

const parentPort = worker.parentPort;
const workerData = worker.workerData as {logFilepath: string};
const workerData = worker.workerData;
if (!parentPort) throw Error("parentPort must be defined");

const file = fs.createWriteStream(workerData.logFilepath, {flags: "a"});
Expand Down
4 changes: 3 additions & 1 deletion packages/logger/test/e2e/logger/workerLoggerHandler.ts
Original file line number Diff line number Diff line change
Expand Up @@ -9,7 +9,9 @@ export type LoggerWorker = {
type WorkerData = {logFilepath: string};

export async function getLoggerWorker(opts: WorkerData): Promise<LoggerWorker> {
const workerThreadjs = new Worker("./workerLogger.js", {workerData: opts});
const workerThreadjs = new Worker("./workerLogger.js", {
workerData: opts,
});
const worker = workerThreadjs as unknown as worker_threads.Worker;

// eslint-disable-next-line @typescript-eslint/no-explicit-any
Expand Down
12 changes: 6 additions & 6 deletions packages/logger/test/e2e/logger/workerLogs.test.ts
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
import path from "node:path";
import fs from "node:fs";
import {fileURLToPath} from "node:url";
import {expect} from "chai";
import {describe, it, expect, vi, beforeEach, afterEach} from "vitest";
import {sleep} from "@lodestar/utils";
import {LoggerWorker, getLoggerWorker} from "./workerLoggerHandler.js";

Expand All @@ -11,7 +11,7 @@ import {LoggerWorker, getLoggerWorker} from "./workerLoggerHandler.js";
const __dirname = path.dirname(fileURLToPath(import.meta.url));

describe("worker logs", function () {
this.timeout(60_000);
vi.setConfig({testTimeout: 60_000});

const logFilepath = path.join(__dirname, "../../../test-logs/test_worker_logs.log");
let loggerWorker: LoggerWorker;
Expand All @@ -36,15 +36,15 @@ describe("worker logs", function () {
fs.createWriteStream(logFilepath, {flags: "a"}).write(logTextMainThread);

const data = await waitForFileSize(logFilepath, logTextMainThread.length);
expect(data).includes(logTextMainThread);
expect(data).toContain(logTextMainThread);
});

it("worker writes to file", async () => {
const logTextWorker = "test-log-worker";
loggerWorker.log(logTextWorker);

const data = await waitForFileSize(logFilepath, logTextWorker.length);
expect(data).includes(logTextWorker);
expect(data).toContain(logTextWorker);
});

it("concurrent write from two write streams in different threads", async () => {
Expand All @@ -57,8 +57,8 @@ describe("worker logs", function () {
file.write(logTextMainThread + "\n");

const data = await waitForFileSize(logFilepath, logTextWorker.length + logTextMainThread.length);
expect(data).includes(logTextWorker);
expect(data).includes(logTextMainThread);
expect(data).toContain(logTextWorker);
expect(data).toContain(logTextMainThread);
});
});

Expand Down
2 changes: 2 additions & 0 deletions packages/logger/test/globalSetup.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,2 @@
export async function setup(): Promise<void> {}
export async function teardown(): Promise<void> {}
6 changes: 0 additions & 6 deletions packages/logger/test/setup.ts

This file was deleted.

4 changes: 2 additions & 2 deletions packages/logger/test/unit/browser.test.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
import {expect} from "chai";
import {describe, it, expect} from "vitest";
import {LogLevel} from "@lodestar/utils";
import {stubLoggerForConsole} from "@lodestar/test-utils/mocha";
import {TimestampFormatCode, logFormats} from "../../src/index.js";
Expand All @@ -22,7 +22,7 @@ describe("browser logger", () => {

logger.warn(message, context, error);
logger.restoreStubs();
expect(logger.getLogs()).deep.equals([output[format]]);
expect(logger.getLogs()).toEqual([output[format]]);
});
}
}
Expand Down
4 changes: 2 additions & 2 deletions packages/logger/test/unit/env.node.test.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
import {expect} from "chai";
import {describe, it, expect} from "vitest";
import {LogLevel} from "@lodestar/utils";
import {stubLoggerForConsole} from "@lodestar/test-utils/mocha";
import {TimestampFormatCode, logFormats} from "../../src/index.js";
Expand All @@ -20,7 +20,7 @@ describe("env logger", () => {

logger.warn(message, context, error);
logger.restoreStubs();
expect(logger.getLogs()).deep.equals([output[format]]);
expect(logger.getLogs()).toEqual([output[format]]);
});
}
}
Expand Down
32 changes: 20 additions & 12 deletions packages/logger/test/unit/node.node.test.ts
Original file line number Diff line number Diff line change
@@ -1,27 +1,35 @@
import {expect} from "chai";
import {describe, it, expect, vi, afterEach, Mock} from "vitest";
import {LogLevel} from "@lodestar/utils";
import {stubLoggerForProcessStd} from "@lodestar/test-utils/mocha";
import {TimestampFormatCode, logFormats} from "../../src/index.js";
import {getNodeLogger} from "../../src/node.js";
import {formatsTestCases} from "../fixtures/loggerFormats.js";

// Node.js maps `process.stdout` to `console._stdout`.
// spy does not work on `process.stdout` directly.
// eslint-disable-next-line @typescript-eslint/naming-convention
type TestConsole = typeof console & {_stdout: {write: Mock}};

describe("node logger", () => {
afterEach(() => {
vi.resetAllMocks();
});

describe("format and options", () => {
for (const testCase of formatsTestCases) {
const {id, opts, message, context, error, output} = typeof testCase === "function" ? testCase() : testCase;
for (const format of logFormats) {
it(`${id} ${format} output`, async () => {
const logger = stubLoggerForProcessStd(
getNodeLogger({
level: LogLevel.info,
format,
module: opts?.module,
timestampFormat: {format: TimestampFormatCode.Hidden},
})
);
vi.spyOn((console as TestConsole)._stdout, "write");

const logger = getNodeLogger({
level: LogLevel.info,
format,
module: opts?.module,
timestampFormat: {format: TimestampFormatCode.Hidden},
});
logger.warn(message, context, error);
logger.restoreStubs();
expect(logger.getLogs()).deep.equals([output[format]]);

expect((console as TestConsole)._stdout.write).toHaveBeenNthCalledWith(1, `${output[format]}\n`);
});
}
}
Expand Down
20 changes: 10 additions & 10 deletions packages/logger/test/unit/utils/json.test.ts
Original file line number Diff line number Diff line change
@@ -1,6 +1,4 @@
/* eslint-disable @typescript-eslint/no-unsafe-member-access, @typescript-eslint/no-unsafe-assignment */
import "../../setup.js";
import {expect} from "chai";
import {describe, it, expect} from "vitest";
import {fromHexString, toHexString} from "@chainsafe/ssz";
import {LodestarError} from "@lodestar/utils";
import {logCtxToJson, logCtxToString} from "../../../src/utils/json.js";
Expand All @@ -13,7 +11,7 @@ describe("Json helper", () => {
type TestCase = {
id: string;
arg: unknown;
json: any;
json: unknown;
};
const testCases: (TestCase | (() => TestCase))[] = [
// Basic types
Expand All @@ -27,13 +25,13 @@ describe("Json helper", () => {

// Functions
// eslint-disable-next-line @typescript-eslint/no-empty-function
{id: "function", arg: function () {}, json: "function () { }"},
{id: "function", arg: function () {}, json: "function() {\n }"},
// eslint-disable-next-line @typescript-eslint/no-empty-function
{id: "arrow function", arg: () => {}, json: "() => { }"},
{id: "arrow function", arg: () => {}, json: "() => {\n }"},
// eslint-disable-next-line @typescript-eslint/no-empty-function
{id: "async function", arg: async function () {}, json: "async function () { }"},
{id: "async function", arg: async function () {}, json: "async function() {\n }"},
// eslint-disable-next-line @typescript-eslint/no-empty-function
{id: "async arrow function", arg: async () => {}, json: "async () => { }"},
{id: "async arrow function", arg: async () => {}, json: "async () => {\n }"},

// Arrays
{id: "array of basic types", arg: [1, 2, 3], json: [1, 2, 3]},
Expand Down Expand Up @@ -119,6 +117,7 @@ describe("Json helper", () => {
// Circular references
() => {
const circularReference: any = {};
// eslint-disable-next-line @typescript-eslint/no-unsafe-assignment, @typescript-eslint/no-unsafe-member-access
circularReference.myself = circularReference;
return {
id: "circular reference",
Expand All @@ -131,7 +130,7 @@ describe("Json helper", () => {
for (const testCase of testCases) {
const {id, arg, json} = typeof testCase === "function" ? testCase() : testCase;
it(id, () => {
expect(logCtxToJson(arg)).to.deep.equal(json);
expect(logCtxToJson(arg)).toEqual(json);
});
}
});
Expand Down Expand Up @@ -180,6 +179,7 @@ describe("Json helper", () => {
// Circular references
() => {
const circularReference: any = {};
// eslint-disable-next-line @typescript-eslint/no-unsafe-assignment, @typescript-eslint/no-unsafe-member-access
circularReference.myself = circularReference;
return {
id: "circular reference",
Expand All @@ -192,7 +192,7 @@ describe("Json helper", () => {
for (const testCase of testCases) {
const {id, json, output} = typeof testCase === "function" ? testCase() : testCase;
it(id, () => {
expect(logCtxToString(json)).to.equal(output);
expect(logCtxToString(json)).toBe(output);
});
}
});
Expand Down
5 changes: 2 additions & 3 deletions packages/logger/test/unit/utils/timeFormat.test.ts
Original file line number Diff line number Diff line change
@@ -1,5 +1,4 @@
import "../../setup.js";
import {expect} from "chai";
import {describe, it, expect} from "vitest";
import {formatEpochSlotTime} from "../../../src/utils/timeFormat.js";

describe("logger / util / formatEpochSlotTime", () => {
Expand All @@ -17,7 +16,7 @@ describe("logger / util / formatEpochSlotTime", () => {
const expectLog = `Eph ${epoch}/${slot} ${sec}`; // "Eph 3/6 11.423";
it(expectLog, () => {
const genesisTime = nowSec - epoch * slotsPerEpoch * secondsPerSlot - slot * secondsPerSlot - sec;
expect(formatEpochSlotTime({genesisTime, secondsPerSlot, slotsPerEpoch}, nowSec * 1000)).to.equal(expectLog);
expect(formatEpochSlotTime({genesisTime, secondsPerSlot, slotsPerEpoch}, nowSec * 1000)).toBe(expectLog);
});
}
});
Loading

0 comments on commit 1200c59

Please sign in to comment.