test_suspend_channel_before_connect.js (2489B)
1 "use strict"; 2 3 var CC = Components.Constructor; 4 5 const ServerSocket = CC( 6 "@mozilla.org/network/server-socket;1", 7 "nsIServerSocket", 8 "init" 9 ); 10 11 var obs = Services.obs; 12 13 // A server that waits for a connect. If a channel is suspended it should not 14 // try to connect to the server until it is is resumed or not try at all if it 15 // is cancelled as in this test. 16 function TestServer() { 17 this.listener = ServerSocket(-1, true, -1); 18 this.port = this.listener.port; 19 this.listener.asyncListen(this); 20 } 21 22 TestServer.prototype = { 23 onSocketAccepted() { 24 Assert.ok(false, "Socket should not have tried to connect!"); 25 }, 26 27 onStopListening() {}, 28 29 stop() { 30 try { 31 this.listener.close(); 32 } catch (ignore) {} 33 }, 34 }; 35 36 var requestListenerObserver = { 37 QueryInterface: ChromeUtils.generateQI(["nsIObserver"]), 38 39 observe(subject, topic) { 40 if ( 41 topic === "http-on-modify-request" && 42 subject instanceof Ci.nsIHttpChannel 43 ) { 44 var chan = subject.QueryInterface(Ci.nsIHttpChannel); 45 chan.suspend(); 46 obs.removeObserver(this, "http-on-modify-request"); 47 48 // Timers are bad, but we need to wait to see that we are not trying to 49 // connect to the server. There are no other event since nothing should 50 // happen until we resume the channel. 51 let timer = Cc["@mozilla.org/timer;1"].createInstance(Ci.nsITimer); 52 timer.initWithCallback( 53 () => { 54 chan.cancel(Cr.NS_BINDING_ABORTED); 55 chan.resume(); 56 }, 57 1000, 58 Ci.nsITimer.TYPE_ONE_SHOT 59 ); 60 } 61 }, 62 }; 63 64 var listener = { 65 onStartRequest: function test_onStartR() {}, 66 67 onDataAvailable: function test_ODA() { 68 do_throw("Should not get any data!"); 69 }, 70 71 onStopRequest: function test_onStopR() { 72 executeSoon(run_next_test); 73 }, 74 }; 75 76 // Add observer and start a channel. Observer is going to suspend the channel on 77 // "http-on-modify-request" even. If a channel is suspended so early it should 78 // not try to connect at all until it is resumed. In this case we are going to 79 // wait for some time and cancel the channel before resuming it. 80 add_test(function testNoConnectChannelCanceledEarly() { 81 let serv = new TestServer(); 82 83 obs.addObserver(requestListenerObserver, "http-on-modify-request"); 84 var chan = NetUtil.newChannel({ 85 uri: "http://localhost:" + serv.port, 86 loadUsingSystemPrincipal: true, 87 }); 88 chan.asyncOpen(listener); 89 90 registerCleanupFunction(function () { 91 serv.stop(); 92 }); 93 });