/
setup.js
427 lines (392 loc) · 13.8 KB
/
setup.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
/* eslint-disable no-console */
const webdriver = require('selenium-webdriver');
const By = webdriver.By;
const until = webdriver.until;
// requiring this automatically adds the chromedriver binary to the PATH
// eslint-disable-next-line
const chromedriver = require('chromedriver');
const HttpServer = require('http-server');
const streams = require('../../test-streams');
const onTravis = !!process.env.TRAVIS;
const chai = require('chai');
const expect = chai.expect;
const browserConfig = {
version: 'latest',
name: 'chrome'
};
/**
* @type {webdriver.ThenableWebDriver}
*/
let browser;
let stream;
// Setup browser config data from env vars
if (onTravis) {
let UA = process.env.UA;
if (!UA) {
throw new Error('No test browser name.');
}
let OS = process.env.OS;
if (!OS) {
throw new Error('No test browser platform.');
}
let UA_VERSION = process.env.UA_VERSION;
if (UA_VERSION) {
browserConfig.version = UA_VERSION;
}
browserConfig.name = UA;
browserConfig.platform = OS;
}
let browserDescription = browserConfig.name;
if (browserConfig.version) {
browserDescription += ` (${browserConfig.version})`;
}
if (browserConfig.platform) {
browserDescription += `, ${browserConfig.platform}`;
}
let hostname = onTravis ? 'localhost' : '127.0.0.1';
// Launch static server
HttpServer.createServer({
showDir: false,
autoIndex: false,
root: './'
}).listen(8000, hostname);
const stringifyResult = (result) => JSON.stringify(result, Object.keys(result).filter(k => k !== 'logs'), 2);
const wait = ms => new Promise(resolve => setTimeout(resolve, ms));
async function retry (attempt, numAttempts = 5, interval = 2000) {
try {
return await attempt();
} catch (e) {
if (--numAttempts === 0) {
// reject with the last error
throw e;
}
await wait(interval);
return retry(attempt, numAttempts, interval);
}
}
async function testLoadedData (url, config) {
const result = await browser.executeAsyncScript(function (url, config) {
const callback = arguments[arguments.length - 1];
window.startStream(url, config, callback);
const video = window.video;
video.onloadeddata = function () {
callback({ code: 'loadeddata', logs: window.logString });
};
},
url,
config
);
expect(result, stringifyResult(result)).to.have.property('code').which.equals('loadeddata');
}
async function testIdleBufferLength (url, config) {
const result = await browser.executeAsyncScript(function (url, config) {
const callback = arguments[arguments.length - 1];
const autoplay = false;
window.startStream(url, config, callback, autoplay);
const video = window.video;
const maxBufferLength = window.hls.config.maxBufferLength;
video.onprogress = function () {
const buffered = video.buffered;
if (buffered.length) {
const bufferEnd = buffered.end(buffered.length - 1);
const duration = video.duration;
console.log('[test] > progress: ' + bufferEnd.toFixed(2) + '/' + duration.toFixed(2) +
' buffered.length: ' + buffered.length);
if (bufferEnd >= maxBufferLength || bufferEnd > duration - (config.avBufferOffset || 1)) {
callback({ code: 'loadeddata', logs: window.logString });
}
}
};
},
url,
config
);
expect(result, stringifyResult(result)).to.have.property('code').which.equals('loadeddata');
}
async function testSmoothSwitch (url, config) {
const result = await browser.executeAsyncScript(function (url, config) {
const callback = arguments[arguments.length - 1];
window.startStream(url, config, callback);
const video = window.video;
window.hls.once(window.Hls.Events.FRAG_CHANGED, function (event, data) {
window.switchToHighestLevel('next');
});
window.hls.on(window.Hls.Events.LEVEL_SWITCHED, function (event, data) {
console.log('[test] > level switched: ' + data.level);
let currentTime = video.currentTime;
if (data.level === window.hls.levels.length - 1) {
console.log('[test] > switched on level: ' + data.level);
window.setTimeout(function () {
let newCurrentTime = video.currentTime;
console.log('[test] > currentTime delta : ' + (newCurrentTime - currentTime));
callback({
currentTimeDelta: newCurrentTime - currentTime,
logs: window.logString
});
}, 2000);
}
});
},
url,
config
);
expect(result, stringifyResult(result)).to.have.property('currentTimeDelta').which.is.gt(0);
}
async function testSeekOnLive (url, config) {
const result = await browser.executeAsyncScript(function (url, config) {
const callback = arguments[arguments.length - 1];
window.startStream(url, config, callback);
const video = window.video;
video.onloadeddata = function () {
window.setTimeout(function () {
video.currentTime = video.duration - 5;
}, 5000);
};
video.onseeked = function () {
callback({ code: 'seeked', logs: window.logString });
};
},
url,
config
);
expect(result, stringifyResult(result)).to.have.property('code').which.equals('seeked');
}
async function testSeekOnVOD (url, config) {
const result = await browser.executeAsyncScript(function (url, config) {
const callback = arguments[arguments.length - 1];
window.startStream(url, config, callback);
const video = window.video;
video.onloadeddata = function () {
window.setTimeout(function () {
video.currentTime = video.duration - 5;
// Fail test early if more than 2 buffered ranges are found
video.onprogress = function () {
if (video.buffered.length > 2) {
callback({ code: 'buffer-gaps', bufferedRanges: video.buffered.length, logs: window.logString });
}
};
}, 5000);
};
video.onended = function () {
callback({ code: 'ended', logs: window.logString });
};
},
url,
config
);
expect(result, stringifyResult(result)).to.have.property('code').which.equals('ended');
}
async function testSeekEndVOD (url, config) {
const result = await browser.executeAsyncScript(function (url, config) {
const callback = arguments[arguments.length - 1];
window.startStream(url, config, callback);
const video = window.video;
video.onloadeddata = function () {
window.setTimeout(function () {
video.currentTime = video.duration;
}, 5000);
};
video.onended = function () {
callback({ code: 'ended', logs: window.logString });
};
},
url,
config
);
expect(result, stringifyResult(result)).to.have.property('code').which.equals('ended');
}
async function testIsPlayingVOD (url, config) {
const result = await browser.executeAsyncScript(function (url, config) {
const callback = arguments[arguments.length - 1];
window.startStream(url, config, callback);
const video = window.video;
video.onloadeddata = function () {
let expectedPlaying = !(
video.paused || // not playing when video is paused
video.ended || // not playing when video is ended
video.buffered.length === 0
); // not playing if nothing buffered
let currentTime = video.currentTime;
if (expectedPlaying) {
window.setTimeout(function () {
console.log('[test] > video expected playing. last currentTime/new currentTime=' +
currentTime + '/' + video.currentTime);
callback({ playing: currentTime !== video.currentTime });
}, 5000);
} else {
console.log('[test] > video not playing. paused/ended/buffered.length=' +
video.paused + '/' + video.ended + '/' + video.buffered.length);
callback({ playing: false });
}
};
},
url,
config
);
expect(result, stringifyResult(result)).to.have.property('playing').which.is.true;
}
async function testSeekBackToStart (url, config) {
const result = await browser.executeAsyncScript(function (url, config) {
const callback = arguments[arguments.length - 1];
window.startStream(url, config, callback);
const video = window.video;
video.ontimeupdate = function () {
if (video.currentTime > 0 && !video.paused) {
window.setTimeout(function () {
video.onseeked = function () {
delete video.onseeked;
video.ontimeupdate = function () {
if (video.currentTime > 0 && !video.paused) {
delete video.ontimeupdate;
callback({ playing: true });
}
};
};
video.currentTime = 0;
delete video.ontime;
}, 500);
}
};
},
url,
config
);
expect(result, stringifyResult(result)).to.have.property('playing').which.is.true;
}
describe(`testing hls.js playback in the browser on "${browserDescription}"`, function () {
before(async function () {
// high timeout because sometimes getSession() takes a while
this.timeout(100000);
if (!stream) {
throw new Error('Stream not defined');
}
let capabilities = {
name: `"${stream.description}" on "${browserDescription}"`,
browserName: browserConfig.name,
platform: browserConfig.platform,
version: browserConfig.version,
commandTimeout: 90
};
if (browserConfig.name === 'chrome') {
capabilities.chromeOptions = {
args: [
'--autoplay-policy=no-user-gesture-required',
'--disable-web-security'
]
};
}
browser = new webdriver.Builder();
if (onTravis) {
capabilities['tunnel-identifier'] = process.env.TRAVIS_JOB_NUMBER;
capabilities.build = 'HLSJS-' + process.env.TRAVIS_BUILD_NUMBER;
capabilities.username = process.env.SAUCE_USERNAME;
capabilities.accessKey = process.env.SAUCE_ACCESS_KEY;
capabilities.avoidProxy = true;
browser = browser.usingServer(`http://${process.env.SAUCE_USERNAME}:${process.env.SAUCE_ACCESS_KEY}@ondemand.saucelabs.com:80/wd/hub`);
}
browser = browser.withCapabilities(capabilities).build();
let start = Date.now();
try {
await retry(async function () {
console.log('Retrieving web driver session...');
const [timeouts, session] = await Promise.all([
browser.manage().setTimeouts({ script: 75000 }),
browser.getSession()
]);
console.log(`Retrieved session in ${Date.now() - start}ms`);
if (onTravis) {
console.log(`Job URL: https://saucelabs.com/jobs/${session.getId()}`);
} else {
console.log(`WebDriver SessionID: ${session.getId()}`);
}
});
} catch (err) {
throw new Error(`failed setting up session: ${err}`);
}
});
beforeEach(async function () {
try {
await retry(async () => {
console.log('Loading test page...');
try {
await browser.get(`http://${hostname}:8000/tests/functional/auto/index.html`);
} catch (e) {
throw new Error('failed to open test page');
}
console.log('Test page loaded.');
console.log('Locating ID \'hlsjs-functional-tests\'');
try {
await browser.wait(
until.elementLocated(By.css('body#hlsjs-functional-tests')),
5000,
'Failed to load test page, source of other page below.'
);
} catch (e) {
const source = await browser.getPageSource();
console.log(source);
throw e;
}
console.log('Located the ID, page confirmed loaded');
});
} catch (e) {
throw new Error(`error getting test page loaded: ${e}`);
}
});
afterEach(async function () {
// if (onTravis || (!onTravis && this.currentTest.isFailed())) {
const logString = await browser.executeScript('return logString');
console.log(`${onTravis ? 'travis_fold:start:debug_logs' : ''}\n${logString}\n${onTravis ? 'travis_fold:end:debug_logs' : ''}`);
// }
});
after(async function () {
console.log('Quitting browser...');
await browser.quit();
console.log('Browser quit.');
});
for (let name in streams) {
stream = streams[name];
let url = stream.url;
let config = stream.config || {};
if (
!stream.blacklist_ua ||
stream.blacklist_ua.indexOf(browserConfig.name) === -1
) {
it(
`should receive video loadeddata event for ${stream.description}`,
testLoadedData.bind(null, url, config)
);
if (stream.startSeek) {
it(
`seek back to start and play for ${stream.description}`,
testSeekBackToStart.bind(null, url, config)
);
}
if (stream.abr) {
it(
`should "smooth switch" to highest level and still play(readyState === 4) after 12s for ${stream.description}`,
testSmoothSwitch.bind(null, url, config)
);
}
if (stream.live) {
it(
`should seek near the end and receive video seeked event for ${stream.description}`,
testSeekOnLive.bind(null, url, config)
);
} else {
it(
`should buffer up to maxBufferLength or video.duration for ${stream.description}`,
testIdleBufferLength.bind(null, url, config)
);
it(
`should play ${stream.description}`,
testIsPlayingVOD.bind(null, url, config)
);
it(
`should seek 5s from end and receive video ended event for ${stream.description} with 2 or less buffered ranges`,
testSeekOnVOD.bind(null, url, config)
);
// it(`should seek on end and receive video ended event for ${stream.description}`, testSeekEndVOD.bind(null, url));
}
}
}
});