package de.zalando.toga.provider;
import de.zalando.toga.generator.Generator;
import org.junit.rules.MethodRule;
import org.junit.runners.model.FrameworkMethod;
import org.junit.runners.model.Statement;
import java.io.File;
import java.util.regex.Pattern;
public class ExampleProviderRule implements MethodRule {
private final ExampleProvider exampleProvider;
private Pattern pattern;
private String current;
/**
* This rule will execute all tests in this class for every example in the specified input folder.
* @param dir this folder will be searched for json files containing example data.
* @param pattern the pattern to apply. See {@link ExampleProvider} for details.
*/
public ExampleProviderRule(final File dir, final Pattern pattern) {
this.pattern = pattern;
exampleProvider = new ExampleProvider(dir);
}
/**
* Takes the given json-schema specification file and then invokes a {@link de.zalando.toga.generator.Generator} to
* create examples in the given example directory. Afterwards the given pattern is used to extract all relevant examples
* for test execution.
*
* @param specification the json-schema file that contains the specification under test
* @param exampleDirectory the directory to generate the examples to
* @param pattern the pattern to filter the examples with. See {@link ExampleProvider} for details.
*/
public ExampleProviderRule(final File specification, final File exampleDirectory, final Pattern pattern) {
// TODO: make generation of multiple files possible
Generator generator = new Generator();
generator.load(specification);
generator.generate(new File(exampleDirectory, specification.getName()));
this.pattern = pattern;
exampleProvider = new ExampleProvider(exampleDirectory);
}
public String getExampleJson() {
return current;
}
@Override
public Statement apply(Statement base, FrameworkMethod method, Object target) {
return new Statement() {
@Override
public void evaluate() throws Throwable {
for (String input : exampleProvider.getExamples(pattern)) {
current = input;
base.evaluate();
}
}
};
}
}