test-helpers.js 10 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414
  1. import document from 'global/document';
  2. import sinon from 'sinon';
  3. import window from 'global/window';
  4. import URLToolkit from 'url-toolkit';
  5. import videojs from 'video.js';
  6. /* eslint-disable no-unused-vars */
  7. // needed so MediaSource can be registered with videojs
  8. import MediaSource from 'videojs-contrib-media-sources';
  9. /* eslint-enable */
  10. import testDataManifests from './test-manifests.js';
  11. import xhrFactory from '../src/xhr';
  12. // a SourceBuffer that tracks updates but otherwise is a noop
  13. class MockSourceBuffer extends videojs.EventTarget {
  14. constructor() {
  15. super();
  16. this.updates_ = [];
  17. this.updating = false;
  18. this.on('updateend', function() {
  19. this.updating = false;
  20. });
  21. this.buffered = videojs.createTimeRanges();
  22. this.duration_ = NaN;
  23. Object.defineProperty(this, 'duration', {
  24. get() {
  25. return this.duration_;
  26. },
  27. set(duration) {
  28. this.updates_.push({
  29. duration
  30. });
  31. this.duration_ = duration;
  32. }
  33. });
  34. }
  35. abort() {
  36. this.updates_.push({
  37. abort: true
  38. });
  39. }
  40. appendBuffer(bytes) {
  41. this.updates_.push({
  42. append: bytes
  43. });
  44. this.updating = true;
  45. }
  46. remove(start, end) {
  47. this.updates_.push({
  48. remove: [start, end]
  49. });
  50. }
  51. }
  52. class MockMediaSource extends videojs.EventTarget {
  53. constructor() {
  54. super();
  55. this.readyState = 'closed';
  56. this.on('sourceopen', function() {
  57. this.readyState = 'open';
  58. });
  59. this.sourceBuffers = [];
  60. this.duration = NaN;
  61. this.seekable = videojs.createTimeRange();
  62. }
  63. addSeekableRange_(start, end) {
  64. this.seekable = videojs.createTimeRange(start, end);
  65. }
  66. addSourceBuffer(mime) {
  67. let sourceBuffer = new MockSourceBuffer();
  68. sourceBuffer.mimeType_ = mime;
  69. this.sourceBuffers.push(sourceBuffer);
  70. return sourceBuffer;
  71. }
  72. endOfStream(error) {
  73. this.readyState = 'ended';
  74. this.error_ = error;
  75. }
  76. }
  77. export class MockTextTrack {
  78. constructor() {
  79. this.cues = [];
  80. }
  81. addCue(cue) {
  82. this.cues.push(cue);
  83. }
  84. removeCue(cue) {
  85. for (let i = 0; i < this.cues.length; i++) {
  86. if (this.cues[i] === cue) {
  87. this.cues.splice(i, 1);
  88. break;
  89. }
  90. }
  91. }
  92. }
  93. // return an absolute version of a page-relative URL
  94. export const absoluteUrl = function(relativeUrl) {
  95. return URLToolkit.buildAbsoluteURL(window.location.href, relativeUrl);
  96. };
  97. export const useFakeMediaSource = function() {
  98. let RealMediaSource = videojs.MediaSource;
  99. let realCreateObjectURL = videojs.URL.createObjectURL;
  100. let id = 0;
  101. videojs.MediaSource = MockMediaSource;
  102. videojs.MediaSource.supportsNativeMediaSources =
  103. RealMediaSource.supportsNativeMediaSources;
  104. videojs.URL.createObjectURL = function() {
  105. id++;
  106. return 'blob:videojs-contrib-hls-mock-url' + id;
  107. };
  108. return {
  109. restore() {
  110. videojs.MediaSource = RealMediaSource;
  111. videojs.URL.createObjectURL = realCreateObjectURL;
  112. }
  113. };
  114. };
  115. export const useFakeEnvironment = function(assert) {
  116. let realXMLHttpRequest = videojs.xhr.XMLHttpRequest;
  117. let fakeEnvironment = {
  118. requests: [],
  119. restore() {
  120. this.clock.restore();
  121. videojs.xhr.XMLHttpRequest = realXMLHttpRequest;
  122. this.xhr.restore();
  123. ['warn', 'error'].forEach((level) => {
  124. if (this.log && this.log[level] && this.log[level].restore) {
  125. if (assert) {
  126. let calls = (this.log[level].args || []).map((args) => {
  127. return args.join(', ');
  128. }).join('\n ');
  129. assert.equal(this.log[level].callCount,
  130. 0,
  131. 'no unexpected logs at level "' + level + '":\n ' + calls);
  132. }
  133. this.log[level].restore();
  134. }
  135. });
  136. }
  137. };
  138. fakeEnvironment.log = {};
  139. ['warn', 'error'].forEach((level) => {
  140. // you can use .log[level].args to get args
  141. sinon.stub(videojs.log, level);
  142. fakeEnvironment.log[level] = videojs.log[level];
  143. Object.defineProperty(videojs.log[level], 'calls', {
  144. get() {
  145. // reset callCount to 0 so they don't have to
  146. let callCount = this.callCount;
  147. this.callCount = 0;
  148. return callCount;
  149. }
  150. });
  151. });
  152. fakeEnvironment.clock = sinon.useFakeTimers();
  153. fakeEnvironment.xhr = sinon.useFakeXMLHttpRequest();
  154. // Sinon 1.10.2 handles abort incorrectly (triggering the error event)
  155. // Later versions fixed this but broke the ability to set the response
  156. // to an arbitrary object (in our case, a typed array).
  157. XMLHttpRequest.prototype = Object.create(XMLHttpRequest.prototype);
  158. XMLHttpRequest.prototype.abort = function abort() {
  159. this.response = this.responseText = '';
  160. this.errorFlag = true;
  161. this.requestHeaders = {};
  162. this.responseHeaders = {};
  163. if (this.readyState > 0 && this.sendFlag) {
  164. this.readyStateChange(4);
  165. this.sendFlag = false;
  166. }
  167. this.readyState = 0;
  168. };
  169. XMLHttpRequest.prototype.downloadProgress = function downloadProgress(rawEventData) {
  170. this.dispatchEvent(new sinon.ProgressEvent('progress',
  171. rawEventData,
  172. rawEventData.target));
  173. };
  174. // add support for xhr.responseURL
  175. XMLHttpRequest.prototype.open = (function(origFn) {
  176. return function() {
  177. this.responseURL = absoluteUrl(arguments[1]);
  178. return origFn.apply(this, arguments);
  179. };
  180. }(XMLHttpRequest.prototype.open));
  181. fakeEnvironment.requests.length = 0;
  182. fakeEnvironment.xhr.onCreate = function(xhr) {
  183. xhr.responseURL = xhr.url;
  184. fakeEnvironment.requests.push(xhr);
  185. };
  186. videojs.xhr.XMLHttpRequest = fakeEnvironment.xhr;
  187. return fakeEnvironment;
  188. };
  189. // patch over some methods of the provided tech so it can be tested
  190. // synchronously with sinon's fake timers
  191. export const mockTech = function(tech) {
  192. if (tech.isMocked_) {
  193. // make this function idempotent because HTML and Flash based
  194. // playback have very different lifecycles. For HTML, the tech
  195. // is available on player creation. For Flash, the tech isn't
  196. // ready until the source has been loaded and one tick has
  197. // expired.
  198. return;
  199. }
  200. tech.isMocked_ = true;
  201. tech.src_ = null;
  202. tech.time_ = null;
  203. tech.paused_ = !tech.autoplay();
  204. tech.paused = function() {
  205. return tech.paused_;
  206. };
  207. if (!tech.currentTime_) {
  208. tech.currentTime_ = tech.currentTime;
  209. }
  210. tech.currentTime = function() {
  211. return tech.time_ === null ? tech.currentTime_() : tech.time_;
  212. };
  213. tech.setSrc = function(src) {
  214. tech.src_ = src;
  215. };
  216. tech.src = function(src) {
  217. if (src !== null) {
  218. return tech.setSrc(src);
  219. }
  220. return tech.src_ === null ? tech.src : tech.src_;
  221. };
  222. tech.currentSrc_ = tech.currentSrc;
  223. tech.currentSrc = function() {
  224. return tech.src_ === null ? tech.currentSrc_() : tech.src_;
  225. };
  226. tech.play_ = tech.play;
  227. tech.play = function() {
  228. tech.play_();
  229. tech.paused_ = false;
  230. tech.trigger('play');
  231. };
  232. tech.pause_ = tech.pause;
  233. tech.pause = function() {
  234. tech.pause_();
  235. tech.paused_ = true;
  236. tech.trigger('pause');
  237. };
  238. tech.setCurrentTime = function(time) {
  239. tech.time_ = time;
  240. setTimeout(function() {
  241. tech.trigger('seeking');
  242. setTimeout(function() {
  243. tech.trigger('seeked');
  244. }, 1);
  245. }, 1);
  246. };
  247. };
  248. export const createPlayer = function(options, src, clock) {
  249. let video;
  250. let player;
  251. video = document.createElement('video');
  252. video.className = 'video-js';
  253. if (src) {
  254. if (typeof src === 'string') {
  255. video.src = src;
  256. } else if (src.src) {
  257. let source = document.createElement('source');
  258. source.src = src.src;
  259. if (src.type) {
  260. source.type = src.type;
  261. }
  262. video.appendChild(source);
  263. }
  264. }
  265. document.querySelector('#qunit-fixture').appendChild(video);
  266. player = videojs(video, options || {
  267. flash: {
  268. swf: ''
  269. }
  270. });
  271. player.buffered = function() {
  272. return videojs.createTimeRange(0, 0);
  273. };
  274. if (clock) {
  275. clock.tick(1);
  276. }
  277. mockTech(player.tech_);
  278. return player;
  279. };
  280. export const openMediaSource = function(player, clock) {
  281. // ensure the Flash tech is ready
  282. player.tech_.triggerReady();
  283. clock.tick(1);
  284. // mock the tech *after* it has finished loading so that we don't
  285. // mock a tech that will be unloaded on the next tick
  286. mockTech(player.tech_);
  287. player.tech_.hls.xhr = xhrFactory();
  288. // simulate the sourceopen event
  289. player.tech_.hls.mediaSource.readyState = 'open';
  290. player.tech_.hls.mediaSource.dispatchEvent({
  291. type: 'sourceopen',
  292. swfId: player.tech_.el().id
  293. });
  294. clock.tick(1);
  295. };
  296. export const standardXHRResponse = function(request, data) {
  297. if (!request.url) {
  298. return;
  299. }
  300. let contentType = 'application/json';
  301. // contents off the global object
  302. let manifestName = (/(?:.*\/)?(.*)\.m3u8/).exec(request.url);
  303. if (manifestName) {
  304. manifestName = manifestName[1];
  305. } else {
  306. manifestName = request.url;
  307. }
  308. if (/\.m3u8?/.test(request.url)) {
  309. contentType = 'application/vnd.apple.mpegurl';
  310. } else if (/\.ts/.test(request.url)) {
  311. contentType = 'video/MP2T';
  312. }
  313. if (!data) {
  314. data = testDataManifests[manifestName];
  315. }
  316. request.response = new Uint8Array(1024).buffer;
  317. request.respond(200, {'Content-Type': contentType}, data);
  318. };
  319. export const playlistWithDuration = function(time, conf) {
  320. let result = {
  321. targetDuration: 10,
  322. mediaSequence: conf && conf.mediaSequence ? conf.mediaSequence : 0,
  323. discontinuityStarts: [],
  324. segments: [],
  325. endList: conf && typeof conf.endList !== 'undefined' ? !!conf.endList : true,
  326. uri: conf && typeof conf.uri !== 'undefined' ? conf.uri : 'playlist.m3u8',
  327. discontinuitySequence:
  328. conf && conf.discontinuitySequence ? conf.discontinuitySequence : 0,
  329. attributes: conf && typeof conf.attributes !== 'undefined' ? conf.attributes : {}
  330. };
  331. let count = Math.floor(time / 10);
  332. let remainder = time % 10;
  333. let i;
  334. let isEncrypted = conf && conf.isEncrypted;
  335. let extension = conf && conf.extension ? conf.extension : '.ts';
  336. for (i = 0; i < count; i++) {
  337. result.segments.push({
  338. uri: i + extension,
  339. resolvedUri: i + extension,
  340. duration: 10,
  341. timeline: result.discontinuitySequence
  342. });
  343. if (isEncrypted) {
  344. result.segments[i].key = {
  345. uri: i + '-key.php',
  346. resolvedUri: i + '-key.php'
  347. };
  348. }
  349. }
  350. if (remainder) {
  351. result.segments.push({
  352. uri: i + extension,
  353. duration: remainder,
  354. timeline: result.discontinuitySequence
  355. });
  356. }
  357. return result;
  358. };