Skip to content
Draft
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
17 changes: 17 additions & 0 deletions .github/workflows/stage-2-test.yaml
Original file line number Diff line number Diff line change
Expand Up @@ -100,12 +100,29 @@ jobs:
with:
node-version: ${{ inputs.nodejs_version }}
GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }}
- name: "Install dependencies"
run: npm ci
- name: "Setup Python"
uses: actions/setup-python@v6
with:
python-version: ${{ inputs.python_version }}
cache: 'pip'
cache-dependency-path: '**/requirements*.txt'
- name: "Cache generated dependencies"
id: schema-cache
uses: actions/cache@v4
with:
path: |
schemas/digital-letters/
output/digital-letters/
src/digital-letters-events/types/
src/digital-letters-events/validators/
src/digital-letters-events/digital_letters_events/models/
Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I suppose once we merge https://github.com/NHSDigital/nhs-notify-digital-letters/pull/254/changes then we need to add also guard-functions

key: generated-deps-${{ runner.os }}-${{ hashFiles('src/cloudevents/**', 'src/typescript-schema-generator/**', 'src/python-schema-generator/**') }}
- name: "Generate dependencies"
if: steps.schema-cache.outputs.cache-hit != 'true'
run: |
npm run generate-dependencies
- name: "Run unit test suite"
run: |
make test-unit
Expand Down
3 changes: 3 additions & 0 deletions .gitignore
Original file line number Diff line number Diff line change
Expand Up @@ -59,3 +59,6 @@ coverage-*/
**/playwright-report
**/test-results
plugin-cache

# Generated by npm run test:unit:parallel — do not commit
jest.config.cjs
Original file line number Diff line number Diff line change
Expand Up @@ -12,7 +12,10 @@ import { IAccessTokenRepository, NotifyClient } from 'app/notify-api-client';
import { RequestAlreadyReceivedError } from 'domain/request-already-received-error';

