aboutsummaryrefslogtreecommitdiff
path: root/contexts/data/lib/closure-library/closure/goog/fs/fs_test.html
blob: b9b5d1e491adc4ff68f439ff06803e86f5452665 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
<!DOCTYPE html>
<html>
<!--
Copyright 2011 The Closure Library Authors. All Rights Reserved.

Use of this source code is governed by the Apache License, Version 2.0.
See the COPYING file for details.
-->
<!--
-->
<head>
<title>Closure Integration Tests - goog.fs</title>
<script src="../base.js"></script>
<script>
goog.require('goog.array');
goog.require('goog.async.Deferred');
goog.require('goog.async.DeferredList');
goog.require('goog.dom');
goog.require('goog.fs');
goog.require('goog.fs.DirectoryEntry.Behavior');
goog.require('goog.testing.AsyncTestCase');
goog.require('goog.testing.PropertyReplacer');
goog.require('goog.testing.jsunit');
</script>
</head>
<body>
<div id="closureTestRunnerLog"></div>
<script>

var TEST_DIR = 'goog-fs-test-dir';

var fsExists = goog.isDef(goog.global.requestFileSystem) ||
    goog.isDef(goog.global.webkitRequestFileSystem);
var deferredFs = fsExists ? goog.fs.getTemporary() : null;
var asyncTestCase = goog.testing.AsyncTestCase.createAndInstall();
var stubs = new goog.testing.PropertyReplacer();


function setUpPage() {
  if (!fsExists) {
    return;
  }

  loadTestDir().addErrback(function(err) {
    var msg;
    if (err.code == goog.fs.Error.ErrorCode.QUOTA_EXCEEDED) {
      msg = err.message + '. If you\'re using Chrome, you probably need to ' +
          'pass --unlimited-quota-for-files on the command line.';
    } else if (err.code == goog.fs.Error.ErrorCode.SECURITY &&
               window.location.href.match(/^file:/)) {
      msg = err.message + '. file:// URLs can\'t access the filesystem API.';
    } else {
      msg = err.message;
    }
    var body = goog.dom.getDocument().body;
    goog.dom.insertSiblingBefore(
        goog.dom.createDom('h1', {}, msg), body.childNodes[0]);
  });
}

function tearDown() {
  if (!fsExists) {
    return;
  }

  loadTestDir().
      addCallback(function(dir) { return dir.removeRecursively(); }).
      addBoth(continueTesting);
  asyncTestCase.waitForAsync('removing filesystem');
}

function testUnavailableTemporaryFilesystem() {
  stubs.set(goog.global, 'requestFileSystem', null);
  stubs.set(goog.global, 'webkitRequestFileSystem', null);
  asyncTestCase.waitForAsync('testUnavailableTemporaryFilesystem');

  goog.fs.getTemporary(1024).addErrback(function(e) {
    assertEquals('File API unsupported', e.message);
    continueTesting();
  });
}


function testUnavailablePersistentFilesystem() {
  stubs.set(goog.global, 'requestFileSystem', null);
  stubs.set(goog.global, 'webkitRequestFileSystem', null);
  asyncTestCase.waitForAsync('testUnavailablePersistentFilesystem');

  goog.fs.getPersistent(2048).addErrback(function(e) {
    assertEquals('File API unsupported', e.message);
    continueTesting();
  });
}


function testIsFile() {
  if (!fsExists) {
    return;
  }

  loadFile('test', goog.fs.DirectoryEntry.Behavior.CREATE).
      addCallback(function(fileEntry) {
        assertFalse(fileEntry.isDirectory());
        assertTrue(fileEntry.isFile());
      }).addBoth(continueTesting);
  asyncTestCase.waitForAsync('testIsFile');
}

