Skip to content

Commit 9c02cca

Browse files
committed
Fix broken tests
1 parent e7790bb commit 9c02cca

File tree

13 files changed

+143
-34
lines changed

13 files changed

+143
-34
lines changed

lib/buildtools/src/build/__tests__/all.test.ts

Lines changed: 6 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -14,7 +14,7 @@ vi.mock(import('../../getGitRoot.js'));
1414
vi.spyOn(all, 'buildAll');
1515
const mockedBuildBundle = vi.spyOn(modules, 'buildBundle');
1616
const mockedBuildTab = vi.spyOn(modules, 'buildTab');
17-
const mockedBuildJson = vi.spyOn(docs, 'buildSingleBundleDocs');
17+
const mockedBuildSingleBundleDocs = vi.spyOn(docs, 'buildSingleBundleDocs');
1818

1919
const mockedRunTsc = vi.spyOn(tsc, 'runTsc').mockResolvedValue({
2020
severity: Severity.SUCCESS,
@@ -46,7 +46,7 @@ describe('Test the buildAll command', () => {
4646
input: {} as any
4747
});
4848

49-
mockedBuildJson.mockResolvedValueOnce({
49+
mockedBuildSingleBundleDocs.mockResolvedValueOnce({
5050
type: 'docs',
5151
severity: Severity.SUCCESS,
5252
path: '/build/jsons',
@@ -64,7 +64,7 @@ describe('Test the buildAll command', () => {
6464
input: {} as any
6565
});
6666

67-
mockedBuildJson.mockResolvedValueOnce({
67+
mockedBuildSingleBundleDocs.mockResolvedValueOnce({
6868
type: 'docs',
6969
severity: Severity.SUCCESS,
7070
path: '/build/jsons',
@@ -83,7 +83,7 @@ describe('Test the buildAll command', () => {
8383
input: {} as any
8484
});
8585

86-
mockedBuildJson.mockResolvedValueOnce({
86+
mockedBuildSingleBundleDocs.mockResolvedValueOnce({
8787
type: 'docs',
8888
severity: Severity.SUCCESS,
8989
path: '/build/jsons',
@@ -130,7 +130,7 @@ describe('Test the buildAll command', () => {
130130
errors: []
131131
});
132132

133-
mockedBuildJson.mockResolvedValueOnce({
133+
mockedBuildSingleBundleDocs.mockResolvedValueOnce({
134134
type: 'docs',
135135
severity: Severity.SUCCESS,
136136
path: '/build/jsons',
@@ -151,7 +151,7 @@ describe('Test the buildAll command', () => {
151151
input: {} as any
152152
});
153153

154-
mockedBuildJson.mockResolvedValueOnce({
154+
mockedBuildSingleBundleDocs.mockResolvedValueOnce({
155155
type: 'docs',
156156
severity: Severity.ERROR,
157157
errors: [],

lib/buildtools/src/build/docs/index.ts

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -53,12 +53,12 @@ export async function buildSingleBundleDocs(bundle: ResolvedBundle, outDir: stri
5353
return buildJson(bundle, outDir, project);
5454
}
5555

56-
type BuildAllBundleDocsResult = ResultType;
56+
type BuildHtmlResult = ResultType;
5757

5858
/**
5959
* Builds HTML documentation for all bundles. Needs to be run after {@link buildSingleBundleDocs}
6060
*/
61-
export async function buildHtml(bundles: Record<string, ResolvedBundle>, outDir: string, logLevel: td.LogLevel): Promise<BuildAllBundleDocsResult> {
61+
export async function buildHtml(bundles: Record<string, ResolvedBundle>, outDir: string, logLevel: td.LogLevel): Promise<BuildHtmlResult> {
6262
const jsonStats = await mapAsync(Object.values(bundles), async ({ name, directory }) => {
6363
try {
6464
const stats = await fs.stat(`${directory}/dist/docs.json`);
Lines changed: 37 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,37 @@
1+
import { describe, expect, test } from "vitest";
2+
import { Severity } from "../../types.js";
3+
import { processResult } from "../commandUtils.js";
4+
5+
describe('Testing processResults', () => {
6+
const testCases: [any, Severity][] = [
7+
[{ severity: Severity.SUCCESS }, Severity.SUCCESS],
8+
[{ severity: Severity.ERROR }, Severity.ERROR],
9+
[
10+
{
11+
items: [{ severity: Severity.ERROR }, { severity: Severity.SUCCESS }]
12+
},
13+
Severity.ERROR
14+
],
15+
[
16+
{
17+
item1: { severity: Severity.WARN },
18+
item2: {
19+
item3: {},
20+
item4: {
21+
item5: { severity: Severity.WARN },
22+
severity: Severity.ERROR
23+
}
24+
}
25+
},
26+
Severity.ERROR
27+
]
28+
];
29+
30+
test.each(testCases)('%#', (obj, expected) => {
31+
if (expected === Severity.ERROR) {
32+
expect(() => processResult(obj, false)).processExit();
33+
} else {
34+
expect(() => processResult(obj, false)).not.processExit();
35+
}
36+
});
37+
});

lib/buildtools/src/commands/build.ts

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -118,5 +118,5 @@ export const getBuildHtmlCommand = () => new Command('html')
118118

119119
const htmlResult = await buildHtml(resolveResult.bundles, outDir, logLevel);
120120
console.log(formatResult(htmlResult, 'html'));
121-
processResult({ results: htmlResult }, false);
121+
processResult(htmlResult, false);
122122
});

lib/buildtools/src/commands/commandUtils.ts

Lines changed: 21 additions & 16 deletions
Original file line numberDiff line numberDiff line change
@@ -1,9 +1,8 @@
11
import { InvalidArgumentError, Option } from '@commander-js/extra-typings';
22
import chalk from 'chalk';
33
import { LogLevel } from 'typedoc';
4-
import type { LintResult } from '../prebuild/lint.js';
5-
import type { TscResult } from '../prebuild/tsc.js';
6-
import type { ErrorResult, Severity } from '../types.js';
4+
import { Severity, type ErrorResult } from '../types.js';
5+
import { isSeverity } from '../utils.js';
76

87
export const lintOption = new Option('--lint', 'Run ESLint when building')
98
.default(false);
@@ -46,27 +45,33 @@ export function objectKeys<T extends string | number | symbol>(obj: Record<T, un
4645
* are errors, or if there are warnings and `errorOnWarning` has been given as `true`.\
4746
* Mainly intended for use with CI pipelines so that processes can exit with non-zero codes
4847
*/
49-
export function processResult({ results, tsc, lint }: { results?: { severity: Severity }, tsc?: TscResult, lint?: LintResult }, errorOnWarning: boolean) {
50-
const severities: Severity[] = [];
48+
export function processResult(obj: object, errorOnWarning: boolean) {
49+
function* severities(obj: object): Generator<Severity> {
50+
if (obj === null) {
51+
yield Severity.SUCCESS;
52+
return;
53+
}
5154

52-
if (results) {
53-
severities.push(results.severity);
54-
}
55+
if (Array.isArray(obj)) {
56+
for (const item of obj) {
57+
yield* severities(item);
58+
}
5559

56-
if (tsc) {
57-
severities.push(tsc.severity);
58-
}
60+
return;
61+
}
5962

60-
if (lint) {
61-
severities.push(lint.severity);
63+
for (const [key, value] of Object.entries(obj)) {
64+
if (key === 'severity' && isSeverity(value)) yield value;
65+
if (typeof value === 'object') yield* severities(value);
66+
}
6267
}
6368

64-
for (const severity of severities) {
69+
for (const severity of severities(obj)) {
6570
switch (severity) {
66-
case 'warn': {
71+
case Severity.WARN: {
6772
if (!errorOnWarning) continue;
6873
}
69-
case 'error':
74+
case Severity.ERROR:
7075
process.exit(1);
7176
}
7277
}

lib/buildtools/src/prebuild/lint.ts

Lines changed: 4 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -2,7 +2,7 @@ import { promises as fs, type Dirent } from 'fs';
22
import pathlib from 'path';
33
import chalk from 'chalk';
44
import { ESLint } from 'eslint';
5-
import { getGitRoot } from '../getGitRoot.js';
5+
import { getGitRoot, getOutDir } from '../getGitRoot.js';
66
import { Severity, type InputAsset } from '../types.js';
77
import { findSeverity, flatMapAsync, isNodeError } from '../utils.js';
88

@@ -49,13 +49,14 @@ export async function runEslint(input: InputAsset, fix: boolean, stats: boolean)
4949
}
5050

5151
if (stats) {
52-
await fs.mkdir(`${gitRoot}/lintstats`, { recursive: true });
52+
const outDir = await getOutDir();
53+
await fs.mkdir(`${outDir}/lintstats`, { recursive: true });
5354

5455
const statsFormatter = await linter.loadFormatter('json');
5556
const statsFormatted = await statsFormatter.format(linterResults);
5657
const stringified = JSON.stringify(JSON.parse(statsFormatted), null, 2);
5758

58-
await fs.writeFile(`${gitRoot}/lintstats/${input.type}-${input.name}.json`, stringified);
59+
await fs.writeFile(`${outDir}/lintstats/${input.type}-${input.name}.json`, stringified);
5960
}
6061

6162
const outputFormatter = await linter.loadFormatter('stylish');

lib/buildtools/src/utils.ts

Lines changed: 6 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -2,6 +2,12 @@ import { Severity, type ResolvedBundle, type ResolvedTab } from './types.js';
22

33
export type AwaitedReturn<T extends (...args: any[]) => Promise<any>> = Awaited<ReturnType<T>>;
44

5+
export function isSeverity(obj: unknown): obj is Severity {
6+
if (typeof obj !== 'string') return false;
7+
8+
return obj === Severity.ERROR || obj === Severity.WARN || obj === Severity.SUCCESS;
9+
}
10+
511
export function compareSeverity(lhs: Severity, rhs: Severity): Severity {
612
switch (lhs) {
713
case Severity.SUCCESS:

lib/buildtools/vitest.d.ts

Lines changed: 8 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -8,8 +8,14 @@ declare module 'vitest' {
88
commandSuccess: () => Promise<T>
99

1010
/**
11-
* Asserts that process.exit was called with the specified code
11+
* Asserts that process.exit was called with the specified code when the promise resolves
1212
*/
1313
commandExit: (code?: number) => Promise<T>
14+
15+
/**
16+
* Asserts that process.exit was called with the specified code when the
17+
* function is called
18+
*/
19+
processExit: (code?: number) => T
1420
}
15-
}
21+
}

lib/buildtools/vitest.setup.ts

Lines changed: 24 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -3,6 +3,10 @@ import { expect, vi } from 'vitest';
33

44
class MockProcessError extends Error {
55
constructor(public readonly code: number) { super(); }
6+
7+
toString() {
8+
return `process.exit was called with ${this.code}`;
9+
}
610
};
711

812
vi.mock('chalk', () => {
@@ -90,5 +94,25 @@ expect.extend({
9094
message: () => `Command rejected with unexpected error: ${error}`
9195
};
9296
}
97+
},
98+
processExit(received: () => any, expected: number = 1) {
99+
try {
100+
received();
101+
return {
102+
pass: false,
103+
message: () => `Expected function to call process.exit with code ${expected}`
104+
};
105+
} catch (error) {
106+
if (error instanceof MockProcessError) {
107+
return {
108+
pass: error.code === expected,
109+
message: () => `process.exit called with ${expected}`
110+
};
111+
}
112+
return {
113+
pass: false,
114+
message: () => `Function threw an unexpected error: ${error}`
115+
};
116+
}
93117
}
94118
});

lib/markdown-tree/src/__tests__/index.test.ts

Lines changed: 22 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,7 @@
11
import fs from 'fs';
22
import { describe, expect, test, vi } from 'vitest';
33
import { generateStructure } from '../structure';
4+
import { generateTree } from '../tree';
45
import { isRootYamlObject, isYamlObject } from '../types';
56

67
const mockExistsSync = vi.spyOn(fs, 'existsSync');
@@ -50,7 +51,27 @@ describe('Test isRootYamlObject', () => {
5051
});
5152
});
5253

53-
describe('Test structure generation', () => {
54+
test('structure generation', () => {
55+
const [structure, commentLoc, warnings] = generateStructure({
56+
name: 'root',
57+
children: [{
58+
name: 'item1',
59+
comment: 'this is a comment'
60+
},
61+
'item2',
62+
{
63+
name: 'item3',
64+
comment: 'also a comment'
65+
}
66+
]
67+
});
68+
expect(warnings.length).toEqual(0);
69+
expect(generateTree(structure, commentLoc)).toMatchInlineSnapshot(`
70+
"root
71+
├── item1 // this is a comment
72+
├── item2
73+
└── item3 // also a comment"
74+
`);
5475
});
5576

5677
describe('Test tree validation', () => {

0 commit comments

Comments
 (0)