Chromium Code Reviews| OLD | NEW |
|---|---|
| (Empty) | |
| 1 /* | |
|
ojan
2014/08/12 02:01:18
This should be an html file so we can pull it in w
michaelpg
2014/08/14 00:46:02
Done.
| |
| 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 function NetworkSimulator(assert, done) { | |
| 8 this._assert = assert; | |
| 9 this._done = done; | |
| 10 this._pendingPromises = []; | |
| 11 } | |
| 12 | |
| 13 NetworkSimulator._testInProgress = false; | |
| 14 | |
| 15 NetworkSimulator.prototype.schedulePromise = function(promise) { | |
| 16 this._pendingPromises.push(promise); | |
| 17 return promise; | |
| 18 }; | |
| 19 | |
| 20 NetworkSimulator.prototype.resolvePromises = function() { | |
| 21 var self = this; | |
| 22 return new Promise(function(resolve, reject) { | |
| 23 var pendingPromises = self._pendingPromises; | |
| 24 self._pendingPromises = []; | |
| 25 function allResolved(results) { | |
| 26 if (self._pendingPromises.length) { | |
| 27 resolve(self.resolvePromises()); | |
| 28 return; | |
| 29 } | |
| 30 resolve(results); | |
| 31 } | |
| 32 Promise.all(pendingPromises).then(allResolved, allResolved); | |
| 33 }); | |
| 34 }; | |
| 35 | |
| 36 NetworkSimulator.prototype.runTest = function(testCase) { | |
| 37 if (NetworkSimulator._testInProgress) { | |
| 38 this._assert(false, "runTest calls cannot be nested"); | |
| 39 this._done(); | |
| 40 return; | |
| 41 } | |
| 42 | |
| 43 NetworkSimulator._testInProgress = true; | |
| 44 | |
| 45 var self = this; | |
| 46 return new Promise(function(resolve, reject) { | |
| 47 var realNet = window.net; | |
| 48 | |
| 49 function reset() { | |
| 50 window.net = realNet; | |
| 51 NetworkSimulator._testInProgress = false; | |
| 52 } | |
| 53 | |
| 54 // All net.* methods should return promises. This watches all | |
| 55 // promises generated by test-overridden methods. | |
| 56 window.net = {}; | |
| 57 ['probe', 'jsonp', 'get', 'post', | |
| 58 'ajax', 'json', 'xml'].forEach(function(method) { | |
| 59 if (method in self) { | |
| 60 net[method] = function() { | |
| 61 return self.schedulePromise(self[method].apply(self, arguments)); | |
| 62 }; | |
| 63 }; | |
| 64 }); | |
| 65 | |
| 66 try { | |
| 67 testCase(); | |
| 68 } catch(e) { | |
| 69 // Make sure errors thrown in the test case don't leave window.net in a ba d state. | |
| 70 reset(); | |
| 71 self._assert(false, "Test case threw an error:" + e); | |
| 72 } | |
| 73 | |
| 74 self.resolvePromises().then(function() { | |
| 75 reset(); | |
| 76 self._assert(window.net == realNet); | |
| 77 resolve(); | |
| 78 }).catch(function(e) { | |
| 79 reset(); | |
| 80 self._assert(false, "Failed to finish test: " + e); | |
| 81 }); | |
| 82 }); | |
| 83 }; | |
| OLD | NEW |