Skip to content

test(logger): migrate to vitest & custom matchers #3131

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

Merged
merged 4 commits into from
Sep 27, 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
11 changes: 5 additions & 6 deletions .github/workflows/reusable-run-linting-check-and-unit-tests.yml
Original file line number Diff line number Diff line change
Expand Up @@ -43,9 +43,10 @@ jobs:
workspace: [
"packages/batch",
"packages/commons",
"packages/jmespath",
"packages/event-handler",
"packages/idempotency",
"packages/event-handler"
"packages/jmespath",
"packages/logger",
]
fail-fast: false
steps:
Expand Down Expand Up @@ -88,15 +89,13 @@ jobs:
nodeVersion: ${{ matrix.version }}
- name: Run linting
run: |
npm run lint -w packages/logger \
-w packages/tracer \
npm run lint -w -w packages/tracer \
-w packages/metrics \
-w packages/parameters \
-w packages/parser
- name: Run unit tests
run: |
npm t -w packages/logger \
-w packages/tracer \
npm t -w packages/tracer \
-w packages/metrics \
-w packages/parameters \
-w packages/parser
Expand Down
1 change: 0 additions & 1 deletion .husky/pre-push
Original file line number Diff line number Diff line change
@@ -1,5 +1,4 @@
npm t \
-w packages/logger \
-w packages/metrics \
-w packages/tracer \
-w packages/parameters \
Expand Down
7 changes: 4 additions & 3 deletions packages/logger/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -10,9 +10,10 @@
"access": "public"
},
"scripts": {
"test": "npm run test:unit",
"test:unit": "jest --group=unit --detectOpenHandles --coverage --verbose",
"jest": "jest --detectOpenHandles --verbose",
"test": "vitest --run tests/unit",
"test:unit": "vitest --run tests/unit",
"test:unit:coverage": "vitest --run tests/unit --coverage.enabled --coverage.thresholds.100 --coverage.include='src/**'",
"test:unit:types": "echo 'Not Implemented'",
"test:e2e:nodejs18x": "RUNTIME=nodejs18x jest --group=e2e",
"test:e2e:nodejs20x": "RUNTIME=nodejs20x jest --group=e2e",
"test:e2e": "jest --group=e2e",
Expand Down
5 changes: 2 additions & 3 deletions packages/logger/src/Logger.ts
Original file line number Diff line number Diff line change
Expand Up @@ -418,16 +418,15 @@ class Logger extends Utility implements LoggerInterface {
/**
* @deprecated This method is deprecated and will be removed in the future major versions. Use {@link resetKeys()} instead.
*/
/* istanbul ignore next */
public static injectLambdaContextAfterOrOnError(
/* v8 ignore start */ public static injectLambdaContextAfterOrOnError(
logger: Logger,
_persistentAttributes: LogAttributes,
options?: InjectLambdaContextOptions
): void {
if (options && (options.clearState || options?.resetKeys)) {
logger.resetKeys();
}
}
} /* v8 ignore stop */

/**
* @deprecated - This method is deprecated and will be removed in the next major version.
Expand Down
10 changes: 7 additions & 3 deletions packages/logger/tests/tsconfig.json
Original file line number Diff line number Diff line change
@@ -1,8 +1,12 @@
{
"extends": "../tsconfig.json",
"compilerOptions": {
"rootDir": "../",
"rootDir": "../../",
"noEmit": true
},
"include": ["../src/**/*", "./**/*"]
}
"include": [
"../../testing/src/setupEnv.ts",
"../src/**/*",
"./**/*"
]
}
8 changes: 1 addition & 7 deletions packages/logger/tests/unit/configFromEnv.test.ts
Original file line number Diff line number Diff line change
@@ -1,16 +1,10 @@
/**
* Test Logger EnvironmentVariablesService class
*
* @group unit/logger/config
*/
import { beforeEach, describe, expect, it, jest } from '@jest/globals';
import { beforeEach, describe, expect, it } from 'vitest';
import { EnvironmentVariablesService } from '../../src/config/EnvironmentVariablesService.js';

