Home > Blockchain >  Generate a random list based on limited items with spock-genesis
Generate a random list based on limited items with spock-genesis

Time:09-19

I use spock-genesis and would like to have an infinite lists generator parametrized with a list of values. A generated item should be a list that contains at most the list of parametrized values in random order.

Some invariants are:

def 'list generator'() {
    expect:
    xs.size() <= 3
    xs.findAll({x -> x == 1}).size() <= 1
    xs.findAll({x -> x == 2}).size() <= 1
    xs.findAll({x -> x == 3}).size() <= 1

    where:
    xs << listGen([1, 2, 3])
}

I'm about to write own Generator implementation but there is chance I overthink something and it's possible to compose such generator with already existing spock-genesis units.

CodePudding user response:

Try this

List listGen(List list) {
    list.subsequences()
            .collect { it.permutations() }
            .inject([[]]) { result, subseq -> result   subseq }
}

The result of listGen([1, 2, 3]) will be:

[[], [1], [1, 2, 3], [3, 2, 1], [2, 1, 3], [3, 1, 2], [1, 3, 2], [2, 3, 1], [2], [3, 2], [2, 3], [2, 1], [1, 2], [3], [1, 3], [3, 1]]

Your test passes with this implementation.

UPD: As per the OP clarifications below in the comments, they expect the permutations to be random, so here is the line of code that will do that using spock-genesis any:

where:
xs << Gen.any(listGen([1, 2, 3])).take(42).collect() // I assume 42 here should be random as well then

CodePudding user response:

I'm not quite sure what you want, is just a list of every possible permutation of the list [1,2,3]? If so then this should be enough.

[1, 2, 3].permutations()
  • Related