function testIsDirectory() {
  if (!fsExists) {
    return;
  }

  loadDirectory('test', goog.fs.DirectoryEntry.Behavior.CREATE).
      addCallback(function(fileEntry) {
        assertTrue(fileEntry.isDirectory());
        assertFalse(fileEntry.isFile());
      }).addBoth(continueTesting);
  asyncTestCase.waitForAsync('testIsDirectory');
}

function testReadFileUtf16() {
  if (!fsExists) {
    return;
  }
  var str = 'test content';
  var buf = new ArrayBuffer(str.length * 2);
  var arr = new Uint16Array(buf);
  for (var i = 0; i < str.length; i++) {
    arr[i] = str.charCodeAt(i);
  }

  loadFile('test', goog.fs.DirectoryEntry.Behavior.CREATE).
      addCallback(goog.partial(writeToFile, arr.buffer)).
      addCallback(goog.partial(checkFileContentWithEncoding, str, 'UTF-16')).
      addBoth(continueTesting);
  asyncTestCase.waitForAsync('testReadFile');
}

function testReadFileUtf8() {
  if (!fsExists) {
    return;
  }
  var str = 'test content';
  var buf = new ArrayBuffer(str.length);
  var arr = new Uint8Array(buf);
  for (var i = 0; i < str.length; i++) {
    arr[i] = str.charCodeAt(i) & 0xff;
  }

  loadFile('test', goog.fs.DirectoryEntry.Behavior.CREATE).
      addCallback(goog.partial(writeToFile, arr.buffer)).
      addCallback(goog.partial(checkFileContentWithEncoding, str, 'UTF-8')).
      addBoth(continueTesting);
  asyncTestCase.waitForAsync('testReadFileUtf8');
}

function testReadFileAsArrayBuffer() {
  if (!fsExists) {
    return;
  }
  var str = 'test content';
  var buf = new ArrayBuffer(str.length);
  var arr = new Uint8Array(buf);
  for (var i = 0; i < str.length; i++) {
    arr[i] = str.charCodeAt(i) & 0xff;
  }

  loadFile('test', goog.fs.DirectoryEntry.Behavior.CREATE).
      addCallback(goog.partial(writeToFile, arr.buffer)).
      addCallback(goog.partial(checkFileContentAs, arr.buffer, 'ArrayBuffer',
          undefined)).
      addBoth(continueTesting);
  asyncTestCase.waitForAsync('testReadFileAsArrayBuffer');
}

function testReadFileAsBinaryString() {
  if (!fsExists) {
    return;
  }
  var str = 'test content';
  var buf = new ArrayBuffer(str.length);
  var arr = new Uint8Array(buf);
  for (var i = 0; i < str.length; i++) {
    arr[i] = str.charCodeAt(i);
  }

  loadFile('test', goog.fs.DirectoryEntry.Behavior.CREATE).
      addCallback(goog.partial(writeToFile, arr.buffer)).
      addCallback(goog.partial(checkFileContentAs, str, 'BinaryString',
          undefined)).
      addBoth(continueTesting);
  asyncTestCase.waitForAsync('testReadFileAsArrayBuffer');
}

function testWriteFile() {
  if (!fsExists) {
    return;
  }

  loadFile('test', goog.fs.DirectoryEntry.Behavior.CREATE).
      addCallback(goog.partial(writeToFile, 'test content')).
      addCallback(goog.partial(checkFileContent, 'test content')).
      addBoth(continueTesting);
  asyncTestCase.waitForAsync('testWriteFile');
}

function testRemoveFile() {
  if (!fsExists) {
    return;
  }

  loadFile('test', goog.fs.DirectoryEntry.Behavior.CREATE).
      addCallback(goog.partial(writeToFile, 'test content')).
      addCallback(function(file) { return file.remove(); }).
      addCallback(goog.partial(checkFileRemoved, 'test')).
      addBoth(continueTesting);
  asyncTestCase.waitForAsync('testRemoveFile');
}

