-
Notifications
You must be signed in to change notification settings - Fork 12
Expand file tree
/
Copy pathcontrollerSetup.ts
More file actions
293 lines (264 loc) · 10.9 KB
/
controllerSetup.ts
File metadata and controls
293 lines (264 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
// Add debug logging for tests
import debugModule from 'debug';
import { emptyDir, ensureDir, pathExists, readFile, unlink, writeFile, writeJSON } from 'fs-extra';
import { Socket } from 'node:net';
import * as path from 'node:path';
import { getAdapterName, getAppName } from '../../../lib/adapterTools';
import { executeCommand } from '../../../lib/executeCommand';
import type { DBConnection } from './dbConnection';
import { getTestAdapterDir, getTestControllerDir, getTestDBDir, getTestDataDir, getTestLogDir } from './tools';
const debug = debugModule('testing:integration:ControllerSetup');
export class ControllerSetup {
public constructor(
private adapterDir: string,
private testDir: string,
) {
debug('Creating ControllerSetup...');
this.adapterName = getAdapterName(this.adapterDir);
this.appName = getAppName(this.adapterDir);
this.testAdapterDir = getTestAdapterDir(this.adapterDir, this.testDir);
this.testControllerDir = getTestControllerDir(this.appName, this.testDir);
this.testDataDir = getTestDataDir(this.appName, this.testDir);
debug(` directories:`);
debug(` controller: ${this.testControllerDir}`);
debug(` adapter: ${this.testAdapterDir}`);
debug(` data: ${this.testDataDir}`);
debug(` appName: ${this.appName}`);
debug(` adapterName: ${this.adapterName}`);
}
private appName: string;
private adapterName: string;
private testAdapterDir: string;
private testControllerDir: string;
private testDataDir: string;
/**
* Gets the path to the file that tracks the installed controller version
*/
private getControllerVersionFilePath(): string {
return path.join(this.testDir, '.controller-version');
}
/**
* Reads the currently installed controller version from the tracking file
*/
private async getInstalledControllerVersion(): Promise<string | null> {
const versionFilePath = this.getControllerVersionFilePath();
if (await pathExists(versionFilePath)) {
try {
const version = await readFile(versionFilePath, 'utf8');
return version.trim();
} catch (error) {
debug(`Failed to read controller version file: ${String(error)}`);
return null;
}
}
return null;
}
/**
* Saves the controller version to the tracking file
*/
private async saveControllerVersion(version: string): Promise<void> {
const versionFilePath = this.getControllerVersionFilePath();
await writeFile(versionFilePath, version, 'utf8');
}
/**
* Clears the tmp directory when switching controller versions
*/
private async clearTmpDirectory(): Promise<void> {
debug('Clearing tmp directory for controller version switch...');
// Clear the node_modules directory
const nodeModulesPath = path.join(this.testDir, 'node_modules');
if (await pathExists(nodeModulesPath)) {
await emptyDir(nodeModulesPath);
}
// Clear the data directory
if (await pathExists(this.testDataDir)) {
await emptyDir(this.testDataDir);
}
debug(' => tmp directory cleared!');
}
public async prepareTestDir(controllerVersion: string = 'dev'): Promise<void> {
debug(`Preparing the test directory. JS-Controller version: "${controllerVersion}"...`);
// Make sure the test dir exists
await ensureDir(this.testDir);
// Check if the controller version has changed
const installedVersion = await this.getInstalledControllerVersion();
if (installedVersion && installedVersion !== controllerVersion) {
debug(`Controller version changed from "${installedVersion}" to "${controllerVersion}"`);
await this.clearTmpDirectory();
}
// Write the package.json
const packageJson = {
name: path.basename(this.testDir),
version: '1.0.0',
main: 'index.js',
scripts: {
test: 'echo "Error: no test specified" && exit 1',
},
keywords: [],
author: '',
license: 'ISC',
dependencies: {
[`${this.appName}.js-controller`]: controllerVersion,
},
description: '',
};
await writeJSON(path.join(this.testDir, 'package.json'), packageJson, {
spaces: 2,
});
// Delete a possible package-lock.json as it can mess with future installations
const pckLockPath = path.join(this.testDir, 'package-lock.json');
if (await pathExists(pckLockPath)) {
await unlink(pckLockPath);
}
// Set the engineStrict flag on new Node.js versions to be in line with newer ioBroker installations
const nodeMajorVersion = parseInt(process.versions.node.split('.')[0], 10);
if (nodeMajorVersion >= 10) {
await writeFile(path.join(this.testDir, '.npmrc'), 'engine-strict=true', 'utf8');
}
// Remember if JS-Controller is installed already. If so, we need to call `setup first` afterwards
const wasJsControllerInstalled = await this.isJsControllerInstalled();
// Defer to npm to install the controller (if it wasn't already)
debug('(Re-)installing JS Controller...');
await executeCommand('npm', ['i', '--omit=dev'], {
cwd: this.testDir,
stderr: 'pipe',
});
// Prepare/clean the databases and config
if (wasJsControllerInstalled) {
await this.setupJsController();
}
// Save the controller version for future reference
await this.saveControllerVersion(controllerVersion);
debug(' => done!');
}
/**
* Tests if JS-Controller is already installed
*/
async isJsControllerInstalled(): Promise<boolean> {
debug('Testing if JS-Controller is installed...');
// We expect js-controller to be installed if the dir in <testDir>/node_modules and the data directory exist
const isInstalled = (await pathExists(this.testControllerDir)) && (await pathExists(this.testDataDir));
debug(` => ${isInstalled}`);
return isInstalled;
}
/**
* Tests if an instance of JS-Controller is already running by attempting to connect to the Objects DB
*/
public isJsControllerRunning(): Promise<boolean> {
debug('Testing if JS-Controller is running...');
return new Promise<boolean>(resolve => {
const client = new Socket();
const timeout = setTimeout(() => {
// Assume the connection failed after 1 s
client.destroy();
debug(` => false`);
resolve(false);
}, 1000);
// Try to connect to an existing ObjectsDB
client
.connect({
port: 9000,
host: '127.0.0.1',
})
.on('connect', () => {
// The connection succeeded
client.destroy();
debug(` => true`);
clearTimeout(timeout);
resolve(true);
})
.on('error', () => {
client.destroy();
debug(` => false`);
clearTimeout(timeout);
resolve(false);
});
});
}
// /**
// * Installs a new instance of JS-Controller into the test directory
// * @param appName The branded name of "iobroker"
// * @param testDir The directory the integration tests are executed in
// */
// public async installJsController(): Promise<void> {
// debug("Installing newest JS-Controller from github...");
// // First npm install the JS-Controller into the correct directory
// const installUrl = `${this.appName}/${this.appName}.js-controller`;
// const installResult = await executeCommand(
// "npm",
// ["i", installUrl, "--save"],
// {
// cwd: this.testDir,
// },
// );
// if (installResult.exitCode !== 0)
// throw new Error("JS-Controller could not be installed!");
// debug(" => done!");
// }
/**
* Sets up an existing JS-Controller instance for testing by executing "iobroker setup first"
*/
async setupJsController(): Promise<void> {
debug('Initializing JS-Controller installation...');
// Stop the controller before calling setup first
await executeCommand('node', [`${this.appName}.js`, 'stop'], {
cwd: this.testControllerDir,
stdout: 'ignore',
stderr: 'pipe',
});
const setupResult = await executeCommand('node', [`${this.appName}.js`, 'setup', 'first', '--console'], {
cwd: this.testControllerDir,
stdout: 'ignore',
stderr: 'pipe',
});
if (setupResult.exitCode !== 0) {
const errorMessage = setupResult.stderr
? `${this.appName} setup first failed!\nstderr: ${setupResult.stderr}`
: `${this.appName} setup first failed!`;
throw new Error(errorMessage);
}
debug(' => done!');
}
/**
* Changes the objects and states db to use alternative ports
*/
public setupSystemConfig(dbConnection: DBConnection): void {
debug(`Moving databases to different ports...`);
const systemConfig = dbConnection.getSystemConfig();
systemConfig.objects.port = 19001;
systemConfig.states.port = 19000;
dbConnection.setSystemConfig(systemConfig);
debug(' => done!');
}
/**
* Clears the log dir for integration tests (and creates it if it doesn't exist)
*/
public clearLogDir(): Promise<void> {
debug('Cleaning log directory...');
return emptyDir(getTestLogDir(this.appName, this.testDir));
}
/**
* Clears the sqlite DB dir for integration tests (and creates it if it doesn't exist)
*/
public clearDBDir(): Promise<void> {
debug('Cleaning SQLite directory...');
return emptyDir(getTestDBDir(this.appName, this.testDir));
}
/**
* Disables all admin instances in the objects DB
*/
public async disableAdminInstances(dbConnection: DBConnection): Promise<void> {
debug('Disabling admin instances...');
const instanceObjects = await dbConnection.getObjectViewAsync('system', 'instance', {
startkey: 'system.adapter.admin.',
endkey: 'system.adapter.admin.\u9999',
});
for (const { id, value: obj } of instanceObjects.rows) {
if (obj && obj.common) {
obj.common.enabled = false;
await dbConnection.setObject(id, obj);
}
}
debug(' => done!');
}
}