test-helpers.js (2215B)
1 // A special path component meaning "this directory." 2 const kCurrentDirectory = '.'; 3 4 // A special path component meaning "the parent directory." 5 const kParentDirectory = '..'; 6 7 // Array of separators used to separate components in hierarchical paths. 8 let kPathSeparators; 9 if (navigator.userAgent.includes('Windows NT')) { 10 // Windows uses both '/' and '\' as path separators. 11 kPathSeparators = ['/', '\\']; 12 } else { 13 kPathSeparators = ['/']; 14 } 15 16 async function getFileSize(handle) { 17 const file = await handle.getFile(); 18 return file.size; 19 } 20 21 async function getFileContents(handle) { 22 const file = await handle.getFile(); 23 return new Response(file).text(); 24 } 25 26 async function getDirectoryEntryCount(handle) { 27 let result = 0; 28 for await (let entry of handle) { 29 result++; 30 } 31 return result; 32 } 33 34 async function getSortedDirectoryEntries(handle) { 35 let result = []; 36 for await (let entry of handle.values()) { 37 if (entry.kind === 'directory') 38 result.push(entry.name + '/'); 39 else 40 result.push(entry.name); 41 } 42 result.sort(); 43 return result; 44 } 45 46 async function createDirectory(name, parent) { 47 return await parent.getDirectoryHandle(name, {create: true}); 48 } 49 50 async function createEmptyFile(name, parent) { 51 const handle = await parent.getFileHandle(name, {create: true}); 52 // Make sure the file is empty. 53 assert_equals(await getFileSize(handle), 0); 54 return handle; 55 } 56 57 async function createFileWithContents(name, contents, parent) { 58 const handle = await createEmptyFile(name, parent); 59 const writer = await handle.createWritable(); 60 await writer.write(new Blob([contents])); 61 await writer.close(); 62 return handle; 63 } 64 65 async function cleanup(test, value, cleanup_func) { 66 test.add_cleanup(async () => { 67 try { 68 await cleanup_func(); 69 } catch (e) { 70 // Ignore any errors when removing files, as tests might already remove 71 // the file. 72 } 73 }); 74 return value; 75 } 76 77 async function cleanup_writable(test, value) { 78 return cleanup(test, value, async () => { 79 try { 80 await value.close(); 81 } catch (e) { 82 // Ignore any errors when closing writables, since attempting to close 83 // aborted or closed writables will error. 84 } 85 }); 86 }