test_localstreams.js (2580B)
1 // Tests bug 304414 2 3 "use strict"; 4 5 const PR_RDONLY = 0x1; // see prio.h 6 7 // Does some sanity checks on the stream and returns the number of bytes read 8 // when the checks passed. 9 function test_stream(stream) { 10 // This test only handles blocking streams; that's desired for file streams 11 // anyway. 12 Assert.equal(stream.isNonBlocking(), false); 13 14 // Check that the stream is not buffered 15 Assert.equal( 16 Cc["@mozilla.org/io-util;1"] 17 .getService(Ci.nsIIOUtil) 18 .inputStreamIsBuffered(stream), 19 false 20 ); 21 22 // Wrap it in a binary stream (to avoid wrong results that 23 // scriptablestream would produce with binary content) 24 var binstream = Cc["@mozilla.org/binaryinputstream;1"].createInstance( 25 Ci.nsIBinaryInputStream 26 ); 27 binstream.setInputStream(stream); 28 29 var numread = 0; 30 for (;;) { 31 Assert.equal(stream.available(), binstream.available()); 32 var avail = stream.available(); 33 Assert.notEqual(avail, -1); 34 35 // PR_UINT32_MAX and PR_INT32_MAX; the files we're testing with aren't that 36 // large. 37 Assert.notEqual(avail, Math.pow(2, 32) - 1); 38 Assert.notEqual(avail, Math.pow(2, 31) - 1); 39 40 if (!avail) { 41 // For blocking streams, available() only returns 0 on EOF 42 // Make sure that there is really no data left 43 var could_read = false; 44 try { 45 binstream.readByteArray(1); 46 could_read = true; 47 } catch (e) { 48 // We expect the exception, so do nothing here 49 } 50 if (could_read) { 51 do_throw("Data readable when available indicated EOF!"); 52 } 53 return numread; 54 } 55 56 dump("Trying to read " + avail + " bytes\n"); 57 // Note: Verification that this does return as much bytes as we asked for is 58 // done in the binarystream implementation 59 binstream.readByteArray(avail); 60 61 numread += avail; 62 } 63 } 64 65 function stream_for_file(file) { 66 var str = Cc["@mozilla.org/network/file-input-stream;1"].createInstance( 67 Ci.nsIFileInputStream 68 ); 69 str.init(file, PR_RDONLY, 0, 0); 70 return str; 71 } 72 73 function stream_from_channel(file) { 74 var uri = Services.io.newFileURI(file); 75 return NetUtil.newChannel({ 76 uri, 77 loadUsingSystemPrincipal: true, 78 }).open(); 79 } 80 81 function run_test() { 82 // Get a file and a directory in order to do some testing 83 var file = do_get_file("../unit/data/test_readline6.txt"); 84 var len = file.fileSize; 85 Assert.equal(test_stream(stream_for_file(file)), len); 86 Assert.equal(test_stream(stream_from_channel(file)), len); 87 var dir = file.parent; 88 test_stream(stream_from_channel(dir)); // Can't do size checking 89 }