All Downloads are FREE. Search and download functionalities are using the official Maven repository.

spock.genesis.generators.composites.DefinedMapGenerator.groovy Maven / Gradle / Ivy

Go to download

Mostly lazy data generators for property based testing using the Spock test framework

The newest version!
package spock.genesis.generators.composites

import groovy.transform.CompileStatic
import spock.genesis.generators.Generator
import spock.genesis.generators.Permutable
import spock.genesis.generators.UnmodifiableIterator

@CompileStatic
class DefinedMapGenerator extends Generator> implements Permutable {

    private final List keys
    private final TupleGenerator valuesGenerator

    DefinedMapGenerator(Map> keysToValueGenerators) {
        List keys = []
        List iterables = []
        keysToValueGenerators.each { key, iterable ->
            keys << key
            iterables << iterable
        }
        this.keys = keys
        this.valuesGenerator = new TupleGenerator(iterables)
    }

    DefinedMapGenerator(List keys,  TupleGenerator valuesGenerator) {
        int values = valuesGenerator.generators.size()
        if (keys.size() != values) {
            throw new IllegalArgumentException("Keys size (${keys.size()}) does not match values size ($values")
        }
        this.keys = keys.collect() //defensive copy
        this.valuesGenerator = valuesGenerator
    }

    @Override
    UnmodifiableIterator> iterator() {

        new UnmodifiableIterator>() {
            final private Iterator> iterator = valuesGenerator.iterator()

            @Override
            boolean hasNext() {
                iterator.hasNext()
            }

            @Override
            Map next() {
                List values = iterator.next()
                Map result = [:]
                keys.eachWithIndex { K key, int i ->
                    result[key] = values[i]
                }
                result
            }
        }
    }

    DefinedMapGenerator permute() {
        new DefinedMapGenerator(keys, valuesGenerator.permute())
    }

    DefinedMapGenerator permute(int maxDepth) {
        new DefinedMapGenerator(keys, valuesGenerator.permute(maxDepth))
    }

    boolean isFinite() {
        valuesGenerator.finite
    }

    @Override
    DefinedMapGenerator seed(Long seed) {
        valuesGenerator.seed(seed)
        super.seed(seed)
        this
    }
}




© 2015 - 2025 Weber Informatics LLC | Privacy Policy