I’m writing an integration test for a Gradle plugi...
# getting-started
a
I’m writing an integration test for a Gradle plugin that generates a HTML site. I’ve got the expected file structure, and I need to compare it against the actual generated site. I think it would be nice to generate a pretty file tree
Copy code
`
└── site/
    ├── styles/
    │   └── site.css
    ├── images/
    │   └── icon.png
    └── index.html
the expected/actual so the test assertion is just a simple string-comparison check, and I like that it would give a clear test-failure How can I generate such a pretty tree in Kotlin/JVM? Or maybe there’s a test assertion library that can help?
👀 1
it was less difficult than I thought to come up with something workable!
Copy code
import java.io.File

fun File.toPrettyTreeString(): String {
  return walk().joinToString("\n") { file ->
    val relativeFile = file.relativeTo(this)
    val depth = relativeFile.invariantSeparatorsPath.count { it == '/' }

    file.name.prependIndent(" ".repeat(depth))
  }
}
generates:
Copy code
html
    index.html
    -basic -project
     it.protected
      index.html
      -protected-class
       index.html
       protected-fun.html
       -protected-class.html
Next step is to try and compare file contents….
d
just cleaned it up and made it self-contained. gist: https://gist.github.com/mfwgenerics/d1ec89eb80c95da9d542a03b49b5e15b playground link: https://pl.kotl.in/W9vDI9E-x output:
Copy code
`
└── site
    ├── styles
    │   └── site.css
    ├── images
    │   └── icon.png
    └── index.html
hope it helps!
a
thanks, that’s half of the problem. I like the output, it’s pretty with the proper ascii pipe The first part is how to convert a java.io.File to a Node… In the end I found out that Kotest has a util for comparing file structures and content, so I just used that https://github.com/kotest/kotest/blob/ed015bd0e061dc1854f7e0702038b569b7e0a766/kotest-assertions/kotest-assertions-core/src/jvmMain/kotlin/io/kotest/matchers/file/matchers.kt#L250 https://github.com/kotest/kotest/blob/ed015bd0e061dc1854f7e0702038b569b7e0a766/kotest-assertions/kotest-assertions-core/src/jvmMain/kotlin/io/kotest/matchers/file/matchers.kt#L289
d
I would also lean towards kotest for this. for posterity I have updated the file tree gist to work with
java.nio.file.Path
(obtainable by calling
File.toPath
)
a
😬 StackOverflowError
I did have to change
Copy code
val entries = dir.listDirectoryEntries()
to
Copy code
val entries = dir.toFile().walk().maxDepth(1).toList()
since Gradle 7.6 limits Kotlin to 1.4
ah, this is the fix
Copy code
val entries = dir.toFile().walk().maxDepth(1).filter { it != dir.toFile() }
I refactored it :)
the result is exactly what I’m looking for thanks very much for your help!
d
Glad it helped 👏. That refactor looks great!