test_fetch-bom.js (2074B)
1 /* Any copyright is dedicated to the Public Domain. 2 http://creativecommons.org/publicdomain/zero/1.0/ */ 3 "use strict"; 4 5 // Tests for DevToolsUtils.fetch BOM detection. 6 7 const { HttpServer } = ChromeUtils.importESModule( 8 "resource://testing-common/httpd.sys.mjs" 9 ); 10 const BinaryOutputStream = Components.Constructor( 11 "@mozilla.org/binaryoutputstream;1", 12 "nsIBinaryOutputStream", 13 "setOutputStream" 14 ); 15 16 function write8(bos) { 17 bos.write8(0xef); 18 bos.write8(0xbb); 19 bos.write8(0xbf); 20 bos.write8(0x68); 21 bos.write8(0xc4); 22 bos.write8(0xb1); 23 } 24 25 function write16be(bos) { 26 bos.write8(0xfe); 27 bos.write8(0xff); 28 bos.write8(0x00); 29 bos.write8(0x68); 30 bos.write8(0x01); 31 bos.write8(0x31); 32 } 33 34 function write16le(bos) { 35 bos.write8(0xff); 36 bos.write8(0xfe); 37 bos.write8(0x68); 38 bos.write8(0x00); 39 bos.write8(0x31); 40 bos.write8(0x01); 41 } 42 43 function getHandler(writer) { 44 return function (request, response) { 45 response.setStatusLine(request.httpVersion, 200, "OK"); 46 47 const bos = new BinaryOutputStream(response.bodyOutputStream); 48 writer(bos); 49 }; 50 } 51 52 const server = new HttpServer(); 53 server.registerDirectory("/", do_get_cwd()); 54 server.registerPathHandler("/u8", getHandler(write8)); 55 server.registerPathHandler("/u16be", getHandler(write16be)); 56 server.registerPathHandler("/u16le", getHandler(write16le)); 57 server.start(-1); 58 59 const port = server.identity.primaryPort; 60 const serverURL = "http://localhost:" + port; 61 62 do_get_profile(); 63 64 registerCleanupFunction(() => { 65 return new Promise(resolve => server.stop(resolve)); 66 }); 67 68 add_task(async function () { 69 await test_one(serverURL + "/u8", "UTF-8"); 70 await test_one(serverURL + "/u16be", "UTF-16BE"); 71 await test_one(serverURL + "/u16le", "UTF-16LE"); 72 }); 73 74 async function test_one(url, encoding) { 75 // Be sure to set the encoding to something that will yield an 76 // invalid result if BOM sniffing is not done. 77 await DevToolsUtils.fetch(url, { charset: "ISO-8859-1" }).then( 78 ({ content }) => { 79 Assert.equal(content, "hı", "The content looks correct for " + encoding); 80 } 81 ); 82 }