willowtreeapps / assertk

assertions for kotlin inspired by assertj
MIT License
761 stars 85 forks source link

add containsOnce/containsAllOnce assertions #399

Open wjtk opened 2 years ago

wjtk commented 2 years ago

I think that would be helpful to add two assertions for Iterables: containsOnce(elem) - works as contains, but throws when elem occurs more than one time containsAllOnce(vararg elements) - as above, but for list of elems (like contains/containsAll) I've added first assertion in my project and I found it useful.

Wdyt? Can I try to make PR?

wjtk commented 2 years ago

I've made PR, can you review it, please?

wjtk commented 2 years ago

@evant @rf43 @nishtahir, please?

evant commented 9 months ago

Sorry for the late reply but I think the first usecase is now covered with

assertThat(list).single().isEqualTo(expected)

I'm a little confused by containsAllOnce(), what's the usecase of such a method?

wjtk commented 9 months ago

Hi @evant, I think you didn't see my PR. Let's start with example, there is list:

val list = listOf(1, 2, 3, 4, 1)

and my proposed assertions should work as:

assertThat(list).containsOnce(2) // ok
assertThat(list).containsOnce(1) // error, 1 is two times on the list

assertThat(list). containsAllOnce(2, 3, 4) // ok
assertThat(list). containsAllOnce(2, 3) // ok
assertThat(list).containsAllOnce(1, 2) // error because 1 is two times on the list

Is there any straightforward equivalent now?, WDYT?

PS. Maybe it could be just one method with vararg:

        val list = listOf(1, 2, 3, 4, 1)
        assertThat(list).containsOnlyOnce(2, 3, 4)
        assertThat(list).containsOnlyOnce(2)
evant commented 9 months ago

Right, I'm curious what you'd use that for. It may be just me but it seem tricky to think about what matches and what doesn't.

wjtk commented 9 months ago

I have a case that I need this. Sometimes is useful to check that element exists and is not duplicated on the list.

I checked assertj yesterday, and it has containsOnlyOnce assertion, so I think I'm not the only one, that would use it. I found usages of it in my company repos, even in kotlin projects.