function testMoveFile() {
  if (!fsExists) {
    return;
  }

  var deferredSubdir = loadDirectory(
      'subdir', goog.fs.DirectoryEntry.Behavior.CREATE);
  var deferredWrittenFile =
      loadFile('test', goog.fs.DirectoryEntry.Behavior.CREATE).
      addCallback(goog.partial(writeToFile, 'test content'));
  goog.async.DeferredList.gatherResults([deferredSubdir, deferredWrittenFile]).
      addCallback(splitArgs(function(dir, file) { return file.moveTo(dir); })).
      addCallback(goog.partial(checkFileContent, 'test content')).
      addCallback(goog.partial(checkFileRemoved, 'test')).
      addBoth(continueTesting);
  asyncTestCase.waitForAsync('testMoveFile');
}

function testCopyFile() {
  if (!fsExists) {
    return;
  }

  var deferredFile = loadFile('test', goog.fs.DirectoryEntry.Behavior.CREATE);
  var deferredSubdir = loadDirectory(
      'subdir', goog.fs.DirectoryEntry.Behavior.CREATE);
  var deferredWrittenFile = deferredFile.branch().
      addCallback(goog.partial(writeToFile, 'test content'));
  goog.async.DeferredList.gatherResults([deferredSubdir, deferredWrittenFile]).
      addCallback(splitArgs(function(dir, file) { return file.copyTo(dir); })).
      addCallback(goog.partial(checkFileContent, 'test content')).
      awaitDeferred(deferredFile).
      addCallback(goog.partial(checkFileContent, 'test content')).
      addBoth(continueTesting);
  asyncTestCase.waitForAsync('testMoveFile');
}

function testAbortWrite() {
  // TODO(nicksantos): This test is broken in newer versions of chrome.
  // We don't know why yet.
  if (true) return;

  if (!fsExists) {
    return;
  }

  var deferredFile = loadFile('test', goog.fs.DirectoryEntry.Behavior.CREATE);
  deferredFile.branch().
      addCallback(goog.partial(startWrite, 'test content')).
      addCallback(function(writer) { writer.abort(); }).
      addCallback(
          goog.partial(waitForEvent, goog.fs.FileSaver.EventType.ABORT)).
      awaitDeferred(deferredFile).
      addCallback(goog.partial(checkFileContent, '')).
      addBoth(continueTesting);
  asyncTestCase.waitForAsync('testWriteFile');
}

function testSeek() {
  if (!fsExists) {
    return;
  }

  var deferredFile = loadFile('test', goog.fs.DirectoryEntry.Behavior.CREATE);
  deferredFile.branch().
      addCallback(goog.partial(writeToFile, 'test content')).
      addCallback(function(file) { return file.createWriter(); }).
      addCallback(
          goog.partial(checkReadyState, goog.fs.FileSaver.ReadyState.INIT)).
      addCallback(function(writer) {
        writer.seek(5);
        writer.write(goog.fs.getBlob('stuff and things'));
      }).
      addCallback(
          goog.partial(checkReadyState, goog.fs.FileSaver.ReadyState.WRITING)).
      addCallback(
          goog.partial(waitForEvent, goog.fs.FileSaver.EventType.WRITE)).
      awaitDeferred(deferredFile).
      addCallback(goog.partial(checkFileContent, 'test stuff and things')).
      addBoth(continueTesting);
  asyncTestCase.waitForAsync('testWriteFile');
}

function testTruncate() {
  if (!fsExists) {
    return;
  }

  var deferredFile = loadFile('test', goog.fs.DirectoryEntry.Behavior.CREATE);
  deferredFile.branch().
      addCallback(goog.partial(writeToFile, 'test content')).
      addCallback(function(file) { return file.createWriter(); }).
      addCallback(
          goog.partial(checkReadyState, goog.fs.FileSaver.ReadyState.INIT)).
      addCallback(function(writer) { writer.truncate(4); }).
      addCallback(
          goog.partial(checkReadyState, goog.fs.FileSaver.ReadyState.WRITING)).
      addCallback(
          goog.partial(waitForEvent, goog.fs.FileSaver.EventType.WRITE)).
      awaitDeferred(deferredFile).
      addCallback(goog.partial(checkFileContent, 'test')).
      addBoth(continueTesting);
  asyncTestCase.waitForAsync('testWriteFile');
}

