Debian Codegraph @

closure-library/closure/goog/fs/fs_test.js

raw
1 // Copyright 2011 The Closure Library Authors. All Rights Reserved.
2 //
3 // Licensed under the Apache License, Version 2.0 (the "License");
4 // you may not use this file except in compliance with the License.
5 // You may obtain a copy of the License at
6 //
7 // http://www.apache.org/licenses/LICENSE-2.0
8 //
9 // Unless required by applicable law or agreed to in writing, software
10 // distributed under the License is distributed on an "AS-IS" BASIS,
11 // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12 // See the License for the specific language governing permissions and
13 // limitations under the License.
14
15 goog.provide('goog.fsTest');
16 goog.setTestOnly('goog.fsTest');
17
18 goog.require('goog.Promise');
19 goog.require('goog.array');
20 goog.require('goog.dom');
21 goog.require('goog.dom.TagName');
22 goog.require('goog.events');
23 goog.require('goog.fs');
24 goog.require('goog.fs.DirectoryEntry');
25 goog.require('goog.fs.Error');
26 goog.require('goog.fs.FileReader');
27 goog.require('goog.fs.FileSaver');
28 goog.require('goog.string');
29 goog.require('goog.testing.PropertyReplacer');
30 goog.require('goog.testing.jsunit');
31
32 var TEST_DIR = 'goog-fs-test-dir';
33
34 var fsExists = goog.isDef(goog.global.requestFileSystem) ||
35 goog.isDef(goog.global.webkitRequestFileSystem);
36 var deferredFs = fsExists ? goog.fs.getTemporary() : null;
37 var stubs = new goog.testing.PropertyReplacer();
38
39 function setUpPage() {
40 if (!fsExists) {
41 return;
42 }
43
44 return loadTestDir().then(null, function(err) {
45 var msg;
46 if (err.code == goog.fs.Error.ErrorCode.QUOTA_EXCEEDED) {
47 msg = err.message + '. If you\'re using Chrome, you probably need to ' +
48 'pass --unlimited-quota-for-files on the command line.';
49 } else if (
50 err.code == goog.fs.Error.ErrorCode.SECURITY &&
51 window.location.href.match(/^file:/)) {
52 msg = err.message + '. file:// URLs can\'t access the filesystem API.';
53 } else {
54 msg = err.message;
55 }
56 var body = goog.dom.getDocument().body;
57 goog.dom.insertSiblingBefore(
58 goog.dom.createDom(goog.dom.TagName.H1, {}, msg), body.childNodes[0]);
59 });
60 }
61
62 function tearDown() {
63 if (!fsExists) {
64 return;
65 }
66
67 return loadTestDir().then(function(dir) { return dir.removeRecursively(); });
68 }
69
70 function testUnavailableTemporaryFilesystem() {
71 stubs.set(goog.global, 'requestFileSystem', null);
72 stubs.set(goog.global, 'webkitRequestFileSystem', null);
73
74 return goog.fs.getTemporary(1024).then(
75 fail, function(e) { assertEquals('File API unsupported', e.message); });
76 }
77
78
79 function testUnavailablePersistentFilesystem() {
80 stubs.set(goog.global, 'requestFileSystem', null);
81 stubs.set(goog.global, 'webkitRequestFileSystem', null);
82
83 return goog.fs.getPersistent(2048).then(
84 fail, function(e) { assertEquals('File API unsupported', e.message); });
85 }
86
87
88 function testIsFile() {
89 if (!fsExists) {
90 return;
91 }
92
93 return loadFile('test', goog.fs.DirectoryEntry.Behavior.CREATE)
94 .then(function(fileEntry) {
95 assertFalse(fileEntry.isDirectory());
96 assertTrue(fileEntry.isFile());
97 });
98 }
99
100 function testIsDirectory() {
101 if (!fsExists) {
102 return;
103 }
104
105 return loadDirectory('test', goog.fs.DirectoryEntry.Behavior.CREATE)
106 .then(function(fileEntry) {
107 assertTrue(fileEntry.isDirectory());
108 assertFalse(fileEntry.isFile());
109 });
110 }
111
112 function testReadFileUtf16() {
113 if (!fsExists) {
114 return;
115 }
116 var str = 'test content';
117 var buf = new ArrayBuffer(str.length * 2);
118 var arr = new Uint16Array(buf);
119 for (var i = 0; i < str.length; i++) {
120 arr[i] = str.charCodeAt(i);
121 }
122
123 return loadFile('test', goog.fs.DirectoryEntry.Behavior.CREATE)
124 .then(goog.partial(writeToFile, arr.buffer))
125 .then(goog.partial(checkFileContentWithEncoding, str, 'UTF-16'));
126 }
127
128 function testReadFileUtf8() {
129 if (!fsExists) {
130 return;
131 }
132 var str = 'test content';
133 var buf = new ArrayBuffer(str.length);
134 var arr = new Uint8Array(buf);
135 for (var i = 0; i < str.length; i++) {
136 arr[i] = str.charCodeAt(i) & 0xff;
137 }
138
139 return loadFile('test', goog.fs.DirectoryEntry.Behavior.CREATE)
140 .then(goog.partial(writeToFile, arr.buffer))
141 .then(goog.partial(checkFileContentWithEncoding, str, 'UTF-8'));
142 }
143
144 function testReadFileAsArrayBuffer() {
145 if (!fsExists) {
146 return;
147 }
148 var str = 'test content';
149 var buf = new ArrayBuffer(str.length);
150 var arr = new Uint8Array(buf);
151 for (var i = 0; i < str.length; i++) {
152 arr[i] = str.charCodeAt(i) & 0xff;
153 }
154
155 return loadFile('test', goog.fs.DirectoryEntry.Behavior.CREATE)
156 .then(goog.partial(writeToFile, arr.buffer))
157 .then(
158 goog.partial(
159 checkFileContentAs, arr.buffer, 'ArrayBuffer', undefined));
160 }
161
162 function testReadFileAsBinaryString() {
163 if (!fsExists) {
164 return;
165 }
166 var str = 'test content';
167 var buf = new ArrayBuffer(str.length);
168 var arr = new Uint8Array(buf);
169 for (var i = 0; i < str.length; i++) {
170 arr[i] = str.charCodeAt(i);
171 }
172
173 return loadFile('test', goog.fs.DirectoryEntry.Behavior.CREATE)
174 .then(goog.partial(writeToFile, arr.buffer))
175 .then(goog.partial(checkFileContentAs, str, 'BinaryString', undefined));
176 }
177
178 function testWriteFile() {
179 if (!fsExists) {
180 return;
181 }
182
183 return loadFile('test', goog.fs.DirectoryEntry.Behavior.CREATE)
184 .then(goog.partial(writeToFile, 'test content'))
185 .then(goog.partial(checkFileContent, 'test content'));
186 }
187
188 function testRemoveFile() {
189 if (!fsExists) {
190 return;
191 }
192
193 return loadFile('test', goog.fs.DirectoryEntry.Behavior.CREATE)
194 .then(goog.partial(writeToFile, 'test content'))
195 .then(function(file) { return file.remove(); })
196 .then(goog.partial(checkFileRemoved, 'test'));
197 }
198
199 function testMoveFile() {
200 if (!fsExists) {
201 return;
202 }
203
204 var deferredSubdir =
205 loadDirectory('subdir', goog.fs.DirectoryEntry.Behavior.CREATE);
206 var deferredWrittenFile =
207 loadFile('test', goog.fs.DirectoryEntry.Behavior.CREATE)
208 .then(goog.partial(writeToFile, 'test content'));
209 return goog.Promise.all([deferredSubdir, deferredWrittenFile])
210 .then(splitArgs(function(dir, file) { return file.moveTo(dir); }))
211 .then(goog.partial(checkFileContent, 'test content'))
212 .then(goog.partial(checkFileRemoved, 'test'));
213 }
214
215 function testCopyFile() {
216 if (!fsExists) {
217 return;
218 }
219
220 var deferredFile = loadFile('test', goog.fs.DirectoryEntry.Behavior.CREATE);
221 var deferredSubdir =
222 loadDirectory('subdir', goog.fs.DirectoryEntry.Behavior.CREATE);
223 var deferredWrittenFile =
224 deferredFile.then(goog.partial(writeToFile, 'test content'));
225 return goog.Promise.all([deferredSubdir, deferredWrittenFile])
226 .then(splitArgs(function(dir, file) { return file.copyTo(dir); }))
227 .then(goog.partial(checkFileContent, 'test content'))
228 .then(function() { return deferredFile; })
229 .then(goog.partial(checkFileContent, 'test content'));
230 }
231
232 function testAbortWrite() {
233 // TODO(nicksantos): This test is broken in newer versions of chrome.
234 // We don't know why yet.
235 if (true) return;
236
237 if (!fsExists) {
238 return;
239 }
240
241 var deferredFile = loadFile('test', goog.fs.DirectoryEntry.Behavior.CREATE);
242 return deferredFile.then(goog.partial(startWrite, 'test content'))
243 .then(function(writer) {
244 return new goog.Promise(function(resolve) {
245 goog.events.listenOnce(
246 writer, goog.fs.FileSaver.EventType.ABORT, resolve);
247 writer.abort();
248 });
249 })
250 .then(function() { return loadFile('test'); })
251 .then(goog.partial(checkFileContent, ''));
252 }
253
254 function testSeek() {
255 if (!fsExists) {
256 return;
257 }
258
259 var deferredFile = loadFile('test', goog.fs.DirectoryEntry.Behavior.CREATE);
260 return deferredFile.then(goog.partial(writeToFile, 'test content'))
261 .then(function(file) { return file.createWriter(); })
262 .then(goog.partial(checkReadyState, goog.fs.FileSaver.ReadyState.INIT))
263 .then(function(writer) {
264 writer.seek(5);
265 writer.write(goog.fs.getBlob('stuff and things'));
266 return writer;
267 })
268 .then(goog.partial(checkReadyState, goog.fs.FileSaver.ReadyState.WRITING))
269 .then(goog.partial(waitForEvent, goog.fs.FileSaver.EventType.WRITE))
270 .then(function() { return deferredFile; })
271 .then(goog.partial(checkFileContent, 'test stuff and things'));
272 }
273
274 function testTruncate() {
275 if (!fsExists) {
276 return;
277 }
278
279 var deferredFile = loadFile('test', goog.fs.DirectoryEntry.Behavior.CREATE);
280 return deferredFile.then(goog.partial(writeToFile, 'test content'))
281 .then(function(file) { return file.createWriter(); })
282 .then(goog.partial(checkReadyState, goog.fs.FileSaver.ReadyState.INIT))
283 .then(function(writer) {
284 writer.truncate(4);
285 return writer;
286 })
287 .then(goog.partial(checkReadyState, goog.fs.FileSaver.ReadyState.WRITING))
288 .then(goog.partial(waitForEvent, goog.fs.FileSaver.EventType.WRITE))
289 .then(function() { return deferredFile; })
290 .then(goog.partial(checkFileContent, 'test'));
291 }
292
293 function testGetLastModified() {
294 if (!fsExists) {
295 return;
296 }
297 var now = goog.now();
298 return loadFile('test', goog.fs.DirectoryEntry.Behavior.CREATE)
299 .then(function(entry) { return entry.getLastModified(); })
300 .then(function(date) {
301 assertRoughlyEquals(
302 'Expected the last modified date to be within ' +
303 'a few milliseconds of the test start time.',
304 now, date.getTime(), 2000);
305 });
306 }
307
308 function testCreatePath() {
309 if (!fsExists) {
310 return;
311 }
312
313 return loadTestDir()
314 .then(function(testDir) { return testDir.createPath('foo'); })
315 .then(function(fooDir) {
316 assertEquals('/goog-fs-test-dir/foo', fooDir.getFullPath());
317 return fooDir.createPath('bar/baz/bat');
318 })
319 .then(function(batDir) {
320 assertEquals('/goog-fs-test-dir/foo/bar/baz/bat', batDir.getFullPath());
321 });
322 }
323
324 function testCreateAbsolutePath() {
325 if (!fsExists) {
326 return;
327 }
328
329 return loadTestDir()
330 .then(function(testDir) {
331 return testDir.createPath('/' + TEST_DIR + '/fee/fi/fo/fum');
332 })
333 .then(function(absDir) {
334 assertEquals('/goog-fs-test-dir/fee/fi/fo/fum', absDir.getFullPath());
335 });
336 }
337
338 function testCreateRelativePath() {
339 if (!fsExists) {
340 return;
341 }
342
343 return loadTestDir()
344 .then(function(dir) { return dir.createPath('../' + TEST_DIR + '/dir'); })
345 .then(function(relDir) {
346 assertEquals('/goog-fs-test-dir/dir', relDir.getFullPath());
347 return relDir.createPath('.');
348 })
349 .then(function(sameDir) {
350 assertEquals('/goog-fs-test-dir/dir', sameDir.getFullPath());
351 return sameDir.createPath('./././.');
352 })
353 .then(function(reallySameDir) {
354 assertEquals('/goog-fs-test-dir/dir', reallySameDir.getFullPath());
355 return reallySameDir.createPath('./new/../..//dir/./new////.');
356 })
357 .then(function(newDir) {
358 assertEquals('/goog-fs-test-dir/dir/new', newDir.getFullPath());
359 });
360 }
361
362 function testCreateBadPath() {
363 if (!fsExists) {
364 return;
365 }
366
367 return loadTestDir()
368 .then(function() { return loadTestDir(); })
369 .then(function(dir) {
370 // There is only one layer of parent directory from the test dir.
371 return dir.createPath('../../../../' + TEST_DIR + '/baz/bat');
372 })
373 .then(function(batDir) {
374 assertEquals(
375 'The parent directory of the root directory should ' +
376 'point back to the root directory.',
377 '/goog-fs-test-dir/baz/bat', batDir.getFullPath());
378 })
379 .
380
381 then(function() { return loadTestDir(); })
382 .then(function(dir) {
383 // An empty path should return the same as the input directory.
384 return dir.createPath('');
385 })
386 .then(function(testDir) {
387 assertEquals('/goog-fs-test-dir', testDir.getFullPath());
388 });
389 }
390
391 function testGetAbsolutePaths() {
392 if (!fsExists) {
393 return;
394 }
395
396 return loadFile('foo', goog.fs.DirectoryEntry.Behavior.CREATE)
397 .then(function() { return loadTestDir(); })
398 .then(function(testDir) { return testDir.getDirectory('/'); })
399 .then(function(root) {
400 assertEquals('/', root.getFullPath());
401 return root.getDirectory('/' + TEST_DIR);
402 })
403 .then(function(testDir) {
404 assertEquals('/goog-fs-test-dir', testDir.getFullPath());
405 return testDir.getDirectory('//' + TEST_DIR + '////');
406 })
407 .then(function(testDir) {
408 assertEquals('/goog-fs-test-dir', testDir.getFullPath());
409 return testDir.getDirectory('////');
410 })
411 .then(function(testDir) { assertEquals('/', testDir.getFullPath()); });
412 }
413
414
415 function testListEmptyDirectory() {
416 if (!fsExists) {
417 return;
418 }
419
420 return loadTestDir()
421 .then(function(dir) { return dir.listDirectory(); })
422 .then(function(entries) { assertArrayEquals([], entries); });
423 }
424
425
426 function testListDirectory() {
427 if (!fsExists) {
428 return;
429 }
430
431 return loadDirectory('testDir', goog.fs.DirectoryEntry.Behavior.CREATE)
432 .then(function() {
433 return loadFile('testFile', goog.fs.DirectoryEntry.Behavior.CREATE);
434 })
435 .then(function() { return loadTestDir(); })
436 .then(function(testDir) { return testDir.listDirectory(); })
437 .then(function(entries) {
438 // Verify the contents of the directory listing.
439 assertEquals(2, entries.length);
440
441 var dir = goog.array.find(
442 entries, function(entry) { return entry.getName() == 'testDir'; });
443 assertNotNull(dir);
444 assertTrue(dir.isDirectory());
445
446 var file = goog.array.find(
447 entries, function(entry) { return entry.getName() == 'testFile'; });
448 assertNotNull(file);
449 assertTrue(file.isFile());
450 });
451 }
452
453
454 function testListBigDirectory() {
455 // TODO(nicksantos): This test is broken in newer versions of chrome.
456 // We don't know why yet.
457 if (true) return;
458
459 if (!fsExists) {
460 return;
461 }
462
463 function getFileName(i) {
464 return 'file' + goog.string.padNumber(i, String(count).length);
465 }
466
467 // NOTE: This was intended to verify that the results from repeated
468 // DirectoryReader.readEntries() callbacks are appropriately concatenated.
469 // In current versions of Chrome (March 2011), all results are returned in the
470 // first callback regardless of directory size. The count can be increased in
471 // the future to test batched result lists once they are implemented.
472 var count = 100;
473
474 var expectedNames = [];
475
476 var def = goog.Promise.resolve();
477 for (var i = 0; i < count; i++) {
478 var name = getFileName(i);
479 expectedNames.push(name);
480
481 def.then(function() {
482 return loadFile(name, goog.fs.DirectoryEntry.Behavior.CREATE);
483 });
484 }
485
486 return def.then(function() { return loadTestDir(); })
487 .then(function(testDir) { return testDir.listDirectory(); })
488 .then(function(entries) {
489 assertEquals(count, entries.length);
490
491 assertSameElements(
492 expectedNames, goog.array.map(entries, function(entry) {
493 return entry.getName();
494 }));
495 assertTrue(goog.array.every(entries, function(entry) {
496 return entry.isFile();
497 }));
498 });
499 }
500
501
502 function testSliceBlob() {
503 // A mock blob object whose slice returns the parameters it was called with.
504 var blob = {
505 'size': 10,
506 'slice': function(start, end) {
507 return [start, end];
508 }
509 };
510
511 // Simulate Firefox 13 that implements the new slice.
512 var tmpStubs = new goog.testing.PropertyReplacer();
513 tmpStubs.set(goog.userAgent, 'GECKO', true);
514 tmpStubs.set(goog.userAgent, 'WEBKIT', false);
515 tmpStubs.set(goog.userAgent, 'IE', false);
516 tmpStubs.set(goog.userAgent, 'VERSION', '13.0');
517 tmpStubs.set(goog.userAgent, 'isVersionOrHigherCache_', {});
518
519 // Expect slice to be called with no change to parameters
520 assertArrayEquals([2, 10], goog.fs.sliceBlob(blob, 2));
521 assertArrayEquals([-2, 10], goog.fs.sliceBlob(blob, -2));
522 assertArrayEquals([3, 6], goog.fs.sliceBlob(blob, 3, 6));
523 assertArrayEquals([3, -6], goog.fs.sliceBlob(blob, 3, -6));
524
525 // Simulate IE 10 that implements the new slice.
526 var tmpStubs = new goog.testing.PropertyReplacer();
527 tmpStubs.set(goog.userAgent, 'GECKO', false);
528 tmpStubs.set(goog.userAgent, 'WEBKIT', false);
529 tmpStubs.set(goog.userAgent, 'IE', true);
530 tmpStubs.set(goog.userAgent, 'VERSION', '10.0');
531 tmpStubs.set(goog.userAgent, 'isVersionOrHigherCache_', {});
532
533 // Expect slice to be called with no change to parameters
534 assertArrayEquals([2, 10], goog.fs.sliceBlob(blob, 2));
535 assertArrayEquals([-2, 10], goog.fs.sliceBlob(blob, -2));
536 assertArrayEquals([3, 6], goog.fs.sliceBlob(blob, 3, 6));
537 assertArrayEquals([3, -6], goog.fs.sliceBlob(blob, 3, -6));
538
539 // Simulate Firefox 4 that implements the old slice.
540 tmpStubs.set(goog.userAgent, 'GECKO', true);
541 tmpStubs.set(goog.userAgent, 'WEBKIT', false);
542 tmpStubs.set(goog.userAgent, 'IE', false);
543 tmpStubs.set(goog.userAgent, 'VERSION', '2.0');
544 tmpStubs.set(goog.userAgent, 'isVersionOrHigherCache_', {});
545
546 // Expect slice to be called with transformed parameters.
547 assertArrayEquals([2, 8], goog.fs.sliceBlob(blob, 2));
548 assertArrayEquals([8, 2], goog.fs.sliceBlob(blob, -2));
549 assertArrayEquals([3, 3], goog.fs.sliceBlob(blob, 3, 6));
550 assertArrayEquals([3, 1], goog.fs.sliceBlob(blob, 3, -6));
551
552 // Simulate Firefox 5 that implements mozSlice (new spec).
553 delete blob.slice;
554 blob.mozSlice = function(start, end) { return ['moz', start, end]; };
555 tmpStubs.set(goog.userAgent, 'GECKO', true);
556 tmpStubs.set(goog.userAgent, 'WEBKIT', false);
557 tmpStubs.set(goog.userAgent, 'IE', false);
558 tmpStubs.set(goog.userAgent, 'VERSION', '5.0');
559 tmpStubs.set(goog.userAgent, 'isVersionOrHigherCache_', {});
560
561 // Expect mozSlice to be called with no change to parameters.
562 assertArrayEquals(['moz', 2, 10], goog.fs.sliceBlob(blob, 2));
563 assertArrayEquals(['moz', -2, 10], goog.fs.sliceBlob(blob, -2));
564 assertArrayEquals(['moz', 3, 6], goog.fs.sliceBlob(blob, 3, 6));
565 assertArrayEquals(['moz', 3, -6], goog.fs.sliceBlob(blob, 3, -6));
566
567 // Simulate Chrome 20 that implements webkitSlice (new spec).
568 delete blob.mozSlice;
569 blob.webkitSlice = function(start, end) { return ['webkit', start, end]; };
570 tmpStubs.set(goog.userAgent, 'GECKO', false);
571 tmpStubs.set(goog.userAgent, 'WEBKIT', true);
572 tmpStubs.set(goog.userAgent, 'IE', false);
573 tmpStubs.set(goog.userAgent, 'VERSION', '536.10');
574 tmpStubs.set(goog.userAgent, 'isVersionOrHigherCache_', {});
575
576 // Expect webkitSlice to be called with no change to parameters.
577 assertArrayEquals(['webkit', 2, 10], goog.fs.sliceBlob(blob, 2));
578 assertArrayEquals(['webkit', -2, 10], goog.fs.sliceBlob(blob, -2));
579 assertArrayEquals(['webkit', 3, 6], goog.fs.sliceBlob(blob, 3, 6));
580 assertArrayEquals(['webkit', 3, -6], goog.fs.sliceBlob(blob, 3, -6));
581
582 tmpStubs.reset();
583 }
584
585
586 function testGetBlobThrowsError() {
587 stubs.remove(goog.global, 'BlobBuilder');
588 stubs.remove(goog.global, 'WebKitBlobBuilder');
589 stubs.remove(goog.global, 'Blob');
590
591 try {
592 goog.fs.getBlob();
593 fail();
594 } catch (e) {
595 assertEquals(
596 'This browser doesn\'t seem to support creating Blobs', e.message);
597 }
598
599 stubs.reset();
600 }
601
602
603 function testGetBlobWithProperties() {
604 // Skip test if browser doesn't support Blob API.
605 if (typeof(goog.global.Blob) != 'function') {
606 return;
607 }
608
609 var blob = goog.fs.getBlobWithProperties(['test'], 'text/test', 'native');
610 assertEquals('text/test', blob.type);
611 }
612
613
614 function testGetBlobWithPropertiesThrowsError() {
615 stubs.remove(goog.global, 'BlobBuilder');
616 stubs.remove(goog.global, 'WebKitBlobBuilder');
617 stubs.remove(goog.global, 'Blob');
618
619 try {
620 goog.fs.getBlobWithProperties();
621 fail();
622 } catch (e) {
623 assertEquals(
624 'This browser doesn\'t seem to support creating Blobs', e.message);
625 }
626
627 stubs.reset();
628 }
629
630
631 function testGetBlobWithPropertiesUsingBlobBuilder() {
632 function BlobBuilder() {
633 this.parts = [];
634 this.append = function(value, endings) {
635 this.parts.push({value: value, endings: endings});
636 };
637 this.getBlob = function(type) { return {type: type, builder: this}; };
638 }
639 stubs.set(goog.global, 'BlobBuilder', BlobBuilder);
640
641 var blob = goog.fs.getBlobWithProperties(['test'], 'text/test', 'native');
642 assertEquals('text/test', blob.type);
643 assertEquals('test', blob.builder.parts[0].value);
644 assertEquals('native', blob.builder.parts[0].endings);
645
646 stubs.reset();
647 }
648
649
650 function loadTestDir() {
651 return deferredFs.then(function(fs) {
652 return fs.getRoot().getDirectory(
653 TEST_DIR, goog.fs.DirectoryEntry.Behavior.CREATE);
654 });
655 }
656
657 function loadFile(filename, behavior) {
658 return loadTestDir().then(function(dir) {
659 return dir.getFile(filename, behavior);
660 });
661 }
662
663 function loadDirectory(filename, behavior) {
664 return loadTestDir().then(function(dir) {
665 return dir.getDirectory(filename, behavior);
666 });
667 }
668
669 function startWrite(content, file) {
670 return file.createWriter()
671 .then(goog.partial(checkReadyState, goog.fs.FileSaver.ReadyState.INIT))
672 .then(function(writer) {
673 writer.write(goog.fs.getBlob(content));
674 return writer;
675 })
676 .then(
677 goog.partial(checkReadyState, goog.fs.FileSaver.ReadyState.WRITING));
678 }
679
680 function waitForEvent(type, target) {
681 var done;
682 var promise = new goog.Promise(function(_done) { done = _done; });
683 goog.events.listenOnce(target, type, done);
684 return promise;
685 }
686
687 function writeToFile(content, file) {
688 return startWrite(content, file)
689 .then(goog.partial(waitForEvent, goog.fs.FileSaver.EventType.WRITE))
690 .then(function() { return file; });
691 }
692
693 function checkFileContent(content, file) {
694 return checkFileContentAs(content, 'Text', undefined, file);
695 }
696
697 function checkFileContentWithEncoding(content, encoding, file) {
698 return checkFileContentAs(content, 'Text', encoding, file);
699 }
700
701 function checkFileContentAs(content, filetype, encoding, file) {
702 return file.file()
703 .then(function(blob) {
704 return goog.fs.FileReader['readAs' + filetype](blob, encoding);
705 })
706 .then(goog.partial(checkEquals, content));
707 }
708
709 function checkEquals(a, b) {
710 if (a instanceof ArrayBuffer && b instanceof ArrayBuffer) {
711 assertEquals(a.byteLength, b.byteLength);
712 var viewA = new DataView(a);
713 var viewB = new DataView(b);
714 for (var i = 0; i < a.byteLength; i++) {
715 assertEquals(viewA.getUint8(i), viewB.getUint8(i));
716 }
717 } else {
718 assertEquals(a, b);
719 }
720 }
721
722 function checkFileRemoved(filename) {
723 return loadFile(filename).then(
724 goog.partial(fail, 'expected file to be removed'), function(err) {
725 assertEquals(err.code, goog.fs.Error.ErrorCode.NOT_FOUND);
726 });
727 }
728
729 function checkReadyState(expectedState, writer) {
730 assertEquals(expectedState, writer.getReadyState());
731 return writer;
732 }
733
734 function splitArgs(fn) {
735 return function(args) { return fn(args[0], args[1]); };
736 }