com.github.mvysny.kaributesting.v10.CheckboxGroup.kt Maven / Gradle / Ivy
Go to download
Show more of this group Show more artifacts with this name
Show all versions of karibu-testing-v10 Show documentation
Show all versions of karibu-testing-v10 Show documentation
Karibu Testing, support for browserless Vaadin testing in Kotlin
package com.github.mvysny.kaributesting.v10
import com.vaadin.flow.component.Component
import com.vaadin.flow.component.HasValue
import com.vaadin.flow.component.ItemLabelGenerator
import com.vaadin.flow.component.checkbox.CheckboxGroup
import com.vaadin.flow.data.provider.DataProvider
import java.lang.reflect.Method
import kotlin.test.fail
/**
* Fetches renderings of items currently displayed in the checkbox group component.
*/
public fun CheckboxGroup.getItemLabels(): List {
val items: List = dataProvider._findAll()
return items.map { itemLabelGenerator.apply(it) }
}
private val __CheckboxGroup_getDataProvider: Method by lazy(LazyThreadSafetyMode.PUBLICATION) {
val m = CheckboxGroup::class.java.getDeclaredMethod("getDataProvider")
m.isAccessible = true
m
}
/**
* `CheckboxGroup.getDataProvider()` is private since Vaadin 24.0.0.beta1
*/
@Suppress("UNCHECKED_CAST")
public val CheckboxGroup.dataProvider: DataProvider
get() = __CheckboxGroup_getDataProvider.invoke(this) as DataProvider
/**
* Select all items in this [CheckboxGroup] by [labels]. Fails if the item is not found. Fails if this component is not editable.
*/
public fun CheckboxGroup.selectByLabel(vararg labels: String) {
selectByLabel(labels.toSet(), itemLabelGenerator)
}
/**
* Beware: the function will poll all items from the [dataProvider]. Use cautiously and only for small data providers.
*/
internal fun HasValue<*, Set>.selectByLabel(labels: Set, itemLabelGenerator: ItemLabelGenerator) {
// maps label to items that have the label
@Suppress("UNCHECKED_CAST")
val items: Map> = ((this as Component).dataProvider as DataProvider)
._findAll()
.groupBy { itemLabelGenerator.apply(it) }
// select all items that have the label
val itemsWithLabels = items.filterKeys { key -> labels.contains(key) }
val e = itemsWithLabels.entries.firstOrNull { it.value.size > 1 }
if (e != null) {
fail("${toPrettyString()}: Multiple items found with label '${e.key}': ${e.value}")
}
if (itemsWithLabels.keys.size < labels.size) {
fail("${toPrettyString()}: No item found with label(s) '${labels.minus(items.keys)}'. Available items: ${items.keys}")
}
_value = itemsWithLabels.values.flatten().toSet()
}