function testGetLastModified() {
  if (!fsExists) {
    return;
  }
  var now = goog.now();
  loadFile('test', goog.fs.DirectoryEntry.Behavior.CREATE).
      addCallback(function(entry) {
        return entry.getLastModified();
      }).addCallback(function(date) {
        assertRoughlyEquals('Expected the last modified date to be within ' +
                            'a few milliseconds of the test start time.',
                            now, date.getTime(), 2000);
      }).addCallback(continueTesting);

  asyncTestCase.waitForAsync('testGetLastModified');
}

function testCreatePath() {
  if (!fsExists) {
    return;
  }

  loadTestDir().
      addCallback(function(testDir) {
        return testDir.createPath('foo');
      }).
      addCallback(function(fooDir) {
        assertEquals('/goog-fs-test-dir/foo', fooDir.getFullPath());
        return fooDir.createPath('bar/baz/bat');
      }).
      addCallback(function(batDir) {
        assertEquals('/goog-fs-test-dir/foo/bar/baz/bat', batDir.getFullPath());
      }).
      addBoth(continueTesting);
  asyncTestCase.waitForAsync('testCreatePath');
}

function testCreateAbsolutePath() {
  if (!fsExists) {
    return;
  }

  loadTestDir().
      addCallback(function(testDir) {
        return testDir.createPath('/' + TEST_DIR + '/fee/fi/fo/fum');
      }).
      addCallback(function(absDir) {
        assertEquals('/goog-fs-test-dir/fee/fi/fo/fum', absDir.getFullPath());
      }).
      addBoth(continueTesting);
  asyncTestCase.waitForAsync('testCreateAbsolutePath');
}

function testCreateRelativePath() {
  if (!fsExists) {
    return;
  }

  loadTestDir().
      addCallback(function(dir) {
        return dir.createPath('../' + TEST_DIR + '/dir');
      }).
      addCallback(function(relDir) {
        assertEquals('/goog-fs-test-dir/dir', relDir.getFullPath());
        return relDir.createPath('.');
      }).
      addCallback(function(sameDir) {
        assertEquals('/goog-fs-test-dir/dir', sameDir.getFullPath());
        return sameDir.createPath('./././.');
      }).
      addCallback(function(reallySameDir) {
        assertEquals('/goog-fs-test-dir/dir', reallySameDir.getFullPath());
        return reallySameDir.createPath('./new/../..//dir/./new////.');
      }).
      addCallback(function(newDir) {
        assertEquals('/goog-fs-test-dir/dir/new', newDir.getFullPath());
      }).
      addBoth(continueTesting);
  asyncTestCase.waitForAsync('testCreateRelativePath');

}

function testCreateBadPath() {
  if (!fsExists) {
    return;
  }

  loadTestDir().
      awaitDeferred(loadTestDir()).
      addCallback(function(dir) {
        // There is only one layer of parent directory from the test dir.
        return dir.createPath('../../../../' + TEST_DIR + '/baz/bat');
      }).
      addCallback(function(batDir) {
        assertEquals('The parent directory of the root directory should ' +
                     'point back to the root directory.',
                     '/goog-fs-test-dir/baz/bat', batDir.getFullPath());
      }).

      awaitDeferred(loadTestDir()).
      addCallback(function(dir) {
        // An empty path should return the same as the input directory.
        return dir.createPath('');
      }).
      addCallback(function(testDir) {
        assertEquals('/goog-fs-test-dir', testDir.getFullPath());
      }).
      addBoth(continueTesting);
  asyncTestCase.waitForAsync('testCreateBadPath');
}

