package org.the_jk.cleversync import com.google.common.truth.Truth.assertThat import org.junit.Before import org.junit.Rule import org.junit.Test import org.junit.rules.TemporaryFolder import org.junit.runner.RunWith import org.robolectric.RobolectricTestRunner import org.robolectric.annotation.Config import org.robolectric.shadows.ShadowLooper import org.the_jk.cleversync.io.Directory import org.the_jk.cleversync.io.ModifiableTree import org.the_jk.cleversync.io.TreeFactory @Config(manifest=Config.NONE) @RunWith(RobolectricTestRunner::class) class LocalTreeTest { @get:Rule val folder = TemporaryFolder() private lateinit var tree: ModifiableTree @Before fun setUp() { tree = TreeFactory.localModifiableTree(folder.root.toPath()) } @Test fun empty() { val content = tree.list() assertThat(content.directories).isEmpty() assertThat(content.files).isEmpty() assertThat(content.links).isEmpty() } @Test fun emptyLive() { val content = tree.liveList().safeValue() assertThat(content?.directories).isEmpty() assertThat(content?.files).isEmpty() assertThat(content?.links).isEmpty() } @Test fun createDirectory() { val foo = tree.createDirectory("foo") assertThat(foo.name).isEqualTo("foo") val fooContent = foo.list() assertThat(fooContent.directories).isEmpty() assertThat(fooContent.files).isEmpty() assertThat(fooContent.links).isEmpty() val content = tree.list() assertThat(content.directories).contains(foo) assertThat(content.files).isEmpty() assertThat(content.links).isEmpty() } @Test fun observeCreateDirectory() { val content = tree.liveList() var dir: Directory? = null content.observeForever { if (it.directories.size == 1) dir = it.directories[0] } tree.createDirectory("foo") while (dir == null) { ShadowLooper.idleMainLooper() } assertThat(dir?.name).isEqualTo("foo") } @Test fun createFile() { val foo = tree.createFile("foo") // Files are not created until you write to them. assertThat(tree.list().files).isEmpty() foo.write().use { os -> os.write(byteArrayOf(1, 2, 3, 4)) } assertThat(tree.list().files).contains(foo) assertThat(foo.size).isEqualTo(4.toULong()) foo.read().use { assertThat(it.readBytes()).isEqualTo(byteArrayOf(1, 2, 3, 4)) } } @Test fun overwriteFile() { val foo = tree.createFile("foo") foo.write().use { os -> os.write(byteArrayOf(1, 2, 3, 4)) } foo.write().use { os -> os.write(byteArrayOf(127)) assertThat(foo.size).isEqualTo(4.toULong()) } assertThat(foo.size).isEqualTo(1.toULong()) assertThat(tree.list().files).hasSize(1) foo.read().use { assertThat(it.readBytes()).isEqualTo(byteArrayOf(127)) } } }