describe('Class: EnvironmentVariablesService', () => {
const ENVIRONMENT_VARIABLES = process.env;

beforeEach(() => {
jest.resetModules();
process.env = { ...ENVIRONMENT_VARIABLES };
});

Expand Down
79 changes: 35 additions & 44 deletions packages/logger/tests/unit/formatters.test.ts
Original file line number Diff line number Diff line change
@@ -1,17 +1,5 @@
/**
* Test Logger formatter
*
* @group unit/logger/logFormatter
*/
import { AssertionError } from 'node:assert';
import {
afterAll,
beforeEach,
describe,
expect,
it,
jest,
} from '@jest/globals';
import { afterAll, beforeEach, describe, expect, it, vi } from 'vitest';
import { EnvironmentVariablesService } from '../../src/config/EnvironmentVariablesService.js';
import { PowertoolsLogFormatter } from '../../src/formatter/PowertoolsLogFormatter.js';
import {
Expand Down Expand Up @@ -73,8 +61,6 @@ const unformattedAttributes: UnformattedAttributes = {

process.env.POWERTOOLS_DEV = 'true';

const logSpy = jest.spyOn(console, 'info');

const logger = new Logger();

const jsonReplacerFn: CustomJsonReplacerFn = (_: string, value: unknown) =>
Expand Down Expand Up @@ -120,14 +106,13 @@ describe('Formatters', () => {
beforeEach(() => {
process.env = { ...ENVIRONMENT_VARIABLES };
const mockDate = new Date(1466424490000);
jest.useFakeTimers().setSystemTime(mockDate);
jest.resetAllMocks();
vi.useFakeTimers().setSystemTime(mockDate);
vi.resetAllMocks();
unformattedAttributes.timestamp = mockDate;
});

afterAll(() => {
jest.useRealTimers();
unformattedAttributes.timestamp = new Date();
vi.useRealTimers();
});

// #region base log keys
Expand Down Expand Up @@ -477,7 +462,7 @@ describe('Formatters', () => {
Difference between UTC and `America/New_York`(GMT -04.00) is 240 minutes.
The positive value indicates that `America/New_York` is behind UTC.
*/
jest.spyOn(Date.prototype, 'getTimezoneOffset').mockReturnValue(240);
vi.spyOn(Date.prototype, 'getTimezoneOffset').mockReturnValue(240);

// Act
const timestamp = formatterWithEnv.formatTimestamp(new Date());
Expand All @@ -493,7 +478,7 @@ describe('Formatters', () => {
Difference between UTC and `America/New_York`(GMT -04.00) is 240 minutes.
The positive value indicates that `America/New_York` is behind UTC.
*/
jest.spyOn(Date.prototype, 'getTimezoneOffset').mockReturnValue(240);
vi.spyOn(Date.prototype, 'getTimezoneOffset').mockReturnValue(240);

// Act
const timestamp = formatterWithEnv.formatTimestamp(new Date());
Expand All @@ -509,7 +494,7 @@ describe('Formatters', () => {
Difference between UTC and `America/New_York`(GMT -04.00) is 240 minutes.
The positive value indicates that `America/New_York` is behind UTC.
*/
jest.spyOn(Date.prototype, 'getTimezoneOffset').mockReturnValue(240);
vi.spyOn(Date.prototype, 'getTimezoneOffset').mockReturnValue(240);

// Act
const timestamp = formatterWithEnv.formatTimestamp(new Date());
Expand All @@ -521,12 +506,12 @@ describe('Formatters', () => {
it('it formats the timestamp to ISO 8601 with correct milliseconds for `Asia/Dhaka` timezone', () => {
// Prepare
process.env.TZ = 'Asia/Dhaka';
jest.useFakeTimers().setSystemTime(new Date('2016-06-20T12:08:10.910Z'));
vi.setSystemTime(new Date('2016-06-20T12:08:10.910Z'));
/*
Difference between UTC and `Asia/Dhaka`(GMT +06.00) is 360 minutes.
The negative value indicates that `Asia/Dhaka` is ahead of UTC.
*/
jest.spyOn(Date.prototype, 'getTimezoneOffset').mockReturnValue(-360);
vi.spyOn(Date.prototype, 'getTimezoneOffset').mockReturnValue(-360);
const formatter = new PowertoolsLogFormatter({
envVarsService: new EnvironmentVariablesService(),
});
Expand All @@ -542,12 +527,12 @@ describe('Formatters', () => {
// Prepare
process.env.TZ = 'Asia/Dhaka';
const mockDate = new Date('2016-06-20T20:08:10.910Z');
jest.useFakeTimers().setSystemTime(mockDate);
vi.setSystemTime(mockDate);
/*
Difference between UTC and `Asia/Dhaka`(GMT +06.00) is 360 minutes.
The negative value indicates that `Asia/Dhaka` is ahead of UTC.
*/
jest.spyOn(Date.prototype, 'getTimezoneOffset').mockReturnValue(-360);
vi.spyOn(Date.prototype, 'getTimezoneOffset').mockReturnValue(-360);
const formatter = new PowertoolsLogFormatter({
envVarsService: new EnvironmentVariablesService(),
});
Expand All @@ -566,7 +551,7 @@ describe('Formatters', () => {
Difference between UTC and `Asia/Dhaka`(GMT +06.00) is 360 minutes.
The negative value indicates that `Asia/Dhaka` is ahead of UTC.
*/
jest.spyOn(Date.prototype, 'getTimezoneOffset').mockReturnValue(-360);
vi.spyOn(Date.prototype, 'getTimezoneOffset').mockReturnValue(-360);
const formatter = new PowertoolsLogFormatter();

// Act
Expand All @@ -579,7 +564,7 @@ describe('Formatters', () => {
it('defaults to :UTC when the TZ env variable is set to :/etc/localtime', () => {
// Prepare
process.env.TZ = ':/etc/localtime';
jest.spyOn(Date.prototype, 'getTimezoneOffset').mockReturnValue(0);
vi.spyOn(Date.prototype, 'getTimezoneOffset').mockReturnValue(0);
const formatter = new PowertoolsLogFormatter({
envVarsService: new EnvironmentVariablesService(),
});
Expand Down Expand Up @@ -676,8 +661,9 @@ describe('Formatters', () => {
logger.info('foo', { circularObject });

// Assess
expect(logSpy).toHaveBeenCalledTimes(1);
expect(JSON.parse(logSpy.mock.calls[0][0])).toEqual(
expect(console.info).toHaveBeenCalledTimes(1);
expect(console.info).toHaveLoggedNth(
1,
expect.objectContaining({
level: 'INFO',
message: 'foo',
Expand All @@ -696,8 +682,9 @@ describe('Formatters', () => {
logger.info('foo', bigIntValue);

// Assess
expect(logSpy).toHaveBeenCalledTimes(1);
expect(JSON.parse(logSpy.mock.calls[0][0])).toEqual(
expect(console.info).toHaveBeenCalledTimes(1);
expect(console.info).toHaveLoggedNth(
1,
expect.objectContaining({
level: 'INFO',
message: 'foo',
Expand All @@ -720,8 +707,9 @@ describe('Formatters', () => {
logger.info('foo', values);

// Assess
expect(logSpy).toHaveBeenCalledTimes(1);
expect(JSON.parse(logSpy.mock.calls[0][0])).toEqual(
expect(console.info).toHaveBeenCalledTimes(1);
expect(console.info).toHaveLoggedNth(
1,
expect.objectContaining({
level: 'INFO',
message: 'foo',
Expand All @@ -738,8 +726,9 @@ describe('Formatters', () => {
loggerWithReplacer.info('foo', valueWithSet);

// Assess
expect(logSpy).toHaveBeenCalledTimes(1);
expect(JSON.parse(logSpy.mock.calls[0][0])).toEqual(
expect(console.info).toHaveBeenCalledTimes(1);
expect(console.info).toHaveLoggedNth(
1,
expect.objectContaining({
level: 'INFO',
message: 'foo',
Expand All @@ -759,8 +748,9 @@ describe('Formatters', () => {
loggerWithReplacer.info('foo', valueWithSetAndBigInt);

// Assess
expect(logSpy).toHaveBeenCalledTimes(1);
expect(JSON.parse(logSpy.mock.calls[0][0])).toEqual(
expect(console.info).toHaveBeenCalledTimes(1);
expect(console.info).toHaveLoggedNth(
1,
expect.objectContaining({
level: 'INFO',
message: 'foo',
Expand All @@ -778,8 +768,9 @@ describe('Formatters', () => {
childLogger.info('foo', { foo: new Set([1, 2]) });

// Assess
expect(logSpy).toHaveBeenCalledTimes(1);
expect(JSON.parse(logSpy.mock.calls[0][0])).toEqual(
expect(console.info).toHaveBeenCalledTimes(1);
expect(console.info).toHaveLoggedNth(
1,
expect.objectContaining({
level: 'INFO',
message: 'foo',
Expand All @@ -795,8 +786,8 @@ describe('Formatters', () => {
loggerWithCustomLogFormatter.info('foo');

// Assess
expect(logSpy).toHaveBeenCalledTimes(1);
expect(JSON.parse(logSpy.mock.calls[0][0])).toEqual({
expect(console.info).toHaveBeenCalledTimes(1);
expect(console.info).toHaveLoggedNth(1, {
logLevel: 12,
message: 'foo',
timestamp: expect.any(String),
Expand All @@ -811,8 +802,8 @@ describe('Formatters', () => {
childLogger.info('foo');

// Assess
expect(logSpy).toHaveBeenCalledTimes(1);
expect(JSON.parse(logSpy.mock.calls[0][0])).toEqual({
expect(console.info).toHaveBeenCalledTimes(1);
expect(console.info).toHaveLoggedNth(1, {
logLevel: 12,
message: 'foo',
timestamp: expect.any(String),
Expand Down
Loading