From 6a59820de33ef9341cdbc41a45196b1c0775d6bd Mon Sep 17 00:00:00 2001 From: James Strachan Date: Tue, 9 Oct 2012 08:36:51 +0100 Subject: [PATCH] added a test case for File.relativePath() along with fixing a bug if you pass the same file as the argument; it should have returned the empty string --- libraries/stdlib/src/kotlin/io/Files.kt | 5 ++++- libraries/stdlib/test/IoTest.kt | 24 +++++++++++++++++------- 2 files changed, 21 insertions(+), 8 deletions(-) diff --git a/libraries/stdlib/src/kotlin/io/Files.kt b/libraries/stdlib/src/kotlin/io/Files.kt index d6ee6ccea0a..b2d76273072 100644 --- a/libraries/stdlib/src/kotlin/io/Files.kt +++ b/libraries/stdlib/src/kotlin/io/Files.kt @@ -73,7 +73,10 @@ public fun File.relativePath(descendant: File): String { val prefix = this.directory.canonicalPath val answer = descendant.canonicalPath return if (answer.startsWith(prefix)) { - answer.substring(prefix.size + 1) + val prefixSize = prefix.size + if (answer.size > prefixSize) { + answer.substring(prefixSize + 1) + } else "" } else { answer } diff --git a/libraries/stdlib/test/IoTest.kt b/libraries/stdlib/test/IoTest.kt index 60ab5a51180..b73f1f727af 100644 --- a/libraries/stdlib/test/IoTest.kt +++ b/libraries/stdlib/test/IoTest.kt @@ -6,10 +6,10 @@ import kotlin.io.* import kotlin.util.* import java.io.* import java.util.* -import junit.framework.TestCase +import org.junit.Test as test -class IoTest() : TestCase() { - fun testLineIteratorWithManualClose() { +class IoTest(){ + test fun testLineIteratorWithManualClose() { val reader = sample().buffered() try { val list = reader.lineIterator().toArrayList() @@ -23,7 +23,7 @@ class IoTest() : TestCase() { return StringReader("Hello\nWorld"); } - fun testLineIterator() { + test fun testLineIterator() { // TODO we should maybe zap the useLines approach as it encourages // use of iterators which don't close the underlying stream val list1 = sample().useLines{it.toArrayList()} @@ -33,7 +33,7 @@ class IoTest() : TestCase() { assertEquals(arrayList("Hello", "World"), list2) } - fun testForEach() { + test fun testForEach() { val list = ArrayList() val reader = sample().buffered() @@ -50,7 +50,7 @@ class IoTest() : TestCase() { assertEquals(arrayList("Hello", "World"), list) } - fun testForEachLine() { + test fun testForEachLine() { val list = ArrayList() val reader = sample() @@ -72,7 +72,7 @@ class IoTest() : TestCase() { assertEquals(arrayList("Hello", "World"), list) } - fun testListFiles() { + test fun testListFiles() { val dir = File.createTempFile("temp", System.nanoTime().toString()) dir.delete() dir.mkdir() @@ -86,4 +86,14 @@ class IoTest() : TestCase() { assertNotNull(result) assertEquals(result!!.size, 2) } + + test fun relativePath() { + val file1 = File("src") + val file2 = File(file1, "kotlin") + val file3 = File("test") + + assertEquals("kotlin", file1.relativePath(file2)) + assertEquals("", file1.relativePath(file1)) + assertEquals(file3.canonicalPath, file1.relativePath(file3)) + } }