Skip to content

Commit f9ea611

Browse files
dwrthsdangol
andauthored
refactor(logger): use vitest env helpers in unit tests (#4360)
Co-authored-by: David <[email protected]> Co-authored-by: Swopnil Dangol <[email protected]>
1 parent cb1261b commit f9ea611

File tree

8 files changed

+115
-90
lines changed

8 files changed

+115
-90
lines changed

packages/logger/tests/unit/formatters.test.ts

Lines changed: 30 additions & 23 deletions
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,13 @@
11
import { AssertionError } from 'node:assert';
2-
import { afterAll, beforeEach, describe, expect, it, vi } from 'vitest';
2+
import {
3+
afterAll,
4+
afterEach,
5+
beforeEach,
6+
describe,
7+
expect,
8+
it,
9+
vi,
10+
} from 'vitest';
311
import { PowertoolsLogFormatter } from '../../src/formatter/PowertoolsLogFormatter.js';
412
import {
513
LogFormatter,
@@ -53,13 +61,8 @@ const unformattedAttributes: UnformattedAttributes = {
5361
},
5462
};
5563

56-
process.env.POWERTOOLS_DEV = 'true';
57-
58-
const logger = new Logger();
59-
6064
const jsonReplacerFn: CustomJsonReplacerFn = (_: string, value: unknown) =>
6165
value instanceof Set ? [...value] : value;
62-
const loggerWithReplacer = new Logger({ jsonReplacerFn });
6366

6467
/**
6568
* A custom log formatter that formats logs using only the message, log level as a number, and timestamp.
@@ -90,15 +93,19 @@ class CustomFormatter extends LogFormatter {
9093
);
9194
}
9295
}
93-
const loggerWithCustomLogFormatter = new Logger({
94-
logFormatter: new CustomFormatter(),
95-
});
9696

9797
describe('Formatters', () => {
98-
const ENVIRONMENT_VARIABLES = process.env;
98+
// Ensure dev mode is on for logger initialization
99+
vi.stubEnv('POWERTOOLS_DEV', 'true');
100+
const logger = new Logger();
101+
const loggerWithReplacer = new Logger({ jsonReplacerFn });
102+
const loggerWithCustomLogFormatter = new Logger({
103+
logFormatter: new CustomFormatter(),
104+
});
105+
vi.unstubAllEnvs();
99106

100107
beforeEach(() => {
101-
process.env = { ...ENVIRONMENT_VARIABLES };
108+
vi.stubEnv('POWERTOOLS_DEV', 'true');
102109
const mockDate = new Date(1466424490000);
103110
vi.useFakeTimers().setSystemTime(mockDate);
104111
vi.clearAllMocks();
@@ -109,6 +116,10 @@ describe('Formatters', () => {
109116
vi.useRealTimers();
110117
});
111118

119+
afterEach(() => {
120+
vi.unstubAllEnvs();
121+
});
122+
112123
// #region base log keys
113124

114125
it('formats the base log keys', () => {
@@ -451,8 +462,7 @@ describe('Formatters', () => {
451462

452463
it('formats stack as string when not in dev mode', () => {
453464
// Prepare
454-
const originalDevMode = process.env.POWERTOOLS_DEV;
455-
delete process.env.POWERTOOLS_DEV; // Ensure dev mode is off
465+
vi.stubEnv('POWERTOOLS_DEV', 'false'); // Ensure dev mode is off
456466

457467
const error = new Error('Test error');
458468
const formatter = new PowertoolsLogFormatter();
@@ -463,9 +473,6 @@ describe('Formatters', () => {
463473
// Assess
464474
expect(formattedError.stack).toEqual(expect.any(String));
465475
expect(Array.isArray(formattedError.stack)).toBe(false);
466-
467-
// Cleanup
468-
process.env.POWERTOOLS_DEV = originalDevMode;
469476
});
470477

471478
it('formats custom errors by including only enumerable properties', () => {
@@ -528,7 +535,7 @@ describe('Formatters', () => {
528535

529536
it('formats the timestamp to ISO 8601, accounting for the `America/New_York` timezone offset', () => {
530537
// Prepare
531-
process.env.TZ = 'America/New_York';
538+
vi.stubEnv('TZ', 'America/New_York');
532539
/*
533540
Difference between UTC and `America/New_York`(GMT -04.00) is 240 minutes.
534541
The positive value indicates that `America/New_York` is behind UTC.
@@ -544,7 +551,7 @@ describe('Formatters', () => {
544551

545552
it('formats the timestamp to ISO 8601 with correct milliseconds for `America/New_York` timezone', () => {
546553
// Prepare
547-
process.env.TZ = 'America/New_York';
554+
vi.stubEnv('TZ', 'America/New_York');
548555
/*
549556
Difference between UTC and `America/New_York`(GMT -04.00) is 240 minutes.
550557
The positive value indicates that `America/New_York` is behind UTC.
@@ -560,7 +567,7 @@ describe('Formatters', () => {
560567

561568
it('formats the timestamp to ISO 8601, adjusting for `America/New_York` timezone, preserving milliseconds and accounting for date change', () => {
562569
// Prepare
563-
process.env.TZ = 'America/New_York';
570+
vi.stubEnv('TZ', 'America/New_York');
564571
/*
565572
Difference between UTC and `America/New_York`(GMT -04.00) is 240 minutes.
566573
The positive value indicates that `America/New_York` is behind UTC.
@@ -576,7 +583,7 @@ describe('Formatters', () => {
576583

577584
it('it formats the timestamp to ISO 8601 with correct milliseconds for `Asia/Dhaka` timezone', () => {
578585
// Prepare
579-
process.env.TZ = 'Asia/Dhaka';
586+
vi.stubEnv('TZ', 'Asia/Dhaka');
580587
vi.setSystemTime(new Date('2016-06-20T12:08:10.910Z'));
581588
/*
582589
Difference between UTC and `Asia/Dhaka`(GMT +06.00) is 360 minutes.
@@ -594,7 +601,7 @@ describe('Formatters', () => {
594601

595602
it('formats the timestamp to ISO 8601, adjusting for `Asia/Dhaka` timezone, preserving milliseconds and accounting for date change', () => {
596603
// Prepare
597-
process.env.TZ = 'Asia/Dhaka';
604+
vi.stubEnv('TZ', 'Asia/Dhaka');
598605
const mockDate = new Date('2016-06-20T20:08:10.910Z');
599606
vi.setSystemTime(mockDate);
600607
/*
@@ -613,7 +620,7 @@ describe('Formatters', () => {
613620

614621
it('returns defaults to :UTC when an env variable service is not set', () => {
615622
// Prepare
616-
process.env.TZ = undefined;
623+
vi.stubEnv('TZ', undefined);
617624

618625
vi.spyOn(Date.prototype, 'getTimezoneOffset').mockReturnValue(-360);
619626
const formatter = new PowertoolsLogFormatter();
@@ -627,7 +634,7 @@ describe('Formatters', () => {
627634

628635
it('defaults to :UTC when the TZ env variable is set to :/etc/localtime', () => {
629636
// Prepare
630-
process.env.TZ = ':/etc/localtime';
637+
vi.stubEnv('TZ', ':/etc/localtime');
631638
vi.spyOn(Date.prototype, 'getTimezoneOffset').mockReturnValue(0);
632639
const formatter = new PowertoolsLogFormatter();
633640

packages/logger/tests/unit/initializeLogger.test.ts

Lines changed: 19 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -1,18 +1,28 @@
1-
import { beforeEach, describe, expect, it, type Mock, vi } from 'vitest';
1+
import {
2+
afterEach,
3+
beforeEach,
4+
describe,
5+
expect,
6+
it,
7+
type Mock,
8+
vi,
9+
} from 'vitest';
210
import { LogJsonIndent, LogLevel } from '../../src/constants.js';
311
import { Logger } from '../../src/Logger.js';
412

513
describe('Log levels', () => {
6-
const ENVIRONMENT_VARIABLES = process.env;
7-
814
beforeEach(() => {
9-
process.env = { ...ENVIRONMENT_VARIABLES, POWERTOOLS_DEV: 'true' };
15+
vi.stubEnv('POWERTOOLS_DEV', 'true');
1016
vi.clearAllMocks();
1117
});
1218

19+
afterEach(() => {
20+
vi.unstubAllEnvs();
21+
});
22+
1323
it('uses the default service name when none is provided', () => {
1424
// Prepare
15-
process.env.POWERTOOLS_SERVICE_NAME = undefined;
25+
vi.stubEnv('POWERTOOLS_SERVICE_NAME', undefined);
1626
const logger = new Logger();
1727

1828
// Act
@@ -28,7 +38,7 @@ describe('Log levels', () => {
2838

2939
it('uses service name specified in environment variables', () => {
3040
// Prepare
31-
process.env.POWERTOOLS_SERVICE_NAME = 'hello-world';
41+
vi.stubEnv('POWERTOOLS_SERVICE_NAME', 'hello-world');
3242
const logger = new Logger();
3343

3444
// Act
@@ -44,7 +54,7 @@ describe('Log levels', () => {
4454

4555
it('uses service name specified in the constructor', () => {
4656
// Prepare
47-
process.env.POWERTOOLS_SERVICE_NAME = undefined;
57+
vi.stubEnv('POWERTOOLS_SERVICE_NAME', undefined);
4858
const logger = new Logger({ serviceName: 'hello-world' });
4959

5060
// Act
@@ -60,7 +70,7 @@ describe('Log levels', () => {
6070

6171
it('overrides the service name when creating a child logger', () => {
6272
// Prepare
63-
process.env.POWERTOOLS_SERVICE_NAME = 'hello-world';
73+
vi.stubEnv('POWERTOOLS_SERVICE_NAME', 'hello-world');
6474
const logger = new Logger();
6575
const childLogger = logger.createChild({ serviceName: 'child-service' });
6676

@@ -127,7 +137,7 @@ describe('Log levels', () => {
127137

128138
it("doesn't use the global console object by default", () => {
129139
// Prepare
130-
process.env.POWERTOOLS_DEV = undefined;
140+
vi.stubEnv('POWERTOOLS_DEV', undefined);
131141
const logger = new Logger();
132142

133143
// Assess

packages/logger/tests/unit/injectLambdaContext.test.ts

Lines changed: 6 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -1,7 +1,7 @@
11
import context from '@aws-lambda-powertools/testing-utils/context';
22
import middy from '@middy/core';
33
import type { Context } from 'aws-lambda';
4-
import { beforeEach, describe, expect, it, vi } from 'vitest';
4+
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
55
import { search } from '../../src/correlationId.js';
66
import { Logger } from '../../src/Logger.js';
77
import { injectLambdaContext } from '../../src/middleware/middy.js';
@@ -20,16 +20,15 @@ const getContextLogEntries = (overrides?: Record<string, unknown>) => ({
2020
});
2121

2222
describe('Inject Lambda Context', () => {
23-
const ENVIRONMENT_VARIABLES = process.env;
24-
2523
beforeEach(() => {
26-
process.env = {
27-
...ENVIRONMENT_VARIABLES,
28-
POWERTOOLS_DEV: 'true',
29-
};
24+
vi.stubEnv('POWERTOOLS_DEV', 'true');
3025
vi.clearAllMocks();
3126
});
3227

28+
afterEach(() => {
29+
vi.unstubAllEnvs();
30+
});
31+
3332
it('adds the context to log messages when the feature is enabled', () => {
3433
// Prepare
3534
const logger = new Logger();

packages/logger/tests/unit/logBuffer.test.ts

Lines changed: 18 additions & 11 deletions
Original file line numberDiff line numberDiff line change
@@ -1,22 +1,29 @@
11
import context from '@aws-lambda-powertools/testing-utils/context';
22
import type { Context } from 'aws-lambda';
33
import middy from 'middy5';
4-
import { beforeEach, describe, expect, it, type Mock, vi } from 'vitest';
4+
import {
5+
afterEach,
6+
beforeEach,
7+
describe,
8+
expect,
9+
it,
10+
type Mock,
11+
vi,
12+
} from 'vitest';
513
import { LogLevel, UncaughtErrorLogMessage } from '../../src/constants.js';
614
import { Logger } from '../../src/Logger.js';
715
import { injectLambdaContext } from '../../src/middleware/middy.js';
816

917
describe('Buffer logs', () => {
10-
const ENVIRONMENT_VARIABLES = process.env;
11-
1218
beforeEach(() => {
13-
process.env = {
14-
...ENVIRONMENT_VARIABLES,
15-
POWERTOOLS_DEV: 'true',
16-
};
19+
vi.stubEnv('POWERTOOLS_DEV', 'true');
1720
vi.clearAllMocks();
1821
});
1922

23+
afterEach(() => {
24+
vi.unstubAllEnvs();
25+
});
26+
2027
it('does not buffer logs when disabled', () => {
2128
// Prepare
2229
const logger = new Logger({
@@ -94,7 +101,7 @@ describe('Buffer logs', () => {
94101

95102
it('outputs a warning when the Advanced Logging Configuration Log Level is less verbose than the Log Buffering Log Level', () => {
96103
// Assemble
97-
process.env.AWS_LAMBDA_LOG_LEVEL = 'INFO';
104+
vi.stubEnv('AWS_LAMBDA_LOG_LEVEL', 'INFO');
98105
const logger = new Logger({
99106
logLevel: LogLevel.DEBUG,
100107
logBufferOptions: { enabled: true, bufferAtVerbosity: 'DEBUG' },
@@ -116,7 +123,7 @@ describe('Buffer logs', () => {
116123

117124
it('When the buffer is flushed it outputs a warning if the Advanced Logging Configuration Log Level is less verbose than the Log Buffering Log Level', () => {
118125
// Assemble
119-
process.env.AWS_LAMBDA_LOG_LEVEL = 'INFO';
126+
vi.stubEnv('AWS_LAMBDA_LOG_LEVEL', 'INFO');
120127
const logger = new Logger({
121128
logLevel: LogLevel.DEBUG,
122129
logBufferOptions: { enabled: true, bufferAtVerbosity: 'DEBUG' },
@@ -195,7 +202,7 @@ describe('Buffer logs', () => {
195202

196203
it('does not output buffered logs when trace id is not set', () => {
197204
// Prepare
198-
process.env._X_AMZN_TRACE_ID = undefined;
205+
vi.stubEnv('_X_AMZN_TRACE_ID', undefined);
199206
const logger = new Logger({ logBufferOptions: { enabled: true } });
200207

201208
// Act
@@ -210,7 +217,7 @@ describe('Buffer logs', () => {
210217

211218
it('it safely short circuits when clearBuffer is called without a trace id', () => {
212219
// Prepare
213-
process.env._X_AMZN_TRACE_ID = undefined;
220+
vi.stubEnv('_X_AMZN_TRACE_ID', undefined);
214221
const logger = new Logger({
215222
logLevel: LogLevel.ERROR,
216223
logBufferOptions: { enabled: true, bufferAtVerbosity: LogLevel.DEBUG },

packages/logger/tests/unit/logEvent.test.ts

Lines changed: 10 additions & 11 deletions
Original file line numberDiff line numberDiff line change
@@ -1,7 +1,7 @@
11
import context from '@aws-lambda-powertools/testing-utils/context';
22
import middy from '@middy/core';
33
import type { Context } from 'aws-lambda';
4-
import { beforeEach, describe, expect, it, vi } from 'vitest';
4+
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
55
import { Logger } from '../../src/Logger.js';
66
import { injectLambdaContext } from '../../src/middleware/middy.js';
77

@@ -10,17 +10,16 @@ const event = {
1010
};
1111

1212
describe('Log event', () => {
13-
const ENVIRONMENT_VARIABLES = process.env;
14-
1513
beforeEach(() => {
16-
process.env = {
17-
...ENVIRONMENT_VARIABLES,
18-
POWERTOOLS_LOGGER_LOG_EVENT: 'true',
19-
POWERTOOLS_DEV: 'true',
20-
};
14+
vi.stubEnv('POWERTOOLS_LOGGER_LOG_EVENT', 'true');
15+
vi.stubEnv('POWERTOOLS_DEV', 'true');
2116
vi.clearAllMocks();
2217
});
2318

19+
afterEach(() => {
20+
vi.unstubAllEnvs();
21+
});
22+
2423
it('logs the event with the correct log level and message', () => {
2524
// Prepare
2625
const logger = new Logger();
@@ -35,7 +34,7 @@ describe('Log event', () => {
3534

3635
it("doesn't log the event when the feature is disabled", () => {
3736
// Prepare
38-
process.env.POWERTOOLS_LOGGER_LOG_EVENT = 'false';
37+
vi.stubEnv('POWERTOOLS_LOGGER_LOG_EVENT', 'false');
3938
const logger = new Logger();
4039

4140
// Act
@@ -112,7 +111,7 @@ describe('Log event', () => {
112111

113112
it('prefers the local logEvent configuration over the environment variable', async () => {
114113
// Prepare
115-
process.env.POWERTOOLS_LOGGER_LOG_EVENT = 'false';
114+
vi.stubEnv('POWERTOOLS_LOGGER_LOG_EVENT', 'false');
116115
const logger = new Logger();
117116
const handler = middy(async () => {}).use(
118117
injectLambdaContext(logger, { logEvent: true })
@@ -127,7 +126,7 @@ describe('Log event', () => {
127126

128127
it('passes down the log event configuration to child loggers', () => {
129128
// Prepare
130-
process.env.POWERTOOLS_LOGGER_LOG_EVENT = 'false';
129+
vi.stubEnv('POWERTOOLS_LOGGER_LOG_EVENT', 'false');
131130
const logger = new Logger();
132131
const childLogger = logger.createChild();
133132

0 commit comments

Comments
 (0)