jest.mock('utils');
jest.mock('node:crypto');
jest.mock('node:crypto', () => ({
...jest.requireActual<typeof import('node:crypto')>('node:crypto'),
randomUUID: jest.fn(),
}));
jest.mock('axios', () => {
const original: AxiosStatic = jest.requireActual('axios');

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -9,7 +9,10 @@ import { PDMResourceAvailable } from 'digital-letters-events';
import { randomUUID } from 'node:crypto';

jest.mock('utils');
jest.mock('node:crypto');
jest.mock('node:crypto', () => ({
...jest.requireActual<typeof import('node:crypto')>('node:crypto'),
randomUUID: jest.fn(),
}));

const mockLogger = jest.mocked(logger);
const mockRandomUUID = jest.mocked(randomUUID);
Expand Down
1 change: 1 addition & 0 deletions lambdas/mesh-acknowledge/pytest.ini
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,7 @@ addopts = -v --tb=short

[coverage:run]
relative_files = True
data_file = lambdas/mesh-acknowledge/.coverage
omit =
*/mesh_acknowledge/__tests__/*
*/test_*.py
Expand Down
1 change: 1 addition & 0 deletions lambdas/mesh-download/pytest.ini
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,7 @@ addopts = -v --tb=short

[coverage:run]
relative_files = True
data_file = lambdas/mesh-download/.coverage
omit =
*/tests/*
*/test_*.py
Expand Down
1 change: 1 addition & 0 deletions lambdas/mesh-poll/pytest.ini
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,7 @@ addopts = -v --tb=short

[coverage:run]
relative_files = True
data_file = lambdas/mesh-poll/.coverage
omit =
*/mesh_poll/__tests__/*
*/test_*.py
Expand Down
1 change: 1 addition & 0 deletions lambdas/report-sender/pytest.ini
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,7 @@ addopts = -v --tb=short

[coverage:run]
relative_files = True
data_file = lambdas/report-sender/.coverage
omit =
*/report_sender/__tests__/*
*/test_*.py
Expand Down
1 change: 1 addition & 0 deletions package.json
Original file line number Diff line number Diff line change
Expand Up @@ -54,6 +54,7 @@
"lint:fix": "npm run lint:fix --workspaces",
"start": "npm run start --workspace frontend",
"test:unit": "npm run test:unit --workspaces",
"test:unit:parallel": "tsx scripts/generate-parallel-jest-config.ts && cross-env NODE_OPTIONS=\"$NODE_OPTIONS --experimental-vm-modules\" jest --config jest.config.cjs",
"typecheck": "npm run typecheck --workspaces"
},
"version": "0.0.1",
Expand Down
153 changes: 153 additions & 0 deletions scripts/generate-parallel-jest-config.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,153 @@
/**
* Generates jest.config.cjs from the individual workspace jest.config.ts files.
*/

import { execFileSync } from 'node:child_process';
import * as fs from 'node:fs';
import * as os from 'node:os';
import * as path from 'node:path';

const repoRoot = path.resolve(__dirname, '..');
const outputPath = path.join(repoRoot, 'jest.config.cjs');

interface PackageJson {
workspaces?: string[];
}

const rootPkg = JSON.parse(
fs.readFileSync(path.join(repoRoot, 'package.json'), 'utf8'),
) as PackageJson;

const workspaces: string[] = rootPkg.workspaces ?? [];

/**
* Inline TypeScript written to a temp .ts file and executed by tsx so each
* workspace jest.config.ts is evaluated in an isolated Node process with a
* fresh module registry (preventing shared mutable baseJestConfig state).
*/
const EVALUATOR = (configPath: string): string => `
import config from ${JSON.stringify(configPath)};
process.stdout.write(JSON.stringify(config));
`;

/** Serialise a plain JS value to source code, indented with the given prefix. */
function serialise(value: unknown, indent = ' '): string {
if (value === null) return 'null';
if (value === undefined) return 'undefined';
if (typeof value === 'string') return JSON.stringify(value);
if (typeof value === 'number' || typeof value === 'boolean')
return String(value);

if (Array.isArray(value)) {
if (value.length === 0) return '[]';
const items = value
.map((v) => `${indent} ${serialise(v, indent + ' ')}`)
.join(',\n');
return `[\n${items},\n${indent}]`;
}

if (typeof value === 'object') {
const entries = Object.entries(value as Record<string, unknown>).filter(
([, v]) => v !== undefined,
);
if (entries.length === 0) return '{}';
const lines = entries
.map(
([k, v]) =>
`${indent} ${JSON.stringify(k)}: ${serialise(v, indent + ' ')}`,
)
.join(',\n');
return `{\n${lines},\n${indent}}`;
}

return String(value);
}

interface ProjectEntry {
workspace: string;
config: Record<string, unknown>;
}

function main(): void {
const projects: ProjectEntry[] = [];

for (const ws of workspaces) {
const wsDir = path.join(repoRoot, ws);

const hasCjs = fs.existsSync(path.join(wsDir, 'jest.config.cjs'));
const hasTs = fs.existsSync(path.join(wsDir, 'jest.config.ts'));

if (hasCjs && !hasTs) {
throw new Error(
`${ws} has jest.config.cjs but no jest.config.ts. ` +
`Migrate it to jest.config.ts so the generator can handle it uniformly.`,
);
}

if (!hasTs) {
// No Jest config → no Jest tests (e.g. src/digital-letters-events)
continue;
}

// Evaluate the workspace config in an isolated tsx subprocess so that the
// shared mutable `baseJestConfig` object is freshly initialised for every
// workspace. Dynamic import() in the parent process would share the cached
// module instance and accumulate mutations.
const configPath = path.join(wsDir, 'jest.config.ts');
const tsxBin = path.join(repoRoot, 'node_modules', '.bin', 'tsx');
const tmpFile = path.join(os.tmpdir(), `jest-config-eval-${Date.now()}.ts`);
let json: string;
try {
fs.writeFileSync(tmpFile, EVALUATOR(configPath), 'utf8');
json = execFileSync(tsxBin, [tmpFile], {
cwd: repoRoot,
encoding: 'utf8',
});
} finally {
fs.rmSync(tmpFile, { force: true });
}
const wsConfig = JSON.parse(json) as Record<string, unknown>;

// Inject rootDir and displayName. Jest resolves all relative paths inside a
// project entry relative to that project's rootDir.
const entry: Record<string, unknown> = {
...wsConfig,
rootDir: `<rootDir>/${ws}`,
displayName: ws,
};

projects.push({ workspace: ws, config: entry });
}

// Build the projects array source
const projectLines = projects.map((p) => {
const body = serialise(p.config, ' ');
return ` // ${p.workspace}\n ${body}`;
});

const banner = `/**
* Root Jest config — runs all TypeScript workspace test suites in
* parallel via Jest's native \`projects\` support.
*
* ⚠️ THIS FILE IS AUTO-GENERATED. Do not edit it directly.
*
* Generated by scripts/generate-parallel-jest-config.ts
*/

/** @type {import('jest').Config} */
module.exports = {
projects: [
${projectLines.join(',\n\n')}
],
};
`;

fs.writeFileSync(outputPath, banner, 'utf8');
console.log(`Written: ${path.relative(repoRoot, outputPath)}`);
console.log(` ${projects.length} project(s) included`);
for (const p of projects) {
console.log(` ${p.workspace}`);
}
}

main();
Loading
Loading