-
Notifications
You must be signed in to change notification settings - Fork 637
/
environment.js
315 lines (269 loc) · 9.51 KB
/
environment.js
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
'use strict';
const winston = require('../source/utils/winston');
const child_process = require('child_process');
const puppeteer = require('puppeteer');
const net = require('net');
const request = require('superagent');
const mkdirp = require('mkdirp');
const util = require('util');
const rimraf = util.promisify(require('rimraf'));
const portrange = 45032;
module.exports = (config) => new Environment(config);
const prependLines = (pre, text) => {
return text.split('\n').filter((l) => l)
.map((line) => pre + line)
.join('\n');
}
// Environment provides
class Environment {
constructor(config) {
this.config = config || {};
this.config.rootPath = typeof this.config.rootPath === 'string' ? this.config.rootPath : '';
this.config.serverTimeout = this.config.serverTimeout || 35000;
this.config.headless = this.config.headless === undefined ? true : this.config.headless;
this.config.viewWidth = 1920;
this.config.viewHeight = 1080;
this.config.showServerOutput = this.config.showServerOutput === undefined ? true : this.config.showServerOutput;
this.config.serverStartupOptions = this.config.serverStartupOptions || [];
this.shuttinDown = false;
}
getRootUrl() { return this.rootUrl; }
getPort() {
const tmpPortrange = portrange + Math.floor(Math.random() * 5000);
return new Promise((resolve, reject) => {
const server = net.createServer();
server.listen(tmpPortrange, () => {
server.once('close', () => {
this.port = tmpPortrange;
this.rootUrl = `http://localhost:${this.port}${this.config.rootPath}`;
resolve();
});
server.close();
});
server.on('error', () => {
this.getPort().then(resolve);
});
});
}
async init() {
try {
this.browser = await puppeteer.launch({
headless: this.config.headless,
defaultViewport: {
width: this.config.viewWidth,
height: this.config.viewHeight
}
});
await this.getPort();
await this.startServer();
} catch (err) {
winston.error(err);
throw new Error('Cannot confirm ungit start!!\n' + err);
}
}
startServer() {
winston.info('Starting ungit server...', this.config.serverStartupOptions);
this.hasStarted = false;
const options = ['bin/ungit',
'--cliconfigonly',
`--port=${this.port}`,
`--rootPath=${this.config.rootPath}`,
'--no-launchBrowser',
'--dev',
'--no-bugtracking',
`--autoShutdownTimeout=${this.config.serverTimeout}`,
'--logLevel=debug',
'--maxNAutoRestartOnCrash=0',
'--no-autoCheckoutOnBranchCreate',
'--alwaysLoadActiveBranch',
`--numRefsToShow=${this.config.numRefsToShow || 5}`]
.concat(this.config.serverStartupOptions);
const ungitServer = this.ungitServerProcess = child_process.spawn('node', options);
return new Promise((resolve, reject) => {
ungitServer.stdout.on('data', (stdout) => {
const stdoutStr = stdout.toString();
if (this.config.showServerOutput) winston.verbose(prependLines('[server] ', stdoutStr));
if (stdoutStr.indexOf('Ungit server already running') >= 0) {
winston.info('server-already-running');
}
if (stdoutStr.indexOf('## Ungit started ##') >= 0) {
if (this.hasStarted) {
reject(new Error('Ungit started twice, probably crashed.'));
} else {
this.hasStarted = true;
winston.info('Ungit server started.');
resolve();
}
}
});
ungitServer.stderr.on('data', (stderr) => {
const stderrStr = stderr.toString();
winston.error(prependLines('[server ERROR] ', stderrStr));
if (stderrStr.indexOf('EADDRINUSE') > -1) {
winston.info('retrying with different port');
ungitServer.kill('SIGINT');
reject(new Error('EADDRINUSE'));
}
});
ungitServer.on('exit', () => winston.info('UNGIT SERVER EXITED'));
});
}
async shutdown() {
this.shuttinDown = true;
await this.backgroundAction('POST', '/api/testing/cleanup')
if (this.ungitServerProcess) {
this.ungitServerProcess.kill('SIGINT');
this.ungitServerProcess = null;
}
if (this.browser) {
await this.browser.close();
this.browser = null;
this.page = null;
}
}
// server helpers
async backgroundAction(method, url, body) {
url = this.getRootUrl() + url;
let req;
if (method === 'GET') {
req = request.get(url).withCredentials().query(body);
} else if (method === 'POST') {
req = request.post(url).send(body);
} else if (method === 'DELETE') {
req = request.delete(url).send(body);
}
req.set({ 'encoding': 'utf8', 'cache-control': 'no-cache', 'Content-Type': 'application/json' });
const response = await req;
return response.body;
}
async createRepos(testRepoPaths, config) {
for (let i = 0; i < config.length; i++) {
const conf = config[i];
conf.bare = !!conf.bare;
await this.initRepo(conf);
await this.createCommits(conf, conf.initCommits);
testRepoPaths.push(conf.path);
}
}
async initRepo(options) {
if (options.path) {
await rimraf(options.path);
await mkdirp(options.path);
} else {
winston.info('Creating temp folder');
options.path = await this.createTempFolder();
}
await this.backgroundAction('POST', '/api/init', options);
}
async createTempFolder() {
const res = await this.backgroundAction('POST', '/api/testing/createtempdir');
return res.path;
}
async createCommits(config, limit, x) {
x = x || 0
if (!limit || limit < 0 || x === limit) return;
await this.createTestFile(`${config.path}/testy${x}`);
await this.backgroundAction('POST', '/api/commit', {
path: config.path,
message: `Init Commit ${x}`,
files: [{ name: `testy${x}` }]
});
await this.createCommits(config, limit, x + 1);
}
createTestFile(filename, repoPath) {
return this.backgroundAction('POST', '/api/testing/createfile', { file: filename, path: repoPath });
}
// browser helpers
async goto(url) {
winston.info('Go to page: ' + url);
if (!this.page) {
const pages = await this.browser.pages();
const page = this.page = pages[0];
page.on('console', (message) => {
const text = `[ui ${message.type()}] ${(new Date()).toISOString()} - ${message.text()}}`;
if (message.type() === 'error' && !this.shuttinDown) {
winston.error(text);
} else {
winston.info(text);
}
});
}
await this.page.goto(url);
}
async openUngit(tempDirPath) {
await this.goto(`${this.getRootUrl()}/#/repository?path=${encodeURIComponent(tempDirPath)}`);
await this.waitForElementVisible('.repository-actions');
await this.wait(1000);
}
waitForElementVisible(selector) {
return this.page.waitForSelector(selector, { visible: true });
}
waitForElementHidden(selector) {
return this.page.waitForSelector(selector, { hidden: true });
}
wait(duration) {
return this.page.waitFor(duration);
}
type(text) {
return this.page.keyboard.type(text);
}
async insert(selector, text) {
await this.waitForElementVisible(selector);
await this.page.$eval(selector, (ele) => ele.value = '');
await this.page.focus(selector);
await this.type(text);
}
press(key) {
return this.page.keyboard.press(key);
}
async click(selector) {
let elementHandle = await this.waitForElementVisible(selector);
try {
await elementHandle.click();
} catch (err1) {
elementHandle = await this.waitForElementVisible(selector);
try {
await elementHandle.click(); // try click a second time to reduce test flakiness
} catch (err2) {
winston.error(`Failed to click element: ${selector}`);
throw err2;
}
}
}
async commit(commitMessage) {
await this.waitForElementVisible('.files .file .btn-default');
await this.insert('.staging input.form-control', commitMessage);
await this.click('.commit-btn');
await this.waitForElementHidden('.files .file .btn-default');
await this.wait(1000);
}
async _createRef(type, name) {
await this.click('.current ~ .new-ref button.showBranchingForm');
await this.insert('.ref-icons.new-ref.editing input', name);
await this.click(`.new-ref ${type === 'branch' ? '.btn-primary' : '.btn-default'}`);
await this.waitForElementVisible(`.ref.${type}[data-ta-name="${name}"]`);
}
createTag(name) {
return this._createRef('tag', name);
}
createBranch(name) {
return this._createRef('branch', name);
}
async _verifyRefAction(action) {
try {
await this.page.waitForSelector('.modal-dialog .btn-primary', { visible: true, timeout: 2000 });
await this.click('.modal-dialog .btn-primary');
} catch (err) { /* ignore */ }
await this.waitForElementHidden(`[data-ta-action="${action}"]:not([style*="display: none"])`);
}
async refAction(ref, local, action) {
await this.click(`.branch[data-ta-name="${ref}"][data-ta-local="${local}"]`);
await this.click(`[data-ta-action="${action}"]:not([style*="display: none"]) .dropmask`);
await this._verifyRefAction(action);
}
async moveRef(ref, targetNodeCommitTitle) {
await this.click(`.branch[data-ta-name="${ref}"]`);
await this.click(`[data-ta-node-title="${targetNodeCommitTitle}"] [data-ta-action="move"]:not([style*="display: none"]) .dropmask`);
await this._verifyRefAction('move');
}
}