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

spock.genesis.generators.CyclicGenerator.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

import groovy.transform.CompileStatic
import spock.genesis.extension.ExtensionMethods

/**
 * A lazy infinite generator that repeats an iterator.
 * This generator keeps track of 1 iterator worth of data so infinite sources could lead to excessive memory usage.
 * @param < E >   the generated type
 */
@CompileStatic
class CyclicGenerator extends GeneratorDecorator {

    CyclicGenerator(E... array) {
        this(array.size() == 1 ? new ObjectIteratorGenerator(array[0]) : array.toList())
    }

    CyclicGenerator(Iterable iterable) {
        super(ExtensionMethods.toGenerator(iterable))
    }

    @Override
    UnmodifiableIterator iterator() {
        new UnmodifiableIterator() {
            private Iterator source = generator.iterator()
            private final List repeatSource = []
            private boolean hasRepeated = false
            private boolean started = false

            @Override
            boolean hasNext() {
                if (started) {
                    true
                } else {
                    source.hasNext()
                }
            }

            @Override
            E next() {
                started = true
                if (!source.hasNext()) {
                    hasRepeated = true
                    source = repeatSource.iterator()
                }
                E val = source.next()
                if (!hasRepeated) {
                    repeatSource.add(val)
                }
                val
            }
        }
    }
    boolean isFinite() {
        !iterator().hasNext()
    }
}




© 2015 - 2025 Weber Informatics LLC | Privacy Policy