diff options
Diffstat (limited to 'app/src/test/java/invalid/lena/scrcpy/AtomicFilesTest.java')
| -rw-r--r-- | app/src/test/java/invalid/lena/scrcpy/AtomicFilesTest.java | 54 |
1 files changed, 54 insertions, 0 deletions
diff --git a/app/src/test/java/invalid/lena/scrcpy/AtomicFilesTest.java b/app/src/test/java/invalid/lena/scrcpy/AtomicFilesTest.java new file mode 100644 index 0000000..7124fd2 --- /dev/null +++ b/app/src/test/java/invalid/lena/scrcpy/AtomicFilesTest.java @@ -0,0 +1,54 @@ +package invalid.lena.scrcpy; + +import static org.junit.Assert.assertArrayEquals; +import static org.junit.Assert.assertFalse; + +import org.junit.Rule; +import org.junit.Test; +import org.junit.rules.TemporaryFolder; + +import java.io.File; +import java.nio.file.Files; + +public class AtomicFilesTest { + + @Rule + public TemporaryFolder dir = new TemporaryFolder(); + + @Test + public void writeCreatesFile() throws Exception { + File f = new File(dir.getRoot(), "x"); + AtomicFiles.write(f, "hello".getBytes()); + assertArrayEquals("hello".getBytes(), Files.readAllBytes(f.toPath())); + } + + @Test + public void writeReplacesExistingWhole() throws Exception { + File f = new File(dir.getRoot(), "x"); + AtomicFiles.write(f, "old".getBytes()); + AtomicFiles.write(f, "new-and-longer".getBytes()); + assertArrayEquals("new-and-longer".getBytes(), Files.readAllBytes(f.toPath())); + } + + @Test + public void writeLeavesNoTempBehind() throws Exception { + File f = new File(dir.getRoot(), "x"); + AtomicFiles.write(f, "data".getBytes()); + assertFalse(new File(dir.getRoot(), "x.tmp").exists()); + } + + @Test + public void staleTempDoesNotCorruptDestination() throws Exception { + // A crash after staging but before the rename leaves a partial ".tmp". + // The destination must still hold the previous good content, and the + // next successful write must overwrite the stale temp cleanly. + File f = new File(dir.getRoot(), "x"); + AtomicFiles.write(f, "good".getBytes()); + Files.write(new File(dir.getRoot(), "x.tmp").toPath(), "partial".getBytes()); + assertArrayEquals("good".getBytes(), Files.readAllBytes(f.toPath())); + + AtomicFiles.write(f, "good2".getBytes()); + assertArrayEquals("good2".getBytes(), Files.readAllBytes(f.toPath())); + assertFalse(new File(dir.getRoot(), "x.tmp").exists()); + } +} |