OLD | NEW |
| (Empty) |
1 <!-- | |
2 Copyright 2014 The Chromium Authors. All rights reserved. | |
3 Use of this source code is governed by a BSD-style license that can be | |
4 found in the LICENSE file. | |
5 --> | |
6 | |
7 <script> | |
8 function NetworkSimulator(assert, done) { | |
9 this._assert = assert; | |
10 this._done = done; | |
11 this._pendingPromises = []; | |
12 } | |
13 | |
14 NetworkSimulator._testInProgress = false; | |
15 | |
16 NetworkSimulator.prototype.schedulePromise = function(promise) { | |
17 this._pendingPromises.push(promise); | |
18 return promise; | |
19 }; | |
20 | |
21 NetworkSimulator.prototype.resolvePromises = function() { | |
22 var self = this; | |
23 return new Promise(function(resolve, reject) { | |
24 var pendingPromises = self._pendingPromises; | |
25 self._pendingPromises = []; | |
26 function allResolved(results) { | |
27 if (self._pendingPromises.length) { | |
28 resolve(self.resolvePromises()); | |
29 return; | |
30 } | |
31 resolve(results); | |
32 } | |
33 Promise.all(pendingPromises).then(allResolved, allResolved); | |
34 }); | |
35 }; | |
36 | |
37 NetworkSimulator.prototype.runTest = function(testCase) { | |
38 if (NetworkSimulator._testInProgress) { | |
39 this._assert(false, "runTest calls cannot be nested"); | |
40 this._done(); | |
41 return; | |
42 } | |
43 | |
44 NetworkSimulator._testInProgress = true; | |
45 | |
46 var self = this; | |
47 var realNet = window.net; | |
48 | |
49 function reset() { | |
50 window.net = realNet; | |
51 NetworkSimulator._testInProgress = false; | |
52 } | |
53 | |
54 return Promise.resolve().then(function() { | |
55 // All net.* methods should return promises. This watches all | |
56 // promises generated by test-overridden methods. | |
57 window.net = {}; | |
58 ['probe', 'jsonp', 'get', 'post', | |
59 'ajax', 'json', 'xml'].forEach(function(method) { | |
60 if (method in self) { | |
61 net[method] = function() { | |
62 return self.schedulePromise(self[method].apply(self, arguments)); | |
63 }; | |
64 }; | |
65 }); | |
66 }).then(function() { | |
67 return testCase(); | |
68 }).catch(function(e) { | |
69 // Make sure errors thrown in the test case don't leave window.net in a bad
state. | |
70 reset(); | |
71 throw e; | |
72 }).then(function() { | |
73 return self.resolvePromises().then(function() { | |
74 reset(); | |
75 self._assert(window.net == realNet); | |
76 }).catch(function(e) { | |
77 reset(); | |
78 self._assert(false, "Failed to finish test:" + e); | |
79 }) | |
80 }).then(this._done, this._done); | |
81 }; | |
82 </script> | |
OLD | NEW |