Skip to content

Commit

Permalink
added guarding test to make sure no triversing back up tree in visitor
Browse files Browse the repository at this point in the history
  • Loading branch information
vextorspace committed Jul 13, 2024
1 parent d158343 commit 1d11412
Show file tree
Hide file tree
Showing 4 changed files with 72 additions and 0 deletions.
8 changes: 8 additions & 0 deletions composeApp/src/commonMain/kotlin/model/ItemVisitor.kt
Original file line number Diff line number Diff line change
@@ -0,0 +1,8 @@
package model

class ItemVisitor(val action: ItemVisitorAction) {
fun visit(item: Item) {
action.accept(item)
item.subItems.forEach { visit(it) }
}
}
5 changes: 5 additions & 0 deletions composeApp/src/commonMain/kotlin/model/ItemVisitorAction.kt
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
package model

interface ItemVisitorAction {
fun accept(item: Item)
}
10 changes: 10 additions & 0 deletions composeApp/src/commonTest/kotlin/model/ItemVisitorCollector.kt
Original file line number Diff line number Diff line change
@@ -0,0 +1,10 @@
package model

class ItemVisitorCollector : ItemVisitorAction {
val items = mutableListOf<Item>()

override fun accept(item: Item) {
items.add(item)
}

}
Original file line number Diff line number Diff line change
@@ -0,0 +1,49 @@
package model

import io.kotest.matchers.collections.shouldContainExactlyInAnyOrder
import kotlin.test.Test

class ItemVisitorVisitsAllSubItemsTest {

@Test
fun `ItemVisitor visits all sub items`() {
// Given
val item = Item("parent")
val child = Item("child")
val sibling = Item("sibling")
val grandChild = Item("grandChild")
child.add(grandChild)
item.add(child)
item.add(sibling)

val itemCollector = ItemVisitorCollector()
val visitor = ItemVisitor(itemCollector)

// When
visitor.visit(item)

// Then
itemCollector.items shouldContainExactlyInAnyOrder listOf(item, child, sibling, grandChild)
}

@Test
fun `ItemVisitor starting at child does not get other branches`() {
// Given
val item = Item("parent")
val child = Item("child")
val sibling = Item("sibling")
val grandChild = Item("grandChild")
child.add(grandChild)
item.add(child)
item.add(sibling)

val itemCollector = ItemVisitorCollector()
val visitor = ItemVisitor(itemCollector)

// When
visitor.visit(child)

// Then
itemCollector.items shouldContainExactlyInAnyOrder listOf(child, grandChild)
}
}

0 comments on commit 1d11412

Please sign in to comment.