test_multipart_streamconv.js (2582B)
1 "use strict"; 2 3 const { HttpServer } = ChromeUtils.importESModule( 4 "resource://testing-common/httpd.sys.mjs" 5 ); 6 7 var httpserver = null; 8 9 ChromeUtils.defineLazyGetter(this, "uri", function () { 10 return "http://localhost:" + httpserver.identity.primaryPort + "/multipart"; 11 }); 12 13 function make_channel(url) { 14 return NetUtil.newChannel({ uri: url, loadUsingSystemPrincipal: true }); 15 } 16 17 var multipartBody = 18 "--boundary\r\nSet-Cookie: foo=bar\r\n\r\nSome text\r\n--boundary\r\nContent-Type: text/x-test\r\n\r\n<?xml version='1.1'?>\r\n<root/>\r\n--boundary\r\n\r\n<?xml version='1.0'?><root/>\r\n--boundary--"; 19 20 function contentHandler(metadata, response) { 21 response.setHeader("Content-Type", 'multipart/mixed; boundary="boundary"'); 22 response.bodyOutputStream.write(multipartBody, multipartBody.length); 23 } 24 25 var numTests = 2; 26 var testNum = 0; 27 28 var testData = [ 29 { data: "Some text", type: "text/plain" }, 30 { data: "<?xml version='1.1'?>\r\n<root/>", type: "text/x-test" }, 31 { data: "<?xml version='1.0'?><root/>", type: "text/xml" }, 32 ]; 33 34 function responseHandler(request, buffer) { 35 Assert.equal(buffer, testData[testNum].data); 36 Assert.equal( 37 request.QueryInterface(Ci.nsIChannel).contentType, 38 testData[testNum].type 39 ); 40 if (++testNum == numTests) { 41 httpserver.stop(do_test_finished); 42 } 43 } 44 45 var multipartListener = { 46 _buffer: "", 47 _index: 0, 48 49 QueryInterface: ChromeUtils.generateQI([ 50 "nsIStreamListener", 51 "nsIRequestObserver", 52 ]), 53 54 onStartRequest() { 55 this._buffer = ""; 56 }, 57 58 onDataAvailable(request, stream, offset, count) { 59 try { 60 this._buffer = this._buffer.concat(read_stream(stream, count)); 61 dump("BUFFEEE: " + this._buffer + "\n\n"); 62 } catch (ex) { 63 do_throw("Error in onDataAvailable: " + ex); 64 } 65 }, 66 67 onStopRequest(request) { 68 this._index++; 69 // Second part should be last part 70 Assert.equal( 71 request.QueryInterface(Ci.nsIMultiPartChannel).isLastPart, 72 this._index == testData.length 73 ); 74 try { 75 responseHandler(request, this._buffer); 76 } catch (ex) { 77 do_throw("Error in closure function: " + ex); 78 } 79 }, 80 }; 81 82 function run_test() { 83 httpserver = new HttpServer(); 84 httpserver.registerPathHandler("/multipart", contentHandler); 85 httpserver.start(-1); 86 87 var streamConv = Cc["@mozilla.org/streamConverters;1"].getService( 88 Ci.nsIStreamConverterService 89 ); 90 var conv = streamConv.asyncConvertData( 91 "multipart/mixed", 92 "*/*", 93 multipartListener, 94 null 95 ); 96 97 var chan = make_channel(uri); 98 chan.asyncOpen(conv); 99 do_test_pending(); 100 }