function testGetAbsolutePaths() {
  if (!fsExists) {
    return;
  }

  loadFile('foo', goog.fs.DirectoryEntry.Behavior.CREATE).
      awaitDeferred(loadTestDir()).
      addCallback(function(testDir) {
        return testDir.getDirectory('/');
      }).
      addCallback(function(root) {
        assertEquals('/', root.getFullPath());
        return root.getDirectory('/' + TEST_DIR);
      }).
      addCallback(function(testDir) {
        assertEquals('/goog-fs-test-dir', testDir.getFullPath());
        return testDir.getDirectory('//' + TEST_DIR + '////');
      }).
      addCallback(function(testDir) {
        assertEquals('/goog-fs-test-dir', testDir.getFullPath());
        return testDir.getDirectory('////');
      }).
      addCallback(function(testDir) {
        assertEquals('/', testDir.getFullPath());
      }).
      addBoth(continueTesting);
  asyncTestCase.waitForAsync('testGetAbsolutePaths');
}


function continueTesting(result) {
  asyncTestCase.continueTesting();
  if (result instanceof Error) {
    throw result;
  }
}

function testListEmptyDirectory() {
  if (!fsExists) {
    return;
  }

  loadTestDir().
      addCallback(function(dir) { return dir.listDirectory(); }).
      addCallback(function(entries) { assertArrayEquals([], entries); }).
      addCallback(continueTesting);
  asyncTestCase.waitForAsync('testListEmptyDirectory');
}


function testListDirectory() {
  if (!fsExists) {
    return;
  }

  goog.async.Deferred.succeed().
      // Create the test directory and test entries.
      awaitDeferred(
          loadDirectory('testDir', goog.fs.DirectoryEntry.Behavior.CREATE)).
      awaitDeferred(
          loadFile('testFile', goog.fs.DirectoryEntry.Behavior.CREATE)).
      awaitDeferred(loadTestDir()).

      // Verify the contents of the directory listing.
      addCallback(function(testDir) { return testDir.listDirectory(); }).
      addCallback(function(entries) {
        assertEquals(2, entries.length);

        var dir = goog.array.find(entries, function(entry) {
          return entry.getName() == 'testDir';
        });
        assertNotNull(dir);
        assertTrue(dir.isDirectory());

        var file = goog.array.find(entries, function(entry) {
          return entry.getName() == 'testFile';
        });
        assertNotNull(file);
        assertTrue(file.isFile());
      }).
      addCallback(continueTesting);

  asyncTestCase.waitForAsync('testListDirectory');
}


function testListBigDirectory() {
  // TODO(nicksantos): This test is broken in newer versions of chrome.
  // We don't know why yet.
  if (true) return;

  if (!fsExists) {
    return;
  }

  function getFileName(i) {
    return 'file' + goog.string.padNumber(i, String(count).length);
  }

  // NOTE: This was intended to verify that the results from repeated
  // DirectoryReader.readEntries() callbacks are appropriately concatenated.
  // In current versions of Chrome (March 2011), all results are returned in the
  // first callback regardless of directory size. The count can be increased in
  // the future to test batched result lists once they are implemented.
  var count = 100;

  var expectedNames = [];

  var def = goog.async.Deferred.succeed();
  for (var i = 0; i < count; i++) {
    var name = getFileName(i);
    expectedNames.push(name);

    def.awaitDeferred(
        loadFile(name, goog.fs.DirectoryEntry.Behavior.CREATE));
  }

  def.awaitDeferred(loadTestDir()).
      addCallback(function(testDir) { return testDir.listDirectory(); }).
      addCallback(function(entries) {
        assertEquals(count, entries.length);

        assertSameElements(expectedNames,
                           goog.array.map(entries, function(entry) {
                             return entry.getName();
                           }));
        assertTrue(goog.array.every(entries, function(entry) {
                     return entry.isFile();
                   }));
      }).
      addCallback(continueTesting);

  asyncTestCase.waitForAsync('testListBigDirectory');
}


