-
Notifications
You must be signed in to change notification settings - Fork 12
Expand file tree
/
Copy pathcontrollerSetup.js
More file actions
298 lines (298 loc) · 12.2 KB
/
controllerSetup.js
File metadata and controls
298 lines (298 loc) · 12.2 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
"use strict";
var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
if (k2 === undefined) k2 = k;
var desc = Object.getOwnPropertyDescriptor(m, k);
if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
desc = { enumerable: true, get: function() { return m[k]; } };
}
Object.defineProperty(o, k2, desc);
}) : (function(o, m, k, k2) {
if (k2 === undefined) k2 = k;
o[k2] = m[k];
}));
var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {
Object.defineProperty(o, "default", { enumerable: true, value: v });
}) : function(o, v) {
o["default"] = v;
});
var __importStar = (this && this.__importStar) || (function () {
var ownKeys = function(o) {
ownKeys = Object.getOwnPropertyNames || function (o) {
var ar = [];
for (var k in o) if (Object.prototype.hasOwnProperty.call(o, k)) ar[ar.length] = k;
return ar;
};
return ownKeys(o);
};
return function (mod) {
if (mod && mod.__esModule) return mod;
var result = {};
if (mod != null) for (var k = ownKeys(mod), i = 0; i < k.length; i++) if (k[i] !== "default") __createBinding(result, mod, k[i]);
__setModuleDefault(result, mod);
return result;
};
})();
var __importDefault = (this && this.__importDefault) || function (mod) {
return (mod && mod.__esModule) ? mod : { "default": mod };
};
Object.defineProperty(exports, "__esModule", { value: true });
exports.ControllerSetup = void 0;
// Add debug logging for tests
const debug_1 = __importDefault(require("debug"));
const fs_extra_1 = require("fs-extra");
const node_net_1 = require("node:net");
const path = __importStar(require("node:path"));
const adapterTools_1 = require("../../../lib/adapterTools");
const executeCommand_1 = require("../../../lib/executeCommand");
const tools_1 = require("./tools");
const debug = (0, debug_1.default)('testing:integration:ControllerSetup');
class ControllerSetup {
constructor(adapterDir, testDir) {
this.adapterDir = adapterDir;
this.testDir = testDir;
debug('Creating ControllerSetup...');
this.adapterName = (0, adapterTools_1.getAdapterName)(this.adapterDir);
this.appName = (0, adapterTools_1.getAppName)(this.adapterDir);
this.testAdapterDir = (0, tools_1.getTestAdapterDir)(this.adapterDir, this.testDir);
this.testControllerDir = (0, tools_1.getTestControllerDir)(this.appName, this.testDir);
this.testDataDir = (0, tools_1.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}`);
}
/**
* Gets the path to the file that tracks the installed controller version
*/
getControllerVersionFilePath() {
return path.join(this.testDir, '.controller-version');
}
/**
* Reads the currently installed controller version from the tracking file
*/
async getInstalledControllerVersion() {
const versionFilePath = this.getControllerVersionFilePath();
if (await (0, fs_extra_1.pathExists)(versionFilePath)) {
try {
const version = await (0, fs_extra_1.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
*/
async saveControllerVersion(version) {
const versionFilePath = this.getControllerVersionFilePath();
await (0, fs_extra_1.writeFile)(versionFilePath, version, 'utf8');
}
/**
* Clears the tmp directory when switching controller versions
*/
async clearTmpDirectory() {
debug('Clearing tmp directory for controller version switch...');
// Clear the node_modules directory
const nodeModulesPath = path.join(this.testDir, 'node_modules');
if (await (0, fs_extra_1.pathExists)(nodeModulesPath)) {
await (0, fs_extra_1.emptyDir)(nodeModulesPath);
}
// Clear the data directory
if (await (0, fs_extra_1.pathExists)(this.testDataDir)) {
await (0, fs_extra_1.emptyDir)(this.testDataDir);
}
debug(' => tmp directory cleared!');
}
async prepareTestDir(controllerVersion = 'dev') {
debug(`Preparing the test directory. JS-Controller version: "${controllerVersion}"...`);
// Make sure the test dir exists
await (0, fs_extra_1.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 (0, fs_extra_1.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 (0, fs_extra_1.pathExists)(pckLockPath)) {
await (0, fs_extra_1.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 (0, fs_extra_1.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 (0, executeCommand_1.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() {
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 (0, fs_extra_1.pathExists)(this.testControllerDir)) && (await (0, fs_extra_1.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
*/
isJsControllerRunning() {
debug('Testing if JS-Controller is running...');
return new Promise(resolve => {
const client = new node_net_1.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() {
debug('Initializing JS-Controller installation...');
// Stop the controller before calling setup first
await (0, executeCommand_1.executeCommand)('node', [`${this.appName}.js`, 'stop'], {
cwd: this.testControllerDir,
stdout: 'ignore',
stderr: 'pipe',
});
const setupResult = await (0, executeCommand_1.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
*/
setupSystemConfig(dbConnection) {
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)
*/
clearLogDir() {
debug('Cleaning log directory...');
return (0, fs_extra_1.emptyDir)((0, tools_1.getTestLogDir)(this.appName, this.testDir));
}
/**
* Clears the sqlite DB dir for integration tests (and creates it if it doesn't exist)
*/
clearDBDir() {
debug('Cleaning SQLite directory...');
return (0, fs_extra_1.emptyDir)((0, tools_1.getTestDBDir)(this.appName, this.testDir));
}
/**
* Disables all admin instances in the objects DB
*/
async disableAdminInstances(dbConnection) {
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!');
}
}
exports.ControllerSetup = ControllerSetup;