|
| 1 | +package httpserver.file; |
| 2 | + |
| 3 | +import org.junit.Test; |
| 4 | + |
| 5 | +import java.io.IOException; |
| 6 | +import java.nio.file.Path; |
| 7 | +import java.nio.file.Paths; |
| 8 | + |
| 9 | +import static httpserver.file.FileHelpers.tempDir; |
| 10 | +import static java.nio.file.Files.exists; |
| 11 | +import static java.nio.file.Files.readAllBytes; |
| 12 | +import static org.junit.Assert.*; |
| 13 | + |
| 14 | +public class FileOperatorTest { |
| 15 | + |
| 16 | + private final Path path; |
| 17 | + private final Path dir; |
| 18 | + private FileOperator fileOperator; |
| 19 | + |
| 20 | + public FileOperatorTest() throws IOException { |
| 21 | + dir = tempDir(); |
| 22 | + path = Paths.get(dir.toString(), "/example.txt"); |
| 23 | + fileOperator = new FileOperator(); |
| 24 | + } |
| 25 | + |
| 26 | + @Test |
| 27 | + public void createsFileAtPath() throws Exception { |
| 28 | + fileOperator.createFileAtPath(path); |
| 29 | + |
| 30 | + assertTrue(exists(path)); |
| 31 | + } |
| 32 | + |
| 33 | + @Test |
| 34 | + public void deletesFileAtPath() throws Exception { |
| 35 | + fileOperator.createFileAtPath(path); |
| 36 | + fileOperator.deleteFileAtPath(path); |
| 37 | + |
| 38 | + assertFalse(exists(path)); |
| 39 | + } |
| 40 | + |
| 41 | + @Test |
| 42 | + public void appendsToFileContentsAtPath() throws Exception { |
| 43 | + fileOperator.createFileAtPath(path); |
| 44 | + assertEquals("", fileContents(path)); |
| 45 | + |
| 46 | + fileOperator.appendToFile(path, "first line\r\n".getBytes()); |
| 47 | + assertEquals("first line\r\n", |
| 48 | + fileContents(path)); |
| 49 | + |
| 50 | + fileOperator.appendToFile(path, "second line\r\n".getBytes()); |
| 51 | + assertEquals("first line\r\nsecond line\r\n", |
| 52 | + fileContents(path)); |
| 53 | + } |
| 54 | + |
| 55 | + @Test |
| 56 | + public void replacesFileContentsAtPath() throws Exception { |
| 57 | + fileOperator.createFileAtPath(path); |
| 58 | + assertEquals("", fileContents(path)); |
| 59 | + |
| 60 | + fileOperator.replaceContents(path, "first line\r\n".getBytes()); |
| 61 | + assertEquals("first line\r\n", fileContents(path)); |
| 62 | + |
| 63 | + fileOperator.replaceContents(path, "second line\r\n".getBytes()); |
| 64 | + assertEquals("second line\r\n", fileContents(path)); |
| 65 | + } |
| 66 | + |
| 67 | + private String fileContents(Path path) throws IOException { |
| 68 | + return new String(readAllBytes(path)); |
| 69 | + } |
| 70 | +} |
0 commit comments