function testSliceBlob() {
  // A mock blob object whose slice returns the parameters it was called with.
  var blob = {
    'size': 10,
    'slice': function(start, end) {
      return [start, end];
    }
  };

  // Simulate Firefox 13 that implements the new slice.
  var tmpStubs = new goog.testing.PropertyReplacer();
  tmpStubs.set(goog.userAgent, 'GECKO', true);
  tmpStubs.set(goog.userAgent, 'WEBKIT', false);
  tmpStubs.set(goog.userAgent, 'IE', false);
  tmpStubs.set(goog.userAgent, 'VERSION', '13.0');
  tmpStubs.set(goog.userAgent, 'isVersionCache_', {});

  // Expect slice to be called with no change to parameters
  assertArrayEquals([2, 10], goog.fs.sliceBlob(blob, 2));
  assertArrayEquals([-2, 10], goog.fs.sliceBlob(blob, -2));
  assertArrayEquals([3, 6], goog.fs.sliceBlob(blob, 3, 6));
  assertArrayEquals([3, -6], goog.fs.sliceBlob(blob, 3, -6));

  // Simulate IE 10 that implements the new slice.
  var tmpStubs = new goog.testing.PropertyReplacer();
  tmpStubs.set(goog.userAgent, 'GECKO', false);
  tmpStubs.set(goog.userAgent, 'WEBKIT', false);
  tmpStubs.set(goog.userAgent, 'IE', true);
  tmpStubs.set(goog.userAgent, 'VERSION', '10.0');
  tmpStubs.set(goog.userAgent, 'isVersionCache_', {});

  // Expect slice to be called with no change to parameters
  assertArrayEquals([2, 10], goog.fs.sliceBlob(blob, 2));
  assertArrayEquals([-2, 10], goog.fs.sliceBlob(blob, -2));
  assertArrayEquals([3, 6], goog.fs.sliceBlob(blob, 3, 6));
  assertArrayEquals([3, -6], goog.fs.sliceBlob(blob, 3, -6));

  // Simulate Firefox 4 that implements the old slice.
  tmpStubs.set(goog.userAgent, 'GECKO', true);
  tmpStubs.set(goog.userAgent, 'WEBKIT', false);
  tmpStubs.set(goog.userAgent, 'IE', false);
  tmpStubs.set(goog.userAgent, 'VERSION', '2.0');
  tmpStubs.set(goog.userAgent, 'isVersionCache_', {});

  // Expect slice to be called with transformed parameters.
  assertArrayEquals([2, 8], goog.fs.sliceBlob(blob, 2));
  assertArrayEquals([8, 2], goog.fs.sliceBlob(blob, -2));
  assertArrayEquals([3, 3], goog.fs.sliceBlob(blob, 3, 6));
  assertArrayEquals([3, 1], goog.fs.sliceBlob(blob, 3, -6));

  // Simulate Firefox 5 that implements mozSlice (new spec).
  delete blob.slice
  blob.mozSlice = function(start, end) {
    return ['moz', start, end];
  }
  tmpStubs.set(goog.userAgent, 'GECKO', true);
  tmpStubs.set(goog.userAgent, 'WEBKIT', false);
  tmpStubs.set(goog.userAgent, 'IE', false);
  tmpStubs.set(goog.userAgent, 'VERSION', '5.0');
  tmpStubs.set(goog.userAgent, 'isVersionCache_', {});

  // Expect mozSlice to be called with no change to parameters.
  assertArrayEquals(['moz', 2, 10], goog.fs.sliceBlob(blob, 2));
  assertArrayEquals(['moz', -2, 10], goog.fs.sliceBlob(blob, -2));
  assertArrayEquals(['moz', 3, 6], goog.fs.sliceBlob(blob, 3, 6));
  assertArrayEquals(['moz', 3, -6], goog.fs.sliceBlob(blob, 3, -6));

  // Simulate Chrome 20 that implements webkitSlice (new spec).
  delete blob.mozSlice;
  blob.webkitSlice = function(start, end) {
    return ['webkit', start, end];
  }
  tmpStubs.set(goog.userAgent, 'GECKO', false);
  tmpStubs.set(goog.userAgent, 'WEBKIT', true);
  tmpStubs.set(goog.userAgent, 'IE', false);
  tmpStubs.set(goog.userAgent, 'VERSION', '536.10');
  tmpStubs.set(goog.userAgent, 'isVersionCache_', {});

  // Expect webkitSlice to be called with no change to parameters.
  assertArrayEquals(['webkit', 2, 10], goog.fs.sliceBlob(blob, 2));
  assertArrayEquals(['webkit', -2, 10], goog.fs.sliceBlob(blob, -2));
  assertArrayEquals(['webkit', 3, 6], goog.fs.sliceBlob(blob, 3, 6));
  assertArrayEquals(['webkit', 3, -6], goog.fs.sliceBlob(blob, 3, -6));

  tmpStubs.reset();
}


