test_multipart_streamconv_inputstream.js (2736B)
1 /* Any copyright is dedicated to the Public Domain. 2 https://creativecommons.org/publicdomain/zero/1.0/ */ 3 4 "use strict"; 5 6 function make_channel(url) { 7 return NetUtil.newChannel({ uri: url, loadUsingSystemPrincipal: true }); 8 } 9 10 var multipartBody = 11 "--boundary\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--"; 12 13 var testData = [ 14 { data: "Some text", type: "text/plain" }, 15 { data: "<?xml version='1.1'?>\r\n<root/>", type: "text/x-test" }, 16 { data: "<?xml version='1.0'?><root/>", type: "text/xml" }, 17 ]; 18 19 function responseHandler(request, index, buffer) { 20 Assert.equal(buffer, testData[index].data); 21 Assert.equal( 22 request.QueryInterface(Ci.nsIChannel).contentType, 23 testData[index].type 24 ); 25 } 26 27 add_task(async function test_inputstream() { 28 let uri = "http://localhost"; 29 let httpChan = make_channel(uri); 30 31 let inputStream = Cc["@mozilla.org/io/string-input-stream;1"].createInstance( 32 Ci.nsIStringInputStream 33 ); 34 35 inputStream.setUTF8Data(multipartBody); 36 37 let channel = Cc["@mozilla.org/network/input-stream-channel;1"] 38 .createInstance(Ci.nsIInputStreamChannel) 39 .QueryInterface(Ci.nsIChannel); 40 41 channel.setURI(httpChan.URI); 42 channel.loadInfo = httpChan.loadInfo; 43 channel.contentStream = inputStream; 44 channel.contentType = `multipart/mixed; boundary="boundary"`; 45 46 await new Promise(resolve => { 47 let streamConv = Cc["@mozilla.org/streamConverters;1"].getService( 48 Ci.nsIStreamConverterService 49 ); 50 let multipartListener = { 51 _buffer: "", 52 _index: 0, 53 54 QueryInterface: ChromeUtils.generateQI([ 55 "nsIStreamListener", 56 "nsIRequestObserver", 57 ]), 58 59 onStartRequest() {}, 60 onDataAvailable(request, stream, offset, count) { 61 try { 62 this._buffer = this._buffer.concat(read_stream(stream, count)); 63 dump("BUFFEEE: " + this._buffer + "\n\n"); 64 } catch (ex) { 65 do_throw("Error in onDataAvailable: " + ex); 66 } 67 }, 68 69 onStopRequest(request) { 70 try { 71 responseHandler(request, this._index, this._buffer); 72 } catch (ex) { 73 do_throw("Error in closure function: " + ex); 74 } 75 76 this._index++; 77 this._buffer = ""; 78 79 let isLastPart = request.QueryInterface( 80 Ci.nsIMultiPartChannel 81 ).isLastPart; 82 Assert.equal(isLastPart, this._index == testData.length); 83 84 if (isLastPart) { 85 resolve(); 86 } 87 }, 88 }; 89 let conv = streamConv.asyncConvertData( 90 "multipart/mixed", 91 "*/*", 92 multipartListener, 93 null 94 ); 95 96 channel.asyncOpen(conv); 97 }); 98 });