-
Notifications
You must be signed in to change notification settings - Fork 38
/
device-test.js
527 lines (417 loc) · 15.8 KB
/
device-test.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
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
const events = require('events');
const EventEmitter = events.EventEmitter;
const chai = require('chai');
// const {Device, Socket} = require('../');
const Device = require('../lib/device');
const Socket = require('../lib/ps4socket');
const chaiAsPromised = require("chai-as-promised");
chai.use(chaiAsPromised);
// var expect = chai.expect;
chai.should();
chai.Assertion.addProperty('sendKeyInitialDelay', function() {
this.assert(
this._obj[0][0] === '*setTimeout'
, 'expected #{this} to start with the sendKeyInitialDelay'
, 'expected #{this} to NOT start with the sendKeyInitialDelay'
);
this.assert(
this._obj[0][1] >= 1495 && this._obj[0][1] <= 1500
, 'expected #{this} to start with the sendKeyInitialDelay'
, 'expected #{this} to NOT start with the sendKeyInitialDelay'
);
this._obj = this._obj.slice(1);
});
class FakeSocket extends EventEmitter {
constructor(device) {
super();
this.isOpen = true;
this._device = device;
this.pendingStandbyResults = [];
this.pendingStartResults = [];
this.startedTitles = [];
}
close() {
this.isOpen = false;
}
remoteControl(op, holdTime) {
if (holdTime) {
this._device.emit('send_rc_key', op, holdTime);
} else {
this._device.emit('send_rc_key', op);
}
}
requestStandby(cb) {
if (!this.pendingStandbyResults.length) {
cb(new Error('No pending requestStandby results'));
return;
}
var result = this.pendingStandbyResults.shift();
cb(result);
}
startTitle(titleId, cb) {
if (!this.pendingStartResults.length) {
cb(new Error('No pending startRequest results'));
return;
}
this.startedTitles.push(titleId);
var result = this.pendingStartResults.shift();
cb(result);
}
}
class FakeWaker {
constructor() {
this.calls = [];
this.pendingResults = [];
this.loginResult = {}; // success by default
}
wake(opts, device, cb) {
this.calls.push([opts, device]);
if (!this.pendingResults.length) {
throw new Error("No pendingResult set on FakeWaker");
}
let result = this.pendingResults.shift();
const [err, socket] = result;
if (socket) {
socket._loginResult = this.loginResult;
}
cb(...result);
}
}
function assertUnexpectedError(e) {
throw e;
}
describe("Device", function() {
var device;
var pendingDetectPromise;
var waker;
var socket;
var events;
var _originalSetTimeout;
beforeEach(function() {
device = new Device();
waker = new FakeWaker();
socket = new FakeSocket(device);
events = [];
device._retryDelay = 0;
device._detect = () => {
if (pendingDetectPromise) {
return pendingDetectPromise.then(d => {
return {device: d, rinfo: {}};
});
} else {
return Promise.reject(new Error('no pending detect'));
}
};
device._waker = () => waker;
let _deviceDotEmit = device.emit.bind(device);
device.emit = function(...args) {
_deviceDotEmit(...args);
if (args[0] !== 'login_result') {
events.push(args);
}
};
// patch setTimeout so we don't have to wait
_originalSetTimeout = global.setTimeout;
global.setTimeout = function(cb, delay) {
device.emit('*setTimeout', delay);
cb();
};
});
afterEach(function() {
global.setTimeout = _originalSetTimeout;
});
describe("[test-util]", function() {
it("Connecting unexpectedly errors", function() {
return device._connect().should.be.rejectedWith(/no pending detect/);
});
});
describe(".isConnected", function() {
it("=== false by default", function() {
device.isConnected.should.be.false;
});
it("=== true when connected", function() {
// NOTE: this is not a great test....
device._socket = {};
device.isConnected.should.be.true;
});
});
// yes yes, black box testing and all that...
// but it's just simpler to test these util
// functions directly
describe("._detectAwake", function() {
it("resolves to True when awake", function() {
pendingDetectPromise = Promise.resolve({
status: 'OK'
});
return device._detectAwake().should.become(true);
});
it("resolves to False when standby", function() {
pendingDetectPromise = Promise.resolve({
status: 'Standby'
});
return device._detectAwake().should.become(false);
});
});
describe("._connect", function() {
it("respects autoLogin: false", async function() {
pendingDetectPromise = Promise.resolve({
status: 'Standby'
});
waker.pendingResults.push([null, null]);
await device._connect(false).should.become(undefined);
waker.calls.should.have.lengthOf(1);
waker.calls.should.have.nested.property('[0][0].autoLogin')
.that.is.false;
});
});
describe("._connectIfAwake", function() {
it("resolves to null when not awake", function() {
pendingDetectPromise = Promise.resolve({
status: 'Standby'
});
return device._connectIfAwake().should.become(null);
});
it("connects when awake", function() {
pendingDetectPromise = Promise.resolve({
address: '123.456.789.0',
status: 'OK'
});
waker.pendingResults.push([null, socket]);
return device._connectIfAwake().should.become(socket);
});
});
describe(".turnOn", function() {
it("Rejects when no device found", function() {
pendingDetectPromise = Promise.reject(new Error('detect timeout'));
return device.turnOn().should.be.rejectedWith(/detect timeout/);
});
it("Rejects when wake fails", function() {
pendingDetectPromise = Promise.resolve({
address: '123.456.789.0',
status: 'OK'
});
waker.pendingResults.push([new Error('wake timeout')]);
return device.turnOn().should.be.rejectedWith(/wake timeout/);
});
it("Connects to the device detected", function() {
pendingDetectPromise = Promise.resolve({
address: '123.456.789.0',
status: 'OK'
});
waker.pendingResults.push([null, socket]);
return device.turnOn().then(() => {
waker.calls.should.have.length(1);
waker.calls.should.have.nested.property(
'[0][1].address',
'123.456.789.0');
}).catch(assertUnexpectedError);
});
it("Waits for successful login if timeOut=false", async function() {
pendingDetectPromise = Promise.resolve({
address: '123.456.789.0',
status: 'OK'
});
waker.pendingResults.push([null, socket]);
const raceResult = await Promise.race([
device.turnOn(/* timeOut = */ false),
new Promise((resolve) => _originalSetTimeout(() =>
resolve('timeout'),
10
)),
]);
raceResult.should.equal('timeout');
});
it("Finishes with successful login if timeOut=false", async function() {
pendingDetectPromise = Promise.resolve({
address: '123.456.789.0',
status: 'OK'
});
waker.pendingResults.push([null, socket]);
const raceResultWithLogin = await Promise.race([
device.turnOn(/* timeOut = */ false),
new Promise((resolve) => {
_originalSetTimeout(() => {
device.emit('login_result', {result: 0});
console.log('delay');
_originalSetTimeout(() => resolve('delay'), 1000);
}, 10);
}),
]);
raceResultWithLogin.should.not.equal('delay');
});
it("Finishes immediately with successful login if timeOut=false", async function() {
pendingDetectPromise = Promise.resolve({
address: '123.456.789.0',
status: 'OK'
});
waker.pendingResults.push([null, socket]);
waker.loginResult = {result: 0};
await device.turnOn(/* timeOut = */ false);
});
});
describe(".turnOff", function() {
it("does nothing when already off", function() {
pendingDetectPromise = Promise.resolve({
status: 'Standby'
});
// it would be an error if it tried to connect
return device.turnOff().should.become(device);
});
it("retries once", function() {
pendingDetectPromise = Promise.resolve({
address: '123.456.789.0',
status: 'OK'
});
waker.pendingResults.push([null, socket]);
waker.pendingResults.push([null, socket]);
socket.pendingStandbyResults = ["Error", null];
return device.turnOff().should.become(device);
});
// NOTE: this test describes the behavior for all
// login-requiring methods:
it("Rejects early when login fails", function() {
pendingDetectPromise = Promise.resolve({
address: '123.456.789.0',
status: 'OK'
});
waker.pendingResults.push([null, socket]);
waker.loginResult = {error: "Login error"}
return device.turnOff().should.be.rejectedWith(/Login error/);
});
it("Errors on second error", function() {
pendingDetectPromise = Promise.resolve({
address: '123.456.789.0',
status: 'OK'
});
waker.pendingResults.push([null, socket]);
waker.pendingResults.push([null, socket]);
socket.pendingStandbyResults = ["Error", "Error2"];
return device.turnOff().should.be.rejectedWith(/Error2/);
});
});
describe(".sendKeys", function() {
beforeEach(function() {
pendingDetectPromise = Promise.resolve({
address: '123.456.789.0',
status: 'OK'
});
waker.pendingResults.push([null, socket]);
});
it("rejects empty argument", function() {
return device.sendKeys().should.be.rejectedWith(/No keys/);
});
it("rejects unknown keys", function() {
return device.sendKeys(['awesome-button']).should.be.rejectedWith(/Unknown key names/);
});
it("rejects varargs invocation (single value)", function() {
return device.sendKeys('awesome-button')
.should.be.rejectedWith(/called with an array/);
});
it("rejects varargs invocation (tuple)", function() {
return device.sendKeys(['awesome-button', 2500])
.should.be.rejectedWith(/must be a string or a tuple/);
});
it("Sends single direction", function() {
return device.sendKeys(['right']).then(function() {
events.should.have.sendKeyInitialDelay
.and.deep.equal([
['send_rc_key', Socket.RCKeys.OPEN_RC],
['*setTimeout', 200],
['send_rc_key', Socket.RCKeys.RIGHT],
['send_rc_key', Socket.RCKeys.KEY_OFF],
['sent-key', 'RIGHT'],
['*setTimeout', 200],
['send_rc_key', Socket.RCKeys.CLOSE_RC],
['*setTimeout', 200],
]);
});
});
it("Holds direction", function() {
return device.sendKeys([['left', 1000]]).then(function() {
events.should.have.sendKeyInitialDelay
.and.deep.equal([
['send_rc_key', Socket.RCKeys.OPEN_RC],
['*setTimeout', 200],
// send "down", wait, send "held", then finally clean
['send_rc_key', Socket.RCKeys.LEFT],
['*setTimeout', 1000],
['send_rc_key', Socket.RCKeys.LEFT, 1000],
['send_rc_key', Socket.RCKeys.KEY_OFF],
['sent-key', 'LEFT'],
['*setTimeout', 200],
['send_rc_key', Socket.RCKeys.CLOSE_RC],
['*setTimeout', 200],
]);
});
});
it("Sends single ps press", function() {
return device.sendKeys(['ps']).then(function() {
events.should.have.sendKeyInitialDelay
.and.deep.equal([
['send_rc_key', Socket.RCKeys.OPEN_RC],
['*setTimeout', 200],
['send_rc_key', Socket.RCKeys.PS],
['send_rc_key', Socket.RCKeys.KEY_OFF],
['sent-key', 'PS'],
['*setTimeout', 1000],
['send_rc_key', Socket.RCKeys.CLOSE_RC],
['*setTimeout', 200],
]);
});
});
it("holds PS button", function() {
return device.sendKeys([['ps', 1000]]).then(function() {
events.should.have.sendKeyInitialDelay
.and.deep.equal([
['send_rc_key', Socket.RCKeys.OPEN_RC],
['*setTimeout', 200],
// send "down", wait, send "held"
['send_rc_key', Socket.RCKeys.PS],
['*setTimeout', 1000],
['send_rc_key', Socket.RCKeys.PS, 1000],
// NOTE: we do NOT clear with KEY_OFF
['sent-key', 'PS'],
['*setTimeout', 1000],
['send_rc_key', Socket.RCKeys.CLOSE_RC],
['*setTimeout', 200],
]);
});
});
it("doesn't wait when it connected a while ago", function() {
return (async () => {
await device.openSocket();
device._connectedAt = Date.now() - 3000;
await device.sendKeys(['up']);
events.should.deep.equal([
['send_rc_key', Socket.RCKeys.OPEN_RC],
['*setTimeout', 200],
['send_rc_key', Socket.RCKeys.UP],
['send_rc_key', Socket.RCKeys.KEY_OFF],
['sent-key', 'UP'],
['*setTimeout', 200],
['send_rc_key', Socket.RCKeys.CLOSE_RC],
['*setTimeout', 200],
]);
})();
});
});
describe("startTitle", function() {
beforeEach(function() {
pendingDetectPromise = Promise.resolve({
address: '123.456.789.0',
status: 'OK'
});
waker.pendingResults.push([null, socket]);
});
it("works", function() {
socket.pendingStartResults.push(null);
return device.startTitle("CUSA00123").then(res => {
res.should.deep.equal(device);
socket.startedTitles.should.deep.equal([
'CUSA00123'
]);
})
.catch(assertUnexpectedError);
});
});
});