-
-
Notifications
You must be signed in to change notification settings - Fork 197
/
Copy pathandroid-livesync-tool.ts
534 lines (428 loc) · 16.5 KB
/
android-livesync-tool.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
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
import { Yok } from "../../../lib/common/yok";
import { assert } from "chai";
import * as sinon from "sinon";
import { LoggerStub } from "../../stubs";
import { AndroidLivesyncTool } from "../../../lib/services/livesync/android-livesync-tool";
import { LiveSyncSocket } from "../../../lib/services/livesync/livesync-socket";
import { MobileHelper } from "../../../lib/common/mobile/mobile-helper";
import { FileSystem } from "../../../lib/common/file-system";
import { DevicePlatformsConstants } from "../../../lib/common/mobile/device-platforms-constants";
import * as path from "path";
import temp = require("temp");
import * as crypto from "crypto";
temp.track();
const protocolVersion = "0.2.0";
class TestSocket extends LiveSyncSocket {
public accomulatedData: Buffer[] = [];
public connect() {
return this;
}
public writeAsync(data: Buffer | string, cb?: string | Function, encoding?: Function | string): Promise<Boolean> {
if (data instanceof Buffer) {
this.accomulatedData.push(data);
} else {
const buffer = Buffer.from(data, 'utf8');
this.accomulatedData.push(buffer);
}
if (cb && cb instanceof Function) {
cb.call(this);
}
return new Promise((resolve, reject) => {
setTimeout(() => resolve(true), 0);
});
}
}
const rootJsFilePath = "test.js";
const rootCssFilePath = "test.css";
const nestedJsFilePath = path.join("testdir", "testdir.js");
const nestedCssFilePath = path.join("testdir", "testdir.css");
const fileContents = {
[rootJsFilePath]: "Test js content",
[rootCssFilePath]: "Test css content",
[nestedJsFilePath]: "Test js in dir",
[nestedCssFilePath]: "Test css in dir"
};
const projectCreated = false;
const testAppPath = temp.mkdirSync("testsyncapp");
const testAppPlatformPath = path.join(testAppPath, "platforms", "android", "app", "src", "main", "assets", "app");
const createTestProject = (testInjector: IInjector) => {
if (!projectCreated) {
const fs = testInjector.resolve("fs");
_.forEach(fileContents, (value, key) => {
fs.writeFile(path.join(testAppPlatformPath, key), value);
});
}
};
const createTestInjector = (socket: INetSocket, fileStreams: IDictionary<NodeJS.ReadableStream>): IInjector => {
const testInjector = new Yok();
testInjector.register("fs", FileSystem);
testInjector.register("logger", LoggerStub);
testInjector.register("injector", testInjector);
testInjector.register("mobileHelper", MobileHelper);
testInjector.register("androidProcessService", {
forwardFreeTcpToAbstractPort: () => Promise.resolve(""),
getAppProcessId: () => Promise.resolve("1234")
});
testInjector.register("LiveSyncSocket", () => socket);
testInjector.register("devicePlatformsConstants", DevicePlatformsConstants);
testInjector.register("errors", {
failWithHelp: (message: string): void => {
throw new Error(message);
},
fail: (message: string) => {
throw new Error(message);
},
failWithoutHelp: (message: string) => {
throw new Error(message);
}
});
return testInjector;
};
const getFileName = (buffer: Buffer) => {
const fileNameSizeLength = buffer.readUInt8(1);
const fileNameSizeEnd = fileNameSizeLength + 2;
const fileNameSize = buffer.toString("utf8", 2, fileNameSizeEnd);
const fileNameEnd = fileNameSizeEnd + Number(fileNameSize);
const fileName = buffer.toString("utf8", fileNameSizeEnd, fileNameEnd);
return { fileName, fileNameEnd };
};
const getFileContentSize = (buffer: Buffer, offset: number) => {
const fileContentSizeLength = buffer.readUInt8(offset);
const fileContentSizeBegin = offset + 1;
const fileContentSizeEnd = fileContentSizeBegin + fileContentSizeLength;
const fileContentSize = Number(buffer.toString("utf8", fileContentSizeBegin, fileContentSizeEnd));
return { fileContentSize, fileContentSizeEnd };
};
const getFileContent = (buffer: Buffer, offset: number, contentLength: number) => {
const fileContentEnd = offset + Number(contentLength);
const fileContent = buffer.toString("utf8", offset, fileContentEnd);
return { fileContent, fileContentEnd };
};
const getOperation = (buffer: Buffer) => {
const operation = buffer.toString("utf8", 0, 1);
return Number(operation);
};
const compareHash = (buffer: Buffer, dataStart: number, dataEnd: number, hashStart: number) => {
const headerBuffer = buffer.slice(dataStart, dataEnd);
const hashEnd = hashStart + 16;
const headerHash = buffer.slice(hashStart, hashEnd);
const computedHash = crypto.createHash("md5").update(headerBuffer).digest();
const headerHashMatch = headerHash.equals(computedHash);
return headerHashMatch;
};
const getSendFileData = (buffers: Buffer[]) => {
const buffer = Buffer.concat(buffers);
const operation = getOperation(buffer);
const { fileName, fileNameEnd } = getFileName(buffer);
const { fileContentSize, fileContentSizeEnd } = getFileContentSize(buffer, fileNameEnd);
const headerHashMatch = compareHash(buffer, 0, fileContentSizeEnd, fileContentSizeEnd);
const headerHashEnd = fileContentSizeEnd + 16;
const { fileContent, fileContentEnd } = getFileContent(buffer, headerHashEnd, fileContentSize);
const fileHashMatch = compareHash(buffer, headerHashEnd, fileContentEnd, fileContentEnd);
return { operation, fileName, fileContent, headerHashMatch, fileHashMatch };
};
const getRemoveFileData = (buffers: Buffer[]) => {
const buffer = Buffer.concat(buffers);
const operation = getOperation(buffer);
const { fileName, fileNameEnd } = getFileName(buffer);
const headerHashMatch = compareHash(buffer, 0, fileNameEnd, fileNameEnd);
return { operation, fileName, headerHashMatch };
};
const getSyncData = (buffers: Buffer[]) => {
const buffer = Buffer.concat(buffers);
const operation = getOperation(buffer);
const operationUid = buffer.toString("utf8", 1, 33);
const doRefresh = buffer.readUInt8(33);
return { operationUid, doRefresh, operation };
};
const getSyncResponse = (reportCode: number, message: string) => {
const buffer = Buffer.alloc(1 + Buffer.byteLength(message, "utf8"));
buffer.writeUInt8(reportCode, 0);
buffer.write(message, 1);
return buffer;
};
const getHandshakeBuffer = () => {
const packageName = "org.comp.test";
const handshakeBuffer = Buffer.alloc(Buffer.byteLength(protocolVersion) + Buffer.byteLength(packageName) + 1);
let offset = handshakeBuffer.writeUInt8(Buffer.byteLength(protocolVersion), 0);
offset = offset + handshakeBuffer.write(protocolVersion, offset);
handshakeBuffer.write(packageName, offset);
return handshakeBuffer;
};
const stubSocketEventAttach = (socket: any, sandbox: sinon.SinonSandbox, attachMethod: string, eventName: string, data: any, attachCountForAction: number, emitEvent?: string) => {
const originalMethod = socket[attachMethod];
let attachCount = 0;
emitEvent = emitEvent || eventName;
sandbox.stub(socket, attachMethod).callsFake(function (event: string) {
originalMethod.apply(this, arguments);
if (eventName === event) {
attachCount++;
if (attachCount === attachCountForAction) {
socket.emit(emitEvent, data);
}
}
});
};
const connectTimeout = 100;
describe("AndroidLivesyncTool", () => {
let testInjector: IInjector = null;
let livesyncTool: IAndroidLivesyncTool = null;
let testSocket: ILiveSyncSocket;
let sandbox: sinon.SinonSandbox = null;
let fileStreams: IDictionary<NodeJS.ReadableStream> = null;
let connectData: IAndroidLivesyncToolConfiguration;
beforeEach(() => {
connectData = {
appIdentifier: "test",
deviceIdentifier: "test",
appPlatformsPath: testAppPlatformPath,
connectTimeout
};
sandbox = sinon.sandbox.create();
testSocket = new TestSocket();
fileStreams = {};
testInjector = createTestInjector(testSocket, fileStreams);
createTestProject(testInjector);
livesyncTool = testInjector.resolve(AndroidLivesyncTool);
});
afterEach(() => {
sandbox.restore();
});
describe("methods", () => {
describe("connect", () => {
it("should retry if first socket connect emits close", async () => {
//arrange
const connectStub: sinon.SinonStub = sandbox.stub(testSocket, "connect");
connectData.connectTimeout = null;
stubSocketEventAttach(testSocket, sandbox, "on", "close", false, 1);
stubSocketEventAttach(testSocket, sandbox, "once", "data", getHandshakeBuffer(), 2);
//act
await livesyncTool.connect(connectData);
//assert
assert(connectStub.calledTwice);
assert.equal(livesyncTool.protocolVersion, protocolVersion);
});
it("should retry if first socket connect errors", () => {
//arrange
const errorMessage = "Socket error";
connectData.connectTimeout = null;
stubSocketEventAttach(testSocket, sandbox, "on", "close", new Error(errorMessage), 1, "error");
stubSocketEventAttach(testSocket, sandbox, "once", "data", getHandshakeBuffer(), 2);
//act
const connectPromise = livesyncTool.connect(connectData);
//assert
return assert.isRejected(connectPromise, errorMessage);
});
it("should reject if appIdentifier is missing", () => {
//arrange
connectData.appIdentifier = "";
//act
const connectPromise = livesyncTool.connect(connectData);
//assert
return assert.isRejected(connectPromise, AndroidLivesyncTool.APP_IDENTIFIER_MISSING_ERROR);
});
it("should reject if appPlatformsPath is missing", () => {
//arrange
connectData.appPlatformsPath = "";
//act
const connectPromise = livesyncTool.connect(connectData);
//assert
return assert.isRejected(connectPromise, AndroidLivesyncTool.APP_PLATFORMS_PATH_MISSING_ERROR);
});
it("should fail eventually", () => {
//act
const connectPromise = livesyncTool.connect(connectData);
//assert
return assert.isRejected(connectPromise, AndroidLivesyncTool.SOCKET_CONNECTION_TIMED_OUT_ERROR);
});
it("should fail if connection alreday exists", async () => {
//arrange
stubSocketEventAttach(testSocket, sandbox, "once", "data", getHandshakeBuffer(), 1);
await livesyncTool.connect(connectData);
//act
const connectPromise = livesyncTool.connect(connectData);
//assert
await assert.isRejected(connectPromise, AndroidLivesyncTool.SOCKET_CONNECTION_ALREADY_EXISTS_ERROR);
});
});
describe("which require connection", () => {
beforeEach(async () => {
stubSocketEventAttach(testSocket, sandbox, "once", "data", getHandshakeBuffer(), 1);
await livesyncTool.connect(connectData);
});
describe("sendFile", () => {
it("sends correct information", async () => {
//arrange
const filePath = path.join(testAppPlatformPath, rootJsFilePath);
//act
await livesyncTool.sendFile(filePath);
const sendFileData = getSendFileData((testSocket as TestSocket).accomulatedData);
//assert
assert.equal(sendFileData.fileContent, fileContents[rootJsFilePath]);
assert.equal(sendFileData.fileName, rootJsFilePath);
assert(sendFileData.headerHashMatch);
assert(sendFileData.fileHashMatch);
assert.equal(sendFileData.operation, AndroidLivesyncTool.CREATE_FILE_OPERATION);
});
it("rejects if file doesn't exist", () => {
//act
const sendFilePromise = livesyncTool.sendFile("nonexistent.js");
//assert
return assert.isRejected(sendFilePromise);
});
it("rejects if no connection", () => {
//arrange
livesyncTool.end();
const filePath = path.join(testAppPlatformPath, rootJsFilePath);
//act
const sendFilePromise = livesyncTool.sendFile(filePath);
//assert
return assert.isRejected(sendFilePromise, AndroidLivesyncTool.NO_SOCKET_CONNECTION_AVAILABLE_ERROR);
});
it("rejects if socket sends error", () => {
//arrange
const errorMessage = "Some error";
const filePath = path.join(testAppPlatformPath, rootJsFilePath);
testSocket.emit('error', errorMessage);
//act
const sendFilePromise = livesyncTool.sendFile(filePath);
//assert
return assert.isRejected(sendFilePromise, errorMessage);
});
it("rejects if error received", async () => {
//arrange
const filePath = path.join(testAppPlatformPath, rootJsFilePath);
const errorMessage = "Some error";
await livesyncTool.sendFile(filePath);
sandbox.stub(testSocket, "writeAsync").callsFake((data) => {
testSocket.emit('data', getSyncResponse(AndroidLivesyncTool.ERROR_REPORT, errorMessage));
return Promise.resolve();
});
//act
const sendFilePromise = livesyncTool.sendFile(filePath);
//assert
assert.isRejected(sendFilePromise, errorMessage);
});
});
describe("remove file", () => {
it("sends correct information", async () => {
//arrange
const filePath = path.join(testAppPlatformPath, rootJsFilePath);
await livesyncTool.removeFile(filePath);
//act
const removeData = getRemoveFileData((testSocket as TestSocket).accomulatedData);
//assert
assert.equal(removeData.fileName, rootJsFilePath);
assert.equal(removeData.operation, AndroidLivesyncTool.DELETE_FILE_OPERATION);
assert(removeData.headerHashMatch);
});
});
describe("sendDoSync", () => {
it("resolves after received data", () => {
//arrange
let doSyncResolved = false;
//act
const doSyncPromise = livesyncTool.sendDoSyncOperation();
const doSyncData = getSyncData((testSocket as TestSocket).accomulatedData);
doSyncPromise.then(() => {
doSyncResolved = true;
}).catch(assert.fail);
//assert
assert.isFalse(doSyncResolved);
testSocket.emit('data', getSyncResponse(AndroidLivesyncTool.OPERATION_END_REPORT, doSyncData.operationUid));
return doSyncPromise.then(() => {
assert.isTrue(doSyncResolved);
});
});
it("resolves after received data without refresh", () => {
//arrange
let doSyncResolved = false;
//act
const doSyncPromise = livesyncTool.sendDoSyncOperation();
const doSyncData = getSyncData((testSocket as TestSocket).accomulatedData);
doSyncPromise.then(() => {
doSyncResolved = true;
}).catch(assert.fail);
//assert
assert.isFalse(doSyncResolved);
testSocket.emit('data', getSyncResponse(AndroidLivesyncTool.OPERATION_END_NO_REFRESH_REPORT_CODE, doSyncData.operationUid));
return doSyncPromise.then(() => {
assert.isTrue(doSyncResolved);
});
});
it("rejects after received error", () => {
//arrange
let doSyncRejected = false;
const errorMessage = "Some error";
//act
const doSyncPromise = livesyncTool.sendDoSyncOperation();
doSyncPromise.catch(() => {
doSyncRejected = true;
});
//assert
assert.isFalse(doSyncRejected);
testSocket.emit('data', getSyncResponse(AndroidLivesyncTool.ERROR_REPORT, errorMessage));
return assert.isRejected(doSyncPromise, errorMessage);
});
it("rejects after socket closed", () => {
//arrange
let doSyncRejected = false;
//act
const doSyncPromise = livesyncTool.sendDoSyncOperation();
doSyncPromise.catch(() => {
doSyncRejected = true;
});
//assert
assert.isFalse(doSyncRejected);
testSocket.emit('close', true);
return assert.isRejected(doSyncPromise);
});
it("rejects after timeout", () => {
//act
const doSyncPromise = livesyncTool.sendDoSyncOperation({ timeout: 50 });
//assert
return assert.isRejected(doSyncPromise);
});
});
});
describe("sendFiles", () => {
it("calls sendFile for each file", async () => {
//arrange
const filePaths = _.keys(fileContents).map(filePath => path.join(testAppPlatformPath, filePath));
const sendFileStub = sandbox.stub(livesyncTool, "sendFile").callsFake(() => Promise.resolve());
//act
await livesyncTool.sendFiles(filePaths);
//assert
_.forEach(filePaths, (filePath) => {
assert(sendFileStub.calledWith(filePath));
});
});
});
describe("sendDirectory", () => {
it("calls sendFile for each file in directory", async () => {
//arrange
const filePaths = _.keys(fileContents).map(filePath => path.join(testAppPlatformPath, filePath));
const sendFileStub = sandbox.stub(livesyncTool, "sendFile").callsFake(() => Promise.resolve());
//act
await livesyncTool.sendDirectory(testAppPlatformPath);
//assert
_.forEach(filePaths, (filePath) => {
assert(sendFileStub.calledWith(filePath));
});
});
});
describe("removeFiles", () => {
it("calls removeFile for each file", async () => {
//arrange
const filePaths = _.keys(fileContents).map(filePath => path.join(testAppPlatformPath, filePath));
const removeFileStub = sandbox.stub(livesyncTool, "removeFile").callsFake(() => Promise.resolve());
//act
await livesyncTool.removeFiles(filePaths);
//assert
_.forEach(filePaths, (filePath) => {
assert(removeFileStub.calledWith(filePath));
});
});
});
});
});