-
-
Notifications
You must be signed in to change notification settings - Fork 205
Expand file tree
/
Copy pathpass-through.service.spec.ts
More file actions
321 lines (285 loc) · 10.9 KB
/
pass-through.service.spec.ts
File metadata and controls
321 lines (285 loc) · 10.9 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
import { Test } from '@nestjs/testing';
import chalk from 'chalk';
import { Command, createCommand } from 'commander';
import { COMMANDER_PROGRAM, LOGGER } from '../constants';
import { GeneratorService } from './generator.service';
import { PassThroughService } from './pass-through.service';
import { VersionManagerService } from './version-manager.service';
import { ConfigService } from './config.service';
jest.mock('child_process');
// eslint-disable-next-line @typescript-eslint/no-var-requires
import childProcessImport from 'child_process';
const childProcess = jest.mocked(childProcessImport);
describe('PassThroughService', () => {
let fixture: PassThroughService;
let program: Command;
const log = jest.fn();
const generate = jest.fn().mockResolvedValue(true);
const getSelectedVersion = jest.fn().mockReturnValue('4.2.1');
const filePath = jest.fn().mockReturnValue(`/some/path/to/4.2.1.jar`);
const configServiceMock = {
useDocker: false,
get: jest.fn(),
cwd: '/foo/bar',
};
const getCommand = (name: string) =>
program.commands.find((c) => c.name() === name);
beforeEach(async () => {
program = createCommand();
jest.spyOn(program, 'helpInformation');
const moduleRef = await Test.createTestingModule({
providers: [
PassThroughService,
{
provide: VersionManagerService,
useValue: {
filePath,
getSelectedVersion,
getDockerImageName: (v) =>
`openapitools/openapi-generator-cli:v${
v || getSelectedVersion()
}`,
},
},
{ provide: GeneratorService, useValue: { generate, enabled: true } },
{ provide: ConfigService, useValue: configServiceMock },
{ provide: COMMANDER_PROGRAM, useValue: program },
{ provide: LOGGER, useValue: { log } },
],
}).compile();
fixture = moduleRef.get(PassThroughService);
childProcess.spawn.mockReset().mockReturnValue({ on: jest.fn() });
configServiceMock.get.mockClear();
configServiceMock.get.mockReset();
configServiceMock.useDocker = false;
});
describe('API', () => {
describe('init', () => {
describe('the help command failed', () => {
let error: Error;
beforeEach(async () => {
childProcess.exec.mockImplementation((cmd: string, cb) =>
cb(true, undefined, 'Some error')
);
try {
await fixture.init();
} catch (e) {
error = e;
}
});
it('throws the error', () => {
expect(error.message).toEqual('Some error');
});
it('adds no commands', () => {
expect(program.commands).toHaveLength(0);
});
});
describe('the help command works', () => {
const helpText = [
'usage: openapi-generator-cli <command> [<args>]',
'',
'The most commonly used openapi-generator-cli commands are:',
' author Utilities for authoring generators or customizing templates.',
' config-help Config help for chosen lang',
' generate Generate code with the specified generator.',
' help Display help information about openapi-generator',
' list Lists the available generators',
' meta MetaGenerator. Generator for creating a new template set and configuration for Codegen. The output will be based on the language you specify, and includes default templates to include.',
' validate Validate specification',
' version Show version information used in tooling',
'',
`See 'openapi-generator-cli help <command>' for more information on a specific`,
'command.',
].join('\n');
const completionText = [
' list',
' generate',
' meta',
' help',
' config-help',
' validate',
' version',
' completion',
' batch',
' --version',
' --help',
].join('\n');
beforeEach(async () => {
childProcess.exec.mockImplementation((cmd: string, cb) => {
if (cmd.endsWith('"/some/path/to/4.2.1.jar" help')) {
cb(undefined, helpText);
}
if (cmd.endsWith('"/some/path/to/4.2.1.jar" completion')) {
cb(undefined, completionText);
}
});
await fixture.init();
});
it('adds 10 commands', () => {
expect(program.commands).toHaveLength(10);
});
describe.each([
[
'author',
'Utilities for authoring generators or customizing templates.',
],
['config-help', 'Config help for chosen lang'],
['generate', 'Generate code with the specified generator.'],
['help', 'Display help information about openapi-generator'],
['list', 'Lists the available generators'],
[
'meta',
'MetaGenerator. Generator for creating a new template set and configuration for Codegen. The output will be based on the language you specify, and includes default templates to include.',
],
['validate', 'Validate specification'],
['version', 'Show version information used in tooling'],
['batch', ''],
['completion', ''],
])('%s', (name, desc) => {
let cmd: Command;
const argv = ['foo', 'baz'];
beforeEach(() => {
cmd = getCommand(name);
delete process.env['JAVA_OPTS'];
});
it('adds the correct description', () => {
expect(cmd.description()).toEqual(desc);
});
it('allows unknown options', () => {
expect(cmd['_allowUnknownOption']).toBeTruthy();
});
describe('useDocker is true', () => {
beforeEach(() => {
configServiceMock.useDocker = true;
});
it('delegates to docker', async () => {
await program.parseAsync([name, ...argv], { from: 'user' });
expect(childProcess.spawn).toHaveBeenNthCalledWith(
1,
'docker run --rm -v "/foo/bar:/local" openapitools/openapi-generator-cli:v4.2.1',
[name, ...argv],
{
stdio: 'inherit',
shell: true,
}
);
});
});
it('can delegate', async () => {
await program.parseAsync([name, ...argv], { from: 'user' });
expect(childProcess.spawn).toHaveBeenNthCalledWith(
1,
'java -jar "/some/path/to/4.2.1.jar"',
[name, ...argv],
{
stdio: 'inherit',
shell: true,
}
);
});
it('can delegate with JAVA_OPTS', async () => {
process.env['JAVA_OPTS'] = 'java-opt-1=1';
await program.parseAsync([name, ...argv], { from: 'user' });
expect(childProcess.spawn).toHaveBeenNthCalledWith(
1,
'java java-opt-1=1 -jar "/some/path/to/4.2.1.jar"',
[name, ...argv],
{
stdio: 'inherit',
shell: true,
}
);
});
it('can delegate with custom jar', async () => {
await program.parseAsync(
[name, ...argv, '--custom-generator=../some/custom.jar'],
{ from: 'user' }
);
const cpDelimiter = process.platform === 'win32' ? ';' : ':';
expect(childProcess.spawn).toHaveBeenNthCalledWith(
1,
`java -cp "${[
'/some/path/to/4.2.1.jar',
'../some/custom.jar',
].join(cpDelimiter)}" org.openapitools.codegen.OpenAPIGenerator`,
[name, ...argv],
{
stdio: 'inherit',
shell: true,
}
);
});
if (name === 'generate') {
it('can delegate with custom jar to generate command', async () => {
await program.parseAsync(
[
name,
...argv,
'--generator-key=genKey',
'--custom-generator=../some/custom.jar',
],
{ from: 'user' }
);
expect(generate).toHaveBeenNthCalledWith(
1,
'../some/custom.jar',
'genKey'
);
});
}
});
describe('command behavior', () => {
describe('help', () => {
const programHelp = () =>
chalk.cyanBright(program.helpInformation());
const commandHelp = (name: string) => () =>
chalk.cyanBright(getCommand(name).helpInformation());
describe.each`
cmd | helpText | spawn
${'help'} | ${programHelp} | ${undefined}
${'help generate'} | ${commandHelp('generate')} | ${'a'}
${'help author'} | ${commandHelp('author')} | ${'b'}
${'help hidden'} | ${undefined} | ${'c'}
`('$cmd', ({ cmd, helpText, spawn }) => {
let spy: jest.SpyInstance;
beforeEach(async () => {
spy = jest
.spyOn(console, 'log')
.mockClear()
.mockImplementation();
await program.parseAsync(cmd.split(' '), { from: 'user' });
});
describe('help text', () => {
it(`logs ${helpText ? 1 : 0} times`, () => {
expect(spy).toHaveBeenCalledTimes(helpText ? 1 : 0);
});
// eslint-disable-next-line @typescript-eslint/no-unused-expressions
helpText &&
it('prints the correct help text', () => {
expect(spy).toHaveBeenCalledWith(helpText());
});
});
describe('process spawn', () => {
it(`spawns ${spawn ? 1 : 0} times`, () => {
expect(childProcess.spawn).toHaveBeenCalledTimes(
spawn ? 1 : 0
);
});
// eslint-disable-next-line @typescript-eslint/no-unused-expressions
spawn &&
it('spawns the correct process', () => {
expect(childProcess.spawn).toHaveBeenNthCalledWith(
1,
'java -jar "/some/path/to/4.2.1.jar"',
cmd.split(' '),
{ stdio: 'inherit', shell: true }
);
});
});
});
});
});
});
});
});
});