-
-
Notifications
You must be signed in to change notification settings - Fork 430
/
Copy pathnode-test-bindings.ts
326 lines (309 loc) · 11.2 KB
/
node-test-bindings.ts
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
322
323
324
325
326
import {
Disposable,
DisposableCollection,
} from '@theia/core/lib/common/disposable';
import { EnvVariablesServer as TheiaEnvVariablesServer } from '@theia/core/lib/common/env-variables';
import { waitForEvent } from '@theia/core/lib/common/promise-util';
import URI from '@theia/core/lib/common/uri';
import { FileUri } from '@theia/core/lib/common/file-uri';
import { ProcessUtils } from '@theia/core/lib/node/process-utils';
import {
Container,
ContainerModule,
injectable,
interfaces,
} from '@theia/core/shared/inversify';
import deepmerge from 'deepmerge';
import { dump as dumpYaml } from 'js-yaml';
import { mkdirSync, promises as fs } from 'node:fs';
import { join } from 'node:path';
import { path as tempPath, track } from 'temp';
import {
ArduinoDaemon,
BoardsPackage,
BoardsService,
ConfigService,
ConfigState,
CoreService,
DetectedPorts,
IndexUpdateDidCompleteParams,
IndexUpdateDidFailParams,
IndexUpdateParams,
LibraryPackage,
LibraryService,
NotificationServiceClient,
NotificationServiceServer,
OutputMessage,
ProgressMessage,
ResponseService,
Sketch,
SketchesService,
} from '../../common/protocol';
import { ArduinoDaemonImpl } from '../../node/arduino-daemon-impl';
import { BoardDiscovery } from '../../node/board-discovery';
import { BoardsServiceImpl } from '../../node/boards-service-impl';
import { CliConfig, CLI_CONFIG, DefaultCliConfig } from '../../node/cli-config';
import { ConfigServiceImpl } from '../../node/config-service-impl';
import { CoreClientProvider } from '../../node/core-client-provider';
import { CoreServiceImpl } from '../../node/core-service-impl';
import { IsTempSketch } from '../../node/is-temp-sketch';
import { LibraryServiceImpl } from '../../node/library-service-impl';
import { MonitorManager } from '../../node/monitor-manager';
import { MonitorService } from '../../node/monitor-service';
import {
MonitorServiceFactory,
MonitorServiceFactoryOptions,
} from '../../node/monitor-service-factory';
import { SettingsReader } from '../../node/settings-reader';
import { SketchesServiceImpl } from '../../node/sketches-service-impl';
import {
ConfigDirUriProvider,
EnvVariablesServer,
} from '../../node/theia/env-variables/env-variables-server';
import { bindCommon } from '../common/common-test-bindings';
const tracked = track();
@injectable()
class SilentArduinoDaemon extends ArduinoDaemonImpl {
protected override onData(): void {
// NOOP
}
}
@injectable()
class TestBoardDiscovery extends BoardDiscovery {
mutableDetectedPorts: DetectedPorts = {};
override async start(): Promise<void> {
// NOOP
}
override async stop(): Promise<void> {
// NOOP
}
override get detectedPorts(): DetectedPorts {
return this.mutableDetectedPorts;
}
}
@injectable()
class TestNotificationServiceServer implements NotificationServiceServer {
readonly events: string[] = [];
// eslint-disable-next-line @typescript-eslint/no-unused-vars, unused-imports/no-unused-vars
disposeClient(client: NotificationServiceClient): void {
this.events.push('disposeClient:');
}
notifyDidReinitialize(): void {
this.events.push('notifyDidReinitialize:');
}
notifyIndexUpdateWillStart(params: IndexUpdateParams): void {
this.events.push(`notifyIndexUpdateWillStart:${JSON.stringify(params)}`);
}
notifyIndexUpdateDidProgress(progressMessage: ProgressMessage): void {
this.events.push(
`notifyIndexUpdateDidProgress:${JSON.stringify(progressMessage)}`
);
}
notifyIndexUpdateDidComplete(params: IndexUpdateDidCompleteParams): void {
this.events.push(`notifyIndexUpdateDidComplete:${JSON.stringify(params)}`);
}
notifyIndexUpdateDidFail(params: IndexUpdateDidFailParams): void {
this.events.push(`notifyIndexUpdateDidFail:${JSON.stringify(params)}`);
}
notifyDaemonDidStart(port: number): void {
this.events.push(`notifyDaemonDidStart:${port}`);
}
notifyDaemonDidStop(): void {
this.events.push('notifyDaemonDidStop:');
}
notifyConfigDidChange(event: ConfigState): void {
this.events.push(`notifyConfigDidChange:${JSON.stringify(event)}`);
}
notifyPlatformDidInstall(event: { item: BoardsPackage }): void {
this.events.push(`notifyPlatformDidInstall:${JSON.stringify(event)}`);
}
notifyPlatformDidUninstall(event: { item: BoardsPackage }): void {
this.events.push(`notifyPlatformDidUninstall:${JSON.stringify(event)}`);
}
notifyLibraryDidInstall(event: {
item: LibraryPackage | 'zip-install';
}): void {
this.events.push(`notifyLibraryDidInstall:${JSON.stringify(event)}`);
}
notifyLibraryDidUninstall(event: { item: LibraryPackage }): void {
this.events.push(`notifyLibraryDidUninstall:${JSON.stringify(event)}`);
}
notifyDetectedPortsDidChange(event: { detectedPorts: DetectedPorts }): void {
this.events.push(`notifyAttachedBoardsDidChange:${JSON.stringify(event)}`);
}
notifyRecentSketchesDidChange(event: { sketches: Sketch[] }): void {
this.events.push(`notifyRecentSketchesDidChange:${JSON.stringify(event)}`);
}
dispose(): void {
this.events.push('dispose:');
}
// eslint-disable-next-line @typescript-eslint/no-unused-vars, unused-imports/no-unused-vars
setClient(client: NotificationServiceClient | undefined): void {
this.events.push('setClient:');
}
}
@injectable()
class TestResponseService implements ResponseService {
readonly outputMessages: OutputMessage[] = [];
readonly progressMessages: ProgressMessage[] = [];
appendToOutput(message: OutputMessage): void {
this.outputMessages.push(message);
}
reportProgress(message: ProgressMessage): void {
this.progressMessages.push(message);
}
}
class TestConfigDirUriProvider extends ConfigDirUriProvider {
constructor(private readonly configDirPath: string) {
super();
}
override configDirUri(): URI {
return FileUri.create(this.configDirPath);
}
}
function shouldKeepTestFolder(): boolean {
return (
typeof process.env.ARDUINO_IDE__KEEP_TEST_FOLDER === 'string' &&
/true/i.test(process.env.ARDUINO_IDE__KEEP_TEST_FOLDER)
);
}
export function newTempConfigDirPath(
prefix = 'arduino-ide--slow-tests'
): string {
let tempDirPath;
if (shouldKeepTestFolder()) {
tempDirPath = tempPath(prefix);
mkdirSync(tempDirPath, { recursive: true });
console.log(
`Detected ARDUINO_IDE__KEEP_TEST_FOLDER=true, keeping temporary test configuration folders: ${tempDirPath}`
);
} else {
tempDirPath = tracked.mkdirSync();
}
return join(tempDirPath, '.testArduinoIDE');
}
interface CreateBaseContainerParams {
readonly cliConfig?: CliConfig | (() => Promise<CliConfig>);
readonly configDirPath?: string;
readonly additionalBindings?: (
bind: interfaces.Bind,
rebind: interfaces.Rebind
) => void;
}
export async function createBaseContainer(
params?: CreateBaseContainerParams
): Promise<Container> {
const configDirUriProvider = new TestConfigDirUriProvider(
params?.configDirPath || newTempConfigDirPath()
);
if (params?.cliConfig) {
const config =
typeof params.cliConfig === 'function'
? await params.cliConfig()
: params.cliConfig;
await writeCliConfigFile(
FileUri.fsPath(configDirUriProvider.configDirUri()),
config
);
}
const container = new Container({ defaultScope: 'Singleton' });
const module = new ContainerModule((bind, unbind, isBound, rebind) => {
bindCommon(bind, unbind, isBound, rebind);
bind(CoreClientProvider).toSelf().inSingletonScope();
bind(CoreServiceImpl).toSelf().inSingletonScope();
bind(CoreService).toService(CoreServiceImpl);
bind(BoardsServiceImpl).toSelf().inSingletonScope();
bind(BoardsService).toService(BoardsServiceImpl);
bind(TestResponseService).toSelf().inSingletonScope();
bind(ResponseService).toService(TestResponseService);
bind(MonitorManager).toSelf().inSingletonScope();
bind(MonitorServiceFactory).toFactory(
({ container }) =>
(options: MonitorServiceFactoryOptions) => {
const child = container.createChild();
child
.bind<MonitorServiceFactoryOptions>(MonitorServiceFactoryOptions)
.toConstantValue({
...options,
});
child.bind(MonitorService).toSelf();
return child.get<MonitorService>(MonitorService);
}
);
bind(ConfigDirUriProvider).toConstantValue(configDirUriProvider);
bind(EnvVariablesServer).toSelf().inSingletonScope();
bind(TheiaEnvVariablesServer).toService(EnvVariablesServer);
bind(SilentArduinoDaemon).toSelf().inSingletonScope();
bind(ArduinoDaemon).toService(SilentArduinoDaemon);
bind(ArduinoDaemonImpl).toService(SilentArduinoDaemon);
bind(TestNotificationServiceServer).toSelf().inSingletonScope();
bind(NotificationServiceServer).toService(TestNotificationServiceServer);
bind(ConfigServiceImpl).toSelf().inSingletonScope();
bind(ConfigService).toService(ConfigServiceImpl);
bind(TestBoardDiscovery).toSelf().inSingletonScope();
bind(BoardDiscovery).toService(TestBoardDiscovery);
bind(IsTempSketch).toSelf().inSingletonScope();
bind(SketchesServiceImpl).toSelf().inSingletonScope();
bind(SketchesService).toService(SketchesServiceImpl);
bind(SettingsReader).toSelf().inSingletonScope();
bind(LibraryServiceImpl).toSelf().inSingletonScope();
bind(LibraryService).toService(LibraryServiceImpl);
bind(ProcessUtils).toSelf().inSingletonScope();
params?.additionalBindings?.(bind, rebind);
});
container.load(module);
return container;
}
async function writeCliConfigFile(
containerFolderPath: string,
cliConfig: CliConfig
): Promise<void> {
await fs.mkdir(containerFolderPath, { recursive: true });
const yaml = dumpYaml(cliConfig);
const cliConfigPath = join(containerFolderPath, CLI_CONFIG);
await fs.writeFile(cliConfigPath, yaml);
console.debug(`Created CLI configuration file at ${cliConfigPath}:
${yaml}
`);
}
export async function createCliConfig(
configDirPath: string,
configOverrides: Partial<DefaultCliConfig> = {}
): Promise<DefaultCliConfig> {
const directories = {
data: join(configDirPath, 'data', 'Arduino15'),
downloads: join(configDirPath, 'data', 'Arduino15', 'staging'),
user: join(configDirPath, 'user', 'Arduino'),
};
for (const directoryPath of Object.values(directories)) {
await fs.mkdir(directoryPath, { recursive: true });
}
const config = { directories };
const mergedOverrides = deepmerge(configOverrides, <DefaultCliConfig>{
logging: { level: 'trace' },
});
return deepmerge(config, mergedOverrides);
}
export async function startDaemon(
container: Container,
toDispose: DisposableCollection,
startCustomizations?: (
container: Container,
toDispose: DisposableCollection
) => Promise<void>
): Promise<void> {
const daemon = container.get<ArduinoDaemonImpl>(ArduinoDaemonImpl);
const configService = container.get<ConfigServiceImpl>(ConfigServiceImpl);
const coreClientProvider =
container.get<CoreClientProvider>(CoreClientProvider);
toDispose.push(Disposable.create(() => daemon.stop()));
configService.onStart();
daemon.onStart();
await Promise.all([
waitForEvent(daemon.onDaemonStarted, 20_000),
coreClientProvider.client,
]);
if (startCustomizations) {
await startCustomizations(container, toDispose);
}
}