1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17 package org.apache.commons.io.comparator;
18
19 import static org.junit.jupiter.api.Assertions.assertEquals;
20 import static org.junit.jupiter.api.Assertions.assertFalse;
21 import static org.junit.jupiter.api.Assertions.assertTrue;
22
23 import java.io.BufferedOutputStream;
24 import java.io.File;
25 import java.io.IOException;
26 import java.nio.file.Files;
27
28 import org.apache.commons.io.FileUtils;
29 import org.apache.commons.io.test.TestUtils;
30 import org.junit.jupiter.api.BeforeEach;
31 import org.junit.jupiter.api.Test;
32
33
34
35
36 public class SizeFileComparatorTest extends ComparatorAbstractTest {
37
38 private File smallerDir;
39 private File largerDir;
40 private File smallerFile;
41 private File largerFile;
42
43 @BeforeEach
44 public void setUp() throws Exception {
45 comparator = (AbstractFileComparator) SizeFileComparator.SIZE_COMPARATOR;
46 reverse = SizeFileComparator.SIZE_REVERSE;
47 smallerDir = new File(dir, "smallerdir");
48 largerDir = new File(dir, "largerdir");
49 smallerFile = new File(smallerDir, "smaller.txt");
50 final File equalFile = new File(dir, "equal.txt");
51 largerFile = new File(largerDir, "larger.txt");
52 smallerDir.mkdir();
53 largerDir.mkdir();
54 if (!smallerFile.getParentFile().exists()) {
55 throw new IOException("Cannot create file " + smallerFile
56 + " as the parent directory does not exist");
57 }
58 try (BufferedOutputStream output2 =
59 new BufferedOutputStream(Files.newOutputStream(smallerFile.toPath()))) {
60 TestUtils.generateTestData(output2, 32);
61 }
62 if (!equalFile.getParentFile().exists()) {
63 throw new IOException("Cannot create file " + equalFile
64 + " as the parent directory does not exist");
65 }
66 try (BufferedOutputStream output1 =
67 new BufferedOutputStream(Files.newOutputStream(equalFile.toPath()))) {
68 TestUtils.generateTestData(output1, 48);
69 }
70 if (!largerFile.getParentFile().exists()) {
71 throw new IOException("Cannot create file " + largerFile
72 + " as the parent directory does not exist");
73 }
74 try (BufferedOutputStream output =
75 new BufferedOutputStream(Files.newOutputStream(largerFile.toPath()))) {
76 TestUtils.generateTestData(output, 64);
77 }
78 equalFile1 = equalFile;
79 equalFile2 = equalFile;
80 lessFile = smallerFile;
81 moreFile = largerFile;
82 }
83
84
85
86
87 @Test
88 public void testCompareDirectorySizes() {
89 assertEquals(0, comparator.compare(smallerDir, largerDir), "sumDirectoryContents=false");
90 assertEquals(-1, SizeFileComparator.SIZE_SUMDIR_COMPARATOR.compare(smallerDir, largerDir), "less");
91 assertEquals(1, SizeFileComparator.SIZE_SUMDIR_REVERSE.compare(smallerDir, largerDir), "less");
92 }
93
94
95
96
97 @Test
98 public void testNonExistentFile() {
99 final File nonExistentFile = new File(FileUtils.current(), "non-existent.txt");
100 assertFalse(nonExistentFile.exists());
101 assertTrue(comparator.compare(nonExistentFile, moreFile) < 0, "less");
102 }
103 }