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

spock.genesis.generators.composites.PojoGenerator.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.CompileDynamic
import groovy.transform.CompileStatic
import spock.genesis.extension.ExtensionMethods
import spock.genesis.generators.Generator
import spock.genesis.generators.Permutable
import spock.genesis.generators.UnmodifiableIterator

import java.lang.reflect.Constructor

@CompileStatic
@SuppressWarnings(['Instanceof'])
class PojoGenerator extends Generator implements Closeable, Permutable {
    final Class target
    final Generator generator

    PojoGenerator(Class target, Iterable generator) {
        this.target = target
        this.generator = ExtensionMethods.toGenerator(generator)
    }

    UnmodifiableIterator iterator() {
        new UnmodifiableIterator() {
            private final Iterator iterator = generator.iterator()

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

            @Override
            @CompileDynamic
            E next() {
                T params = iterator.next()
                Class clazz = params.getClass()
                if (hasConstructorFor(clazz)) {
                    target.metaClass.invokeConstructor(params)
                } else if (List.isAssignableFrom(clazz)) {
                    target.newInstance(*params)
                } else if (Map.isAssignableFrom(clazz)) {
                    target.newInstance(params)
                }
            }

            private boolean hasConstructorFor(Class clazz) {
                target.constructors.any { Constructor constructor ->
                    constructor.parameterTypes.length == 1 &&
                            constructor.parameterTypes[0].isAssignableFrom(clazz)
                }
            }
        }
    }

    boolean isFinite() {
        generator.finite
    }

    void close() {
        generator.close()
    }

    @Override
    PojoGenerator seed(Long seed) {
        generator.seed(seed)
        super.seed(seed)
        this
    }

    PojoGenerator permute() {
        if (generator instanceof Permutable) {
            new PojoGenerator(target, ((Permutable) generator).permute())
        } else {
            throw new UnsupportedOperationException("generator of type ${generator.getClass()} is not permutable")
        }
    }

    PojoGenerator permute(int maxDepth) {
        if (generator instanceof Permutable) {
            new PojoGenerator(target, ((Permutable) generator).permute(maxDepth))
        } else {
            throw new UnsupportedOperationException("generator of type ${generator.getClass()} is not permutable")
        }
    }
}




© 2015 - 2025 Weber Informatics LLC | Privacy Policy