Skip to content

test(metrics): migrate tests to vitest & refactor #3355

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 6 commits into from
Nov 25, 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
27 changes: 1 addition & 26 deletions .github/workflows/reusable-run-linting-check-and-unit-tests.yml
Original file line number Diff line number Diff line change
Expand Up @@ -50,6 +50,7 @@ jobs:
"packages/tracer",
"packages/parser",
"packages/parameters",
"packages/metrics"
]
fail-fast: false
steps:
Expand All @@ -70,32 +71,6 @@ jobs:
run: |
npm run test:unit:coverage -w ${{ matrix.workspace }}
npm run test:unit:types -w ${{ matrix.workspace }}
run-linting-check-and-unit-tests-on-utilities:
runs-on: ubuntu-latest
env:
NODE_ENV: dev
strategy:
matrix:
version: [18, 20, 22]
fail-fast: false
steps:
- name: Checkout code
uses: actions/checkout@11bd71901bbe5b1630ceea73d27597364c9af683 # v4.2.2
- name: Setup NodeJS
uses: actions/setup-node@39370e3970a6d050c480ffad4ff0ed4d3fdee5af # v4.1.0
with:
node-version: ${{ matrix.version }}
cache: "npm"
- name: Setup dependencies
uses: aws-powertools/actions/.github/actions/cached-node-modules@d406bac5563f1d8c793519a3eedfe620f6a14872
with:
nodeVersion: ${{ matrix.version }}
- name: Run linting
run: |
npm run lint -w packages/metrics
- name: Run unit tests
run: |
npm t -w packages/metrics
check-examples:
runs-on: ubuntu-latest
env:
Expand Down
3 changes: 0 additions & 3 deletions .husky/pre-push
Original file line number Diff line number Diff line change
@@ -1,6 +1,3 @@
npm t \
-w packages/metrics

npx vitest --run \
--exclude tests/unit/layer-publisher.test.ts \
--coverage --coverage.thresholds.100 \
Expand Down
31 changes: 0 additions & 31 deletions packages/metrics/jest.config.cjs

This file was deleted.