function loadTestDir() {
  return deferredFs.branch().addCallback(function(fs) {
    return fs.getRoot().getDirectory(
        TEST_DIR, goog.fs.DirectoryEntry.Behavior.CREATE);
  });
}

function loadFile(filename, behavior) {
  return loadTestDir().addCallback(function(dir) {
    return dir.getFile(filename, behavior);
  });
}

function loadDirectory(filename, behavior) {
  return loadTestDir().addCallback(function(dir) {
    return dir.getDirectory(filename, behavior);
  });
}

function startWrite(content, file) {
  return file.createWriter().
      addCallback(
          goog.partial(checkReadyState, goog.fs.FileSaver.ReadyState.INIT)).
      addCallback(function(writer) {
        writer.write(goog.fs.getBlob(content));
        return writer;
      }).
      addCallback(
          goog.partial(checkReadyState, goog.fs.FileSaver.ReadyState.WRITING));
}

function waitForEvent(type, target) {
  var d = new goog.async.Deferred();
  goog.events.listenOnce(target, type, d.callback, false, d);
  return d;
}

function writeToFile(content, file) {
  return startWrite(content, file).
      addCallback(
          goog.partial(waitForEvent, goog.fs.FileSaver.EventType.WRITE)).
      addCallback(function() { return file; });
}

function checkFileContent(content, file) {
  return checkFileContentAs(content, 'Text', undefined, file);
}

function checkFileContentWithEncoding(content, encoding, file) {
  checkFileContentAs(content, 'Text', encoding, file);
}

function checkFileContentAs(content, filetype, encoding, file) {
  return file.file().
      addCallback(function(blob) {
        return goog.fs.FileReader['readAs' + filetype](blob, encoding);
      }).
      addCallback(goog.partial(checkEquals, content));
}

function checkEquals(a, b) {
  if (a instanceof ArrayBuffer && b instanceof ArrayBuffer) {
    assertEquals(a.byteLength, b.byteLength);
    var viewA = new DataView(a);
    var viewB = new DataView(b);
    for (var i = 0; i < a.byteLength; i++) {
      assertEquals(viewA.getUint8(i), viewB.getUint8(i));
    }
  } else {
    assertEquals(a, b);
  }
}

function checkFileRemoved(filename) {
  return loadFile(filename).
      addCallback(goog.partial(fail, 'expected file to be removed')).
      addErrback(function(err) {
        assertEquals(err.code, goog.fs.Error.ErrorCode.NOT_FOUND);
        return true; // Go back to callback path
      });
}

function checkReadyState(expectedState, writer) {
  assertEquals(expectedState, writer.getReadyState());
}

function splitArgs(fn) {
  return function(args) { return fn(args[0], args[1]); };
}

</script>
</body>
</html>