基于KotlinTest属性的测试和生成器

在Kotlin中,我对有向图有以下定义。 (我仍在学习Kotlin,因此请原谅所有缺点。总是欢迎提出改进和建议。)我的目标是要有一种方法reverse,该方法可以保持顶点和循环,但可以交换其他边的方向。

// We use an edge list because it makes it the easiest to swap.
data class ReversibleDirectedGraph<T>(val vertices: Set<T>,val edgeList: List<Pair<T,T>>) {

    // This should be a self-inverting function.
    fun reverse(): ReversibleDirectedGraph<T> {
        // Make sure all vertices in edgeList are in vertices.
        val allVertices = edgeList.flatMap { it.toList() }
        require(allVertices.all { it in vertices }) { "Illegal graph specification" }

        // Swap the edges.
        val newEdgeList = edgeList.map { it.second to it.first }
        return ReversibleDirectedGraph(allVertices.toSet(),newEdgeList)
    }
}

fun main() {
    // Example test: works correctly. Double edge reversal results in original graph.
    val g = ReversibleDirectedGraph(setOf(0,1,2,3),listOf(0 to 1,2 to 1,3 to 2,3 to 0,1 to 3))
    println(g)
    val gr = g.reverse()
    println(gr)
    val grr = gr.reverse()
    println(grr)
    println(grr == g)
}

我想使用基于属性的测试来使用KotinTest来测试此代码,但是我在构造它以正确生成无向图的随机样本时遇到了麻烦。如果可以达到该点,则可以反转边缘方向两次,然后确保达到原始图形。

我熟悉Gen.listGen.choose等,但是我似乎无法将各个部分组合在一起以获得最终产品,即随机无向图。

我已经做好了准备,但这显然是缺少的部分,我希望有人能够提供帮助。我怀疑我可以在Scala中做到这一点,因为我在那里有更多的经验,但是我决心学习Kotlin。最终,类似以下内容的东西:

class ReversibleDirectedGraphTest: StringSpec() {
    init {
        "reversibleDirectedGraphTest" {
            forAll { g: ReversibleDirectedGraph<Int> ->
                assertEqual(g.reverse().reverse() == g) }
            }
        }
    }
}

任何帮助/建议将不胜感激。谢谢!

ad3344 回答:基于KotlinTest属性的测试和生成器

我最终遵循@monkjack的建议并创建了自己的.LoaderContainer。我必须将Gen明确地提供给Gen,一个罕见的例外是“绑定必须大于原点”,但这是可行的,并且生成的绝大多数测试用例都是有效,不需要forAll拦截。

try...catch
本文链接:https://www.f2er.com/3127521.html

大家都在问