18 changes: 10 additions & 8 deletions packages/metrics/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -10,13 +10,15 @@
"access": "public"
},
"scripts": {
"test": "npm run test:unit",
"test:unit": "jest --group=unit --detectOpenHandles --coverage --verbose",
"test:e2e:nodejs18x": "RUNTIME=nodejs18x jest --group=e2e",
"test:e2e:nodejs20x": "RUNTIME=nodejs20x jest --group=e2e",
"test:e2e:nodejs22x": "RUNTIME=nodejs22x jest --group=e2e",
"test:e2e": "jest --group=e2e",
"watch": "jest --group=unit --watch ",
"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:unit:watch": "vitest tests/unit",
"test:e2e:nodejs18x": "RUNTIME=nodejs18x vitest --run tests/e2e",
"test:e2e:nodejs20x": "RUNTIME=nodejs20x vitest --run tests/e2e",
"test:e2e:nodejs22x": "RUNTIME=nodejs22x vitest --run tests/e2e",
"test:e2e": "vitest --run tests/e2e",
"build:cjs": "tsc --build tsconfig.json && echo '{ \"type\": \"commonjs\" }' > lib/cjs/package.json",
"build:esm": "tsc --build tsconfig.esm.json && echo '{ \"type\": \"module\" }' > lib/esm/package.json",
"build": "npm run build:esm & npm run build:cjs",
Expand Down Expand Up @@ -96,4 +98,4 @@
"serverless",
"nodejs"
]
}
}
4 changes: 2 additions & 2 deletions packages/metrics/src/Metrics.ts
Original file line number Diff line number Diff line change
Expand Up @@ -827,9 +827,9 @@ class Metrics extends Utility implements MetricsInterface {
/**
* @deprecated Use {@link Metrics.setThrowOnEmptyMetrics | `setThrowOnEmptyMetrics()`} instead.
*/
public throwOnEmptyMetrics(): void {
/* v8 ignore start */ public throwOnEmptyMetrics(): void {
this.shouldThrowOnEmptyMetrics = true;
}
} /* v8 ignore stop */

/**
* Gets the current number of dimensions count.
Expand Down
28 changes: 3 additions & 25 deletions packages/metrics/tests/e2e/basicFeatures.decorators.test.ts
Original file line number Diff line number Diff line change
@@ -1,8 +1,3 @@
/**
* Test metrics standard functions
*
* @group e2e/metrics/decorator
*/
import { join } from 'node:path';
import {
TestStack,
Expand All @@ -12,6 +7,7 @@ import {
CloudWatchClient,
GetMetricStatisticsCommand,
} from '@aws-sdk/client-cloudwatch';
import { afterAll, beforeAll, describe, expect, it } from 'vitest';
import { getMetrics, sortDimensions } from '../helpers/metricsUtils.js';
import { MetricsTestNodejsFunction } from '../helpers/resources.js';
import {
Expand Down Expand Up @@ -74,7 +70,7 @@ describe('Metrics E2E tests, basic features decorator usage', () => {

describe('ColdStart metrics', () => {
it(
'should capture ColdStart Metric',
'captures the ColdStart Metric',
async () => {
const {
EXPECTED_NAMESPACE: expectedNamespace,
Expand Down Expand Up @@ -106,15 +102,6 @@ describe('Metrics E2E tests, basic features decorator usage', () => {
// Check coldstart metric value
const adjustedStartTime = new Date(startTime.getTime() - ONE_MINUTE);
const endTime = new Date(new Date().getTime() + ONE_MINUTE);
console.log(
`Manual command: aws cloudwatch get-metric-statistics --namespace ${expectedNamespace} --metric-name ColdStart --start-time ${Math.floor(
adjustedStartTime.getTime() / 1000
)} --end-time ${Math.floor(
endTime.getTime() / 1000
)} --statistics 'Sum' --period 60 --dimensions '${JSON.stringify(
expectedDimensions
)}'`
);
const coldStartMetricStat = await cloudwatchClient.send(
new GetMetricStatisticsCommand({
Namespace: expectedNamespace,
Expand All @@ -139,7 +126,7 @@ describe('Metrics E2E tests, basic features decorator usage', () => {

describe('Default and extra dimensions', () => {
it(
'should produce a Metric with the default and extra one dimensions',
'produces a Metric with the default and extra one dimensions',
async () => {
const {
EXPECTED_NAMESPACE: expectedNamespace,
Expand Down Expand Up @@ -179,15 +166,6 @@ describe('Metrics E2E tests, basic features decorator usage', () => {
startTime.getTime() - 3 * ONE_MINUTE
);
const endTime = new Date(new Date().getTime() + ONE_MINUTE);
console.log(
`Manual command: aws cloudwatch get-metric-statistics --namespace ${expectedNamespace} --metric-name ${expectedMetricName} --start-time ${Math.floor(
adjustedStartTime.getTime() / 1000
)} --end-time ${Math.floor(
endTime.getTime() / 1000
)} --statistics 'Sum' --period 60 --dimensions '${JSON.stringify(
expectedDimensions
)}'`
);
const metricStat = await cloudwatchClient.send(
new GetMetricStatisticsCommand({
Namespace: expectedNamespace,
Expand Down
28 changes: 3 additions & 25 deletions packages/metrics/tests/e2e/basicFeatures.manual.test.ts
Original file line number Diff line number Diff line change
@@ -1,8 +1,3 @@
/**
* Test metrics standard functions
*
* @group e2e/metrics/standardFunctions
*/
import { join } from 'node:path';
import {
TestStack,
Expand All @@ -12,6 +7,7 @@ import {
CloudWatchClient,
GetMetricStatisticsCommand,
} from '@aws-sdk/client-cloudwatch';
import { afterAll, beforeAll, describe, expect, it } from 'vitest';
import { getMetrics, sortDimensions } from '../helpers/metricsUtils.js';
import { MetricsTestNodejsFunction } from '../helpers/resources.js';
import {
Expand Down Expand Up @@ -72,7 +68,7 @@ describe('Metrics E2E tests, manual usage', () => {

describe('ColdStart metrics', () => {
it(
'should capture ColdStart Metric',
'captures the ColdStart Metric',
async () => {
const { EXPECTED_NAMESPACE: expectedNamespace } = commonEnvironmentVars;

Expand All @@ -92,15 +88,6 @@ describe('Metrics E2E tests, manual usage', () => {
// Check coldstart metric value
const adjustedStartTime = new Date(startTime.getTime() - 60 * 1000);
const endTime = new Date(new Date().getTime() + 60 * 1000);
console.log(
`Manual command: aws cloudwatch get-metric-statistics --namespace ${expectedNamespace} --metric-name ColdStart --start-time ${Math.floor(
adjustedStartTime.getTime() / 1000
)} --end-time ${Math.floor(
endTime.getTime() / 1000
)} --statistics 'Sum' --period 60 --dimensions '${JSON.stringify([
{ Name: 'service', Value: expectedServiceName },
])}'`
);
const coldStartMetricStat = await cloudwatchClient.send(
new GetMetricStatisticsCommand({
Namespace: expectedNamespace,
Expand All @@ -125,7 +112,7 @@ describe('Metrics E2E tests, manual usage', () => {

describe('Default and extra dimensions', () => {
it(
'should produce a Metric with the default and extra one dimensions',
'produces a Metric with the default and extra one dimensions',
async () => {
const {
EXPECTED_NAMESPACE: expectedNamespace,
Expand Down Expand Up @@ -165,15 +152,6 @@ describe('Metrics E2E tests, manual usage', () => {
startTime.getTime() - 3 * ONE_MINUTE
);
const endTime = new Date(new Date().getTime() + ONE_MINUTE);
console.log(
`Manual command: aws cloudwatch get-metric-statistics --namespace ${expectedNamespace} --metric-name ${expectedMetricName} --start-time ${Math.floor(
adjustedStartTime.getTime() / 1000
)} --end-time ${Math.floor(
endTime.getTime() / 1000
)} --statistics 'Sum' --period 60 --dimensions '${JSON.stringify(
expectedDimensions
)}'`
);
const metricStat = await cloudwatchClient.send(
new GetMetricStatisticsCommand({
Namespace: expectedNamespace,
Expand Down
28 changes: 1 addition & 27 deletions packages/metrics/tests/helpers/metricsUtils.ts
Original file line number Diff line number Diff line change
@@ -1,14 +1,10 @@
import type { LambdaInterface } from '@aws-lambda-powertools/commons/types';
import {
type CloudWatchClient,
type Dimension,
ListMetricsCommand,
type ListMetricsCommandOutput,
} from '@aws-sdk/client-cloudwatch';
import type { Context, Handler } from 'aws-lambda';
import promiseRetry from 'promise-retry';
import { MetricUnit, type Metrics } from '../../src/index.js';
import type { ExtraOptions } from '../../src/types/index.js';

const getMetrics = async (
cloudWatchClient: CloudWatchClient,
Expand Down Expand Up @@ -43,29 +39,7 @@ const getMetrics = async (
}, retryOptions);
};

const setupDecoratorLambdaHandler = (
metrics: Metrics,
options: ExtraOptions = {}
): Handler => {
class LambdaFunction implements LambdaInterface {
@metrics.logMetrics(options)
public async handler<TEvent>(
_event: TEvent,
_context: Context
): Promise<string> {
metrics.addMetric('decorator-lambda-test-metric', MetricUnit.Count, 1);

return 'Lambda invoked!';
}
}

const handlerClass = new LambdaFunction();
const handler = handlerClass.handler.bind(handlerClass);

return handler;
};

const sortDimensions = (dimensions?: Dimension[]): Dimension[] | undefined =>
dimensions?.sort((a, b) => (a.Name || '').localeCompare(b?.Name || ''));

export { getMetrics, setupDecoratorLambdaHandler, sortDimensions };
export { getMetrics, sortDimensions };
8 changes: 6 additions & 2 deletions packages/metrics/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/**/*",
"./**/*"
]
}
Loading