1 /*
2  * Copyright (C) 2016 The Android Open Source Project
3  *
4  * Licensed under the Apache License, Version 2.0 (the "License");
5  * you may not use this file except in compliance with the License.
6  * You may obtain a copy of the License at
7  *
8  *      http://www.apache.org/licenses/LICENSE-2.0
9  *
10  * Unless required by applicable law or agreed to in writing, software
11  * distributed under the License is distributed on an "AS IS" BASIS,
12  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13  * See the License for the specific language governing permissions and
14  * limitations under the License
15  */
16 
17 package libcore.java.nio.file;
18 
19 import org.junit.Before;
20 import org.junit.Rule;
21 import org.junit.Test;
22 import org.mockito.Mock;
23 import org.mockito.junit.MockitoJUnit;
24 import org.mockito.junit.MockitoRule;
25 
26 import java.io.BufferedReader;
27 import java.io.BufferedWriter;
28 import java.io.IOException;
29 import java.io.InputStream;
30 import java.io.UncheckedIOException;
31 import java.nio.ByteBuffer;
32 import java.nio.channels.NonReadableChannelException;
33 import java.nio.channels.NonWritableChannelException;
34 import java.nio.channels.SeekableByteChannel;
35 import java.nio.charset.MalformedInputException;
36 import java.nio.charset.StandardCharsets;
37 import java.nio.file.AccessDeniedException;
38 import java.nio.file.CopyOption;
39 import java.nio.file.FileStore;
40 import java.nio.file.FileSystem;
41 import java.nio.file.FileSystemLoopException;
42 import java.nio.file.FileVisitOption;
43 import java.nio.file.FileVisitResult;
44 import java.nio.file.FileVisitor;
45 import java.nio.file.Files;
46 import java.nio.file.LinkOption;
47 import java.nio.file.NoSuchFileException;
48 import java.nio.file.NotDirectoryException;
49 import java.nio.file.OpenOption;
50 import java.nio.file.Path;
51 import java.nio.file.Paths;
52 import java.nio.file.attribute.BasicFileAttributes;
53 import java.nio.file.attribute.FileAttribute;
54 import java.nio.file.attribute.FileAttributeView;
55 import java.nio.file.attribute.FileTime;
56 import java.nio.file.attribute.PosixFilePermission;
57 import java.nio.file.attribute.PosixFilePermissions;
58 import java.nio.file.spi.FileSystemProvider;
59 import java.util.ArrayList;
60 import java.util.Arrays;
61 import java.util.HashMap;
62 import java.util.HashSet;
63 import java.util.Iterator;
64 import java.util.List;
65 import java.util.Map;
66 import java.util.Set;
67 import java.util.concurrent.TimeUnit;
68 import java.util.stream.Stream;
69 
70 import static java.nio.file.FileVisitResult.CONTINUE;
71 import static java.nio.file.FileVisitResult.TERMINATE;
72 import static java.nio.file.StandardOpenOption.APPEND;
73 import static java.nio.file.StandardOpenOption.CREATE_NEW;
74 import static java.nio.file.StandardOpenOption.READ;
75 import static java.nio.file.StandardOpenOption.SYNC;
76 import static java.nio.file.StandardOpenOption.TRUNCATE_EXISTING;
77 import static java.nio.file.StandardOpenOption.WRITE;
78 import static junit.framework.TestCase.assertTrue;
79 import static libcore.java.nio.file.FilesSetup.DATA_FILE;
80 import static libcore.java.nio.file.FilesSetup.NON_EXISTENT_FILE;
81 import static libcore.java.nio.file.FilesSetup.TEST_FILE_DATA;
82 import static libcore.java.nio.file.FilesSetup.TEST_FILE_DATA_2;
83 import static libcore.java.nio.file.FilesSetup.UTF_16_DATA;
84 import static libcore.java.nio.file.FilesSetup.execCmdAndWaitForTermination;
85 import static libcore.java.nio.file.FilesSetup.readFromFile;
86 import static libcore.java.nio.file.FilesSetup.readFromInputStream;
87 import static libcore.java.nio.file.FilesSetup.writeToFile;
88 import static org.junit.Assert.assertEquals;
89 import static org.junit.Assert.assertFalse;
90 import static org.junit.Assert.assertNotNull;
91 import static org.junit.Assert.fail;
92 import static org.mockito.Mockito.mock;
93 import static org.mockito.Mockito.verify;
94 import static org.mockito.Mockito.when;
95 
96 public class Files2Test {
97     @Rule
98     public FilesSetup filesSetup = new FilesSetup();
99     @Rule
100     public MockitoRule mockitoRule = MockitoJUnit.rule();
101     @Mock
102     private Path mockPath;
103     @Mock
104     private Path mockPath2;
105     @Mock
106     private FileSystem mockFileSystem;
107     @Mock
108     private FileSystemProvider mockFileSystemProvider;
109 
110     @Before
setUp()111     public void setUp() throws Exception {
112         when(mockPath.getFileSystem()).thenReturn(mockFileSystem);
113         when(mockPath2.getFileSystem()).thenReturn(mockFileSystem);
114         when(mockFileSystem.provider()).thenReturn(mockFileSystemProvider);
115     }
116 
117     @Test
test_move()118     public void test_move() throws IOException {
119         CopyOption mockCopyOption = mock(CopyOption.class);
120         assertEquals(mockPath2, Files.move(mockPath, mockPath2, mockCopyOption));
121         verify(mockFileSystemProvider).move(mockPath, mockPath2, mockCopyOption);
122     }
123 
124     @Test
test_readSymbolicLink()125     public void test_readSymbolicLink() throws IOException {
126         when(mockFileSystemProvider.readSymbolicLink(mockPath)).thenReturn(mockPath2);
127         assertEquals(mockPath2, Files.readSymbolicLink(mockPath));
128         verify(mockFileSystemProvider).readSymbolicLink(mockPath);
129     }
130 
131     @Test
test_isSameFile()132     public void test_isSameFile() throws IOException {
133         when(mockFileSystemProvider.isSameFile(mockPath, mockPath2)).thenReturn(true);
134         when(mockFileSystemProvider.isSameFile(mockPath2, mockPath)).thenReturn(false);
135         assertTrue(Files.isSameFile(mockPath, mockPath2));
136         assertFalse(Files.isSameFile(mockPath2, mockPath));
137     }
138 
139     @Test
test_getFileStore()140     public void test_getFileStore() throws IOException {
141         when(mockFileSystemProvider.getFileStore(mockPath)).thenThrow(new SecurityException());
142         try {
143             Files.getFileStore(mockPath);
144             fail();
145         } catch (SecurityException expected) {
146         }
147     }
148 
149     @Test
test_isHidden()150     public void test_isHidden() throws IOException {
151         when(mockFileSystemProvider.isHidden(mockPath)).thenReturn(true);
152         when(mockFileSystemProvider.isHidden(mockPath2)).thenReturn(false);
153         assertTrue(Files.isHidden(mockPath));
154         assertFalse(Files.isHidden(mockPath2));
155     }
156 
157     @Test
test_probeContentType()158     public void test_probeContentType() throws IOException {
159         assertEquals("text/plain",
160                 Files.probeContentType(filesSetup.getPathInTestDir("file.txt")));
161         assertEquals("text/x-java",
162                 Files.probeContentType(filesSetup.getPathInTestDir("file.java")));
163     }
164 
165     @Test
test_getFileAttributeView()166     public void test_getFileAttributeView() throws IOException {
167         FileAttributeView mockFileAttributeView = mock(FileAttributeView.class);
168         when(mockFileSystemProvider.getFileAttributeView(mockPath, FileAttributeView.class,
169                 LinkOption.NOFOLLOW_LINKS)).thenReturn(mockFileAttributeView);
170         assertEquals(mockFileAttributeView, Files.getFileAttributeView(mockPath,
171                 FileAttributeView.class, LinkOption.NOFOLLOW_LINKS));
172     }
173 
174     @Test
test_readAttributes()175     public void test_readAttributes() throws IOException {
176         BasicFileAttributes mockBasicFileAttributes = mock(BasicFileAttributes.class);
177         when(mockFileSystemProvider.readAttributes(mockPath, BasicFileAttributes.class,
178                 LinkOption.NOFOLLOW_LINKS)).thenReturn(mockBasicFileAttributes);
179         assertEquals(mockBasicFileAttributes, Files.readAttributes(mockPath,
180                 BasicFileAttributes.class, LinkOption.NOFOLLOW_LINKS));
181 
182     }
183 
184     @Test
test_setAttribute()185     public void test_setAttribute() throws IOException {
186         assertEquals(mockPath, Files.setAttribute(mockPath, "string", 10,
187                 LinkOption.NOFOLLOW_LINKS));
188         verify(mockFileSystemProvider).setAttribute(mockPath, "string", 10,
189                 LinkOption.NOFOLLOW_LINKS);
190     }
191 
192     @Test
test_getAttribute()193     public void test_getAttribute() throws IOException {
194         // Other tests are covered in test_readAttributes.
195         // When file is NON_EXISTENT.
196         try {
197             Files.getAttribute(filesSetup.getTestPath(), "basic:lastModifiedTime");
198             fail();
199         } catch (NoSuchFileException expected) {}
200     }
201 
202     @Test
test_getAttribute_Exception()203     public void test_getAttribute_Exception() throws IOException {
204         // IllegalArgumentException
205         try {
206             Files.getAttribute(filesSetup.getDataFilePath(), "xyz");
207             fail();
208         } catch (IllegalArgumentException expected) {}
209 
210         try {
211             Files.getAttribute(null, "xyz");
212             fail();
213         } catch(NullPointerException expected) {}
214 
215         try {
216             Files.getAttribute(filesSetup.getDataFilePath(), null);
217             fail();
218         } catch(NullPointerException expected) {}
219     }
220 
221     @Test
test_getPosixFilePermissions()222     public void test_getPosixFilePermissions() throws IOException {
223         Set<PosixFilePermission> perm = PosixFilePermissions.fromString("rwx------");
224         FileAttribute<Set<PosixFilePermission>> attr = PosixFilePermissions.asFileAttribute(perm);
225         Files.createFile(filesSetup.getTestPath(), attr);
226         assertEquals(attr.value(), Files.getPosixFilePermissions(filesSetup.getTestPath()));
227     }
228 
229     @Test
test_getPosixFilePermissions_NPE()230     public void test_getPosixFilePermissions_NPE() throws IOException {
231         try {
232             Files.getPosixFilePermissions(null);
233             fail();
234         } catch (NullPointerException expected) {}
235     }
236 
237     @Test
test_setPosixFilePermissions()238     public void test_setPosixFilePermissions() throws IOException {
239         Set<PosixFilePermission> perm = PosixFilePermissions.fromString("rwx------");
240         FileAttribute<Set<PosixFilePermission>> attr = PosixFilePermissions.asFileAttribute(perm);
241         Files.setPosixFilePermissions(filesSetup.getDataFilePath(), perm);
242         assertEquals(attr.value(), Files.getPosixFilePermissions(filesSetup.getDataFilePath()));
243     }
244 
245     @Test
test_setPosixFilePermissions_NPE()246     public void test_setPosixFilePermissions_NPE() throws IOException {
247         Set<PosixFilePermission> perm = PosixFilePermissions.fromString("rwx------");
248         FileAttribute<Set<PosixFilePermission>> attr = PosixFilePermissions.asFileAttribute(perm);
249         try {
250             Files.setPosixFilePermissions(null, perm);
251             fail();
252         } catch(NullPointerException expected) {}
253 
254         try {
255             Files.setPosixFilePermissions(filesSetup.getDataFilePath(), null);
256             fail();
257         } catch(NullPointerException expected) {}
258     }
259 
260     @Test
test_getOwner()261     public void test_getOwner() throws IOException, InterruptedException {
262         String[] statCmd = { "stat", "-c", "%U", filesSetup.getTestDir() + "/" + DATA_FILE };
263         Process statProcess = execCmdAndWaitForTermination(statCmd);
264         String owner = readFromInputStream(statProcess.getInputStream()).trim();
265         assertEquals(owner, Files.getOwner(filesSetup.getDataFilePath()).getName());
266     }
267 
268     @Test
test_getOwner_NPE()269     public void test_getOwner_NPE() throws IOException, InterruptedException {
270         try {
271             Files.getOwner(null);
272             fail();
273         } catch (NullPointerException expected) {}
274     }
275 
276     @Test
test_isSymbolicLink()277     public void test_isSymbolicLink() throws IOException, InterruptedException {
278         assertFalse(Files.isSymbolicLink(filesSetup.getTestPath()));
279         assertFalse(Files.isSymbolicLink(filesSetup.getDataFilePath()));
280 
281         // Creating a symbolic link.
282         String[] symLinkCmd = { "ln", "-s", DATA_FILE,
283                 filesSetup.getTestDir() + "/" + NON_EXISTENT_FILE };
284         execCmdAndWaitForTermination(symLinkCmd);
285         assertTrue(Files.isSymbolicLink(filesSetup.getTestPath()));
286     }
287 
288     @Test
test_isSymbolicLink_NPE()289     public void test_isSymbolicLink_NPE() throws IOException, InterruptedException {
290         try {
291             Files.isSymbolicLink(null);
292             fail();
293         } catch (NullPointerException expected) {}
294     }
295 
296     @Test
test_isDirectory()297     public void test_isDirectory() throws IOException, InterruptedException {
298         assertFalse(Files.isDirectory(filesSetup.getDataFilePath()));
299         // When file doesn't exist.
300         assertFalse(Files.isDirectory(filesSetup.getTestPath()));
301 
302         // Creating a directory.
303         String dirName = "newDir";
304         Path dirPath = filesSetup.getPathInTestDir(dirName);
305         String mkdir[] = { "mkdir", filesSetup.getTestDir() + "/" + dirName };
306         execCmdAndWaitForTermination(mkdir);
307         assertTrue(Files.isDirectory(dirPath));
308     }
309 
310     @Test
test_isDirectory_NPE()311     public void test_isDirectory_NPE() throws IOException {
312         try {
313             Files.isDirectory(null);
314             fail();
315         } catch (NullPointerException expected) {}
316     }
317 
318     @Test
test_isRegularFile()319     public void test_isRegularFile() throws IOException, InterruptedException {
320         assertTrue(Files.isRegularFile(filesSetup.getDataFilePath()));
321         // When file doesn't exist.
322         assertFalse(Files.isRegularFile(filesSetup.getTestPath()));
323 
324         // Check directories.
325         Path dirPath = filesSetup.getPathInTestDir("dir");
326         Files.createDirectory(dirPath);
327         assertFalse(Files.isRegularFile(dirPath));
328 
329         // Check symbolic link.
330         // When linked to itself.
331         Files.createSymbolicLink(filesSetup.getTestPath(),
332                 filesSetup.getTestPath().toAbsolutePath());
333         assertFalse(Files.isRegularFile(filesSetup.getTestPath()));
334 
335         // When linked to some other file.
336         filesSetup.reset();
337         Files.createSymbolicLink(filesSetup.getTestPath(),
338                 filesSetup.getDataFilePath().toAbsolutePath());
339         assertTrue(Files.isRegularFile(filesSetup.getTestPath()));
340 
341         // When asked to not follow the link.
342         assertFalse(Files.isRegularFile(filesSetup.getTestPath(), LinkOption.NOFOLLOW_LINKS));
343 
344         // Device file.
345         Path deviceFilePath = Paths.get("/dev/null");
346         assertTrue(Files.exists(deviceFilePath));
347         assertFalse(Files.isRegularFile(deviceFilePath));
348     }
349 
350     @Test
test_isRegularFile_NPE()351     public void test_isRegularFile_NPE() throws IOException {
352         try {
353             Files.isReadable(null);
354             fail();
355         } catch (NullPointerException expected) {}
356     }
357 
358     @Test
test_getLastModifiedTime()359     public void test_getLastModifiedTime() throws IOException, InterruptedException {
360         String touchCmd[] = { "touch", "-d", "2015-10-09T00:00:00Z",
361                 filesSetup.getTestDir() + "/" + DATA_FILE };
362         execCmdAndWaitForTermination(touchCmd);
363         assertEquals("2015-10-09T00:00:00Z",
364                 Files.getLastModifiedTime(filesSetup.getDataFilePath()).toString());
365 
366         // Non existent file.
367         try {
368             Files.getLastModifiedTime(filesSetup.getTestPath()).toString();
369             fail();
370         } catch (NoSuchFileException expected) {}
371     }
372 
373     @Test
test_getLastModifiedTime_NPE()374     public void test_getLastModifiedTime_NPE() throws IOException {
375         try {
376             Files.getLastModifiedTime(null, LinkOption.NOFOLLOW_LINKS);
377             fail();
378         } catch (NullPointerException expected) {}
379 
380         try {
381             Files.getLastModifiedTime(filesSetup.getDataFilePath(), (LinkOption[]) null);
382             fail();
383         } catch (NullPointerException expected) {}
384     }
385 
386     @Test
test_setLastModifiedTime()387     public void test_setLastModifiedTime() throws IOException, InterruptedException {
388         long timeInMillisToBeSet = System.currentTimeMillis() - 10000;
389         Files.setLastModifiedTime(filesSetup.getDataFilePath(),
390                 FileTime.fromMillis(timeInMillisToBeSet));
391         assertEquals(timeInMillisToBeSet/1000,
392                 Files.getLastModifiedTime(filesSetup.getDataFilePath()).to(TimeUnit.SECONDS));
393 
394         // Non existent file.
395         try {
396             Files.setLastModifiedTime(filesSetup.getTestPath(),
397                     FileTime.fromMillis(timeInMillisToBeSet));
398             fail();
399         } catch (NoSuchFileException expected) {}
400     }
401 
402     @Test
test_setLastModifiedTime_NPE()403     public void test_setLastModifiedTime_NPE() throws IOException, InterruptedException {
404         try {
405             Files.setLastModifiedTime(null, FileTime.fromMillis(System.currentTimeMillis()));
406             fail();
407         } catch (NullPointerException expected) {}
408 
409         // No NullPointerException.
410         Files.setLastModifiedTime(filesSetup.getDataFilePath(), null);
411     }
412 
413     @Test
test_size()414     public void test_size() throws IOException, InterruptedException {
415         int testSizeInBytes = 5000;
416         String ddCmd[] = { "dd", "if=/dev/zero", "of=" + filesSetup.getTestDir() + "/" + DATA_FILE,
417                 "bs="
418                 + testSizeInBytes, "count=1"};
419         execCmdAndWaitForTermination(ddCmd);
420 
421         assertEquals(testSizeInBytes, Files.size(filesSetup.getDataFilePath()));
422 
423         try {
424             Files.size(filesSetup.getTestPath());
425             fail();
426         } catch (NoSuchFileException expected) {}
427     }
428 
429     @Test
test_size_NPE()430     public void test_size_NPE() throws IOException, InterruptedException {
431         try {
432             Files.size(null);
433             fail();
434         } catch (NullPointerException expected) {}
435     }
436 
437     @Test
test_exists()438     public void test_exists() throws IOException {
439         // When file exists.
440         assertTrue(Files.exists(filesSetup.getDataFilePath()));
441 
442         // When file doesn't exist.
443         assertFalse(Files.exists(filesSetup.getTestPath()));
444 
445         // SymLink
446         Files.createSymbolicLink(filesSetup.getTestPath(),
447                 filesSetup.getDataFilePath().toAbsolutePath());
448         assertTrue(Files.exists(filesSetup.getTestPath()));
449 
450         // When link shouldn't be followed
451         assertTrue(Files.exists(filesSetup.getTestPath(), LinkOption.NOFOLLOW_LINKS));
452 
453         // When the target file doesn't exist.
454         Files.delete(filesSetup.getDataFilePath());
455         assertTrue(Files.exists(filesSetup.getTestPath(), LinkOption.NOFOLLOW_LINKS));
456         assertFalse(Files.exists(filesSetup.getTestPath()));
457 
458         // Symlink to itself
459         filesSetup.reset();
460         Files.createSymbolicLink(filesSetup.getTestPath(),
461                 filesSetup.getTestPath().toAbsolutePath());
462         assertFalse(Files.exists(filesSetup.getTestPath()));
463         assertTrue(Files.exists(filesSetup.getTestPath(), LinkOption.NOFOLLOW_LINKS));
464     }
465 
466     @Test
test_exists_NPE()467     public void test_exists_NPE() throws IOException {
468         try {
469             Files.exists(null);
470             fail();
471         } catch (NullPointerException expected) {}
472     }
473 
474     @Test
test_notExists()475     public void test_notExists() throws IOException {
476         // When file exists.
477         assertFalse(Files.notExists(filesSetup.getDataFilePath()));
478 
479         // When file doesn't exist.
480         assertTrue(Files.notExists(filesSetup.getTestPath()));
481 
482         // SymLink
483         Files.createSymbolicLink(filesSetup.getTestPath(),
484                 filesSetup.getDataFilePath().toAbsolutePath());
485         assertFalse(Files.notExists(filesSetup.getTestPath()));
486 
487         // When link shouldn't be followed
488         assertFalse(Files.notExists(filesSetup.getTestPath(), LinkOption.NOFOLLOW_LINKS));
489 
490         // When the target file doesn't exist.
491         Files.delete(filesSetup.getDataFilePath());
492         assertFalse(Files.notExists(filesSetup.getTestPath(), LinkOption.NOFOLLOW_LINKS));
493         assertTrue(Files.notExists(filesSetup.getTestPath()));
494 
495         // Symlink to itself
496         filesSetup.reset();
497         Files.createSymbolicLink(filesSetup.getTestPath(),
498                 filesSetup.getTestPath().toAbsolutePath());
499         assertFalse(Files.notExists(filesSetup.getTestPath()));
500         assertFalse(Files.notExists(filesSetup.getTestPath(), LinkOption.NOFOLLOW_LINKS));
501     }
502 
503     @Test
test_notExists_NPE()504     public void test_notExists_NPE() throws IOException {
505         try {
506             Files.notExists(null);
507             fail();
508         } catch (NullPointerException expected) {}
509 
510         try {
511             Files.notExists(filesSetup.getDataFilePath(), (LinkOption[]) null);
512             fail();
513         } catch (NullPointerException expected) {}
514     }
515 
516     @Test
test_isReadable()517     public void test_isReadable() throws IOException {
518         // When a readable file is available.
519         assertTrue(Files.isReadable(filesSetup.getDataFilePath()));
520 
521         // When a file doesn't exist.
522         assertFalse(Files.isReadable(filesSetup.getTestPath()));
523 
524         // Setting non readable permission for user
525         Set<PosixFilePermission> perm = PosixFilePermissions.fromString("-wxrwxrwx");
526         Files.setPosixFilePermissions(filesSetup.getDataFilePath(), perm);
527         assertFalse(Files.isReadable(filesSetup.getDataFilePath()));
528     }
529 
530     @Test
test_isReadable_NPE()531     public void test_isReadable_NPE() throws IOException {
532         try {
533             Files.isReadable(null);
534             fail();
535         } catch (NullPointerException expected) {}
536     }
537 
538     @Test
test_isWritable()539     public void test_isWritable() throws IOException {
540         // When a readable file is available.
541         assertTrue(Files.isWritable(filesSetup.getDataFilePath()));
542 
543         // When a file doesn't exist.
544         assertFalse(Files.isWritable(filesSetup.getTestPath()));
545 
546         // Setting non writable permission for user
547         Set<PosixFilePermission> perm = PosixFilePermissions.fromString("r-xrwxrwx");
548         Files.setPosixFilePermissions(filesSetup.getDataFilePath(), perm);
549         assertFalse(Files.isWritable(filesSetup.getDataFilePath()));
550     }
551 
552     @Test
test_isWritable_NPE()553     public void test_isWritable_NPE() {
554         try {
555             Files.isWritable(null);
556             fail();
557         } catch (NullPointerException expected) {}
558     }
559 
560     @Test
test_isExecutable()561     public void test_isExecutable() throws IOException {
562         // When a readable file is available.
563         assertFalse(Files.isExecutable(filesSetup.getDataFilePath()));
564 
565         // When a file doesn't exist.
566         assertFalse(Files.isExecutable(filesSetup.getTestPath()));
567 
568         // Setting non executable permission for user
569         Set<PosixFilePermission> perm = PosixFilePermissions.fromString("rw-rwxrwx");
570         Files.setPosixFilePermissions(filesSetup.getDataFilePath(), perm);
571         assertFalse(Files.isExecutable(filesSetup.getDataFilePath()));
572     }
573 
574     @Test
test_isExecutable_NPE()575     public void test_isExecutable_NPE() {
576         try {
577             Files.isExecutable(null);
578             fail();
579         } catch (NullPointerException expected) {}
580     }
581 
582     @Test
test_walkFileTree$Path$Set$int$FileVisitor_symbolicLinkFollow()583     public void test_walkFileTree$Path$Set$int$FileVisitor_symbolicLinkFollow()
584             throws IOException, InterruptedException {
585         // Directory structure.
586         //        root
587         //        ├── dir1
588         //        │   └── dir2 ─ dir3-file1 - file3
589         //        │
590         //        └── file2
591         //
592         // With follow link it should be able to traverse to dir3 and file1 when started from file2.
593 
594         // Directory setup.
595         Path rootDir = filesSetup.getPathInTestDir("root");
596         Path dir1 = filesSetup.getPathInTestDir("root/dir1");
597         Path dir2 = filesSetup.getPathInTestDir("root/dir1/dir2");
598         Path dir3 = filesSetup.getPathInTestDir("root/dir1/dir2/dir3");
599         Path file1 = filesSetup.getPathInTestDir("root/dir1/dir2/dir3/file1");
600         Path file2 = filesSetup.getPathInTestDir("root/file2");
601 
602         Files.createDirectories(dir3);
603         Files.createFile(file1);
604         Files.createSymbolicLink(file2, dir2.toAbsolutePath());
605         assertTrue(Files.isSymbolicLink(file2));
606 
607         Map<Object, VisitOption> dirMap = new HashMap<>();
608         Map<Object, VisitOption> expectedDirMap = new HashMap<>();
609         Set<FileVisitOption> option = new HashSet<>();
610         option.add(FileVisitOption.FOLLOW_LINKS);
611         Files.walkFileTree(file2, option, 50, new TestFileVisitor(dirMap, option));
612 
613         expectedDirMap.put(file1.getFileName(), VisitOption.VISIT_FILE);
614         expectedDirMap.put(file2.getFileName(), VisitOption.POST_VISIT_DIRECTORY);
615         expectedDirMap.put(dir3.getFileName(), VisitOption.POST_VISIT_DIRECTORY);
616 
617         assertEquals(expectedDirMap, dirMap);
618     }
619 
620     @Test
test_walkFileTree$Path$FileVisitor()621     public void test_walkFileTree$Path$FileVisitor() throws IOException {
622         // Directory structure.
623         //    .
624         //    ├── DATA_FILE
625         //    └── root
626         //        ├── dir1
627         //        │   ├── dir2
628         //        │   │   ├── dir3
629         //        │   │   └── file5
630         //        │   ├── dir4
631         //        │   └── file3
632         //        ├── dir5
633         //        └── file1
634         //
635 
636         // Directory Setup.
637         Path rootDir = filesSetup.getPathInTestDir("root");
638         Path dir1 = filesSetup.getPathInTestDir("root/dir1");
639         Path dir2 = filesSetup.getPathInTestDir("root/dir1/dir2");
640         Path dir3 = filesSetup.getPathInTestDir("root/dir1/dir2/dir3");
641         Path dir4 = filesSetup.getPathInTestDir("root/dir1/dir4");
642         Path dir5 = filesSetup.getPathInTestDir("root/dir5");
643         Path file1 = filesSetup.getPathInTestDir("root/file1");
644         Path file3 = filesSetup.getPathInTestDir("root/dir1/file3");
645         Path file5 = filesSetup.getPathInTestDir("root/dir1/dir2/file5");
646 
647         Files.createDirectories(dir3);
648         Files.createDirectories(dir4);
649         Files.createDirectories(dir5);
650         Files.createFile(file3);
651         Files.createFile(file5);
652         Files.createSymbolicLink(file1, filesSetup.getDataFilePath().toAbsolutePath());
653 
654         Map<Object, VisitOption> dirMap = new HashMap<>();
655         Map<Object, VisitOption> expectedDirMap = new HashMap<>();
656         Path returnedPath = Files.walkFileTree(rootDir, new Files2Test.TestFileVisitor(dirMap));
657 
658         assertEquals(rootDir, returnedPath);
659 
660         expectedDirMap.put(rootDir.getFileName(), VisitOption.POST_VISIT_DIRECTORY);
661         expectedDirMap.put(dir1.getFileName(), VisitOption.POST_VISIT_DIRECTORY);
662         expectedDirMap.put(dir2.getFileName(), VisitOption.POST_VISIT_DIRECTORY);
663         expectedDirMap.put(dir3.getFileName(), VisitOption.POST_VISIT_DIRECTORY);
664         expectedDirMap.put(file5.getFileName(), VisitOption.VISIT_FILE);
665         expectedDirMap.put(dir4.getFileName(), VisitOption.POST_VISIT_DIRECTORY);
666         expectedDirMap.put(file3.getFileName(), VisitOption.VISIT_FILE);
667         expectedDirMap.put(dir5.getFileName(), VisitOption.POST_VISIT_DIRECTORY);
668         expectedDirMap.put(file1.getFileName(), VisitOption.VISIT_FILE);
669         assertEquals(expectedDirMap, dirMap);
670     }
671 
672     @Test
test_walkFileTree_depthFirst()673     public void test_walkFileTree_depthFirst() throws IOException {
674         // Directory structure.
675         //    .
676         //    ├── DATA_FILE
677         //    └── root
678         //        ├── dir1 ── file1
679         //        └── dir2 ── file2
680 
681         // Directory Setup.
682         Path rootDir = filesSetup.getPathInTestDir("root");
683         Path dir1 = filesSetup.getPathInTestDir("root/dir1");
684         Path dir2 = filesSetup.getPathInTestDir("root/dir2");
685         Path file1 = filesSetup.getPathInTestDir("root/dir1/file1");
686         Path file2 = filesSetup.getPathInTestDir("root/dir2/file2");
687 
688         Files.createDirectories(dir1);
689         Files.createDirectories(dir2);
690         Files.createFile(file1);
691         Files.createFile(file2);
692 
693         Map<Object, VisitOption> dirMap = new HashMap<>();
694         List<Object> keyList = new ArrayList<>();
695         Files.walkFileTree(rootDir,
696                 new Files2Test.TestFileVisitor(dirMap, keyList));
697         assertEquals(rootDir.getFileName(), keyList.get(0));
698         if (keyList.get(1).equals(dir1.getFileName())) {
699             assertEquals(file1.getFileName(), keyList.get(2));
700             assertEquals(dir2.getFileName(), keyList.get(3));
701             assertEquals(file2.getFileName(), keyList.get(4));
702         } else if (keyList.get(1).equals(dir2.getFileName())){
703             assertEquals(file2.getFileName(), keyList.get(2));
704             assertEquals(dir1.getFileName(), keyList.get(3));
705             assertEquals(file1.getFileName(), keyList.get(4));
706         } else {
707             fail();
708         }
709     }
710 
711     @Test
test_walkFileTree_negativeDepth()712     public void test_walkFileTree_negativeDepth() throws IOException {
713         Path rootDir = filesSetup.getPathInTestDir("root");
714         Path dir1 = filesSetup.getPathInTestDir("root/dir1");
715 
716         Files.createDirectories(dir1);
717 
718         Map<Object, VisitOption> dirMap = new HashMap<>();
719         Set<FileVisitOption> option = new HashSet<>();
720         option.add(FileVisitOption.FOLLOW_LINKS);
721         try {
722             Files.walkFileTree(rootDir, option, -1,
723                     new Files2Test.TestFileVisitor(dirMap));
724             fail();
725         } catch (IllegalArgumentException expected) {}
726     }
727 
728     @Test
test_walkFileTree_maximumDepth()729     public void test_walkFileTree_maximumDepth() throws IOException {
730         // Directory structure.
731         //        root
732         //        ├── dir1
733         //        │   ├── dir2
734         //        │   │   ├── dir3
735         //        │   │   └── file5
736         //        │   ├── dir4
737         //        │   └── file3
738         //        ├── dir5
739         //        └── file1
740         //
741         // depth will be 2. file5, dir3 is not reachable.
742         // Directory Setup.
743         Path rootDir = filesSetup.getPathInTestDir("root");
744         Path dir1 = filesSetup.getPathInTestDir("root/dir1");
745         Path dir2 = filesSetup.getPathInTestDir("root/dir1/dir2");
746         Path dir3 = filesSetup.getPathInTestDir("root/dir1/dir2/dir3");
747         Path dir4 = filesSetup.getPathInTestDir("root/dir1/dir4");
748         Path dir5 = filesSetup.getPathInTestDir("root/dir5");
749         Path file1 = filesSetup.getPathInTestDir("root/file1");
750         Path file3 = filesSetup.getPathInTestDir("root/dir1/file3");
751         Path file5 = filesSetup.getPathInTestDir("root/dir1/dir2/file5");
752 
753         Files.createDirectories(dir3);
754         Files.createDirectories(dir4);
755         Files.createDirectories(dir5);
756         Files.createFile(file1);
757         Files.createFile(file3);
758         Files.createFile(file5);
759 
760         Map<Object, VisitOption> dirMap = new HashMap<>();
761         Map<Object, VisitOption> expectedDirMap = new HashMap<>();
762         Set<FileVisitOption> option = new HashSet<>();
763         option.add(FileVisitOption.FOLLOW_LINKS);
764         Files.walkFileTree(rootDir, option, 2, new Files2Test.TestFileVisitor(dirMap));
765         assertTrue(Files.isDirectory(dir4));
766         expectedDirMap.put(rootDir.getFileName(), VisitOption.POST_VISIT_DIRECTORY);
767         expectedDirMap.put(dir1.getFileName(), VisitOption.POST_VISIT_DIRECTORY);
768         // Both of the directories are at maximum depth, therefore, will be treated as simple file.
769         expectedDirMap.put(dir2.getFileName(), VisitOption.VISIT_FILE);
770         expectedDirMap.put(dir4.getFileName(), VisitOption.VISIT_FILE);
771         expectedDirMap.put(dir5.getFileName(), VisitOption.POST_VISIT_DIRECTORY);
772         expectedDirMap.put(file1.getFileName(), VisitOption.VISIT_FILE);
773         expectedDirMap.put(file3.getFileName(), VisitOption.VISIT_FILE);
774 
775         assertEquals(expectedDirMap, dirMap);
776     }
777 
778     @Test
test_walkFileTree$Path$FileVisitor_NPE()779     public void test_walkFileTree$Path$FileVisitor_NPE() throws IOException {
780         Path rootDir = filesSetup.getPathInTestDir("root");
781         try {
782             Files.walkFileTree(null,
783                     new Files2Test.TestFileVisitor(new HashMap<>()));
784             fail();
785         } catch (NullPointerException expected) {}
786 
787         try {
788             Files.walkFileTree(rootDir, null);
789             fail();
790         } catch (NullPointerException expected) {}
791     }
792 
793     @Test
test_walkFileTree$Path$FileVisitor_FileSystemLoopException()794     public void test_walkFileTree$Path$FileVisitor_FileSystemLoopException() throws IOException {
795         // Directory structure.
796         //    .
797         //    ├── DATA_FILE
798         //    └── root
799         //        └── dir1
800         //             └── file1
801         //
802         // file1 is symlink to dir1
803 
804         // Directory Setup.
805         Path rootDir = filesSetup.getPathInTestDir("root");
806         Path dir1 = filesSetup.getPathInTestDir("root/dir1");
807         Path file1 = filesSetup.getPathInTestDir("root/dir1/file1");
808 
809         Files.createDirectories(dir1);
810         Files.createSymbolicLink(file1, dir1.toAbsolutePath());
811         assertEquals(dir1.getFileName(), Files.readSymbolicLink(file1).getFileName());
812 
813         Map<Object, VisitOption> dirMap = new HashMap<>();
814         Set<FileVisitOption> option = new HashSet<>();
815         option.add(FileVisitOption.FOLLOW_LINKS);
816         try {
817             Files.walkFileTree(rootDir, option, Integer.MAX_VALUE,
818                     new Files2Test.TestFileVisitor(dirMap));
819             fail();
820         } catch (FileSystemLoopException expected) {}
821     }
822 
823     @Test
test_find()824     public void test_find() throws IOException {
825         // Directory structure.
826         //        root
827         //        ├── dir1
828         //        │   ├── dir2
829         //        │   │   ├── dir3
830         //        │   │   └── file5
831         //        │   ├── dir4
832         //        │   └── file3
833         //        ├── dir5
834         //        └── file1
835         //
836 
837         // Directory setup.
838         Path rootDir = Paths.get(filesSetup.getTestDir(), "root");
839         Path dir1 = Paths.get(filesSetup.getTestDir(), "root/dir1");
840         Path dir2 = Paths.get(filesSetup.getTestDir(), "root/dir1/dir2");
841         Path dir3 = Paths.get(filesSetup.getTestDir(), "root/dir1/dir2/dir3");
842         Path dir4 = Paths.get(filesSetup.getTestDir(), "root/dir1/dir4");
843         Path dir5 = Paths.get(filesSetup.getTestDir(), "root/dir5");
844         Path file1 = Paths.get(filesSetup.getTestDir(), "root/file1");
845         Path file3 = Paths.get(filesSetup.getTestDir(), "root/dir1/file3");
846         Path file5 = Paths.get(filesSetup.getTestDir(), "root/dir1/dir2/file5");
847 
848         Files.createDirectories(dir3);
849         Files.createDirectories(dir4);
850         Files.createDirectories(dir5);
851         Files.createFile(file1);
852         Files.createFile(file3);
853         Files.createFile(file5);
854 
855         // When depth is 2 then file4, file5 and dir3 are not reachable.
856         Set<Path> expectedDirSet = new HashSet<>();
857         expectedDirSet.add(rootDir);
858         expectedDirSet.add(dir1);
859         expectedDirSet.add(dir2);
860         expectedDirSet.add(dir4);
861         expectedDirSet.add(dir5);
862         Set<Path> dirSet = new HashSet<>();
863         Stream<Path> pathStream = Files.find(rootDir, 2, (path, attr) -> Files.isDirectory(path));
864         pathStream.forEach(path -> dirSet.add(path));
865         assertEquals(expectedDirSet, dirSet);
866 
867         // Test the case where depth is 0.
868         expectedDirSet.clear();
869         dirSet.clear();
870 
871         expectedDirSet.add(rootDir);
872 
873         pathStream = Files.find(rootDir, 0, (path, attr) -> Files.isDirectory(path));
874         pathStream.forEach(path -> dirSet.add(path));
875         assertEquals(expectedDirSet, dirSet);
876 
877         // Test the case where depth is -1.
878         try {
879             Files.find(rootDir, -1, (path, attr) -> Files.isDirectory(path));
880             fail();
881         } catch (IllegalArgumentException expected) {}
882 
883         // Test the case when BiPredicate always returns false.
884         expectedDirSet.clear();
885         dirSet.clear();
886 
887         pathStream = Files.find(rootDir, 2, (path, attr) -> false);
888         pathStream.forEach(path -> dirSet.add(path));
889         assertEquals(expectedDirSet, dirSet);
890 
891         // Test the case when start is not a directory.
892         expectedDirSet.clear();
893         dirSet.clear();
894 
895         expectedDirSet.add(file1);
896 
897         pathStream = Files.find(file1, 2, (path, attr) -> true);
898         pathStream.forEach(path -> dirSet.add(path));
899         assertEquals(expectedDirSet, dirSet);
900     }
901 
902     @Test
test_find_NPE()903     public void test_find_NPE() throws IOException {
904         Path rootDir = Paths.get(filesSetup.getTestDir(), "root");
905         Files.createDirectories(rootDir);
906         try {
907             Files.find(null, 2, (path, attr) -> Files.isDirectory(path));
908             fail();
909         } catch(NullPointerException expected) {}
910 
911         try {
912             Files.find(rootDir, (Integer)null, (path, attr) -> Files.isDirectory(path));
913             fail();
914         } catch(NullPointerException expected) {}
915 
916         try(Stream<Path> pathStream = Files.find(rootDir, 2, null)) {
917             pathStream.forEach(path -> {/* do nothing */});
918             fail();
919         } catch(NullPointerException expected) {}
920     }
921 
922     @Test
test_lines$Path$Charset()923     public void test_lines$Path$Charset() throws IOException {
924         List<String> lines = new ArrayList<>();
925         lines.add(UTF_16_DATA);
926         lines.add(TEST_FILE_DATA);
927         Files.write(filesSetup.getDataFilePath(), lines, StandardCharsets.UTF_16);
928         try (Stream<String> readLines = Files.lines(filesSetup.getDataFilePath(),
929                 StandardCharsets.UTF_16)) {
930             Iterator<String> lineIterator = lines.iterator();
931             readLines.forEach(line -> assertEquals(line, lineIterator.next()));
932         }
933 
934         // When Path is a directory
935         filesSetup.reset();
936         try (Stream<String> readLines = Files.lines(filesSetup.getTestDirPath(),
937                 StandardCharsets.UTF_16)) {
938             try {
939                 readLines.count();
940                 fail();
941             } catch (UncheckedIOException expected) {}
942         }
943 
944         // When file doesn't exits.
945         filesSetup.reset();
946         try (Stream<String> readLines = Files.lines(filesSetup.getTestPath(),
947                 StandardCharsets.UTF_16)) {
948            fail();
949         } catch (NoSuchFileException expected) {}
950     }
951 
952     @Test
test_lines$Path$Charset_NPE()953     public void test_lines$Path$Charset_NPE() throws IOException {
954         try {
955             Files.lines(null, StandardCharsets.UTF_16);
956             fail();
957         } catch (NullPointerException expected) {}
958 
959         try {
960             Files.lines(filesSetup.getDataFilePath(), null);
961             fail();
962         } catch (NullPointerException expected) {}
963     }
964 
965     @Test
test_lines$Path()966     public void test_lines$Path() throws IOException {
967         List<String> lines = new ArrayList<>();
968         lines.add(TEST_FILE_DATA_2);
969         lines.add(TEST_FILE_DATA);
970         Files.write(filesSetup.getDataFilePath(), lines, StandardCharsets.UTF_8);
971         try (Stream<String> readLines = Files.lines(filesSetup.getDataFilePath())) {
972             Iterator<String> lineIterator = lines.iterator();
973             readLines.forEach(line -> assertEquals(line, lineIterator.next()));
974         }
975 
976         // When Path is a directory
977         filesSetup.reset();
978         try (Stream<String> readLines = Files.lines(filesSetup.getTestDirPath())) {
979             try {
980                 readLines.count();
981                 fail();
982             } catch (UncheckedIOException expected) {}
983         }
984 
985         // When file doesn't exits.
986         filesSetup.reset();
987         try (Stream<String> readLines = Files.lines(filesSetup.getTestPath())) {
988             fail();
989         } catch (NoSuchFileException expected) {}
990     }
991 
992     @Test
test_line$Path_NPE()993     public void test_line$Path_NPE() throws IOException {
994         try {
995             Files.lines(null);
996             fail();
997         } catch (NullPointerException expected) {}
998     }
999 
1000     @Test
test_list()1001     public void test_list() throws Exception {
1002         // Directory Setup for the test.
1003         Path rootDir = Paths.get(filesSetup.getTestDir(), "root");
1004         Path dir1 = Paths.get(filesSetup.getTestDir(), "root/dir1");
1005         Path file1 = Paths.get(filesSetup.getTestDir(), "root/file1");
1006         Path file2 = Paths.get(filesSetup.getTestDir(), "root/dir1/file2");
1007         Path symLink = Paths.get(filesSetup.getTestDir(), "root/symlink");
1008         Files.createDirectories(dir1);
1009         Files.createFile(file1);
1010         Files.createFile(file2);
1011         Files.createSymbolicLink(symLink, file1.toAbsolutePath());
1012 
1013         Set<Path> expectedVisitedFiles = new HashSet<>();
1014         expectedVisitedFiles.add(dir1);
1015         expectedVisitedFiles.add(file1);
1016         expectedVisitedFiles.add(symLink);
1017 
1018         Set<Path> visitedFiles = new HashSet<>();
1019         try (Stream<Path> pathStream = Files.list(rootDir)) {
1020             pathStream.forEach(path -> visitedFiles.add(path));
1021         }
1022         assertEquals(3, visitedFiles.size());
1023 
1024 
1025         // Test the case where directory is empty.
1026         filesSetup.clearAll();
1027         try {
1028             Files.list(Paths.get(filesSetup.getTestDir(), "newDir"));
1029             fail();
1030         } catch (NoSuchFileException expected) {}
1031 
1032         // Test the case where path points to a file.
1033         filesSetup.clearAll();
1034         filesSetup.setUp();
1035         try {
1036             Files.list(filesSetup.getDataFilePath());
1037             fail();
1038         } catch (NotDirectoryException expected) {}
1039     }
1040 
1041     @Test
test_list_NPE()1042     public void test_list_NPE() throws IOException {
1043         try {
1044             Files.list(null);
1045             fail();
1046         } catch (NullPointerException expected) {}
1047     }
1048 
1049     @Test
test_newBufferedReader()1050     public void test_newBufferedReader() throws IOException {
1051         // Test the case where file doesn't exists.
1052         try {
1053             Files.newBufferedReader(filesSetup.getTestPath());
1054             fail();
1055         } catch (NoSuchFileException expected) {}
1056 
1057         BufferedReader bufferedReader = Files.newBufferedReader(filesSetup.getDataFilePath());
1058         assertEquals(TEST_FILE_DATA, bufferedReader.readLine());
1059 
1060         // Test the case where the file content has unicode characters.
1061         writeToFile(filesSetup.getDataFilePath(), UTF_16_DATA);
1062         bufferedReader = Files.newBufferedReader(filesSetup.getDataFilePath());
1063         assertEquals(UTF_16_DATA, bufferedReader.readLine());
1064         bufferedReader.close();
1065 
1066         // Test the case where file is write-only.
1067         Set<PosixFilePermission> perm = PosixFilePermissions.fromString("-w-------");
1068         Files.setPosixFilePermissions(filesSetup.getDataFilePath(), perm);
1069         try {
1070             Files.newBufferedReader(filesSetup.getDataFilePath());
1071             fail();
1072         } catch (AccessDeniedException expected) {}
1073     }
1074 
1075     @Test
test_newBufferedReader_NPE()1076     public void test_newBufferedReader_NPE() throws IOException {
1077         try {
1078             Files.newBufferedReader(null);
1079             fail();
1080         } catch (NullPointerException expected) {}
1081     }
1082 
1083     @Test
test_newBufferedReader$Path$Charset()1084     public void test_newBufferedReader$Path$Charset() throws IOException {
1085         BufferedReader bufferedReader = Files.newBufferedReader(filesSetup.getDataFilePath(),
1086                 StandardCharsets.US_ASCII);
1087         assertEquals(TEST_FILE_DATA, bufferedReader.readLine());
1088 
1089         // When the file has unicode characters.
1090         writeToFile(filesSetup.getDataFilePath(), UTF_16_DATA);
1091         bufferedReader = Files.newBufferedReader(filesSetup.getDataFilePath(),
1092                 StandardCharsets.US_ASCII);
1093         try {
1094             bufferedReader.readLine();
1095             fail();
1096         } catch (MalformedInputException expected) {}
1097     }
1098 
1099     @Test
test_newBufferedReader$Path$Charset_NPE()1100     public void test_newBufferedReader$Path$Charset_NPE() throws IOException {
1101         try {
1102             Files.newBufferedReader(null, StandardCharsets.US_ASCII);
1103             fail();
1104         } catch (NullPointerException expected) {}
1105 
1106         try {
1107             Files.newBufferedReader(filesSetup.getDataFilePath(), null);
1108             fail();
1109         } catch (NullPointerException expected) {}
1110     }
1111 
1112     @Test
test_newBufferedWriter()1113     public void test_newBufferedWriter() throws IOException {
1114         BufferedWriter bufferedWriter = Files.newBufferedWriter(filesSetup.getTestPath());
1115         bufferedWriter.write(TEST_FILE_DATA);
1116         bufferedWriter.close();
1117         assertEquals(TEST_FILE_DATA,
1118                 readFromFile(filesSetup.getTestPath()));
1119 
1120         // When file exists, it should start writing from the beginning.
1121         bufferedWriter = Files.newBufferedWriter(filesSetup.getDataFilePath());
1122         bufferedWriter.write(TEST_FILE_DATA_2);
1123         bufferedWriter.close();
1124         assertEquals(TEST_FILE_DATA_2,
1125                 readFromFile(filesSetup.getDataFilePath()));
1126 
1127         // When file is read-only.
1128         Set<PosixFilePermission> perm = PosixFilePermissions.fromString("r--------");
1129         FileAttribute<Set<PosixFilePermission>> attr = PosixFilePermissions.asFileAttribute(perm);
1130         Files.setPosixFilePermissions(filesSetup.getDataFilePath(), perm);
1131         try {
1132             Files.newBufferedWriter(filesSetup.getDataFilePath());
1133             fail();
1134         } catch (AccessDeniedException expected) {}
1135     }
1136 
1137     @Test
test_newBufferedWriter_NPE()1138     public void test_newBufferedWriter_NPE() throws IOException {
1139         try {
1140             Files.newBufferedWriter(null);
1141             fail();
1142         } catch (NullPointerException expected) {}
1143     }
1144 
1145     @Test
test_newBufferedWriter$Path$Charset()1146     public void test_newBufferedWriter$Path$Charset() throws IOException {
1147         BufferedWriter bufferedWriter = Files.newBufferedWriter(filesSetup.getTestPath(),
1148                 StandardCharsets.US_ASCII);
1149         bufferedWriter.write(TEST_FILE_DATA);
1150         bufferedWriter.close();
1151         assertEquals(TEST_FILE_DATA, readFromFile(filesSetup.getTestPath()));
1152     }
1153 
1154     @Test
test_newBufferedWriter$Path$Charset_NPE()1155     public void test_newBufferedWriter$Path$Charset_NPE() throws IOException {
1156         try {
1157             Files.newBufferedWriter(null, StandardCharsets.US_ASCII);
1158             fail();
1159         } catch (NullPointerException expected) {}
1160 
1161         try {
1162             Files.newBufferedWriter(filesSetup.getTestPath(), (OpenOption[]) null);
1163             fail();
1164         } catch (NullPointerException expected) {}
1165     }
1166 
1167     @Test
test_newByteChannel()1168     public void test_newByteChannel() throws IOException {
1169         // When file doesn't exist
1170         try (SeekableByteChannel sbc = Files.newByteChannel(filesSetup.getTestPath())) {
1171             fail();
1172         } catch (NoSuchFileException expected) {
1173         }
1174 
1175         // When file exists.
1176 
1177         // File opens in READ mode by default. The channel is non writable by default.
1178         try (SeekableByteChannel sbc = Files.newByteChannel(filesSetup.getDataFilePath())) {
1179             sbc.write(ByteBuffer.allocate(10));
1180             fail();
1181         } catch (NonWritableChannelException expected) {
1182         }
1183 
1184         // Read a file.
1185         try (SeekableByteChannel sbc = Files.newByteChannel(filesSetup.getDataFilePath())) {
1186             ByteBuffer readBuffer = ByteBuffer.allocate(10);
1187             int bytesReadCount = sbc.read(readBuffer);
1188 
1189             String readData = new String(Arrays.copyOf(readBuffer.array(), bytesReadCount),
1190                     StandardCharsets.UTF_8);
1191             assertEquals(TEST_FILE_DATA, readData);
1192         }
1193     }
1194 
1195     @Test
test_newByteChannel_openOption_WRITE()1196     public void test_newByteChannel_openOption_WRITE() throws IOException {
1197         // When file doesn't exist
1198         try (SeekableByteChannel sbc = Files.newByteChannel(filesSetup.getTestPath(), WRITE)) {
1199             fail();
1200         } catch (NoSuchFileException expected) {
1201         }
1202 
1203         // When file exists.
1204 
1205         try (SeekableByteChannel sbc = Files.newByteChannel(filesSetup.getDataFilePath(), WRITE)) {
1206             sbc.read(ByteBuffer.allocate(10));
1207             fail();
1208         } catch (NonReadableChannelException expected) {
1209         }
1210 
1211         // Write in file.
1212         try (SeekableByteChannel sbc = Files.newByteChannel(filesSetup.getDataFilePath(), WRITE)) {
1213             sbc.write(ByteBuffer.wrap(TEST_FILE_DATA_2.getBytes()));
1214             sbc.close();
1215 
1216             try (InputStream is = Files.newInputStream(filesSetup.getDataFilePath())) {
1217                 String expectedFileData = TEST_FILE_DATA_2 +
1218                         TEST_FILE_DATA.substring(
1219                                 TEST_FILE_DATA_2.length());
1220                 assertEquals(expectedFileData, readFromInputStream(is));
1221             }
1222         }
1223     }
1224 
1225     @Test
test_newByteChannel_openOption_WRITE_READ()1226     public void test_newByteChannel_openOption_WRITE_READ() throws IOException {
1227         try (SeekableByteChannel sbc = Files.newByteChannel(filesSetup.getDataFilePath(), WRITE,
1228                 READ, SYNC/* Sync makes sure the that InputStream is able to read content written by
1229                  the seekable byte channel without closing/flushing it. */)) {
1230             ByteBuffer readBuffer = ByteBuffer.allocate(10);
1231             int bytesReadCount = sbc.read(readBuffer);
1232 
1233             String readData = new String(Arrays.copyOf(readBuffer.array(), bytesReadCount),
1234                     StandardCharsets.UTF_8);
1235             assertEquals(TEST_FILE_DATA, readData);
1236 
1237             // Pointer will move to the end of the file after read operation. The write should
1238             // append the data at the end of the file.
1239             sbc.write(ByteBuffer.wrap(TEST_FILE_DATA_2.getBytes()));
1240             try (InputStream is = Files.newInputStream(filesSetup.getDataFilePath())) {
1241                 String expectedFileData = TEST_FILE_DATA + TEST_FILE_DATA_2;
1242                 assertEquals(expectedFileData, readFromInputStream(is));
1243             }
1244         }
1245     }
1246 
1247     @Test
test_newByteChannel_NPE()1248     public void test_newByteChannel_NPE() throws IOException {
1249         try (SeekableByteChannel sbc = Files.newByteChannel(null)) {
1250             fail();
1251         } catch(NullPointerException expected) {}
1252 
1253         try (SeekableByteChannel sbc = Files.newByteChannel(filesSetup.getDataFilePath(),
1254                 (OpenOption[]) null)) {
1255             fail();
1256         } catch(NullPointerException expected) {}
1257     }
1258 
1259     @Test
test_readAllLine()1260     public void test_readAllLine() throws IOException {
1261         // Multi-line file.
1262         assertTrue(Files.exists(filesSetup.getDataFilePath()));
1263         writeToFile(filesSetup.getDataFilePath(), "\n" + TEST_FILE_DATA_2,
1264                 APPEND);
1265         List<String> out = Files.readAllLines(filesSetup.getDataFilePath());
1266         assertEquals(2, out.size());
1267         assertEquals(TEST_FILE_DATA, out.get(0));
1268         assertEquals(TEST_FILE_DATA_2, out.get(1));
1269 
1270         // When file doesn't exist.
1271         filesSetup.reset();
1272         try {
1273             Files.readAllLines(filesSetup.getTestPath());
1274             fail();
1275         } catch (NoSuchFileException expected) {}
1276 
1277         // When file is a directory.
1278         filesSetup.reset();
1279         try {
1280             Files.readAllLines(filesSetup.getTestDirPath());
1281             fail();
1282         } catch (IOException expected) {}
1283     }
1284 
1285     @Test
test_readAllLine_NPE()1286     public void test_readAllLine_NPE() throws IOException {
1287         try {
1288             Files.readAllLines(null);
1289             fail();
1290         } catch (NullPointerException expected) {}
1291     }
1292 
1293     @Test
test_readAllLine$Path$Charset()1294     public void test_readAllLine$Path$Charset() throws IOException {
1295         assertTrue(Files.exists(filesSetup.getDataFilePath()));
1296         writeToFile(filesSetup.getDataFilePath(), "\n" + TEST_FILE_DATA_2, APPEND);
1297         List<String> out = Files.readAllLines(filesSetup.getDataFilePath(), StandardCharsets.UTF_8);
1298         assertEquals(2, out.size());
1299         assertEquals(TEST_FILE_DATA, out.get(0));
1300         assertEquals(TEST_FILE_DATA_2, out.get(1));
1301 
1302         // With UTF-16.
1303         out = Files.readAllLines(filesSetup.getDataFilePath(), StandardCharsets.UTF_16);
1304         assertEquals(1, out.size());
1305 
1306         // UTF-8 data read as UTF-16
1307         String expectedOutput = new String((TEST_FILE_DATA + '\n' + TEST_FILE_DATA_2).getBytes(),
1308                 StandardCharsets.UTF_16);
1309         assertEquals(expectedOutput, out.get(0));
1310 
1311         // When file doesn't exist.
1312         filesSetup.reset();
1313         try {
1314             Files.readAllLines(filesSetup.getTestPath(), StandardCharsets.UTF_16);
1315             fail();
1316         } catch (NoSuchFileException expected) {}
1317 
1318         // When file is a directory.
1319         filesSetup.reset();
1320         try {
1321             Files.readAllLines(filesSetup.getTestDirPath(), StandardCharsets.UTF_16);
1322             fail();
1323         } catch (IOException expected) {}
1324     }
1325 
1326     @Test
test_readAllLine$Path$Charset_NPE()1327     public void test_readAllLine$Path$Charset_NPE() throws IOException {
1328         try {
1329             Files.readAllLines(null, StandardCharsets.UTF_16);
1330             fail();
1331         } catch (NullPointerException expected) {}
1332 
1333         try {
1334             Files.readAllLines(filesSetup.getDataFilePath(), null);
1335             fail();
1336         } catch (NullPointerException expected) {}
1337     }
1338 
1339     @Test
test_walk$Path$FileVisitOption()1340     public void test_walk$Path$FileVisitOption() throws IOException {
1341         // Directory structure.
1342         //        root
1343         //        ├── dir1
1344         //        │   ├── dir2
1345         //        │   │   ├── dir3
1346         //        │   │   └── file5
1347         //        │   ├── dir4
1348         //        │   └── file3
1349         //        ├── dir5
1350         //        └── file1
1351         //
1352         // depth will be 2. file4, file5, dir3 is not reachable.
1353 
1354         Path rootDir = Paths.get(filesSetup.getTestDir(), "root");
1355         Path dir1 = Paths.get(filesSetup.getTestDir(), "root/dir1");
1356         Path dir2 = Paths.get(filesSetup.getTestDir(), "root/dir1/dir2");
1357         Path dir3 = Paths.get(filesSetup.getTestDir(), "root/dir1/dir2/dir3");
1358         Path dir4 = Paths.get(filesSetup.getTestDir(), "root/dir1/dir4");
1359         Path dir5 = Paths.get(filesSetup.getTestDir(), "root/dir5");
1360         Path file1 = Paths.get(filesSetup.getTestDir(), "root/file1");
1361         Path file3 = Paths.get(filesSetup.getTestDir(), "root/dir1/file3");
1362         Path file5 = Paths.get(filesSetup.getTestDir(), "root/dir1/dir2/file5");
1363 
1364         Files.createDirectories(dir3);
1365         Files.createDirectories(dir4);
1366         Files.createDirectories(dir5);
1367         Files.createFile(file1);
1368         Files.createFile(file3);
1369         Files.createFile(file5);
1370 
1371         Set<Path> expectedDirSet = new HashSet<>();
1372         expectedDirSet.add(rootDir);
1373         expectedDirSet.add(dir1);
1374         expectedDirSet.add(dir2);
1375         expectedDirSet.add(dir4);
1376         expectedDirSet.add(file3);
1377         expectedDirSet.add(dir5);
1378         expectedDirSet.add(file1);
1379 
1380         Set<Path> dirSet = new HashSet<>();
1381         try(Stream<Path> pathStream = Files.walk(rootDir, 2,
1382                 FileVisitOption.FOLLOW_LINKS)) {
1383             pathStream.forEach(path -> dirSet.add(path));
1384         }
1385 
1386         assertEquals(expectedDirSet, dirSet);
1387 
1388         // Test case when Path doesn't exist.
1389         try (Stream<Path> pathStream = Files.walk(filesSetup.getTestPath(), 2,
1390                 FileVisitOption.FOLLOW_LINKS)){
1391             fail();
1392         } catch (NoSuchFileException expected) {}
1393 
1394         // Test case when Path is a not a directory.
1395         expectedDirSet.clear();
1396         dirSet.clear();
1397         expectedDirSet.add(filesSetup.getDataFilePath());
1398         try (Stream<Path> pathStream = Files.walk(filesSetup.getDataFilePath(), 2,
1399                 FileVisitOption.FOLLOW_LINKS)){
1400             pathStream.forEach(path -> dirSet.add(path));
1401         }
1402         assertEquals(expectedDirSet, dirSet);
1403 
1404         // Test case when Path doesn't exist.
1405         try (Stream<Path> pathStream = Files.walk(rootDir, -1, FileVisitOption.FOLLOW_LINKS)){
1406             fail();
1407         } catch (IllegalArgumentException expected) {}
1408     }
1409 
1410     @Test
test_walk_FileSystemLoopException()1411     public void test_walk_FileSystemLoopException() throws IOException {
1412         // Directory structure.
1413         //        root
1414         //        └── dir1
1415         //            └── file1
1416         //
1417         // file1 is symbolic link to dir1
1418 
1419         Path rootDir = Paths.get(filesSetup.getTestDir(), "root");
1420         Path dir1 = Paths.get(filesSetup.getTestDir(), "root/dir");
1421         Path file1 = Paths.get(filesSetup.getTestDir(), "root/dir/file1");
1422         Files.createDirectories(dir1);
1423         Files.createSymbolicLink(file1, dir1.toAbsolutePath());
1424         assertTrue(Files.isSymbolicLink(file1));
1425         try(Stream<Path> pathStream = Files.walk(rootDir, FileVisitOption.FOLLOW_LINKS)) {
1426             pathStream.forEach(path -> assertNotNull(path));
1427             fail();
1428         } catch (UncheckedIOException expected) {
1429             assertTrue(expected.getCause() instanceof FileSystemLoopException);
1430         }
1431     }
1432 
1433     @Test
test_walk()1434     public void test_walk() throws IOException {
1435         // Directory structure.
1436         //        root
1437         //        ├── dir1
1438         //        │   ├── dir2
1439         //        │   │   ├── dir3
1440         //        │   │   └── file5
1441         //        │   ├── dir4
1442         //        │   └── file3
1443         //        ├── dir5
1444         //        └── file1
1445         //
1446 
1447         Path rootDir = Paths.get(filesSetup.getTestDir(), "root");
1448         Path dir1 = Paths.get(filesSetup.getTestDir(), "root/dir1");
1449         Path dir2 = Paths.get(filesSetup.getTestDir(), "root/dir1/dir2");
1450         Path dir3 = Paths.get(filesSetup.getTestDir(), "root/dir1/dir2/dir3");
1451         Path dir4 = Paths.get(filesSetup.getTestDir(), "root/dir1/dir4");
1452         Path dir5 = Paths.get(filesSetup.getTestDir(), "root/dir5");
1453         Path file1 = Paths.get(filesSetup.getTestDir(), "root/file1");
1454         Path file3 = Paths.get(filesSetup.getTestDir(), "root/dir1/file3");
1455         Path file5 = Paths.get(filesSetup.getTestDir(), "root/dir1/dir2/file5");
1456 
1457         Files.createDirectories(dir3);
1458         Files.createDirectories(dir4);
1459         Files.createDirectories(dir5);
1460         Files.createFile(file1);
1461         Files.createFile(file3);
1462         Files.createFile(file5);
1463 
1464         Set<Path> expectedDirSet = new HashSet<>();
1465         expectedDirSet.add(rootDir.getFileName());
1466         expectedDirSet.add(dir1.getFileName());
1467         expectedDirSet.add(dir2.getFileName());
1468         expectedDirSet.add(dir4.getFileName());
1469         expectedDirSet.add(file3.getFileName());
1470         expectedDirSet.add(dir5.getFileName());
1471         expectedDirSet.add(file1.getFileName());
1472         expectedDirSet.add(file5.getFileName());
1473         expectedDirSet.add(dir3.getFileName());
1474 
1475         Set<Path> dirSet = new HashSet<>();
1476         try (Stream<Path> pathStream = Files.walk(rootDir)) {
1477             pathStream.forEach(path -> dirSet.add(path.getFileName()));
1478         }
1479 
1480         assertEquals(expectedDirSet, dirSet);
1481 
1482 
1483         // Test case when Path doesn't exist.
1484         try (Stream<Path> pathStream = Files.walk(filesSetup.getTestPath())){
1485             fail();
1486         } catch (NoSuchFileException expected) {}
1487 
1488         // Test case when Path is a not a directory.
1489         expectedDirSet.clear();
1490         dirSet.clear();
1491         expectedDirSet.add(filesSetup.getDataFilePath());
1492         try (Stream<Path> pathStream = Files.walk(filesSetup.getDataFilePath())) {
1493             pathStream.forEach(path -> dirSet.add(path));
1494         }
1495         assertEquals(expectedDirSet, dirSet);
1496     }
1497 
1498     @Test
test_walk_depthFirst()1499     public void test_walk_depthFirst() throws IOException {
1500         // Directory structure.
1501         //        root
1502         //        ├── dir1
1503         //        │   └── file1
1504         //        └── dir2
1505         //            └── file2
1506         //
1507 
1508         Path rootDir = Paths.get(filesSetup.getTestDir(), "root");
1509         Path dir1 = Paths.get(filesSetup.getTestDir(), "root/dir1");
1510         Path file1 = Paths.get(filesSetup.getTestDir(), "root/dir1/file1");
1511         Path dir2 = Paths.get(filesSetup.getTestDir(), "root/dir2");
1512         Path file2 = Paths.get(filesSetup.getTestDir(), "root/dir2/file2");
1513         Files.createDirectories(dir1);
1514         Files.createDirectories(dir2);
1515         Files.createFile(file1);
1516         Files.createFile(file2);
1517         List<Object> fileKeyList = new ArrayList<>();
1518         try(Stream<Path> pathStream = Files.walk(rootDir, FileVisitOption.FOLLOW_LINKS)) {
1519             pathStream.forEach(path -> fileKeyList.add(path.getFileName()));
1520         }
1521         assertEquals(rootDir.getFileName(), fileKeyList.get(0));
1522         if (fileKeyList.get(1).equals(dir1.getFileName())) {
1523             assertEquals(file1.getFileName(), fileKeyList.get(2));
1524             assertEquals(dir2.getFileName(), fileKeyList.get(3));
1525             assertEquals(file2.getFileName(), fileKeyList.get(4));
1526         } else if (fileKeyList.get(1).equals(dir2.getFileName())) {
1527             assertEquals(file2.getFileName(), fileKeyList.get(2));
1528             assertEquals(dir1.getFileName(), fileKeyList.get(3));
1529             assertEquals(file1.getFileName(), fileKeyList.get(4));
1530         } else {
1531             fail();
1532         }
1533     }
1534 
1535     @Test
test_walk$Path$Int$LinkOption_IllegalArgumentException()1536     public void test_walk$Path$Int$LinkOption_IllegalArgumentException() throws IOException {
1537         Map<Path, Boolean> dirMap = new HashMap<>();
1538         Path rootDir = Paths.get(filesSetup.getTestDir(), "rootDir");
1539         try (Stream<Path> pathStream = Files.walk(rootDir, -1,
1540                 FileVisitOption.FOLLOW_LINKS)) {
1541             fail();
1542         } catch (IllegalArgumentException expected) {}
1543     }
1544 
1545     @Test
test_walk$Path$FileVisitOption_NPE()1546     public void test_walk$Path$FileVisitOption_NPE() throws IOException {
1547         try {
1548             Files.walk(null);
1549             fail();
1550         } catch (NullPointerException expected) {}
1551     }
1552 
1553     @Test
test_write$Path$byte$OpenOption()1554     public void test_write$Path$byte$OpenOption() throws IOException {
1555         Files.write(filesSetup.getDataFilePath(), TEST_FILE_DATA_2.getBytes());
1556         assertEquals(TEST_FILE_DATA_2, readFromFile(filesSetup.getDataFilePath()));
1557     }
1558 
1559     @Test
test_write$Path$byte$OpenOption_OpenOption()1560     public void test_write$Path$byte$OpenOption_OpenOption() throws IOException {
1561         Files.write(filesSetup.getTestPath(), TEST_FILE_DATA_2.getBytes(), CREATE_NEW);
1562         assertEquals(TEST_FILE_DATA_2, readFromFile(filesSetup.getTestPath()));
1563 
1564         filesSetup.reset();
1565         Files.write(filesSetup.getDataFilePath(), TEST_FILE_DATA_2.getBytes(), TRUNCATE_EXISTING);
1566         assertEquals(TEST_FILE_DATA_2, readFromFile(filesSetup.getDataFilePath()));
1567 
1568         filesSetup.reset();
1569         Files.write(filesSetup.getDataFilePath(), TEST_FILE_DATA_2.getBytes(), APPEND);
1570         assertEquals(TEST_FILE_DATA + TEST_FILE_DATA_2, readFromFile(
1571                 filesSetup.getDataFilePath()));
1572 
1573         filesSetup.reset();
1574         try {
1575             Files.write(filesSetup.getDataFilePath(), TEST_FILE_DATA_2.getBytes(), READ);
1576             fail();
1577         } catch (IllegalArgumentException expected) {}
1578     }
1579 
1580     @Test
test_write$Path$byte$OpenOption_NPE()1581     public void test_write$Path$byte$OpenOption_NPE() throws IOException {
1582         try {
1583             Files.write(null, TEST_FILE_DATA_2.getBytes(), CREATE_NEW);
1584             fail();
1585         } catch (NullPointerException expected) {}
1586 
1587         try {
1588             Files.write(filesSetup.getTestPath(), (byte[]) null, CREATE_NEW);
1589             fail();
1590         } catch (NullPointerException expected) {}
1591 
1592         try {
1593             Files.write(filesSetup.getTestPath(), TEST_FILE_DATA_2.getBytes(), (OpenOption[]) null);
1594             fail();
1595         } catch (NullPointerException expected) {}
1596     }
1597 
1598     @Test
test_write$Path$Iterable$Charset$OpenOption()1599     public void test_write$Path$Iterable$Charset$OpenOption() throws IOException {
1600         List<String> lines = new ArrayList<>();
1601         lines.add(TEST_FILE_DATA_2);
1602         lines.add(TEST_FILE_DATA);
1603         Files.write(filesSetup.getDataFilePath(), lines, StandardCharsets.UTF_16);
1604         List<String> readLines = Files.readAllLines(filesSetup.getDataFilePath(),
1605                 StandardCharsets.UTF_16);
1606         assertEquals(readLines, lines);
1607     }
1608 
1609     @Test
test_write$Path$Iterable$Charset$OpenOption_NPE()1610     public void test_write$Path$Iterable$Charset$OpenOption_NPE() throws IOException {
1611         try {
1612             Files.write(null, new ArrayList<>(), StandardCharsets.UTF_16);
1613             fail();
1614         } catch (NullPointerException expected) {}
1615 
1616         try {
1617             Files.write(filesSetup.getDataFilePath(), null, StandardCharsets.UTF_16);
1618             fail();
1619         } catch (NullPointerException expected) {}
1620 
1621         try {
1622             Files.write(filesSetup.getDataFilePath(), new ArrayList<>(), (OpenOption[]) null);
1623             fail();
1624         } catch (NullPointerException expected) {}
1625     }
1626 
1627     @Test
test_write$Path$Iterable$OpenOption()1628     public void test_write$Path$Iterable$OpenOption() throws IOException {
1629         List<String> lines = new ArrayList<>();
1630         lines.add(TEST_FILE_DATA_2);
1631         lines.add(TEST_FILE_DATA);
1632         Files.write(filesSetup.getDataFilePath(), lines);
1633         List<String> readLines = Files.readAllLines(filesSetup.getDataFilePath());
1634         assertEquals(readLines, lines);
1635     }
1636 
1637     @Test
test_write$Path$Iterable$OpenOption_NPE()1638     public void test_write$Path$Iterable$OpenOption_NPE() throws IOException {
1639         try {
1640             Files.write(null, new ArrayList<String>());
1641             fail();
1642         } catch (NullPointerException expected) {}
1643 
1644         try {
1645             Files.write(filesSetup.getDataFilePath(), (Iterable<CharSequence>) null);
1646             fail();
1647         } catch (NullPointerException expected) {}
1648     }
1649 
1650     // The ability for Android apps to create hard links was removed in
1651     // https://android-review.googlesource.com/144092 (March 2015).
1652     // https://b/19953790.
1653     @Test
test_createLink()1654     public void test_createLink() throws IOException {
1655         try {
1656             Files.createLink(filesSetup.getTestPath(), filesSetup.getDataFilePath());
1657             fail();
1658         } catch (AccessDeniedException expected) {}
1659     }
1660 
1661     @Test
test_createTempDirectory$Path$String$FileAttributes()1662     public void test_createTempDirectory$Path$String$FileAttributes() throws IOException {
1663         Set<PosixFilePermission> perm = PosixFilePermissions.fromString("rwx------");
1664         FileAttribute<Set<PosixFilePermission>> attr = PosixFilePermissions.asFileAttribute(perm);
1665 
1666         String tmpDir = "tmpDir";
1667         Path tmpDirPath = Files.createTempDirectory(filesSetup.getTestDirPath(), tmpDir, attr);
1668         assertTrue(tmpDirPath.getFileName().toString().startsWith(tmpDir));
1669         assertEquals(filesSetup.getTestDirPath(), tmpDirPath.getParent());
1670         assertTrue(Files.isDirectory(tmpDirPath));
1671         assertEquals(attr.value(), Files.getAttribute(tmpDirPath, attr.name()));
1672 
1673         filesSetup.reset();
1674         // Test case when prefix is null.
1675         tmpDirPath = Files.createTempDirectory(filesSetup.getTestDirPath(), null, attr);
1676         assertEquals(filesSetup.getTestDirPath(), tmpDirPath.getParent());
1677         assertTrue(Files.isDirectory(tmpDirPath));
1678         assertEquals(attr.value(), Files.getAttribute(tmpDirPath, attr.name()));
1679 
1680         try {
1681             Files.createTempDirectory(null, tmpDir, attr);
1682             fail();
1683         } catch (NullPointerException expected) {}
1684 
1685         try {
1686             Files.createTempDirectory(filesSetup.getTestDirPath(), tmpDir, (FileAttribute<?>) null);
1687             fail();
1688         } catch (NullPointerException expected) {}
1689     }
1690 
1691     @Test
test_createTempDirectory$String$FileAttributes()1692     public void test_createTempDirectory$String$FileAttributes() throws IOException {
1693         Set<PosixFilePermission> perm = PosixFilePermissions.fromString("rwx------");
1694         FileAttribute<Set<PosixFilePermission>> attr = PosixFilePermissions.asFileAttribute(perm);
1695 
1696         Path tmpDirectoryLocation = Paths.get(System.getProperty("java.io.tmpdir"));
1697 
1698         String tmpDir = "tmpDir";
1699         Path tmpDirPath = Files.createTempDirectory(tmpDir, attr);
1700         assertTrue(tmpDirPath.getFileName().toString().startsWith(tmpDir));
1701         assertEquals(tmpDirectoryLocation, tmpDirPath.getParent());
1702         assertTrue(Files.isDirectory(tmpDirPath));
1703         assertEquals(attr.value(), Files.getAttribute(tmpDirPath, attr.name()));
1704 
1705         // Test case when prefix is null.
1706         filesSetup.reset();
1707         tmpDirPath = Files.createTempDirectory(null, attr);
1708         assertEquals(tmpDirectoryLocation, tmpDirPath.getParent());
1709         assertTrue(Files.isDirectory(tmpDirPath));
1710         assertEquals(attr.value(), Files.getAttribute(tmpDirPath, attr.name()));
1711 
1712         try {
1713             Files.createTempDirectory(tmpDir, (FileAttribute<?>) null);
1714             fail();
1715         } catch (NullPointerException expected) {}
1716     }
1717 
1718     @Test
test_createTempFile$Path$String$String$FileAttributes()1719     public void test_createTempFile$Path$String$String$FileAttributes() throws IOException {
1720         Set<PosixFilePermission> perm = PosixFilePermissions.fromString("rwx------");
1721         FileAttribute<Set<PosixFilePermission>> attr = PosixFilePermissions.asFileAttribute(perm);
1722 
1723         String tmpFilePrefix = "prefix";
1724         String tmpFileSuffix = "suffix";
1725 
1726         Path tmpFilePath = Files.createTempFile(filesSetup.getTestDirPath(), tmpFilePrefix,
1727                 tmpFileSuffix, attr);
1728 
1729         assertTrue(tmpFilePath.getFileName().toString().startsWith(tmpFilePrefix));
1730         assertTrue(tmpFilePath.getFileName().toString().endsWith(tmpFileSuffix));
1731         assertEquals(filesSetup.getTestDirPath(), tmpFilePath.getParent());
1732         assertTrue(Files.isRegularFile(tmpFilePath));
1733         assertEquals(attr.value(), Files.getAttribute(tmpFilePath, attr.name()));
1734 
1735         // Test case when prefix is null.
1736         filesSetup.reset();
1737         tmpFilePath = Files.createTempFile(filesSetup.getTestDirPath(), null,
1738                 tmpFileSuffix, attr);
1739         assertTrue(tmpFilePath.getFileName().toString().endsWith(tmpFileSuffix));
1740         assertEquals(filesSetup.getTestDirPath(), tmpFilePath.getParent());
1741         assertTrue(Files.isRegularFile(tmpFilePath));
1742         assertEquals(attr.value(), Files.getAttribute(tmpFilePath, attr.name()));
1743 
1744         // Test case when suffix is null.
1745         filesSetup.reset();
1746         tmpFilePath = Files.createTempFile(filesSetup.getTestDirPath(), tmpFilePrefix,
1747                 null, attr);
1748         assertTrue(tmpFilePath.getFileName().toString().startsWith(tmpFilePrefix));
1749         assertEquals(filesSetup.getTestDirPath(), tmpFilePath.getParent());
1750         assertTrue(Files.isRegularFile(tmpFilePath));
1751         assertEquals(attr.value(), Files.getAttribute(tmpFilePath, attr.name()));
1752 
1753         try {
1754             Files.createTempFile(null, tmpFilePrefix, tmpFileSuffix, attr);
1755             fail();
1756         } catch (NullPointerException expected) {}
1757 
1758         try {
1759             Files.createTempFile(filesSetup.getTestDirPath(), tmpFilePrefix, tmpFileSuffix,
1760                 (FileAttribute<?>) null);
1761             fail();
1762         } catch (NullPointerException expected) {}
1763     }
1764 
1765     @Test
test_createTempFile$String$String$FileAttributes()1766     public void test_createTempFile$String$String$FileAttributes() throws IOException {
1767         Set<PosixFilePermission> perm = PosixFilePermissions.fromString("rwx------");
1768         FileAttribute<Set<PosixFilePermission>> attr = PosixFilePermissions.asFileAttribute(perm);
1769 
1770         Path tmpDirectoryLocation = Paths.get(System.getProperty(
1771                 "java.io.tmpdir"));
1772 
1773         String tmpFilePrefix = "prefix";
1774         String tmpFileSuffix = "suffix";
1775         Path tmpFilePath = Files.createTempFile(tmpFilePrefix, tmpFileSuffix, attr);
1776         assertTrue(tmpFilePath.getFileName().toString().startsWith(tmpFilePrefix));
1777         assertTrue(tmpFilePath.getFileName().toString().endsWith(tmpFileSuffix));
1778         assertEquals(tmpDirectoryLocation, tmpFilePath.getParent());
1779         assertTrue(Files.isRegularFile(tmpFilePath));
1780         assertEquals(attr.value(), Files.getAttribute(tmpFilePath, attr.name()));
1781 
1782         // Test case when prefix is null.
1783         filesSetup.reset();
1784         tmpFilePath = Files.createTempFile(null, tmpFileSuffix, attr);
1785         assertEquals(tmpDirectoryLocation, tmpFilePath.getParent());
1786         assertTrue(tmpFilePath.getFileName().toString().endsWith(tmpFileSuffix));
1787         assertTrue(Files.isRegularFile(tmpFilePath));
1788         assertEquals(attr.value(), Files.getAttribute(tmpFilePath, attr.name()));
1789 
1790         // Test case when suffix is null.
1791         filesSetup.reset();
1792         tmpFilePath = Files.createTempFile(tmpFilePrefix, null, attr);
1793         assertEquals(tmpDirectoryLocation, tmpFilePath.getParent());
1794         assertTrue(tmpFilePath.getFileName().toString().startsWith(tmpFilePrefix));
1795         assertTrue(Files.isRegularFile(tmpFilePath));
1796         assertEquals(attr.value(), Files.getAttribute(tmpFilePath, attr.name()));
1797 
1798         try {
1799             Files.createTempFile(tmpFilePrefix, tmpFileSuffix, (FileAttribute<?>) null);
1800             fail();
1801         } catch (NullPointerException expected) {}
1802     }
1803 
1804     @Test
test_newByteChannel$Path$Set_OpenOption$FileAttributes()1805     public void test_newByteChannel$Path$Set_OpenOption$FileAttributes() throws Exception {
1806         FileAttribute stubFileAttribute = mock(FileAttribute.class);
1807         Set<OpenOption> stubSet = new HashSet<>();
1808         Files.newByteChannel(mockPath, stubSet, stubFileAttribute);
1809 
1810         verify(mockFileSystemProvider).newByteChannel(mockPath, stubSet, stubFileAttribute);
1811     }
1812 
1813     // -- Mock Class --
1814 
1815     private static class TestFileVisitor implements FileVisitor<Path> {
1816 
1817         final Map<Object, VisitOption> dirMap;
1818         LinkOption option[];
1819         List<Object> keyList;
1820 
TestFileVisitor(Map<Object, VisitOption> dirMap)1821         public TestFileVisitor(Map<Object, VisitOption> dirMap) {
1822             this(dirMap, (List<Object>) null);
1823         }
1824 
TestFileVisitor(Map<Object, VisitOption> dirMap, Set<FileVisitOption> option)1825         public TestFileVisitor(Map<Object, VisitOption> dirMap, Set<FileVisitOption> option) {
1826             this.dirMap = dirMap;
1827             for (FileVisitOption fileVisitOption : option) {
1828                 if (fileVisitOption.equals(FileVisitOption.FOLLOW_LINKS)) {
1829                     this.option = new LinkOption[0];
1830                 }
1831             }
1832 
1833             if (this.option == null) {
1834                 this.option = new LinkOption[] {LinkOption.NOFOLLOW_LINKS};
1835             }
1836         }
1837 
TestFileVisitor(Map<Object, VisitOption> dirMap, List<Object> pathList)1838         public TestFileVisitor(Map<Object, VisitOption> dirMap, List<Object> pathList) {
1839             this.dirMap = dirMap;
1840             this.option = new LinkOption[] {LinkOption.NOFOLLOW_LINKS};
1841             keyList = pathList;
1842         }
1843 
1844         @Override
preVisitDirectory(Path dir, BasicFileAttributes attrs)1845         public FileVisitResult preVisitDirectory(Path dir, BasicFileAttributes attrs)
1846                 throws IOException {
1847             if (keyList != null) {
1848                 keyList.add(dir.getFileName());
1849             }
1850             dirMap.put(dir.getFileName(), VisitOption.PRE_VISIT_DIRECTORY);
1851             return CONTINUE;
1852         }
1853 
1854         @Override
visitFile(Path file, BasicFileAttributes attrs)1855         public FileVisitResult visitFile(Path file, BasicFileAttributes attrs) throws IOException {
1856             if (keyList != null) {
1857                 keyList.add(file.getFileName());
1858             }
1859             dirMap.put(file.getFileName(), VisitOption.VISIT_FILE);
1860             return CONTINUE;
1861         }
1862 
1863         @Override
visitFileFailed(Path file, IOException exc)1864         public FileVisitResult visitFileFailed(Path file, IOException exc) throws IOException {
1865             if (exc != null) {
1866                 throw exc;
1867             }
1868             return TERMINATE;
1869         }
1870 
1871         @Override
postVisitDirectory(Path dir, IOException exc)1872         public FileVisitResult postVisitDirectory(Path dir, IOException exc) throws IOException {
1873             if (exc != null) {
1874                 throw exc;
1875             }
1876             if (dirMap.getOrDefault(dir.getFileName(), VisitOption.UNVISITED)
1877                     != VisitOption.PRE_VISIT_DIRECTORY) {
1878                 return TERMINATE;
1879             } else {
1880                 dirMap.put(dir.getFileName(), VisitOption.POST_VISIT_DIRECTORY);
1881                 return CONTINUE;
1882             }
1883         }
1884     }
1885 
1886     private enum VisitOption {
1887         PRE_VISIT_DIRECTORY,
1888         VISIT_FILE,
1889         POST_VISIT_DIRECTORY,
1890         UNVISITED,
1891     }
1892 }
1893