Bumping versions
This commit is contained in:
@@ -35,13 +35,13 @@ public class GroovyDslPropertyConverter implements DslPropertyConverter {
|
||||
public Object testSide(Object object) {
|
||||
if (object instanceof GString) {
|
||||
boolean anyPattern = Arrays.stream(((GString) object).getValues())
|
||||
.anyMatch(it -> it instanceof RegexProperty);
|
||||
.anyMatch(it -> it instanceof RegexProperty);
|
||||
if (!anyPattern) {
|
||||
return object;
|
||||
}
|
||||
List<Object> generatedValues = Arrays.stream(((GString) object).getValues())
|
||||
.map(it -> it instanceof RegexProperty ? ((RegexProperty) it).generate() : it)
|
||||
.collect(Collectors.toList());
|
||||
.map(it -> it instanceof RegexProperty ? ((RegexProperty) it).generate() : it)
|
||||
.collect(Collectors.toList());
|
||||
Object[] arrayOfObjects = generatedValues.toArray();
|
||||
String[] strings = Arrays.copyOf(((GString) object).getStrings(), ((GString) object).getStrings().length,
|
||||
String[].class);
|
||||
|
||||
@@ -40,10 +40,11 @@ import java.util.stream.Collectors;
|
||||
public class Common {
|
||||
|
||||
public Map<String, DslProperty> convertObjectsToDslProperties(Map<String, Object> body) {
|
||||
return body.entrySet().stream()
|
||||
.collect(Collectors.toMap((Function<Map.Entry, String>) t -> t.getKey().toString(),
|
||||
(Function<Map.Entry, DslProperty>) t -> toDslProperty(t.getValue()), throwingMerger(),
|
||||
LinkedHashMap::new));
|
||||
return body.entrySet()
|
||||
.stream()
|
||||
.collect(Collectors.toMap((Function<Map.Entry, String>) t -> t.getKey().toString(),
|
||||
(Function<Map.Entry, DslProperty>) t -> toDslProperty(t.getValue()), throwingMerger(),
|
||||
LinkedHashMap::new));
|
||||
}
|
||||
|
||||
private static <T> BinaryOperator<T> throwingMerger() {
|
||||
|
||||
@@ -37,10 +37,10 @@ import java.util.regex.Pattern;
|
||||
public class Headers {
|
||||
|
||||
private static final BiFunction<String, Header, Object> CLIENT_SIDE = (s, header) -> ContractUtils
|
||||
.convertStubSideRecursively(header);
|
||||
.convertStubSideRecursively(header);
|
||||
|
||||
private static final BiFunction<String, Header, Object> SERVER_SIDE = (s, header) -> ContractUtils
|
||||
.convertTestSideRecursively(header);
|
||||
.convertTestSideRecursively(header);
|
||||
|
||||
private Set<Header> entries = new LinkedHashSet<>();
|
||||
|
||||
|
||||
@@ -68,16 +68,16 @@ public final class RegexPatterns {
|
||||
protected static final Pattern HTTPS_URL = UrlHelper.HTTPS_URL;
|
||||
|
||||
protected static final Pattern UUID = Pattern
|
||||
.compile("[a-f0-9]{8}-[a-f0-9]{4}-[a-f0-9]{4}-[a-f0-9]{4}-[a-f0-9]{12}", Pattern.CASE_INSENSITIVE);
|
||||
.compile("[a-f0-9]{8}-[a-f0-9]{4}-[a-f0-9]{4}-[a-f0-9]{4}-[a-f0-9]{12}", Pattern.CASE_INSENSITIVE);
|
||||
|
||||
protected static final Pattern UUID4 = Pattern
|
||||
.compile("[a-f0-9]{8}-[a-f0-9]{4}-4[a-f0-9]{3}-[89ab][a-f0-9]{3}-[a-f0-9]{12}", Pattern.CASE_INSENSITIVE);
|
||||
.compile("[a-f0-9]{8}-[a-f0-9]{4}-4[a-f0-9]{3}-[89ab][a-f0-9]{3}-[a-f0-9]{12}", Pattern.CASE_INSENSITIVE);
|
||||
|
||||
protected static final Pattern ANY_DATE = Pattern
|
||||
.compile("(\\d\\d\\d\\d)-(0[1-9]|1[012])-(0[1-9]|[12][0-9]|3[01])");
|
||||
.compile("(\\d\\d\\d\\d)-(0[1-9]|1[012])-(0[1-9]|[12][0-9]|3[01])");
|
||||
|
||||
protected static final Pattern ANY_DATE_TIME = Pattern.compile(
|
||||
"([0-9]{4})-(1[0-2]|0[1-9])-(3[01]|0[1-9]|[12][0-9])T(2[0-3]|[01][0-9]):([0-5][0-9]):([0-5][0-9])");
|
||||
protected static final Pattern ANY_DATE_TIME = Pattern
|
||||
.compile("([0-9]{4})-(1[0-2]|0[1-9])-(3[01]|0[1-9]|[12][0-9])T(2[0-3]|[01][0-9]):([0-5][0-9]):([0-5][0-9])");
|
||||
|
||||
protected static final Pattern ANY_TIME = Pattern.compile("(2[0-3]|[01][0-9]):([0-5][0-9]):([0-5][0-9])");
|
||||
|
||||
@@ -89,9 +89,9 @@ public final class RegexPatterns {
|
||||
"([0-9]{4})-(1[0-2]|0[1-9])-(3[01]|0[1-9]|[12][0-9])T(2[0-3]|[01][0-9]):([0-5][0-9]):([0-5][0-9])(\\.\\d+)?(Z|[+-][01]\\d:[0-5]\\d)");
|
||||
|
||||
protected static Pattern anyOf(String... values) {
|
||||
return Pattern
|
||||
.compile(Arrays.stream(values).map(it -> '^' + RegexpUtils.escapeSpecialRegexWithSingleEscape(it) + '$')
|
||||
.collect(Collectors.joining("|")));
|
||||
return Pattern.compile(Arrays.stream(values)
|
||||
.map(it -> '^' + RegexpUtils.escapeSpecialRegexWithSingleEscape(it) + '$')
|
||||
.collect(Collectors.joining("|")));
|
||||
}
|
||||
|
||||
public static String multipartParam(Object name, Object value) {
|
||||
|
||||
@@ -742,8 +742,8 @@ public class Response extends Common implements RegexCreatingProperty<ServerDslP
|
||||
@Override
|
||||
public DslProperty matching(final String value) {
|
||||
return this.common.$(
|
||||
this.common.p(
|
||||
notEscaped(Pattern.compile(RegexpUtils.escapeSpecialRegexWithSingleEscape(value) + ".*"))),
|
||||
this.common
|
||||
.p(notEscaped(Pattern.compile(RegexpUtils.escapeSpecialRegexWithSingleEscape(value) + ".*"))),
|
||||
this.common.c(value));
|
||||
}
|
||||
|
||||
|
||||
@@ -59,8 +59,8 @@ public class Xeger {
|
||||
assert random != null;
|
||||
// https://stackoverflow.com/questions/1578789/how-do-i-generate-text-matching-a-regular-expression-from-a-regular-expression
|
||||
String pattern = regex.replace("\\d", "[0-9]") // Used d=Digit
|
||||
.replace("\\w", "[A-Za-z0-9_]") // Used =Word
|
||||
.replace("\\s", "[ \t\r\n]"); // Used s="White"Space
|
||||
.replace("\\w", "[A-Za-z0-9_]") // Used =Word
|
||||
.replace("\\s", "[ \t\r\n]"); // Used s="White"Space
|
||||
this.automaton = new RegExp(pattern).toAutomaton();
|
||||
this.random = random;
|
||||
String generatedCharsSysProp = System.getProperty("springCloudContractGeneratedCharsFromRegex");
|
||||
|
||||
@@ -153,7 +153,7 @@ public class AetherStubDownloader implements StubDownloader {
|
||||
for (int i = 0; i < repos.length; i++) {
|
||||
if (StringUtils.hasText(repos[i])) {
|
||||
final RemoteRepository.Builder builder = new RemoteRepository.Builder("remote" + i, "default", repos[i])
|
||||
.setAuthentication(resolveAuthentication(stubRunnerOptions));
|
||||
.setAuthentication(resolveAuthentication(stubRunnerOptions));
|
||||
if (stubRunnerOptions.getProxyOptions() != null) {
|
||||
final StubRunnerProxyOptions p = stubRunnerOptions.getProxyOptions();
|
||||
builder.setProxy(new Proxy(null, p.getProxyHost(), p.getProxyPort()));
|
||||
@@ -176,7 +176,9 @@ public class AetherStubDownloader implements StubDownloader {
|
||||
}
|
||||
SettingsDecryptionRequest settingsDecryptionRequest = new DefaultSettingsDecryptionRequest(stubServer);
|
||||
String stubServerPassword = new MavenSettings().createSettingsDecrypter()
|
||||
.decrypt(settingsDecryptionRequest).getServer().getPassword();
|
||||
.decrypt(settingsDecryptionRequest)
|
||||
.getServer()
|
||||
.getPassword();
|
||||
return buildAuthentication(stubServerPassword, stubServer.getUsername());
|
||||
}
|
||||
}
|
||||
@@ -272,8 +274,9 @@ public class AetherStubDownloader implements StubDownloader {
|
||||
}
|
||||
|
||||
private void registerShutdownHook() {
|
||||
Runtime.getRuntime().addShutdownHook(
|
||||
new Thread(() -> TemporaryFileStorage.cleanup(AetherStubDownloader.this.deleteStubsAfterTest)));
|
||||
Runtime.getRuntime()
|
||||
.addShutdownHook(
|
||||
new Thread(() -> TemporaryFileStorage.cleanup(AetherStubDownloader.this.deleteStubsAfterTest)));
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
@@ -69,7 +69,7 @@ public class ContractDownloader {
|
||||
log.debug("Will download contracts for [" + this.contractsJarStubConfiguration + "]");
|
||||
}
|
||||
Map.Entry<StubConfiguration, File> unpackedContractStubs = this.stubDownloader
|
||||
.downloadAndUnpackStubJar(this.contractsJarStubConfiguration);
|
||||
.downloadAndUnpackStubJar(this.contractsJarStubConfiguration);
|
||||
if (unpackedContractStubs == null) {
|
||||
throw new IllegalStateException("The contracts failed to be downloaded!");
|
||||
}
|
||||
@@ -145,7 +145,8 @@ public class ContractDownloader {
|
||||
|
||||
private String patternFromProperty(File contractsDirectory) {
|
||||
return ("^" + contractsDirectory.getAbsolutePath() + "(" + File.separator + ")?" + ".*"
|
||||
+ contractsPath().replace("/", File.separator) + ".*$").replace("\\", "\\\\");
|
||||
+ contractsPath().replace("/", File.separator) + ".*$")
|
||||
.replace("\\", "\\\\");
|
||||
}
|
||||
|
||||
private String contractsPath() {
|
||||
@@ -165,7 +166,7 @@ public class ContractDownloader {
|
||||
private String groupArtifactToPattern(File contractsDirectory) {
|
||||
return ("^" + contractsDirectory.getAbsolutePath() + "(" + File.separator + ")?" + ".*"
|
||||
+ slashSeparatedGroupId() + File.separator + this.projectArtifactId + File.separator + ".*$")
|
||||
.replace("\\", "\\\\");
|
||||
.replace("\\", "\\\\");
|
||||
}
|
||||
|
||||
private String fileToPattern(File contractsDirectory) {
|
||||
|
||||
@@ -152,10 +152,11 @@ class StubsStubDownloader implements StubDownloader {
|
||||
String schemeSpecific = schemeSpecificPart();
|
||||
log.info("Stubs are present under [" + schemeSpecific + "]. Will copy them to a temporary directory.");
|
||||
return new ResourceResolvingStubDownloader(stubRunnerOptions, this::repoRootForSchemeSpecificPart,
|
||||
this::anyPattern).downloadAndUnpackStubJar(stubConfiguration);
|
||||
this::anyPattern)
|
||||
.downloadAndUnpackStubJar(stubConfiguration);
|
||||
}
|
||||
return new ResourceResolvingStubDownloader(stubRunnerOptions, this::repoRoot, this::gavPattern)
|
||||
.downloadAndUnpackStubJar(stubConfiguration);
|
||||
.downloadAndUnpackStubJar(stubConfiguration);
|
||||
}
|
||||
|
||||
private RepoRoots repoRootForSchemeSpecificPart(StubRunnerOptions stubRunnerOptions,
|
||||
|
||||
@@ -219,8 +219,9 @@ class GitRepo {
|
||||
if (log.isDebugEnabled()) {
|
||||
log.debug("Project git url [" + projectGitUrl + "]");
|
||||
}
|
||||
CloneCommand command = this.gitFactory.getCloneCommandByCloneRepository().setURI(projectGitUrl)
|
||||
.setDirectory(destinationFolder);
|
||||
CloneCommand command = this.gitFactory.getCloneCommandByCloneRepository()
|
||||
.setURI(projectGitUrl)
|
||||
.setDirectory(destinationFolder);
|
||||
try {
|
||||
Git git = command.call();
|
||||
if (git.getRepository().getRemoteNames().isEmpty()) {
|
||||
@@ -278,8 +279,10 @@ class GitRepo {
|
||||
}
|
||||
|
||||
private void trackBranch(CheckoutCommand checkout, String label) {
|
||||
checkout.setCreateBranch(true).setName(label).setUpstreamMode(CreateBranchCommand.SetupUpstreamMode.TRACK)
|
||||
.setStartPoint("origin/" + label);
|
||||
checkout.setCreateBranch(true)
|
||||
.setName(label)
|
||||
.setUpstreamMode(CreateBranchCommand.SetupUpstreamMode.TRACK)
|
||||
.setStartPoint("origin/" + label);
|
||||
}
|
||||
|
||||
private boolean isBranch(Git git, String label) throws GitAPIException {
|
||||
@@ -389,8 +392,9 @@ class GitRepo {
|
||||
}
|
||||
|
||||
CloneCommand getCloneCommandByCloneRepository() {
|
||||
return Git.cloneRepository().setCredentialsProvider(this.provider)
|
||||
.setTransportConfigCallback(this.callback);
|
||||
return Git.cloneRepository()
|
||||
.setCredentialsProvider(this.provider)
|
||||
.setTransportConfigCallback(this.callback);
|
||||
}
|
||||
|
||||
PushCommand push(Git git) {
|
||||
|
||||
@@ -109,8 +109,9 @@ class ResourceResolvingStubDownloader implements StubDownloader {
|
||||
}
|
||||
|
||||
private void registerShutdownHook() {
|
||||
Runtime.getRuntime().addShutdownHook(
|
||||
new Thread(() -> TemporaryFileStorage.cleanup(stubRunnerOptions.isDeleteStubsAfterTest())));
|
||||
Runtime.getRuntime()
|
||||
.addShutdownHook(
|
||||
new Thread(() -> TemporaryFileStorage.cleanup(stubRunnerOptions.isDeleteStubsAfterTest())));
|
||||
}
|
||||
|
||||
private void copyTheFoundFiles(File tmp, Resource resource, String relativePath) throws IOException {
|
||||
|
||||
@@ -203,8 +203,9 @@ class GitStubDownloader implements StubDownloader {
|
||||
}
|
||||
|
||||
private void registerShutdownHook() {
|
||||
Runtime.getRuntime().addShutdownHook(
|
||||
new Thread(() -> TemporaryFileStorage.cleanup(GitStubDownloader.this.deleteStubsAfterTest)));
|
||||
Runtime.getRuntime()
|
||||
.addShutdownHook(
|
||||
new Thread(() -> TemporaryFileStorage.cleanup(GitStubDownloader.this.deleteStubsAfterTest)));
|
||||
}
|
||||
|
||||
}
|
||||
@@ -351,9 +352,10 @@ class FileWalker extends SimpleFileVisitor<Path> {
|
||||
if (versions.size() > 1 && this.latestSnapshotVersion) {
|
||||
// 2.0.1.BUILD-SNAPSHOT, 2.0.0.BUILD-SNAPSHOT
|
||||
// 2.0.0.BUILD-SNAPSHOT, 2.0.0.RELEASE
|
||||
DefaultArtifactVersionWrapper sameVersionButSnapshot = versions.stream().filter(
|
||||
w -> w.projectVersion.isSameWithoutSuffix(latestFoundVersion.projectVersion) && w.isSnapshot())
|
||||
.findFirst().orElse(latestFoundVersion);
|
||||
DefaultArtifactVersionWrapper sameVersionButSnapshot = versions.stream()
|
||||
.filter(w -> w.projectVersion.isSameWithoutSuffix(latestFoundVersion.projectVersion) && w.isSnapshot())
|
||||
.findFirst()
|
||||
.orElse(latestFoundVersion);
|
||||
// 2.0.0 vs 2.0.0
|
||||
// replace the RELEASE one with SNAPSHOT
|
||||
if (sameVersionButSnapshot != latestFoundVersion) {
|
||||
@@ -366,17 +368,22 @@ class FileWalker extends SimpleFileVisitor<Path> {
|
||||
private File folderWithPredefinedName(File[] files) {
|
||||
if (this.latestSnapshotVersion) {
|
||||
return Arrays.stream(files)
|
||||
.filter(file -> LATEST.stream().anyMatch(s -> s.equals(file.getName().toLowerCase()))).findFirst()
|
||||
.orElse(null);
|
||||
}
|
||||
return Arrays.stream(files).filter(file -> RELEASE.equals(file.getName().toLowerCase())).findFirst()
|
||||
.filter(file -> LATEST.stream().anyMatch(s -> s.equals(file.getName().toLowerCase())))
|
||||
.findFirst()
|
||||
.orElse(null);
|
||||
}
|
||||
return Arrays.stream(files)
|
||||
.filter(file -> RELEASE.equals(file.getName().toLowerCase()))
|
||||
.findFirst()
|
||||
.orElse(null);
|
||||
}
|
||||
|
||||
private List<DefaultArtifactVersionWrapper> pickLatestVersion(File[] files) {
|
||||
return Arrays.stream(files).map(DefaultArtifactVersionWrapper::new)
|
||||
.filter(wrapper -> this.latestSnapshotVersion || wrapper.isNotSnapshot()).sorted()
|
||||
.collect(Collectors.toList());
|
||||
return Arrays.stream(files)
|
||||
.map(DefaultArtifactVersionWrapper::new)
|
||||
.filter(wrapper -> this.latestSnapshotVersion || wrapper.isNotSnapshot())
|
||||
.sorted()
|
||||
.collect(Collectors.toList());
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
@@ -91,7 +91,7 @@ class StubRunnerExecutor implements StubFinder {
|
||||
return runningStubs();
|
||||
}
|
||||
HttpServerStubConfigurer configurer = BeanUtils
|
||||
.instantiateClass(stubRunnerOptions.getHttpServerStubConfigurer());
|
||||
.instantiateClass(stubRunnerOptions.getHttpServerStubConfigurer());
|
||||
startStubServers(configurer, stubRunnerOptions, stubConfiguration, repository);
|
||||
RunningStubs runningCollaborators = runningStubs();
|
||||
log.info("All stubs are now running " + runningCollaborators.toString());
|
||||
@@ -262,7 +262,7 @@ class StubRunnerExecutor implements StubFinder {
|
||||
}
|
||||
else {
|
||||
payload = JsonOutput
|
||||
.toJson(BodyExtractor.extractClientValueFromBody(body == null ? null : body.getClientValue()));
|
||||
.toJson(BodyExtractor.extractClientValueFromBody(body == null ? null : body.getClientValue()));
|
||||
}
|
||||
|
||||
this.messageVerifierSender.send(payload, headers == null ? null : headers.asStubSideMap(),
|
||||
@@ -291,20 +291,20 @@ class StubRunnerExecutor implements StubFinder {
|
||||
log.debug("There are no HTTP related contracts. Won't start any servers");
|
||||
}
|
||||
this.stubServer = new StubServer(stubConfiguration, mappings, contracts, new NoOpHttpServerStub())
|
||||
.start(configuration);
|
||||
.start(configuration);
|
||||
return this.stubServer;
|
||||
}
|
||||
if (!randomPort) {
|
||||
this.stubServer = new StubServer(stubConfiguration, mappings, contracts, httpServerStub())
|
||||
.start(configuration);
|
||||
.start(configuration);
|
||||
}
|
||||
else {
|
||||
this.stubServer = this.portScanner.tryToExecuteWithFreePort(new PortCallback<StubServer>() {
|
||||
@Override
|
||||
public StubServer call(int availablePort) {
|
||||
return new StubServer(stubConfiguration, mappings, contracts, httpServerStub())
|
||||
.start(new HttpServerStubConfiguration(configurer, stubRunnerOptions, stubConfiguration,
|
||||
availablePort, true));
|
||||
.start(new HttpServerStubConfiguration(configurer, stubRunnerOptions, stubConfiguration,
|
||||
availablePort, true));
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
@@ -132,7 +132,7 @@ class StubRunnerFactory {
|
||||
public FileVisitResult visitFile(Path file, BasicFileAttributes attrs) {
|
||||
File potentialStubMapping = file.toFile();
|
||||
Collection<StubGenerator> stubGenerators = this.provider
|
||||
.allOrDefault(new DslToWireMockClientConverter());
|
||||
.allOrDefault(new DslToWireMockClientConverter());
|
||||
if (stubGenerators.stream().anyMatch(s -> s.canReadStubMapping(potentialStubMapping))) {
|
||||
if (log.isDebugEnabled()) {
|
||||
log.debug("Deleting file [" + file.toString() + "] since it contains a valid mapping.");
|
||||
|
||||
@@ -170,22 +170,23 @@ public class StubRunnerOptions {
|
||||
|
||||
public static StubRunnerOptions fromSystemProps() {
|
||||
StubRunnerOptionsBuilder builder = new StubRunnerOptionsBuilder()
|
||||
.withMinPort(Integer.valueOf(System.getProperty("stubrunner.port.range.min", "10000")))
|
||||
.withMaxPort(Integer.valueOf(System.getProperty("stubrunner.port.range.max", "15000")))
|
||||
.withStubRepositoryRoot(ResourceResolver.resource(System.getProperty("stubrunner.repository.root", "")))
|
||||
.withStubsMode(System.getProperty("stubrunner.stubs-mode", "LOCAL"))
|
||||
.withStubsClassifier(System.getProperty("stubrunner.classifier", "stubs"))
|
||||
.withStubs(System.getProperty("stubrunner.ids", ""))
|
||||
.withUsername(System.getProperty("stubrunner.username"))
|
||||
.withPassword(System.getProperty("stubrunner.password"))
|
||||
.withStubPerConsumer(Boolean.parseBoolean(System.getProperty("stubrunner.stubs-per-consumer", "false")))
|
||||
.withConsumerName(System.getProperty("stubrunner.consumer-name"))
|
||||
.withMappingsOutputFolder(System.getProperty("stubrunner.mappings-output-folder"))
|
||||
.withDeleteStubsAfterTest(
|
||||
Boolean.parseBoolean(System.getProperty("stubrunner.delete-stubs-after-test", "true")))
|
||||
.withGenerateStubs(Boolean.parseBoolean(System.getProperty("stubrunner.generate-stubs", "false")))
|
||||
.withFailOnNoStubs(Boolean.parseBoolean(System.getProperty("stubrunner.fail-on-no-stubs", "false")))
|
||||
.withProperties(stubRunnerProps()).withServerId(System.getProperty("stubrunner.server-id", ""));
|
||||
.withMinPort(Integer.valueOf(System.getProperty("stubrunner.port.range.min", "10000")))
|
||||
.withMaxPort(Integer.valueOf(System.getProperty("stubrunner.port.range.max", "15000")))
|
||||
.withStubRepositoryRoot(ResourceResolver.resource(System.getProperty("stubrunner.repository.root", "")))
|
||||
.withStubsMode(System.getProperty("stubrunner.stubs-mode", "LOCAL"))
|
||||
.withStubsClassifier(System.getProperty("stubrunner.classifier", "stubs"))
|
||||
.withStubs(System.getProperty("stubrunner.ids", ""))
|
||||
.withUsername(System.getProperty("stubrunner.username"))
|
||||
.withPassword(System.getProperty("stubrunner.password"))
|
||||
.withStubPerConsumer(Boolean.parseBoolean(System.getProperty("stubrunner.stubs-per-consumer", "false")))
|
||||
.withConsumerName(System.getProperty("stubrunner.consumer-name"))
|
||||
.withMappingsOutputFolder(System.getProperty("stubrunner.mappings-output-folder"))
|
||||
.withDeleteStubsAfterTest(
|
||||
Boolean.parseBoolean(System.getProperty("stubrunner.delete-stubs-after-test", "true")))
|
||||
.withGenerateStubs(Boolean.parseBoolean(System.getProperty("stubrunner.generate-stubs", "false")))
|
||||
.withFailOnNoStubs(Boolean.parseBoolean(System.getProperty("stubrunner.fail-on-no-stubs", "false")))
|
||||
.withProperties(stubRunnerProps())
|
||||
.withServerId(System.getProperty("stubrunner.server-id", ""));
|
||||
builder = httpStubConfigurer(builder);
|
||||
String proxyHost = System.getProperty("stubrunner.proxy.host");
|
||||
if (proxyHost != null) {
|
||||
@@ -211,10 +212,10 @@ public class StubRunnerOptions {
|
||||
Properties properties = System.getProperties();
|
||||
Set<String> propertyNames = properties.stringPropertyNames();
|
||||
propertyNames.stream()
|
||||
// stubrunner.properties.foo.bar=baz
|
||||
.filter(s -> s.toLowerCase().startsWith("stubrunner.properties"))
|
||||
// foo.bar=baz
|
||||
.forEach(s -> map.put(s.substring("stubrunner.properties".length() + 1), System.getProperty(s)));
|
||||
// stubrunner.properties.foo.bar=baz
|
||||
.filter(s -> s.toLowerCase().startsWith("stubrunner.properties"))
|
||||
// foo.bar=baz
|
||||
.forEach(s -> map.put(s.substring("stubrunner.properties".length() + 1), System.getProperty(s)));
|
||||
return map;
|
||||
}
|
||||
|
||||
|
||||
@@ -28,6 +28,7 @@ import org.springframework.context.annotation.Import;
|
||||
|
||||
/**
|
||||
* Annotation to enable a Stub runner server.
|
||||
*
|
||||
* @author Dave Syer
|
||||
* @author Tim Ysewyn
|
||||
*/
|
||||
|
||||
@@ -82,7 +82,8 @@ public class StubRunnerConfiguration {
|
||||
}
|
||||
StubRunnerOptions stubRunnerOptions = stubRunnerOptions(builder);
|
||||
BatchStubRunner batchStubRunner = new BatchStubRunnerFactory(stubRunnerOptions,
|
||||
this.provider.get(stubRunnerOptions), new LazyMessageVerifier(beanFactory)).buildBatchStubRunner();
|
||||
this.provider.get(stubRunnerOptions), new LazyMessageVerifier(beanFactory))
|
||||
.buildBatchStubRunner();
|
||||
// TODO: Consider running it in a separate thread
|
||||
RunningStubs runningStubs = batchStubRunner.runStubs();
|
||||
registerPort(runningStubs);
|
||||
@@ -101,20 +102,23 @@ public class StubRunnerConfiguration {
|
||||
|
||||
private StubRunnerOptionsBuilder builder(StubRunnerProperties props) {
|
||||
return new StubRunnerOptionsBuilder()
|
||||
.withMinMaxPort(Integer.valueOf(resolvePlaceholder(props.getMinPort(), props.getMinPort())),
|
||||
Integer.valueOf(resolvePlaceholder(props.getMaxPort(), props.getMaxPort())))
|
||||
.withStubRepositoryRoot(props.getRepositoryRoot())
|
||||
.withStubsMode(resolvePlaceholder(props.getStubsMode()))
|
||||
.withStubsClassifier(resolvePlaceholder(props.getClassifier()))
|
||||
.withStubs(resolvePlaceholder(props.getIds())).withUsername(resolvePlaceholder(props.getUsername()))
|
||||
.withPassword(resolvePlaceholder(props.getPassword()))
|
||||
.withStubPerConsumer(Boolean.parseBoolean(resolvePlaceholder(props.isStubsPerConsumer())))
|
||||
.withConsumerName(consumerName(props))
|
||||
.withMappingsOutputFolder(resolvePlaceholder(props.getMappingsOutputFolder()))
|
||||
.withDeleteStubsAfterTest(Boolean.parseBoolean(resolvePlaceholder(props.isDeleteStubsAfterTest())))
|
||||
.withGenerateStubs(Boolean.parseBoolean(resolvePlaceholder(props.isGenerateStubs())))
|
||||
.withProperties(props.getProperties()).withHttpServerStubConfigurer(props.getHttpServerStubConfigurer())
|
||||
.withServerId(resolvePlaceholder(props.getServerId())).withFailOnNoStubs(props.isFailOnNoStubs());
|
||||
.withMinMaxPort(Integer.valueOf(resolvePlaceholder(props.getMinPort(), props.getMinPort())),
|
||||
Integer.valueOf(resolvePlaceholder(props.getMaxPort(), props.getMaxPort())))
|
||||
.withStubRepositoryRoot(props.getRepositoryRoot())
|
||||
.withStubsMode(resolvePlaceholder(props.getStubsMode()))
|
||||
.withStubsClassifier(resolvePlaceholder(props.getClassifier()))
|
||||
.withStubs(resolvePlaceholder(props.getIds()))
|
||||
.withUsername(resolvePlaceholder(props.getUsername()))
|
||||
.withPassword(resolvePlaceholder(props.getPassword()))
|
||||
.withStubPerConsumer(Boolean.parseBoolean(resolvePlaceholder(props.isStubsPerConsumer())))
|
||||
.withConsumerName(consumerName(props))
|
||||
.withMappingsOutputFolder(resolvePlaceholder(props.getMappingsOutputFolder()))
|
||||
.withDeleteStubsAfterTest(Boolean.parseBoolean(resolvePlaceholder(props.isDeleteStubsAfterTest())))
|
||||
.withGenerateStubs(Boolean.parseBoolean(resolvePlaceholder(props.isGenerateStubs())))
|
||||
.withProperties(props.getProperties())
|
||||
.withHttpServerStubConfigurer(props.getHttpServerStubConfigurer())
|
||||
.withServerId(resolvePlaceholder(props.getServerId()))
|
||||
.withFailOnNoStubs(props.isFailOnNoStubs());
|
||||
}
|
||||
|
||||
private String[] resolvePlaceholder(String[] string) {
|
||||
@@ -172,7 +176,7 @@ class LazyMessageVerifier implements MessageVerifierSender, MessageVerifierRecei
|
||||
private MessageVerifierSender messageVerifierSender() {
|
||||
if (this.messageVerifierSender == null) {
|
||||
this.messageVerifierSender = this.beanFactory.getBeanProvider(MessageVerifierSender.class)
|
||||
.getIfAvailable(NoOpStubMessages::new);
|
||||
.getIfAvailable(NoOpStubMessages::new);
|
||||
}
|
||||
return this.messageVerifierSender;
|
||||
}
|
||||
@@ -180,7 +184,7 @@ class LazyMessageVerifier implements MessageVerifierSender, MessageVerifierRecei
|
||||
private MessageVerifierReceiver messageVerifierReceiver() {
|
||||
if (this.messageVerifierReceiver == null) {
|
||||
this.messageVerifierReceiver = this.beanFactory.getBeanProvider(MessageVerifierReceiver.class)
|
||||
.getIfAvailable(NoOpStubMessages::new);
|
||||
.getIfAvailable(NoOpStubMessages::new);
|
||||
}
|
||||
return this.messageVerifierReceiver;
|
||||
}
|
||||
|
||||
@@ -28,7 +28,6 @@ import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
|
||||
* Conditional that checks if the user turned off the stubbed discovery mode.
|
||||
*
|
||||
* @author Marcin Grzejszczak
|
||||
*
|
||||
* @since 1.0.0
|
||||
*/
|
||||
@Retention(RetentionPolicy.RUNTIME)
|
||||
|
||||
@@ -29,7 +29,6 @@ import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
|
||||
* is turned on by default.
|
||||
*
|
||||
* @author Marcin Grzejszczak
|
||||
*
|
||||
* @since 1.0.0
|
||||
*/
|
||||
@Retention(RetentionPolicy.RUNTIME)
|
||||
|
||||
@@ -63,7 +63,7 @@ public class StubMapperProperties {
|
||||
return id;
|
||||
}
|
||||
String groupAndArtifact = this.idsToServiceIds
|
||||
.get(stubConfiguration.getGroupId() + ":" + stubConfiguration.getArtifactId());
|
||||
.get(stubConfiguration.getGroupId() + ":" + stubConfiguration.getArtifactId());
|
||||
if (StringUtils.hasText(groupAndArtifact)) {
|
||||
return groupAndArtifact;
|
||||
}
|
||||
|
||||
@@ -123,7 +123,7 @@ class StubRunnerDiscoveryClientWrapper implements BeanPostProcessor {
|
||||
boolean isStubbedDiscoveryEnabled() {
|
||||
if (this.stubbedDiscoveryEnabled == null) {
|
||||
this.stubbedDiscoveryEnabled = Boolean.valueOf(this.beanFactory.getBean(Environment.class)
|
||||
.getProperty("stubrunner.cloud.stubbed.discovery.enabled", "true"));
|
||||
.getProperty("stubrunner.cloud.stubbed.discovery.enabled", "true"));
|
||||
}
|
||||
return this.stubbedDiscoveryEnabled;
|
||||
}
|
||||
@@ -131,7 +131,7 @@ class StubRunnerDiscoveryClientWrapper implements BeanPostProcessor {
|
||||
boolean isCloudDelegateEnabled() {
|
||||
if (this.cloudDelegateEnabled == null) {
|
||||
this.cloudDelegateEnabled = Boolean.valueOf(this.beanFactory.getBean(Environment.class)
|
||||
.getProperty("stubrunner.cloud.delegate.enabled", "false"));
|
||||
.getProperty("stubrunner.cloud.delegate.enabled", "false"));
|
||||
}
|
||||
return this.cloudDelegateEnabled;
|
||||
}
|
||||
|
||||
@@ -99,7 +99,7 @@ public class ConsulStubsRegistrar implements StubsRegistrar {
|
||||
|
||||
protected String name(StubConfiguration stubConfiguration) {
|
||||
String resolvedName = this.stubMapperProperties
|
||||
.fromIvyNotationToId(stubConfiguration.toColonSeparatedDependencyNotation());
|
||||
.fromIvyNotationToId(stubConfiguration.toColonSeparatedDependencyNotation());
|
||||
if (StringUtils.hasText(resolvedName)) {
|
||||
return resolvedName;
|
||||
}
|
||||
|
||||
@@ -28,7 +28,6 @@ import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
|
||||
* Conditional that checks if Eureka is enabled.
|
||||
*
|
||||
* @author Marcin Grzejszczak
|
||||
*
|
||||
* @since 1.0.0
|
||||
*/
|
||||
@Retention(RetentionPolicy.RUNTIME)
|
||||
|
||||
@@ -101,7 +101,9 @@ public class EurekaStubsRegistrar implements StubsRegistrar {
|
||||
EurekaClient client = new CloudEurekaClient(applicationInfoManager, this.eurekaClientConfigBean,
|
||||
transportClientFactories, args, this.context);
|
||||
EurekaRegistration registration = EurekaRegistration.builder(instance)
|
||||
.with(this.eurekaClientConfigBean, this.context).with(client).build();
|
||||
.with(this.eurekaClientConfigBean, this.context)
|
||||
.with(client)
|
||||
.build();
|
||||
EurekaHealthCheckHandler eurekaHealthCheckHandler = new EurekaHealthCheckHandler(
|
||||
StatusAggregator.getDefault());
|
||||
eurekaHealthCheckHandler.setApplicationContext(context);
|
||||
@@ -165,7 +167,7 @@ public class EurekaStubsRegistrar implements StubsRegistrar {
|
||||
|
||||
private String name(StubConfiguration stubConfiguration) {
|
||||
String resolvedName = this.stubMapperProperties
|
||||
.fromIvyNotationToId(stubConfiguration.toColonSeparatedDependencyNotation());
|
||||
.fromIvyNotationToId(stubConfiguration.toColonSeparatedDependencyNotation());
|
||||
if (StringUtils.hasText(resolvedName)) {
|
||||
return resolvedName;
|
||||
}
|
||||
|
||||
@@ -151,8 +151,8 @@ class StubbedServiceInstance implements ServiceInstance {
|
||||
}
|
||||
RunningStubs runningStubs = this.stubFinder.findAllRunningStubs();
|
||||
String mappedServiceName = StringUtils
|
||||
.hasText(this.stubMapperProperties.fromServiceIdToIvyNotation(this.serviceId))
|
||||
? this.stubMapperProperties.fromServiceIdToIvyNotation(this.serviceId) : this.serviceId;
|
||||
.hasText(this.stubMapperProperties.fromServiceIdToIvyNotation(this.serviceId))
|
||||
? this.stubMapperProperties.fromServiceIdToIvyNotation(this.serviceId) : this.serviceId;
|
||||
entry = runningStubs.getEntry(mappedServiceName);
|
||||
CACHE.put(this.serviceId, entry);
|
||||
return entry;
|
||||
|
||||
@@ -87,8 +87,12 @@ public class ZookeeperStubsRegistrar implements StubsRegistrar {
|
||||
|
||||
protected ServiceInstance serviceInstance(StubConfiguration stubConfiguration, int port) {
|
||||
try {
|
||||
return ServiceInstance.builder().uriSpec(new UriSpec(this.zookeeperDiscoveryProperties.getUriSpec()))
|
||||
.address("localhost").port(port).name(name(stubConfiguration)).build();
|
||||
return ServiceInstance.builder()
|
||||
.uriSpec(new UriSpec(this.zookeeperDiscoveryProperties.getUriSpec()))
|
||||
.address("localhost")
|
||||
.port(port)
|
||||
.name(name(stubConfiguration))
|
||||
.build();
|
||||
}
|
||||
catch (Exception e) {
|
||||
throw new IllegalStateException(e);
|
||||
@@ -97,7 +101,7 @@ public class ZookeeperStubsRegistrar implements StubsRegistrar {
|
||||
|
||||
private String name(StubConfiguration stubConfiguration) {
|
||||
String resolvedName = this.stubMapperProperties
|
||||
.fromIvyNotationToId(stubConfiguration.toColonSeparatedDependencyNotation());
|
||||
.fromIvyNotationToId(stubConfiguration.toColonSeparatedDependencyNotation());
|
||||
if (StringUtils.hasText(resolvedName)) {
|
||||
return resolvedName;
|
||||
}
|
||||
@@ -105,8 +109,11 @@ public class ZookeeperStubsRegistrar implements StubsRegistrar {
|
||||
}
|
||||
|
||||
protected ServiceDiscovery serviceDiscovery(ServiceInstance serviceInstance) {
|
||||
return ServiceDiscoveryBuilder.builder(Void.class).basePath(this.zookeeperDiscoveryProperties.getRoot())
|
||||
.client(this.curatorFramework).thisInstance(serviceInstance).build();
|
||||
return ServiceDiscoveryBuilder.builder(Void.class)
|
||||
.basePath(this.zookeeperDiscoveryProperties.getRoot())
|
||||
.client(this.curatorFramework)
|
||||
.thisInstance(serviceInstance)
|
||||
.build();
|
||||
}
|
||||
|
||||
@Override
|
||||
|
||||
@@ -39,9 +39,10 @@ public class StubRunnerRuleCustomPortJUnitTest {
|
||||
// tag::classrule_with_port[]
|
||||
@ClassRule
|
||||
public static StubRunnerRule rule = new StubRunnerRule().repoRoot(repoRoot())
|
||||
.stubsMode(StubRunnerProperties.StubsMode.REMOTE)
|
||||
.downloadStub("org.springframework.cloud.contract.verifier.stubs", "loanIssuance").withPort(35465)
|
||||
.downloadStub("org.springframework.cloud.contract.verifier.stubs:fraudDetectionServer:35466");
|
||||
.stubsMode(StubRunnerProperties.StubsMode.REMOTE)
|
||||
.downloadStub("org.springframework.cloud.contract.verifier.stubs", "loanIssuance")
|
||||
.withPort(35465)
|
||||
.downloadStub("org.springframework.cloud.contract.verifier.stubs:fraudDetectionServer:35466");
|
||||
|
||||
@BeforeClass
|
||||
@AfterClass
|
||||
@@ -67,14 +68,14 @@ public class StubRunnerRuleCustomPortJUnitTest {
|
||||
then(rule.findStubUrl("org.springframework.cloud.contract.verifier.stubs", "loanIssuance")).isNotNull();
|
||||
then(rule.findStubUrl("loanIssuance")).isNotNull();
|
||||
then(rule.findStubUrl("loanIssuance"))
|
||||
.isEqualTo(rule.findStubUrl("org.springframework.cloud.contract.verifier.stubs", "loanIssuance"));
|
||||
.isEqualTo(rule.findStubUrl("org.springframework.cloud.contract.verifier.stubs", "loanIssuance"));
|
||||
then(rule.findStubUrl("org.springframework.cloud.contract.verifier.stubs:fraudDetectionServer")).isNotNull();
|
||||
// and:
|
||||
then(rule.findAllRunningStubs().isPresent("loanIssuance")).isTrue();
|
||||
then(rule.findAllRunningStubs().isPresent("org.springframework.cloud.contract.verifier.stubs",
|
||||
"fraudDetectionServer")).isTrue();
|
||||
then(rule.findAllRunningStubs()
|
||||
.isPresent("org.springframework.cloud.contract.verifier.stubs:fraudDetectionServer")).isTrue();
|
||||
.isPresent("org.springframework.cloud.contract.verifier.stubs", "fraudDetectionServer")).isTrue();
|
||||
then(rule.findAllRunningStubs()
|
||||
.isPresent("org.springframework.cloud.contract.verifier.stubs:fraudDetectionServer")).isTrue();
|
||||
// and: 'Stubs were registered'
|
||||
then(httpGet(rule.findStubUrl("loanIssuance").toString() + "/name")).isEqualTo("loanIssuance");
|
||||
then(httpGet(rule.findStubUrl("fraudDetectionServer").toString() + "/name")).isEqualTo("fraudDetectionServer");
|
||||
|
||||
@@ -39,9 +39,9 @@ public class StubRunnerRuleJUnitTest {
|
||||
// tag::classrule[]
|
||||
@ClassRule
|
||||
public static StubRunnerRule rule = new StubRunnerRule().repoRoot(repoRoot())
|
||||
.stubsMode(StubRunnerProperties.StubsMode.REMOTE)
|
||||
.downloadStub("org.springframework.cloud.contract.verifier.stubs", "loanIssuance")
|
||||
.downloadStub("org.springframework.cloud.contract.verifier.stubs:fraudDetectionServer");
|
||||
.stubsMode(StubRunnerProperties.StubsMode.REMOTE)
|
||||
.downloadStub("org.springframework.cloud.contract.verifier.stubs", "loanIssuance")
|
||||
.downloadStub("org.springframework.cloud.contract.verifier.stubs:fraudDetectionServer");
|
||||
|
||||
@BeforeClass
|
||||
@AfterClass
|
||||
@@ -68,14 +68,14 @@ public class StubRunnerRuleJUnitTest {
|
||||
then(rule.findStubUrl("org.springframework.cloud.contract.verifier.stubs", "loanIssuance")).isNotNull();
|
||||
then(rule.findStubUrl("loanIssuance")).isNotNull();
|
||||
then(rule.findStubUrl("loanIssuance"))
|
||||
.isEqualTo(rule.findStubUrl("org.springframework.cloud.contract.verifier.stubs", "loanIssuance"));
|
||||
.isEqualTo(rule.findStubUrl("org.springframework.cloud.contract.verifier.stubs", "loanIssuance"));
|
||||
then(rule.findStubUrl("org.springframework.cloud.contract.verifier.stubs:fraudDetectionServer")).isNotNull();
|
||||
// and:
|
||||
then(rule.findAllRunningStubs().isPresent("loanIssuance")).isTrue();
|
||||
then(rule.findAllRunningStubs().isPresent("org.springframework.cloud.contract.verifier.stubs",
|
||||
"fraudDetectionServer")).isTrue();
|
||||
then(rule.findAllRunningStubs()
|
||||
.isPresent("org.springframework.cloud.contract.verifier.stubs:fraudDetectionServer")).isTrue();
|
||||
.isPresent("org.springframework.cloud.contract.verifier.stubs", "fraudDetectionServer")).isTrue();
|
||||
then(rule.findAllRunningStubs()
|
||||
.isPresent("org.springframework.cloud.contract.verifier.stubs:fraudDetectionServer")).isTrue();
|
||||
// and: 'Stubs were registered'
|
||||
then(httpGet(rule.findStubUrl("loanIssuance").toString() + "/name")).isEqualTo("loanIssuance");
|
||||
then(httpGet(rule.findStubUrl("fraudDetectionServer").toString() + "/name")).isEqualTo("fraudDetectionServer");
|
||||
|
||||
@@ -30,7 +30,7 @@ public class ClasspathStubProviderTest {
|
||||
@Test
|
||||
public void should_return_null_if_stub_mode_is_not_classpath() {
|
||||
StubDownloader stubDownloader = new ClasspathStubProvider()
|
||||
.build(new StubRunnerOptionsBuilder().withStubsMode(StubRunnerProperties.StubsMode.REMOTE).build());
|
||||
.build(new StubRunnerOptionsBuilder().withStubsMode(StubRunnerProperties.StubsMode.REMOTE).build());
|
||||
|
||||
then(stubDownloader).isNull();
|
||||
}
|
||||
|
||||
@@ -76,7 +76,7 @@ public class CompositeStubDownloaderBuilderTests {
|
||||
StubDownloader downloader = builder.build(new StubRunnerOptionsBuilder().withFailOnNoStubs(true).build());
|
||||
|
||||
BDDAssertions.thenThrownBy(() -> downloader.downloadAndUnpackStubJar(new StubConfiguration("a:b:v")))
|
||||
.isInstanceOf(IllegalArgumentException.class);
|
||||
.isInstanceOf(IllegalArgumentException.class);
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
@@ -61,8 +61,9 @@ public class ContractProjectUpdaterTest extends AbstractGitTest {
|
||||
this.gitRepo.checkout(this.project, "master");
|
||||
setOriginOnProjectToTmp(this.origin, this.project, true);
|
||||
StubRunnerOptions options = new StubRunnerOptionsBuilder()
|
||||
.withStubRepositoryRoot("file://" + this.project.getAbsolutePath() + "/")
|
||||
.withStubsMode(StubRunnerProperties.StubsMode.REMOTE).build();
|
||||
.withStubRepositoryRoot("file://" + this.project.getAbsolutePath() + "/")
|
||||
.withStubsMode(StubRunnerProperties.StubsMode.REMOTE)
|
||||
.build();
|
||||
this.updater = new ContractProjectUpdater(options);
|
||||
}
|
||||
|
||||
@@ -80,7 +81,7 @@ public class ContractProjectUpdaterTest extends AbstractGitTest {
|
||||
git.reset().setMode(ResetCommand.ResetType.HARD).call();
|
||||
}
|
||||
BDDAssertions.then(new File(this.project, "META-INF/com.example/hello-world/0.0.2/mappings/someMapping.json"))
|
||||
.exists();
|
||||
.exists();
|
||||
BDDAssertions.then(this.gitRepo.gitFactory.provider).isNull();
|
||||
BDDAssertions.then(this.outputCapture.toString()).contains("No custom credentials provider will be set");
|
||||
}
|
||||
@@ -88,13 +89,15 @@ public class ContractProjectUpdaterTest extends AbstractGitTest {
|
||||
@Test
|
||||
public void should_push_changes_to_current_branch_using_credentials() throws Exception {
|
||||
StubRunnerOptions options = new StubRunnerOptionsBuilder()
|
||||
.withStubRepositoryRoot("file://" + this.project.getAbsolutePath() + "/")
|
||||
.withStubsMode(StubRunnerProperties.StubsMode.REMOTE).withProperties(new HashMap<String, String>() {
|
||||
{
|
||||
put("git.username", "foo");
|
||||
put("git.password", "bar");
|
||||
}
|
||||
}).build();
|
||||
.withStubRepositoryRoot("file://" + this.project.getAbsolutePath() + "/")
|
||||
.withStubsMode(StubRunnerProperties.StubsMode.REMOTE)
|
||||
.withProperties(new HashMap<String, String>() {
|
||||
{
|
||||
put("git.username", "foo");
|
||||
put("git.password", "bar");
|
||||
}
|
||||
})
|
||||
.build();
|
||||
ContractProjectUpdater updater = new ContractProjectUpdater(options);
|
||||
File stubs = new File(GitRepoTests.class.getResource("/git_samples/sample_stubs").toURI());
|
||||
|
||||
@@ -108,16 +111,19 @@ public class ContractProjectUpdaterTest extends AbstractGitTest {
|
||||
git.reset().setMode(ResetCommand.ResetType.HARD).call();
|
||||
}
|
||||
BDDAssertions.then(new File(this.project, "META-INF/com.example/hello-world/0.0.2/mappings/someMapping.json"))
|
||||
.exists();
|
||||
.exists();
|
||||
BDDAssertions.then(this.outputCapture.toString())
|
||||
.contains("Passed username and password - will set a custom credentials provider");
|
||||
.contains("Passed username and password - will set a custom credentials provider");
|
||||
}
|
||||
|
||||
@Test
|
||||
public void should_push_changes_to_current_branch_using_root_credentials() throws Exception {
|
||||
StubRunnerOptions options = new StubRunnerOptionsBuilder()
|
||||
.withStubRepositoryRoot("file://" + this.project.getAbsolutePath() + "/")
|
||||
.withStubsMode(StubRunnerProperties.StubsMode.REMOTE).withUsername("foo").withPassword("bar").build();
|
||||
.withStubRepositoryRoot("file://" + this.project.getAbsolutePath() + "/")
|
||||
.withStubsMode(StubRunnerProperties.StubsMode.REMOTE)
|
||||
.withUsername("foo")
|
||||
.withPassword("bar")
|
||||
.build();
|
||||
ContractProjectUpdater updater = new ContractProjectUpdater(options);
|
||||
File stubs = new File(GitRepoTests.class.getResource("/git_samples/sample_stubs").toURI());
|
||||
|
||||
@@ -131,9 +137,9 @@ public class ContractProjectUpdaterTest extends AbstractGitTest {
|
||||
git.reset().setMode(ResetCommand.ResetType.HARD).call();
|
||||
}
|
||||
BDDAssertions.then(new File(this.project, "META-INF/com.example/hello-world/0.0.2/mappings/someMapping.json"))
|
||||
.exists();
|
||||
.exists();
|
||||
BDDAssertions.then(this.outputCapture.toString())
|
||||
.contains("Passed username and password - will set a custom credentials provider");
|
||||
.contains("Passed username and password - will set a custom credentials provider");
|
||||
}
|
||||
|
||||
@Test
|
||||
@@ -151,7 +157,7 @@ public class ContractProjectUpdaterTest extends AbstractGitTest {
|
||||
then(revCommit.getShortMessage()).isEqualTo(initialCommit);
|
||||
}
|
||||
BDDAssertions.then(new File(this.project, "META-INF/com.example/hello-world/0.0.2/mappings/someMapping.json"))
|
||||
.doesNotExist();
|
||||
.doesNotExist();
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
@@ -37,7 +37,7 @@ public class FileStubDownloaderTests {
|
||||
Assertions.assertThat(expectedUnixResource).isEqualTo(fileStubDownloader.resolve(unixFileFormat, null));
|
||||
Assertions.assertThat(expectedWindowsResource).isEqualTo(fileStubDownloader.resolve(windowsFileFormat, null));
|
||||
Assertions.assertThat(expectedWindowsResource)
|
||||
.isEqualTo(fileStubDownloader.resolve(windowsFileFormatCorrectPathStart, null));
|
||||
.isEqualTo(fileStubDownloader.resolve(windowsFileFormatCorrectPathStart, null));
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
@@ -59,16 +59,16 @@ public class GitRepoTests extends AbstractGitTest {
|
||||
@Test
|
||||
public void should_throw_exception_when_there_is_no_repo() throws IOException, URISyntaxException {
|
||||
thenThrownBy(() -> this.gitRepo.cloneProject(GitRepoTests.class.getResource("/git_samples/").toURI()))
|
||||
.isInstanceOf(IllegalStateException.class)
|
||||
.hasMessageContaining("Exception occurred while cloning repo");
|
||||
.isInstanceOf(IllegalStateException.class)
|
||||
.hasMessageContaining("Exception occurred while cloning repo");
|
||||
}
|
||||
|
||||
@Test
|
||||
public void should_throw_an_exception_when_failed_to_initialize_the_repo() throws IOException {
|
||||
thenThrownBy(() -> new GitRepo(this.tmpFolder, new ExceptionThrowingJGitFactory())
|
||||
.cloneProject(this.project.toURI())).isInstanceOf(IllegalStateException.class)
|
||||
.hasMessageContaining("Exception occurred while cloning repo")
|
||||
.hasCauseInstanceOf(CustomException.class);
|
||||
.cloneProject(this.project.toURI())).isInstanceOf(IllegalStateException.class)
|
||||
.hasMessageContaining("Exception occurred while cloning repo")
|
||||
.hasCauseInstanceOf(CustomException.class);
|
||||
}
|
||||
|
||||
@Test
|
||||
|
||||
@@ -49,8 +49,10 @@ public class GitStubDownloaderTests {
|
||||
public void should_return_a_null_downloader_for_a_classptath_mode() {
|
||||
StubDownloaderBuilder stubDownloaderBuilder = new ScmStubDownloaderBuilder();
|
||||
|
||||
StubDownloader stubDownloader = stubDownloaderBuilder.build(new StubRunnerOptionsBuilder()
|
||||
.withStubsMode(StubRunnerProperties.StubsMode.CLASSPATH).withProperties(props()).build());
|
||||
StubDownloader stubDownloader = stubDownloaderBuilder
|
||||
.build(new StubRunnerOptionsBuilder().withStubsMode(StubRunnerProperties.StubsMode.CLASSPATH)
|
||||
.withProperties(props())
|
||||
.build());
|
||||
|
||||
then(stubDownloader).isNull();
|
||||
}
|
||||
@@ -59,8 +61,10 @@ public class GitStubDownloaderTests {
|
||||
public void should_return_a_null_downloader_for_a_empty_repo() {
|
||||
StubDownloaderBuilder stubDownloaderBuilder = new ScmStubDownloaderBuilder();
|
||||
|
||||
StubDownloader stubDownloader = stubDownloaderBuilder.build(new StubRunnerOptionsBuilder()
|
||||
.withStubsMode(StubRunnerProperties.StubsMode.REMOTE).withProperties(props()).build());
|
||||
StubDownloader stubDownloader = stubDownloaderBuilder
|
||||
.build(new StubRunnerOptionsBuilder().withStubsMode(StubRunnerProperties.StubsMode.REMOTE)
|
||||
.withProperties(props())
|
||||
.build());
|
||||
|
||||
then(stubDownloader).isNull();
|
||||
}
|
||||
@@ -70,8 +74,10 @@ public class GitStubDownloaderTests {
|
||||
StubDownloaderBuilder stubDownloaderBuilder = new ScmStubDownloaderBuilder();
|
||||
|
||||
StubDownloader stubDownloader = stubDownloaderBuilder
|
||||
.build(new StubRunnerOptionsBuilder().withStubsMode(StubRunnerProperties.StubsMode.REMOTE)
|
||||
.withStubRepositoryRoot("http://www.foo.com/").withProperties(props()).build());
|
||||
.build(new StubRunnerOptionsBuilder().withStubsMode(StubRunnerProperties.StubsMode.REMOTE)
|
||||
.withStubRepositoryRoot("http://www.foo.com/")
|
||||
.withProperties(props())
|
||||
.build());
|
||||
|
||||
then(stubDownloader).isNull();
|
||||
}
|
||||
@@ -80,51 +86,55 @@ public class GitStubDownloaderTests {
|
||||
public void should_pick_stubs_for_group_and_artifact_with_version_from_a_git_repo() throws Exception {
|
||||
StubDownloaderBuilder stubDownloaderBuilder = new ScmStubDownloaderBuilder();
|
||||
String contractFolderLocation = (file("/git_samples/contract-git/").getAbsolutePath() + "/")
|
||||
.replace(File.separator, "/");
|
||||
.replace(File.separator, "/");
|
||||
StubDownloader stubDownloader = stubDownloaderBuilder
|
||||
.build(new StubRunnerOptionsBuilder().withStubsMode(StubRunnerProperties.StubsMode.REMOTE)
|
||||
.withStubRepositoryRoot("git://" + contractFolderLocation).withProperties(props()).build());
|
||||
.build(new StubRunnerOptionsBuilder().withStubsMode(StubRunnerProperties.StubsMode.REMOTE)
|
||||
.withStubRepositoryRoot("git://" + contractFolderLocation)
|
||||
.withProperties(props())
|
||||
.build());
|
||||
|
||||
Map.Entry<StubConfiguration, File> entry = stubDownloader
|
||||
.downloadAndUnpackStubJar(new StubConfiguration("foo.bar:bazService:0.0.1-SNAPSHOT"));
|
||||
.downloadAndUnpackStubJar(new StubConfiguration("foo.bar:bazService:0.0.1-SNAPSHOT"));
|
||||
|
||||
then(entry).isNotNull();
|
||||
then(entry.getValue().getAbsolutePath())
|
||||
.contains("foo.bar" + File.separator + "bazService" + File.separator + "0.0.1-SNAPSHOT");
|
||||
.contains("foo.bar" + File.separator + "bazService" + File.separator + "0.0.1-SNAPSHOT");
|
||||
}
|
||||
|
||||
@Test
|
||||
public void should_pick_latest_build_snapshot_stubs_when_latest_version_set() throws URISyntaxException {
|
||||
StubDownloaderBuilder stubDownloaderBuilder = new ScmStubDownloaderBuilder();
|
||||
String contractFolderLocation = (file("/git_samples/contract-git/").getAbsolutePath() + "/")
|
||||
.replace(File.separator, "/");
|
||||
.replace(File.separator, "/");
|
||||
StubDownloader stubDownloader = stubDownloaderBuilder
|
||||
.build(new StubRunnerOptionsBuilder().withStubsMode(StubRunnerProperties.StubsMode.REMOTE)
|
||||
.withStubRepositoryRoot("git://" + contractFolderLocation).withProperties(props()).build());
|
||||
.build(new StubRunnerOptionsBuilder().withStubsMode(StubRunnerProperties.StubsMode.REMOTE)
|
||||
.withStubRepositoryRoot("git://" + contractFolderLocation)
|
||||
.withProperties(props())
|
||||
.build());
|
||||
|
||||
Map.Entry<StubConfiguration, File> entry = stubDownloader
|
||||
.downloadAndUnpackStubJar(new StubConfiguration("com.example:beer-api-producer-external:+"));
|
||||
.downloadAndUnpackStubJar(new StubConfiguration("com.example:beer-api-producer-external:+"));
|
||||
|
||||
then(entry).isNotNull();
|
||||
then(entry.getValue().getAbsolutePath()).contains("com.example" + File.separator + "beer-api-producer-external"
|
||||
+ File.separator + "1.0.0.BUILD-SNAPSHOT");
|
||||
|
||||
entry = stubDownloader
|
||||
.downloadAndUnpackStubJar(new StubConfiguration("com.example:beer-api-producer-external:latest"));
|
||||
.downloadAndUnpackStubJar(new StubConfiguration("com.example:beer-api-producer-external:latest"));
|
||||
|
||||
then(entry).isNotNull();
|
||||
then(entry.getValue().getAbsolutePath()).contains("com.example" + File.separator + "beer-api-producer-external"
|
||||
+ File.separator + "1.0.0.BUILD-SNAPSHOT");
|
||||
|
||||
entry = stubDownloader
|
||||
.downloadAndUnpackStubJar(new StubConfiguration("com.example:beer-api-producer-external:LATEST"));
|
||||
.downloadAndUnpackStubJar(new StubConfiguration("com.example:beer-api-producer-external:LATEST"));
|
||||
|
||||
then(entry).isNotNull();
|
||||
then(entry.getValue().getAbsolutePath()).contains("com.example" + File.separator + "beer-api-producer-external"
|
||||
+ File.separator + "1.0.0.BUILD-SNAPSHOT");
|
||||
|
||||
entry = stubDownloader
|
||||
.downloadAndUnpackStubJar(new StubConfiguration("com.issue1305:beer-api-producer-external:+"));
|
||||
.downloadAndUnpackStubJar(new StubConfiguration("com.issue1305:beer-api-producer-external:+"));
|
||||
|
||||
then(entry).isNotNull();
|
||||
then(entry.getValue().getAbsolutePath()).contains(
|
||||
@@ -135,24 +145,26 @@ public class GitStubDownloaderTests {
|
||||
public void should_pick_latest_release_stubs_when_release_version_set() throws URISyntaxException {
|
||||
StubDownloaderBuilder stubDownloaderBuilder = new ScmStubDownloaderBuilder();
|
||||
String contractFolderLocation = (file("/git_samples/contract-git/").getAbsolutePath() + "/")
|
||||
.replace(File.separator, "/");
|
||||
.replace(File.separator, "/");
|
||||
StubDownloader stubDownloader = stubDownloaderBuilder
|
||||
.build(new StubRunnerOptionsBuilder().withStubsMode(StubRunnerProperties.StubsMode.REMOTE)
|
||||
.withStubRepositoryRoot("git://" + contractFolderLocation).withProperties(props()).build());
|
||||
.build(new StubRunnerOptionsBuilder().withStubsMode(StubRunnerProperties.StubsMode.REMOTE)
|
||||
.withStubRepositoryRoot("git://" + contractFolderLocation)
|
||||
.withProperties(props())
|
||||
.build());
|
||||
|
||||
Map.Entry<StubConfiguration, File> entry = stubDownloader
|
||||
.downloadAndUnpackStubJar(new StubConfiguration("com.example:beer-api-producer-external:release"));
|
||||
.downloadAndUnpackStubJar(new StubConfiguration("com.example:beer-api-producer-external:release"));
|
||||
|
||||
then(entry).isNotNull();
|
||||
then(entry.getValue().getAbsolutePath()).contains(
|
||||
"com.example" + File.separator + "beer-api-producer-external" + File.separator + "1.0.0.RELEASE");
|
||||
then(entry.getValue().getAbsolutePath())
|
||||
.contains("com.example" + File.separator + "beer-api-producer-external" + File.separator + "1.0.0.RELEASE");
|
||||
|
||||
entry = stubDownloader
|
||||
.downloadAndUnpackStubJar(new StubConfiguration("com.example:beer-api-producer-external:RELEASE"));
|
||||
.downloadAndUnpackStubJar(new StubConfiguration("com.example:beer-api-producer-external:RELEASE"));
|
||||
|
||||
then(entry).isNotNull();
|
||||
then(entry.getValue().getAbsolutePath()).contains(
|
||||
"com.example" + File.separator + "beer-api-producer-external" + File.separator + "1.0.0.RELEASE");
|
||||
then(entry.getValue().getAbsolutePath())
|
||||
.contains("com.example" + File.separator + "beer-api-producer-external" + File.separator + "1.0.0.RELEASE");
|
||||
}
|
||||
|
||||
@Test
|
||||
@@ -160,65 +172,71 @@ public class GitStubDownloaderTests {
|
||||
throws URISyntaxException {
|
||||
StubDownloaderBuilder stubDownloaderBuilder = new ScmStubDownloaderBuilder();
|
||||
String contractFolderLocation = (file("/git_samples/contract-predefined-names-git/").getAbsolutePath()
|
||||
.replace("/", File.separator) + "/").replace(File.separator, "/");
|
||||
.replace("/", File.separator) + "/").replace(File.separator, "/");
|
||||
StubDownloader stubDownloader = stubDownloaderBuilder
|
||||
.build(new StubRunnerOptionsBuilder().withStubsMode(StubRunnerProperties.StubsMode.REMOTE)
|
||||
.withStubRepositoryRoot("git://" + contractFolderLocation).withProperties(props()).build());
|
||||
.build(new StubRunnerOptionsBuilder().withStubsMode(StubRunnerProperties.StubsMode.REMOTE)
|
||||
.withStubRepositoryRoot("git://" + contractFolderLocation)
|
||||
.withProperties(props())
|
||||
.build());
|
||||
|
||||
Map.Entry<StubConfiguration, File> entry = stubDownloader
|
||||
.downloadAndUnpackStubJar(new StubConfiguration("com.example:beer-api-producer-external:+"));
|
||||
.downloadAndUnpackStubJar(new StubConfiguration("com.example:beer-api-producer-external:+"));
|
||||
|
||||
then(entry).isNotNull();
|
||||
then(entry.getValue().getAbsolutePath())
|
||||
.contains("com.example" + File.separator + "beer-api-producer-external" + File.separator + "latest");
|
||||
.contains("com.example" + File.separator + "beer-api-producer-external" + File.separator + "latest");
|
||||
|
||||
entry = stubDownloader
|
||||
.downloadAndUnpackStubJar(new StubConfiguration("com.example:beer-api-producer-external:latest"));
|
||||
.downloadAndUnpackStubJar(new StubConfiguration("com.example:beer-api-producer-external:latest"));
|
||||
|
||||
then(entry).isNotNull();
|
||||
then(entry.getValue().getAbsolutePath())
|
||||
.contains("com.example" + File.separator + "beer-api-producer-external" + File.separator + "latest");
|
||||
.contains("com.example" + File.separator + "beer-api-producer-external" + File.separator + "latest");
|
||||
|
||||
entry = stubDownloader
|
||||
.downloadAndUnpackStubJar(new StubConfiguration("com.example:beer-api-producer-external:LATEST"));
|
||||
.downloadAndUnpackStubJar(new StubConfiguration("com.example:beer-api-producer-external:LATEST"));
|
||||
|
||||
then(entry).isNotNull();
|
||||
then(entry.getValue().getAbsolutePath())
|
||||
.contains("com.example" + File.separator + "beer-api-producer-external" + File.separator + "latest");
|
||||
.contains("com.example" + File.separator + "beer-api-producer-external" + File.separator + "latest");
|
||||
}
|
||||
|
||||
@Test
|
||||
public void should_pick_release_folder_when_release_version_set() throws URISyntaxException {
|
||||
StubDownloaderBuilder stubDownloaderBuilder = new ScmStubDownloaderBuilder();
|
||||
String contractFolderLocation = (file("/git_samples/contract-predefined-names-git/").getAbsolutePath() + "/")
|
||||
.replace(File.separator, "/");
|
||||
.replace(File.separator, "/");
|
||||
StubDownloader stubDownloader = stubDownloaderBuilder
|
||||
.build(new StubRunnerOptionsBuilder().withStubsMode(StubRunnerProperties.StubsMode.REMOTE)
|
||||
.withStubRepositoryRoot("git://" + contractFolderLocation).withProperties(props()).build());
|
||||
.build(new StubRunnerOptionsBuilder().withStubsMode(StubRunnerProperties.StubsMode.REMOTE)
|
||||
.withStubRepositoryRoot("git://" + contractFolderLocation)
|
||||
.withProperties(props())
|
||||
.build());
|
||||
|
||||
Map.Entry<StubConfiguration, File> entry = stubDownloader
|
||||
.downloadAndUnpackStubJar(new StubConfiguration("com.example:beer-api-producer-external:release"));
|
||||
.downloadAndUnpackStubJar(new StubConfiguration("com.example:beer-api-producer-external:release"));
|
||||
|
||||
then(entry).isNotNull();
|
||||
then(entry.getValue().getAbsolutePath())
|
||||
.contains("com.example" + File.separator + "beer-api-producer-external" + File.separator + "release");
|
||||
.contains("com.example" + File.separator + "beer-api-producer-external" + File.separator + "release");
|
||||
|
||||
entry = stubDownloader
|
||||
.downloadAndUnpackStubJar(new StubConfiguration("com.example:beer-api-producer-external:RELEASE"));
|
||||
.downloadAndUnpackStubJar(new StubConfiguration("com.example:beer-api-producer-external:RELEASE"));
|
||||
|
||||
then(entry).isNotNull();
|
||||
then(entry.getValue().getAbsolutePath())
|
||||
.contains("com.example" + File.separator + "beer-api-producer-external" + File.separator + "release");
|
||||
.contains("com.example" + File.separator + "beer-api-producer-external" + File.separator + "release");
|
||||
}
|
||||
|
||||
@Test
|
||||
public void should_fail_to_fetch_stubs_when_concrete_version_was_not_specified() throws URISyntaxException {
|
||||
StubDownloaderBuilder stubDownloaderBuilder = new ScmStubDownloaderBuilder();
|
||||
String contractFolderLocation = (file("/git_samples/contract-git/").getAbsolutePath() + "/")
|
||||
.replace(File.separator, "/");
|
||||
.replace(File.separator, "/");
|
||||
StubDownloader stubDownloader = stubDownloaderBuilder
|
||||
.build(new StubRunnerOptionsBuilder().withStubsMode(StubRunnerProperties.StubsMode.REMOTE)
|
||||
.withStubRepositoryRoot("git://" + contractFolderLocation).withProperties(props()).build());
|
||||
.build(new StubRunnerOptionsBuilder().withStubsMode(StubRunnerProperties.StubsMode.REMOTE)
|
||||
.withStubRepositoryRoot("git://" + contractFolderLocation)
|
||||
.withProperties(props())
|
||||
.build());
|
||||
|
||||
try {
|
||||
stubDownloader.downloadAndUnpackStubJar(new StubConfiguration("foo.bar", "bazService", ""));
|
||||
|
||||
@@ -65,19 +65,19 @@ public class StubRunnerSliceTests {
|
||||
assertThat(this.loanIssuancePort).isBetween(10001, 10020);
|
||||
|
||||
assertThat(this.stubFinder.findStubUrl("org.springframework.cloud.contract.verifier.stubs", "loanIssuance"))
|
||||
.isNotNull();
|
||||
.isNotNull();
|
||||
assertThat(this.stubFinder.findStubUrl("loanIssuance")).isNotNull();
|
||||
assertThat(this.stubFinder.findStubUrl("loanIssuance")).isEqualTo(
|
||||
this.stubFinder.findStubUrl("org.springframework.cloud.contract.verifier.stubs", "loanIssuance"));
|
||||
assertThat(this.stubFinder.findStubUrl("loanIssuance")).isEqualTo(
|
||||
this.stubFinder.findStubUrl("org.springframework.cloud.contract.verifier.stubs:loanIssuance"));
|
||||
assertThat(this.stubFinder.findStubUrl("loanIssuance"))
|
||||
.isEqualTo(this.stubFinder.findStubUrl("org.springframework.cloud.contract.verifier.stubs:loanIssuance"));
|
||||
assertThat(this.stubFinder
|
||||
.findStubUrl("org.springframework.cloud.contract.verifier.stubs:loanIssuance:0.0.1-SNAPSHOT"))
|
||||
.isEqualTo(this.stubFinder.findStubUrl(
|
||||
"org.springframework.cloud.contract.verifier.stubs:loanIssuance:0.0.1-SNAPSHOT:stubs"));
|
||||
.findStubUrl("org.springframework.cloud.contract.verifier.stubs:loanIssuance:0.0.1-SNAPSHOT"))
|
||||
.isEqualTo(this.stubFinder
|
||||
.findStubUrl("org.springframework.cloud.contract.verifier.stubs:loanIssuance:0.0.1-SNAPSHOT:stubs"));
|
||||
assertThat(
|
||||
this.stubFinder.findStubUrl("org.springframework.cloud.contract.verifier.stubs:fraudDetectionServer"))
|
||||
.isNotNull();
|
||||
.isNotNull();
|
||||
assertThat(this.properties.getProperties()).containsEntry("hello", "world").containsEntry("foo", "bar");
|
||||
}
|
||||
|
||||
|
||||
@@ -32,11 +32,11 @@ public class StubsStubDownloaderTests {
|
||||
public void should_pick_stubs_from_a_given_location() {
|
||||
String path = url.getPath();
|
||||
StubRunnerOptions options = new StubRunnerOptionsBuilder().withStubRepositoryRoot("stubs://file://" + path)
|
||||
.build();
|
||||
.build();
|
||||
StubsStubDownloader downloader = new StubsStubDownloader(options);
|
||||
|
||||
Map.Entry<StubConfiguration, File> entry = downloader
|
||||
.downloadAndUnpackStubJar(new StubConfiguration("lv.spring.cloud:bye"));
|
||||
.downloadAndUnpackStubJar(new StubConfiguration("lv.spring.cloud:bye"));
|
||||
|
||||
BDDAssertions.then(entry).isNotNull();
|
||||
BDDAssertions.then(entry.getValue()).exists();
|
||||
@@ -48,11 +48,12 @@ public class StubsStubDownloaderTests {
|
||||
public void should_pick_stubs_from_a_given_location_for_a_find_producer_with_ga() {
|
||||
String path = url.getPath();
|
||||
StubRunnerOptions options = new StubRunnerOptionsBuilder().withStubRepositoryRoot("stubs://file://" + path)
|
||||
.withProperties(propsWithFindProducer()).build();
|
||||
.withProperties(propsWithFindProducer())
|
||||
.build();
|
||||
StubsStubDownloader downloader = new StubsStubDownloader(options);
|
||||
|
||||
Map.Entry<StubConfiguration, File> entry = downloader
|
||||
.downloadAndUnpackStubJar(new StubConfiguration("lv.spring.cloud:bye"));
|
||||
.downloadAndUnpackStubJar(new StubConfiguration("lv.spring.cloud:bye"));
|
||||
|
||||
BDDAssertions.then(entry).isNotNull();
|
||||
File stub = new File(entry.getValue().getPath(), "lv/spring/cloud/bye/lv_bye.json");
|
||||
@@ -63,11 +64,12 @@ public class StubsStubDownloaderTests {
|
||||
public void should_pick_stubs_from_a_given_location_for_a_find_producer_with_gav() {
|
||||
String path = url.getPath();
|
||||
StubRunnerOptions options = new StubRunnerOptionsBuilder().withStubRepositoryRoot("stubs://file://" + path)
|
||||
.withProperties(propsWithFindProducer()).build();
|
||||
.withProperties(propsWithFindProducer())
|
||||
.build();
|
||||
StubsStubDownloader downloader = new StubsStubDownloader(options);
|
||||
|
||||
Map.Entry<StubConfiguration, File> entry = downloader
|
||||
.downloadAndUnpackStubJar(new StubConfiguration("lv.spring:cloud:bye"));
|
||||
.downloadAndUnpackStubJar(new StubConfiguration("lv.spring:cloud:bye"));
|
||||
|
||||
BDDAssertions.then(entry).isNotNull();
|
||||
File stub = new File(entry.getValue().getPath(), "lv/spring/cloud/bye/lv_bye.json");
|
||||
|
||||
@@ -42,9 +42,11 @@ class StubRunnerJUnit5ExtensionCustomMessageVerifierTests {
|
||||
// Visible for testing
|
||||
@RegisterExtension
|
||||
static StubRunnerExtension stubRunnerExtension = new StubRunnerExtension()
|
||||
.stubsMode(StubRunnerProperties.StubsMode.REMOTE).repoRoot(repoRoot())
|
||||
.downloadStub("org.springframework.cloud.contract.verifier.stubs", "bootService")
|
||||
.messageVerifierSender(new MyMessageVerifier()).messageVerifierReceiver(new MyMessageVerifier());
|
||||
.stubsMode(StubRunnerProperties.StubsMode.REMOTE)
|
||||
.repoRoot(repoRoot())
|
||||
.downloadStub("org.springframework.cloud.contract.verifier.stubs", "bootService")
|
||||
.messageVerifierSender(new MyMessageVerifier())
|
||||
.messageVerifierReceiver(new MyMessageVerifier());
|
||||
|
||||
@BeforeAll
|
||||
@AfterAll
|
||||
|
||||
@@ -38,9 +38,10 @@ class StubRunnerJUnit5ExtensionCustomPortTests {
|
||||
|
||||
@RegisterExtension
|
||||
static StubRunnerExtension stubRunnerExtension = new StubRunnerExtension().repoRoot(repoRoot())
|
||||
.stubsMode(StubRunnerProperties.StubsMode.REMOTE)
|
||||
.downloadStub("org.springframework.cloud.contract.verifier.stubs", "loanIssuance").withPort(22345)
|
||||
.downloadStub("org.springframework.cloud.contract.verifier.stubs:fraudDetectionServer:22346");
|
||||
.stubsMode(StubRunnerProperties.StubsMode.REMOTE)
|
||||
.downloadStub("org.springframework.cloud.contract.verifier.stubs", "loanIssuance")
|
||||
.withPort(22345)
|
||||
.downloadStub("org.springframework.cloud.contract.verifier.stubs:fraudDetectionServer:22346");
|
||||
|
||||
@BeforeAll
|
||||
@AfterAll
|
||||
@@ -61,23 +62,23 @@ class StubRunnerJUnit5ExtensionCustomPortTests {
|
||||
@Test
|
||||
void should_start_wiremock_servers() throws Exception {
|
||||
then(stubRunnerExtension.findStubUrl("org.springframework.cloud.contract.verifier.stubs", "loanIssuance"))
|
||||
.isNotNull();
|
||||
.isNotNull();
|
||||
then(stubRunnerExtension.findStubUrl("loanIssuance")).isNotNull();
|
||||
then(stubRunnerExtension.findStubUrl("loanIssuance")).isEqualTo(
|
||||
stubRunnerExtension.findStubUrl("org.springframework.cloud.contract.verifier.stubs", "loanIssuance"));
|
||||
then(stubRunnerExtension.findStubUrl("org.springframework.cloud.contract.verifier.stubs:fraudDetectionServer"))
|
||||
.isNotNull();
|
||||
.isNotNull();
|
||||
then(stubRunnerExtension.findAllRunningStubs().isPresent("loanIssuance")).isTrue();
|
||||
then(stubRunnerExtension.findAllRunningStubs().isPresent("org.springframework.cloud.contract.verifier.stubs",
|
||||
"fraudDetectionServer")).isTrue();
|
||||
then(stubRunnerExtension.findAllRunningStubs()
|
||||
.isPresent("org.springframework.cloud.contract.verifier.stubs:fraudDetectionServer")).isTrue();
|
||||
.isPresent("org.springframework.cloud.contract.verifier.stubs", "fraudDetectionServer")).isTrue();
|
||||
then(stubRunnerExtension.findAllRunningStubs()
|
||||
.isPresent("org.springframework.cloud.contract.verifier.stubs:fraudDetectionServer")).isTrue();
|
||||
then(httpGet(stubRunnerExtension.findStubUrl("loanIssuance").toString() + "/name")).isEqualTo("loanIssuance");
|
||||
then(httpGet(stubRunnerExtension.findStubUrl("fraudDetectionServer").toString() + "/name"))
|
||||
.isEqualTo("fraudDetectionServer");
|
||||
.isEqualTo("fraudDetectionServer");
|
||||
then(stubRunnerExtension.findStubUrl("loanIssuance")).isEqualTo(URI.create("http://localhost:22345").toURL());
|
||||
then(stubRunnerExtension.findStubUrl("fraudDetectionServer"))
|
||||
.isEqualTo(URI.create("http://localhost:22346").toURL());
|
||||
.isEqualTo(URI.create("http://localhost:22346").toURL());
|
||||
}
|
||||
|
||||
private String httpGet(String url) throws Exception {
|
||||
|
||||
@@ -34,8 +34,9 @@ public class StubRunnerJUnit5ExtensionExceptionThrowingTests {
|
||||
|
||||
@RegisterExtension
|
||||
static StubRunnerExtension stubRunnerExtension = new StubRunnerExtension()
|
||||
.stubsMode(StubRunnerProperties.StubsMode.REMOTE).repoRoot(repoRoot())
|
||||
.downloadStub("org.springframework.cloud.contract.verifier.stubs", "bootService");
|
||||
.stubsMode(StubRunnerProperties.StubsMode.REMOTE)
|
||||
.repoRoot(repoRoot())
|
||||
.downloadStub("org.springframework.cloud.contract.verifier.stubs", "bootService");
|
||||
|
||||
@BeforeAll
|
||||
@AfterAll
|
||||
|
||||
@@ -39,10 +39,10 @@ class StubRunnerJUnit5ExtensionTests {
|
||||
// Visible for Junit
|
||||
@RegisterExtension
|
||||
static StubRunnerExtension stubRunnerExtension = new StubRunnerExtension().repoRoot(repoRoot())
|
||||
.stubsMode(StubRunnerProperties.StubsMode.REMOTE)
|
||||
.downloadStub("org.springframework.cloud.contract.verifier.stubs", "loanIssuance")
|
||||
.downloadStub("org.springframework.cloud.contract.verifier.stubs:fraudDetectionServer")
|
||||
.withMappingsOutputFolder("target/outputmappingsforrule");
|
||||
.stubsMode(StubRunnerProperties.StubsMode.REMOTE)
|
||||
.downloadStub("org.springframework.cloud.contract.verifier.stubs", "loanIssuance")
|
||||
.downloadStub("org.springframework.cloud.contract.verifier.stubs:fraudDetectionServer")
|
||||
.withMappingsOutputFolder("target/outputmappingsforrule");
|
||||
|
||||
@BeforeAll
|
||||
@AfterAll
|
||||
@@ -64,12 +64,12 @@ class StubRunnerJUnit5ExtensionTests {
|
||||
@Test
|
||||
void should_start_WireMock_servers() {
|
||||
assertThat(stubRunnerExtension.findStubUrl("org.springframework.cloud.contract.verifier.stubs", "loanIssuance"))
|
||||
.isNotNull();
|
||||
.isNotNull();
|
||||
assertThat(stubRunnerExtension.findStubUrl("loanIssuance")).isNotNull();
|
||||
assertThat(stubRunnerExtension.findStubUrl("loanIssuance")).isEqualTo(
|
||||
stubRunnerExtension.findStubUrl("org.springframework.cloud.contract.verifier.stubs", "loanIssuance"));
|
||||
assertThat(stubRunnerExtension
|
||||
.findStubUrl("org.springframework.cloud.contract.verifier.stubs:fraudDetectionServer")).isNotNull();
|
||||
.findStubUrl("org.springframework.cloud.contract.verifier.stubs:fraudDetectionServer")).isNotNull();
|
||||
}
|
||||
|
||||
@Test
|
||||
|
||||
@@ -39,10 +39,10 @@ class StubRunnerJUnit5MethodExtensionTests {
|
||||
// Visible for Junit
|
||||
@RegisterExtension
|
||||
StubRunnerExtension stubRunnerExtension = new StubRunnerExtension().repoRoot(repoRoot())
|
||||
.stubsMode(StubRunnerProperties.StubsMode.REMOTE)
|
||||
.downloadStub("org.springframework.cloud.contract.verifier.stubs", "loanIssuance")
|
||||
.downloadStub("org.springframework.cloud.contract.verifier.stubs:fraudDetectionServer")
|
||||
.withMappingsOutputFolder("target/outputmappingsforrule");
|
||||
.stubsMode(StubRunnerProperties.StubsMode.REMOTE)
|
||||
.downloadStub("org.springframework.cloud.contract.verifier.stubs", "loanIssuance")
|
||||
.downloadStub("org.springframework.cloud.contract.verifier.stubs:fraudDetectionServer")
|
||||
.withMappingsOutputFolder("target/outputmappingsforrule");
|
||||
|
||||
@BeforeEach
|
||||
@AfterEach
|
||||
@@ -64,12 +64,12 @@ class StubRunnerJUnit5MethodExtensionTests {
|
||||
@Test
|
||||
void should_start_WireMock_servers() {
|
||||
assertThat(stubRunnerExtension.findStubUrl("org.springframework.cloud.contract.verifier.stubs", "loanIssuance"))
|
||||
.isNotNull();
|
||||
.isNotNull();
|
||||
assertThat(stubRunnerExtension.findStubUrl("loanIssuance")).isNotNull();
|
||||
assertThat(stubRunnerExtension.findStubUrl("loanIssuance")).isEqualTo(
|
||||
stubRunnerExtension.findStubUrl("org.springframework.cloud.contract.verifier.stubs", "loanIssuance"));
|
||||
assertThat(stubRunnerExtension
|
||||
.findStubUrl("org.springframework.cloud.contract.verifier.stubs:fraudDetectionServer")).isNotNull();
|
||||
.findStubUrl("org.springframework.cloud.contract.verifier.stubs:fraudDetectionServer")).isNotNull();
|
||||
}
|
||||
|
||||
@Test
|
||||
|
||||
@@ -30,8 +30,8 @@ import static org.assertj.core.api.Assertions.assertThat;
|
||||
*/
|
||||
public class StubRunnerServerConfigurationTests {
|
||||
|
||||
private ApplicationContextRunner contextRunner = new ApplicationContextRunner().withConfiguration(
|
||||
AutoConfigurations.of(StubRunnerConfiguration.class, StubRunnerServerConfiguration.class));
|
||||
private ApplicationContextRunner contextRunner = new ApplicationContextRunner()
|
||||
.withConfiguration(AutoConfigurations.of(StubRunnerConfiguration.class, StubRunnerServerConfiguration.class));
|
||||
|
||||
@Test
|
||||
public void shouldCreateBeansByDefault() {
|
||||
|
||||
@@ -79,9 +79,13 @@ public class RecursiveFilesConverter {
|
||||
}
|
||||
|
||||
public void processFiles() {
|
||||
ContractFileScanner scanner = ContractFileScanner.builder().baseDir(contractsDslDir)
|
||||
.excluded(new HashSet<>(excludedFiles)).ignored(new HashSet<>()).included(new HashSet<>())
|
||||
.includeMatcher(includedContracts).build();
|
||||
ContractFileScanner scanner = ContractFileScanner.builder()
|
||||
.baseDir(contractsDslDir)
|
||||
.excluded(new HashSet<>(excludedFiles))
|
||||
.ignored(new HashSet<>())
|
||||
.included(new HashSet<>())
|
||||
.includeMatcher(includedContracts)
|
||||
.build();
|
||||
MultiValueMap<Path, ContractMetadata> contracts = scanner.findContractsRecursively();
|
||||
if (log.isDebugEnabled()) {
|
||||
log.debug("Found the following contracts " + contracts);
|
||||
@@ -115,7 +119,7 @@ public class RecursiveFilesConverter {
|
||||
|
||||
for (StubGenerator stubGenerator : stubGenerators) {
|
||||
Map<Contract, String> convertedContent = stubGenerator
|
||||
.convertContents(last(entryKey).toString(), contract);
|
||||
.convertContents(last(entryKey).toString(), contract);
|
||||
if (convertedContent == null || convertedContent.isEmpty()) {
|
||||
continue;
|
||||
}
|
||||
|
||||
@@ -55,8 +55,9 @@ public interface StubGenerator<T> {
|
||||
* @return the converted stub mapping
|
||||
*/
|
||||
default T postProcessStubMapping(T stubMapping, Contract contract) {
|
||||
List<StubPostProcessor> processors = StubPostProcessor.PROCESSORS.stream().filter(p -> p.isApplicable(contract))
|
||||
.collect(Collectors.toList());
|
||||
List<StubPostProcessor> processors = StubPostProcessor.PROCESSORS.stream()
|
||||
.filter(p -> p.isApplicable(contract))
|
||||
.collect(Collectors.toList());
|
||||
if (processors.isEmpty()) {
|
||||
return defaultStubMappingPostProcessing(stubMapping, contract);
|
||||
}
|
||||
|
||||
@@ -158,7 +158,7 @@ class DefaultWireMockStubPostProcessor implements WireMockStubPostProcessor {
|
||||
}
|
||||
Object stubMapping = WireMockMetaData.fromMetadata(contract.getMetadata()).getStubMapping();
|
||||
return WireMockMetaData.APPLICABLE_CLASSES.stream()
|
||||
.anyMatch(aClass -> aClass.isAssignableFrom(stubMapping.getClass()));
|
||||
.anyMatch(aClass -> aClass.isAssignableFrom(stubMapping.getClass()));
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
@@ -78,8 +78,10 @@ public class DslToWireMockClientConverter extends DslToWireMockConverter {
|
||||
}
|
||||
|
||||
private List<Contract> httpContracts(ContractMetadata contract) {
|
||||
return contract.getConvertedContract().stream().filter(c -> c.getRequest() != null)
|
||||
.collect(Collectors.toList());
|
||||
return contract.getConvertedContract()
|
||||
.stream()
|
||||
.filter(c -> c.getRequest() != null)
|
||||
.collect(Collectors.toList());
|
||||
}
|
||||
|
||||
private Map<Contract, String> convertContracts(String rootName, ContractMetadata contract,
|
||||
|
||||
@@ -65,8 +65,9 @@ public class WireMockMetaData implements SpringCloudContractMetadata {
|
||||
@Override
|
||||
public String description() {
|
||||
return "Metadata for extending WireMock stubs.\n\nStubMapping can be " + "one of the following classes "
|
||||
+ APPLICABLE_CLASSES.stream().map(aClass -> "`" + aClass.getSimpleName() + "`")
|
||||
.collect(Collectors.toList())
|
||||
+ APPLICABLE_CLASSES.stream()
|
||||
.map(aClass -> "`" + aClass.getSimpleName() + "`")
|
||||
.collect(Collectors.toList())
|
||||
+ ". Please check "
|
||||
+ "the http://wiremock.org/docs/stubbing/ for more information about the StubMapping class properties.";
|
||||
}
|
||||
|
||||
@@ -202,17 +202,27 @@ public class WireMockToDslConverter {
|
||||
Iterator<JsonNode> elements = requestBodyArrayNode.elements();
|
||||
Iterable<JsonNode> iterableFields = () -> elements;
|
||||
List<Map.Entry<String, JsonNode>> requestBodyObjectNodes = new ArrayList<>();
|
||||
StreamSupport.stream(iterableFields.spliterator(), false).filter(f -> f instanceof ObjectNode)
|
||||
.map(f -> (ObjectNode) f).map(ObjectNode::fields)
|
||||
.forEachOrdered(i -> i.forEachRemaining(requestBodyObjectNodes::add));
|
||||
requestBodyObjectNodes.stream().filter(b -> b.getKey().equals("equalTo")).findFirst()
|
||||
.ifPresent(b -> requestBody.append("body ('").append(b.getValue().asText()).append("')"));
|
||||
requestBodyObjectNodes.stream().filter(b -> b.getKey().equals("equalToJson")).findFirst()
|
||||
.ifPresent(b -> requestBody.append("body ('").append(b.getValue().asText()).append("')"));
|
||||
requestBodyObjectNodes.stream().filter(b -> b.getKey().equals("matches")).findFirst()
|
||||
.ifPresent(b -> requestBody.append("body $(consumer(regex('")
|
||||
.append(escapeJava(b.getValue().asText())).append("')), producer('")
|
||||
.append(new Xeger(escapeJava(b.getValue().asText())).generate()).append("'))"));
|
||||
StreamSupport.stream(iterableFields.spliterator(), false)
|
||||
.filter(f -> f instanceof ObjectNode)
|
||||
.map(f -> (ObjectNode) f)
|
||||
.map(ObjectNode::fields)
|
||||
.forEachOrdered(i -> i.forEachRemaining(requestBodyObjectNodes::add));
|
||||
requestBodyObjectNodes.stream()
|
||||
.filter(b -> b.getKey().equals("equalTo"))
|
||||
.findFirst()
|
||||
.ifPresent(b -> requestBody.append("body ('").append(b.getValue().asText()).append("')"));
|
||||
requestBodyObjectNodes.stream()
|
||||
.filter(b -> b.getKey().equals("equalToJson"))
|
||||
.findFirst()
|
||||
.ifPresent(b -> requestBody.append("body ('").append(b.getValue().asText()).append("')"));
|
||||
requestBodyObjectNodes.stream()
|
||||
.filter(b -> b.getKey().equals("matches"))
|
||||
.findFirst()
|
||||
.ifPresent(b -> requestBody.append("body $(consumer(regex('")
|
||||
.append(escapeJava(b.getValue().asText()))
|
||||
.append("')), producer('")
|
||||
.append(new Xeger(escapeJava(b.getValue().asText())).generate())
|
||||
.append("'))"));
|
||||
}
|
||||
return requestBody.toString();
|
||||
}
|
||||
@@ -250,9 +260,8 @@ public class WireMockToDslConverter {
|
||||
Object intermediateObjectForPrettyPrinting = OBJECT_MAPPER.reader().readValue(textNode, Object.class);
|
||||
DefaultIndenter customIndenter = new DefaultIndenter(" ", "\n");
|
||||
return OBJECT_MAPPER
|
||||
.writer(new PrivatePrettyPrinter().withArrayIndenter(customIndenter)
|
||||
.withObjectIndenter(customIndenter))
|
||||
.writeValueAsString(intermediateObjectForPrettyPrinting);
|
||||
.writer(new PrivatePrettyPrinter().withArrayIndenter(customIndenter).withObjectIndenter(customIndenter))
|
||||
.writeValueAsString(intermediateObjectForPrettyPrinting);
|
||||
}
|
||||
catch (IOException e) {
|
||||
throw new RuntimeException("WireMock response body could not be pretty printed");
|
||||
@@ -267,8 +276,12 @@ public class WireMockToDslConverter {
|
||||
responseHeadersBuilder.append("headers {\n");
|
||||
ObjectNode responseHeadersObjectNode = requestHeadersNode.deepCopy();
|
||||
Iterator<Map.Entry<String, JsonNode>> fields = responseHeadersObjectNode.fields();
|
||||
fields.forEachRemaining(c -> responseHeadersBuilder.append("header('").append(c.getKey()).append("',")
|
||||
.append("'").append(c.getValue().asText()).append("')\n"));
|
||||
fields.forEachRemaining(c -> responseHeadersBuilder.append("header('")
|
||||
.append(c.getKey())
|
||||
.append("',")
|
||||
.append("'")
|
||||
.append(c.getValue().asText())
|
||||
.append("')\n"));
|
||||
responseHeadersBuilder.append("}");
|
||||
}
|
||||
return responseHeadersBuilder.toString();
|
||||
|
||||
@@ -153,10 +153,12 @@ class DefaultWireMockStubPostProcessorTests {
|
||||
then(result.getResponse().getStatus()).isEqualTo(200);
|
||||
then(result.getResponse().getBody()).isEqualTo("pong");
|
||||
then(result.getPostServeActions().stream().map(a -> a.getName()).collect(Collectors.toList()))
|
||||
.contains("webhook");
|
||||
PostServeActionDefinition definition = result.getPostServeActions().stream()
|
||||
.filter(a -> a.getName().equals("webhook")).findFirst()
|
||||
.orElseThrow(() -> new AssertionError("No webhook action found"));
|
||||
.contains("webhook");
|
||||
PostServeActionDefinition definition = result.getPostServeActions()
|
||||
.stream()
|
||||
.filter(a -> a.getName().equals("webhook"))
|
||||
.findFirst()
|
||||
.orElseThrow(() -> new AssertionError("No webhook action found"));
|
||||
then(definition.getParameters().getString("method")).isEqualTo("POST");
|
||||
}
|
||||
|
||||
|
||||
@@ -246,7 +246,7 @@ public class ConvertMojo extends AbstractMojo {
|
||||
throws MojoExecutionException {
|
||||
File outputFolderWithOriginals = new File(this.stubsDirectory, rootPath + ORIGINAL_PATH);
|
||||
new CopyContracts(this.project, this.mavenSession, this.mavenResourcesFiltering, config)
|
||||
.copy(contractsDirectory, outputFolderWithOriginals);
|
||||
.copy(contractsDirectory, outputFolderWithOriginals);
|
||||
return outputFolderWithOriginals;
|
||||
}
|
||||
|
||||
@@ -255,7 +255,7 @@ public class ConvertMojo extends AbstractMojo {
|
||||
File outputFolderWithContracts = this.stubsDirectory.getPath().endsWith("contracts") ? this.stubsDirectory
|
||||
: new File(this.stubsDirectory, rootPath + CONTRACTS_PATH);
|
||||
new CopyContracts(this.project, this.mavenSession, this.mavenResourcesFiltering, config)
|
||||
.copy(contractsDirectory, outputFolderWithContracts);
|
||||
.copy(contractsDirectory, outputFolderWithContracts);
|
||||
return outputFolderWithContracts;
|
||||
}
|
||||
|
||||
@@ -285,7 +285,7 @@ public class ConvertMojo extends AbstractMojo {
|
||||
this.contractsRepositoryUrl, this.contractsMode, getLog(), this.contractsRepositoryUsername,
|
||||
this.contractsRepositoryPassword, this.contractsRepositoryProxyHost, this.contractsRepositoryProxyPort,
|
||||
this.deleteStubsAfterTest, this.contractsProperties, this.failOnNoContracts)
|
||||
.downloadAndUnpackContractsIfRequired(config, this.contractsDirectory);
|
||||
.downloadAndUnpackContractsIfRequired(config, this.contractsDirectory);
|
||||
}
|
||||
|
||||
private File stubsOutputDir(String rootPath) {
|
||||
|
||||
@@ -254,8 +254,8 @@ public class GenerateTestsMojo extends AbstractMojo {
|
||||
+ this.skip);
|
||||
}
|
||||
if (this.mavenTestSkip) {
|
||||
getLog().info(
|
||||
"Skipping Spring Cloud Contract Verifier execution: maven.test.skip=" + this.mavenTestSkip);
|
||||
getLog()
|
||||
.info("Skipping Spring Cloud Contract Verifier execution: maven.test.skip=" + this.mavenTestSkip);
|
||||
}
|
||||
return;
|
||||
}
|
||||
@@ -267,7 +267,8 @@ public class GenerateTestsMojo extends AbstractMojo {
|
||||
this.contractsPath, this.contractsRepositoryUrl, this.contractsMode, getLog(),
|
||||
this.contractsRepositoryUsername, this.contractsRepositoryPassword, this.contractsRepositoryProxyHost,
|
||||
this.contractsRepositoryProxyPort, this.deleteStubsAfterTest, this.contractsProperties,
|
||||
this.failOnNoContracts).downloadAndUnpackContractsIfRequired(config, this.contractsDirectory);
|
||||
this.failOnNoContracts)
|
||||
.downloadAndUnpackContractsIfRequired(config, this.contractsDirectory);
|
||||
getLog().info("Directory with contract is present at [" + contractsDirectory + "]");
|
||||
throwExceptionWhenFailOnNoContracts(contractsDirectory, this.contractsRepositoryUrl);
|
||||
|
||||
@@ -307,8 +308,8 @@ public class GenerateTestsMojo extends AbstractMojo {
|
||||
throws MojoExecutionException {
|
||||
if (StringUtils.hasText(contractsRepository)) {
|
||||
if (getLog().isDebugEnabled()) {
|
||||
getLog().debug(
|
||||
"Contracts repository is set, will not throw an exception that the contracts are not found");
|
||||
getLog()
|
||||
.debug("Contracts repository is set, will not throw an exception that the contracts are not found");
|
||||
}
|
||||
return;
|
||||
}
|
||||
|
||||
@@ -46,13 +46,13 @@ class LeftOverPrevention {
|
||||
this.generatedDirectory = generatedDirectory;
|
||||
this.incrementalBuildHelper = new IncrementalBuildHelper(mojoExecution, session);
|
||||
this.incrementalBuildHelper
|
||||
.beforeRebuildExecution(new IncrementalBuildHelperRequest().outputDirectory(generatedDirectory));
|
||||
.beforeRebuildExecution(new IncrementalBuildHelperRequest().outputDirectory(generatedDirectory));
|
||||
}
|
||||
|
||||
void deleteLeftOvers() throws MojoExecutionException {
|
||||
if (generatedDirectory.exists()) {
|
||||
incrementalBuildHelper
|
||||
.afterRebuildExecution(new IncrementalBuildHelperRequest().outputDirectory(generatedDirectory));
|
||||
.afterRebuildExecution(new IncrementalBuildHelperRequest().outputDirectory(generatedDirectory));
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -101,7 +101,7 @@ class MavenContractsDownloader {
|
||||
this.log.info("Another mojo has downloaded the contracts - will reuse them from [" + downloadedContractsDir
|
||||
+ "]");
|
||||
final ContractDownloader.InclusionProperties inclusionProperties = contractDownloader()
|
||||
.createNewInclusionProperties(downloadedContractsDir);
|
||||
.createNewInclusionProperties(downloadedContractsDir);
|
||||
config.setIncludedContracts(inclusionProperties.getIncludedContracts());
|
||||
config.setIncludedRootFolderAntPattern(inclusionProperties.getIncludedRootFolderAntPattern());
|
||||
return downloadedContractsDir;
|
||||
@@ -111,7 +111,7 @@ class MavenContractsDownloader {
|
||||
final ContractDownloader contractDownloader = contractDownloader();
|
||||
final File downloadedContracts = contractDownloader.unpackAndDownloadContracts();
|
||||
final ContractDownloader.InclusionProperties inclusionProperties = contractDownloader
|
||||
.createNewInclusionProperties(downloadedContracts);
|
||||
.createNewInclusionProperties(downloadedContracts);
|
||||
config.setIncludedContracts(inclusionProperties.getIncludedContracts());
|
||||
config.setIncludedRootFolderAntPattern(inclusionProperties.getIncludedRootFolderAntPattern());
|
||||
this.project.getProperties().setProperty(directoryProperty(), downloadedContracts.getAbsolutePath());
|
||||
@@ -147,10 +147,13 @@ class MavenContractsDownloader {
|
||||
|
||||
StubRunnerOptions buildOptions() {
|
||||
StubRunnerOptionsBuilder builder = new StubRunnerOptionsBuilder()
|
||||
.withOptions(StubRunnerOptions.fromSystemProps()).withStubsMode(this.stubsMode)
|
||||
.withUsername(this.repositoryUsername).withPassword(this.repositoryPassword)
|
||||
.withDeleteStubsAfterTest(this.deleteStubsAfterTest).withProperties(this.contractsProperties)
|
||||
.withFailOnNoStubs(this.failOnNoStubs);
|
||||
.withOptions(StubRunnerOptions.fromSystemProps())
|
||||
.withStubsMode(this.stubsMode)
|
||||
.withUsername(this.repositoryUsername)
|
||||
.withPassword(this.repositoryPassword)
|
||||
.withDeleteStubsAfterTest(this.deleteStubsAfterTest)
|
||||
.withProperties(this.contractsProperties)
|
||||
.withFailOnNoStubs(this.failOnNoStubs);
|
||||
if (StringUtils.hasText(this.contractsRepositoryUrl)) {
|
||||
builder.withStubRepositoryRoot(this.contractsRepositoryUrl);
|
||||
}
|
||||
|
||||
@@ -122,10 +122,13 @@ public class PushStubsToScmMojo extends AbstractMojo {
|
||||
|
||||
StubRunnerOptions buildOptions() {
|
||||
StubRunnerOptionsBuilder builder = new StubRunnerOptionsBuilder()
|
||||
.withOptions(StubRunnerOptions.fromSystemProps()).withStubRepositoryRoot(this.contractsRepositoryUrl)
|
||||
.withStubsMode(this.contractsMode).withUsername(this.contractsRepositoryUsername)
|
||||
.withPassword(this.contractsRepositoryPassword).withDeleteStubsAfterTest(this.deleteStubsAfterTest)
|
||||
.withProperties(this.contractsProperties);
|
||||
.withOptions(StubRunnerOptions.fromSystemProps())
|
||||
.withStubRepositoryRoot(this.contractsRepositoryUrl)
|
||||
.withStubsMode(this.contractsMode)
|
||||
.withUsername(this.contractsRepositoryUsername)
|
||||
.withPassword(this.contractsRepositoryPassword)
|
||||
.withDeleteStubsAfterTest(this.deleteStubsAfterTest)
|
||||
.withProperties(this.contractsProperties);
|
||||
return builder.build();
|
||||
}
|
||||
|
||||
|
||||
@@ -132,15 +132,17 @@ public class RunMojo extends AbstractMojo {
|
||||
}
|
||||
BatchStubRunner batchStubRunner = null;
|
||||
StubRunnerOptionsBuilder optionsBuilder = new StubRunnerOptionsBuilder()
|
||||
.withStubsClassifier(this.stubsClassifier);
|
||||
.withStubsClassifier(this.stubsClassifier);
|
||||
if (!StringUtils.hasText(this.stubs)) {
|
||||
StubRunnerOptions options = optionsBuilder.withMinMaxPort(this.httpPort, this.httpPort).build();
|
||||
StubRunner stubRunner = this.localStubRunner.run(resolveStubsDirectory().getAbsolutePath(), options);
|
||||
batchStubRunner = new BatchStubRunner(Collections.singleton(stubRunner));
|
||||
}
|
||||
else {
|
||||
StubRunnerOptions options = optionsBuilder.withStubs(this.stubs).withMinMaxPort(this.minPort, this.maxPort)
|
||||
.withServerId(this.serverId).build();
|
||||
StubRunnerOptions options = optionsBuilder.withStubs(this.stubs)
|
||||
.withMinMaxPort(this.minPort, this.maxPort)
|
||||
.withServerId(this.serverId)
|
||||
.build();
|
||||
batchStubRunner = this.remoteStubRunner.run(options, this.repoSession);
|
||||
}
|
||||
pressAnyKeyToContinue();
|
||||
|
||||
@@ -50,23 +50,27 @@ class MavenContractsDownloaderTests {
|
||||
MavenContractsDownloader mavenContractsDownloader = contractsDownloader(mavenProject, one,
|
||||
this.fileForDependencyOne);
|
||||
File dependencyOneFile = mavenContractsDownloader
|
||||
.downloadAndUnpackContractsIfRequired(new ContractVerifierConfigProperties(), this.defaultFolder);
|
||||
BDDAssertions.then(dependencyOneFile).as("Location for dependency 1 should be computed since it's not cached")
|
||||
.isEqualTo(this.fileForDependencyOne);
|
||||
.downloadAndUnpackContractsIfRequired(new ContractVerifierConfigProperties(), this.defaultFolder);
|
||||
BDDAssertions.then(dependencyOneFile)
|
||||
.as("Location for dependency 1 should be computed since it's not cached")
|
||||
.isEqualTo(this.fileForDependencyOne);
|
||||
|
||||
mavenContractsDownloader = contractsDownloader(mavenProject, one, this.fileForDependencyOne);
|
||||
File fileForDependencyOneAgain = mavenContractsDownloader
|
||||
.downloadAndUnpackContractsIfRequired(new ContractVerifierConfigProperties(), this.defaultFolder);
|
||||
BDDAssertions.then(dependencyOneFile).as("Location for dependency 1 should be taken from cache")
|
||||
.isEqualTo(fileForDependencyOneAgain);
|
||||
.downloadAndUnpackContractsIfRequired(new ContractVerifierConfigProperties(), this.defaultFolder);
|
||||
BDDAssertions.then(dependencyOneFile)
|
||||
.as("Location for dependency 1 should be taken from cache")
|
||||
.isEqualTo(fileForDependencyOneAgain);
|
||||
|
||||
Dependency two = dependency(2);
|
||||
mavenContractsDownloader = contractsDownloader(mavenProject, two, this.fileForDependencyTwo);
|
||||
File dependencyTwoFile = mavenContractsDownloader
|
||||
.downloadAndUnpackContractsIfRequired(new ContractVerifierConfigProperties(), this.defaultFolder);
|
||||
.downloadAndUnpackContractsIfRequired(new ContractVerifierConfigProperties(), this.defaultFolder);
|
||||
|
||||
BDDAssertions.then(dependencyTwoFile).as("Location for dependency 2 should be computed again")
|
||||
.isNotEqualTo(dependencyOneFile).isEqualTo(this.fileForDependencyTwo);
|
||||
BDDAssertions.then(dependencyTwoFile)
|
||||
.as("Location for dependency 2 should be computed again")
|
||||
.isNotEqualTo(dependencyOneFile)
|
||||
.isEqualTo(this.fileForDependencyTwo);
|
||||
}
|
||||
|
||||
private MavenContractsDownloader contractsDownloader(MavenProject mavenProject, Dependency one, File file) {
|
||||
|
||||
@@ -38,10 +38,10 @@ public class PluginUnitTest extends AbstractMojoTest {
|
||||
executeMojo(basedir, "convert");
|
||||
assertFilesPresent(basedir,
|
||||
"target/stubs/META-INF/org.springframework.cloud.verifier.sample/sample-project/0.1/mappings/Sample.json"
|
||||
.replace("/", File.separator));
|
||||
.replace("/", File.separator));
|
||||
assertFilesNotPresent(basedir,
|
||||
"target/stubs/META-INF/org.springframework.cloud.verifier.sample/sample-project/0.1/mappings/Messaging.json"
|
||||
.replace("/", File.separator));
|
||||
.replace("/", File.separator));
|
||||
}
|
||||
|
||||
private Xpp3Dom defaultPackageForTests() {
|
||||
@@ -54,7 +54,7 @@ public class PluginUnitTest extends AbstractMojoTest {
|
||||
executeMojo(basedir, "convert", newParameter("contractsDirectory", "src/test/resources/stubs"));
|
||||
assertFilesPresent(basedir,
|
||||
"target/stubs/META-INF/org.springframework.cloud.verifier.sample/sample-project/0.1/mappings/Sample.json"
|
||||
.replace("/", File.separator));
|
||||
.replace("/", File.separator));
|
||||
}
|
||||
|
||||
@Test
|
||||
@@ -63,10 +63,10 @@ public class PluginUnitTest extends AbstractMojoTest {
|
||||
executeMojo(basedir, "convert");
|
||||
assertFilesPresent(basedir,
|
||||
"target/stubs/META-INF/org.springframework.cloud.verifier.sample/sample-project/0.1/contracts/Sample.groovy"
|
||||
.replace("/", File.separator));
|
||||
.replace("/", File.separator));
|
||||
assertFilesPresent(basedir,
|
||||
"target/stubs/META-INF/org.springframework.cloud.verifier.sample/sample-project/0.1/contracts/Messaging.groovy"
|
||||
.replace("/", File.separator));
|
||||
.replace("/", File.separator));
|
||||
}
|
||||
|
||||
@Test
|
||||
@@ -150,8 +150,12 @@ public class PluginUnitTest extends AbstractMojoTest {
|
||||
@Test
|
||||
public void shouldGenerateStubsByDownloadingContractsFromARepo() throws Exception {
|
||||
File basedir = getBasedir("basic-remote-contracts");
|
||||
executeMojo(basedir, "convert", newParameter("contractsRepositoryUrl", "file://" + PluginUnitTest.class
|
||||
.getClassLoader().getResource("m2repo/repository").getFile().replace("/", File.separator)));
|
||||
executeMojo(basedir, "convert",
|
||||
newParameter("contractsRepositoryUrl",
|
||||
"file://" + PluginUnitTest.class.getClassLoader()
|
||||
.getResource("m2repo/repository")
|
||||
.getFile()
|
||||
.replace("/", File.separator)));
|
||||
assertFilesPresent(basedir,
|
||||
"target/stubs/META-INF/com.example/server/0.1.BUILD-SNAPSHOT/mappings/com/example/server/client1/contracts/shouldMarkClientAsFraud.json");
|
||||
}
|
||||
@@ -159,8 +163,12 @@ public class PluginUnitTest extends AbstractMojoTest {
|
||||
@Test
|
||||
public void shouldGenerateStubsByDownloadingContractsFromARepoWhenCustomPathIsProvided() throws Exception {
|
||||
File basedir = getBasedir("complex-remote-contracts");
|
||||
executeMojo(basedir, "convert", newParameter("contractsRepositoryUrl", "file://" + PluginUnitTest.class
|
||||
.getClassLoader().getResource("m2repo/repository").getFile().replace("/", File.separator)));
|
||||
executeMojo(basedir, "convert",
|
||||
newParameter("contractsRepositoryUrl",
|
||||
"file://" + PluginUnitTest.class.getClassLoader()
|
||||
.getResource("m2repo/repository")
|
||||
.getFile()
|
||||
.replace("/", File.separator)));
|
||||
assertFilesPresent(basedir,
|
||||
"target/stubs/META-INF/com.example.foo.bar.baz/someartifact/0.1.BUILD-SNAPSHOT/mappings/com/example/server/client1/contracts/shouldMarkClientAsFraud.json");
|
||||
assertFilesNotPresent(basedir,
|
||||
@@ -189,8 +197,11 @@ public class PluginUnitTest extends AbstractMojoTest {
|
||||
public void shouldGenerateTestsByDownloadingContractsFromARepo() throws Exception {
|
||||
File basedir = getBasedir("basic-remote-contracts");
|
||||
executeMojo(basedir, "generateTests", defaultPackageForTests(),
|
||||
newParameter("contractsRepositoryUrl", "file://" + PluginUnitTest.class.getClassLoader()
|
||||
.getResource("m2repo/repository").getFile().replace("/", File.separator)));
|
||||
newParameter("contractsRepositoryUrl",
|
||||
"file://" + PluginUnitTest.class.getClassLoader()
|
||||
.getResource("m2repo/repository")
|
||||
.getFile()
|
||||
.replace("/", File.separator)));
|
||||
assertFilesPresent(basedir,
|
||||
"target/generated-test-sources/contracts/org/springframework/cloud/contract/verifier/tests/com/example/server/client1/ContractsTest.java");
|
||||
}
|
||||
@@ -199,8 +210,11 @@ public class PluginUnitTest extends AbstractMojoTest {
|
||||
public void shouldGenerateTestsByDownloadingContractsFromARepoWhenCustomPathIsProvided() throws Exception {
|
||||
File basedir = getBasedir("complex-remote-contracts");
|
||||
executeMojo(basedir, "generateTests", defaultPackageForTests(),
|
||||
newParameter("contractsRepositoryUrl", "file://" + PluginUnitTest.class.getClassLoader()
|
||||
.getResource("m2repo/repository").getFile().replace("/", File.separator)));
|
||||
newParameter("contractsRepositoryUrl",
|
||||
"file://" + PluginUnitTest.class.getClassLoader()
|
||||
.getResource("m2repo/repository")
|
||||
.getFile()
|
||||
.replace("/", File.separator)));
|
||||
assertFilesPresent(basedir,
|
||||
"target/generated-test-sources/contracts/org/springframework/cloud/contract/verifier/tests/com/example/server/client1/ContractsTest.java");
|
||||
assertFilesNotPresent(basedir,
|
||||
@@ -218,7 +232,7 @@ public class PluginUnitTest extends AbstractMojoTest {
|
||||
assertFilesPresent(basedir, path);
|
||||
File test = new File(basedir, path);
|
||||
then(readFileToString(test, defaultCharset())).contains("extends HelloV1Base")
|
||||
.contains("import hello.HelloV1Base");
|
||||
.contains("import hello.HelloV1Base");
|
||||
}
|
||||
|
||||
@Test
|
||||
@@ -231,7 +245,7 @@ public class PluginUnitTest extends AbstractMojoTest {
|
||||
assertFilesPresent(basedir, path);
|
||||
File test = new File(basedir, path);
|
||||
then(readFileToString(test, defaultCharset())).contains("extends HelloV1Base")
|
||||
.contains("import hello.HelloV1Base");
|
||||
.contains("import hello.HelloV1Base");
|
||||
}
|
||||
|
||||
@Test
|
||||
@@ -244,7 +258,7 @@ public class PluginUnitTest extends AbstractMojoTest {
|
||||
assertFilesPresent(basedir, path);
|
||||
File test = new File(basedir, path);
|
||||
then(readFileToString(test, defaultCharset())).contains("extends TestBase")
|
||||
.contains("import com.example.TestBase");
|
||||
.contains("import com.example.TestBase");
|
||||
}
|
||||
|
||||
@Test
|
||||
@@ -257,7 +271,7 @@ public class PluginUnitTest extends AbstractMojoTest {
|
||||
assertFilesPresent(basedir, path);
|
||||
File test = new File(basedir, path);
|
||||
then(readFileToString(test, defaultCharset())).contains("extends TestBase")
|
||||
.contains("import com.example.TestBase");
|
||||
.contains("import com.example.TestBase");
|
||||
}
|
||||
|
||||
@Test
|
||||
@@ -270,8 +284,8 @@ public class PluginUnitTest extends AbstractMojoTest {
|
||||
assertFilesPresent(basedir, path);
|
||||
File test = new File(basedir, path);
|
||||
then(readFileToString(test, defaultCharset()))
|
||||
.contains("public void validate_should_post_a_user() throws Exception {")
|
||||
.contains("public void validate_withList_1() throws Exception {");
|
||||
.contains("public void validate_should_post_a_user() throws Exception {")
|
||||
.contains("public void validate_withList_1() throws Exception {");
|
||||
}
|
||||
|
||||
@Test
|
||||
@@ -322,8 +336,11 @@ public class PluginUnitTest extends AbstractMojoTest {
|
||||
File basedir = getBasedir("complex-common-repo-with-messaging");
|
||||
|
||||
executeMojo(basedir, "generateTests", defaultPackageForTests(),
|
||||
newParameter("contractsRepositoryUrl", "file://" + PluginUnitTest.class.getClassLoader()
|
||||
.getResource("m2repo/repository").getFile().replace("/", File.separator)));
|
||||
newParameter("contractsRepositoryUrl",
|
||||
"file://" + PluginUnitTest.class.getClassLoader()
|
||||
.getResource("m2repo/repository")
|
||||
.getFile()
|
||||
.replace("/", File.separator)));
|
||||
assertFilesPresent(basedir,
|
||||
"target/generated-test-sources/contracts/org/springframework/cloud/contract/verifier/tests/common_repo_with_inclusion/kafka_topics/coupon_sent/src/main/resources/contracts/rule_engine_daemon/MessagingTest.java");
|
||||
assertFilesPresent(basedir,
|
||||
|
||||
@@ -84,10 +84,14 @@ public class TestGenerator {
|
||||
|
||||
public TestGenerator(ContractVerifierConfigProperties configProperties, SingleTestGenerator generator,
|
||||
FileSaver saver) {
|
||||
this(configProperties, generator, saver, ContractFileScanner.builder()
|
||||
.baseDir(configProperties.getContractsDslDir()).excluded(toSet(configProperties.getExcludedFiles()))
|
||||
.ignored(toSet(configProperties.getIgnoredFiles())).included(toSet(configProperties.getIncludedFiles()))
|
||||
.includeMatcher(configProperties.getIncludedContracts()).build());
|
||||
this(configProperties, generator, saver,
|
||||
ContractFileScanner.builder()
|
||||
.baseDir(configProperties.getContractsDslDir())
|
||||
.excluded(toSet(configProperties.getExcludedFiles()))
|
||||
.ignored(toSet(configProperties.getIgnoredFiles()))
|
||||
.included(toSet(configProperties.getIncludedFiles()))
|
||||
.includeMatcher(configProperties.getIncludedContracts())
|
||||
.build());
|
||||
}
|
||||
|
||||
private static Set<String> toSet(List<String> files) {
|
||||
@@ -133,8 +137,10 @@ public class TestGenerator {
|
||||
|
||||
Set<Map.Entry<Path, List<ContractMetadata>>> inProgress = inProgress(contracts);
|
||||
if (!inProgress.isEmpty() && configProperties.isFailOnInProgress()) {
|
||||
String inProgressContractsPaths = inProgress.stream().map(Map.Entry::getKey).map(Path::toString)
|
||||
.collect(Collectors.joining(","));
|
||||
String inProgressContractsPaths = inProgress.stream()
|
||||
.map(Map.Entry::getKey)
|
||||
.map(Path::toString)
|
||||
.collect(Collectors.joining(","));
|
||||
throw new IllegalStateException("In progress contracts found in paths [" + inProgressContractsPaths
|
||||
+ "] and the switch [failOnInProgress] is set to [true]. Either unmark those contracts as in progress, or set the switch to [false].");
|
||||
}
|
||||
@@ -142,14 +148,17 @@ public class TestGenerator {
|
||||
}
|
||||
|
||||
private Set<Map.Entry<Path, List<ContractMetadata>>> inProgress(MultiValueMap<Path, ContractMetadata> contracts) {
|
||||
return contracts.entrySet().stream()
|
||||
.filter(entry -> entry.getValue().stream().anyMatch(ContractMetadata::anyInProgress))
|
||||
.collect(Collectors.toSet());
|
||||
return contracts.entrySet()
|
||||
.stream()
|
||||
.filter(entry -> entry.getValue().stream().anyMatch(ContractMetadata::anyInProgress))
|
||||
.collect(Collectors.toSet());
|
||||
}
|
||||
|
||||
void processAll(MultiValueMap<Path, ContractMetadata> contracts, final String basePackageName) {
|
||||
contracts.entrySet().stream().forEach(
|
||||
entry -> processIncludedDirectory(relativizeContractPath(entry), entry.getValue(), basePackageName));
|
||||
contracts.entrySet()
|
||||
.stream()
|
||||
.forEach(entry -> processIncludedDirectory(relativizeContractPath(entry), entry.getValue(),
|
||||
basePackageName));
|
||||
}
|
||||
|
||||
private String relativizeContractPath(Map.Entry<Path, List<ContractMetadata>> entry) {
|
||||
@@ -169,9 +178,9 @@ public class TestGenerator {
|
||||
convertIllegalPackageChars(includedDirectoryRelativePath));
|
||||
Path classPath = saver.pathToClass(dir, convertedClassName);
|
||||
byte[] classBytes = generator
|
||||
.buildClass(configProperties, contracts, includedDirectoryRelativePath,
|
||||
new SingleTestGenerator.GeneratedClassData(convertedClassName, packageName, classPath))
|
||||
.getBytes(StandardCharsets.UTF_8);
|
||||
.buildClass(configProperties, contracts, includedDirectoryRelativePath,
|
||||
new SingleTestGenerator.GeneratedClassData(convertedClassName, packageName, classPath))
|
||||
.getBytes(StandardCharsets.UTF_8);
|
||||
saver.saveClassFile(classPath, classBytes);
|
||||
counter.incrementAndGet();
|
||||
}
|
||||
|
||||
@@ -64,8 +64,9 @@ interface BodyMethodVisitor {
|
||||
*/
|
||||
default List<MethodVisitor> filterVisitors(List<? extends MethodVisitor> methodVisitors,
|
||||
SingleContractMetadata singleContractMetadata) {
|
||||
return methodVisitors.stream().filter(given -> given.accept(singleContractMetadata))
|
||||
.collect(Collectors.toList());
|
||||
return methodVisitors.stream()
|
||||
.filter(given -> given.accept(singleContractMetadata))
|
||||
.collect(Collectors.toList());
|
||||
}
|
||||
|
||||
/**
|
||||
|
||||
@@ -101,8 +101,9 @@ interface BodyParser extends BodyThen {
|
||||
else if (bodyValue instanceof List) {
|
||||
// ["a=3", "b=4"] == "a=3&b=4"
|
||||
return ((List) bodyValue).stream()
|
||||
.map(o -> convertUnicodeEscapesIfRequired(MapConverter.getTestSideValuesForText(o).toString()))
|
||||
.collect(Collectors.joining("&")).toString();
|
||||
.map(o -> convertUnicodeEscapesIfRequired(MapConverter.getTestSideValuesForText(o).toString()))
|
||||
.collect(Collectors.joining("&"))
|
||||
.toString();
|
||||
}
|
||||
else if (bodyValue instanceof String) {
|
||||
return (String) bodyValue;
|
||||
|
||||
@@ -54,7 +54,7 @@ interface CookieElementProcessor {
|
||||
if (value instanceof NotToEscapePattern) {
|
||||
verifyCookieNotNull(property);
|
||||
return comparisonBuilder().assertThat(cookieValue(property)) + comparisonBuilder()
|
||||
.matches(((NotToEscapePattern) value).getServerValue().pattern().replace("\\", "\\\\"));
|
||||
.matches(((NotToEscapePattern) value).getServerValue().pattern().replace("\\", "\\\\"));
|
||||
}
|
||||
else if (value instanceof String || value instanceof Pattern) {
|
||||
verifyCookieNotNull(property);
|
||||
|
||||
@@ -37,7 +37,7 @@ class CustomModeGiven implements Given, BodyMethodVisitor, CustomModeAcceptor {
|
||||
this.blockBuilder = blockBuilder;
|
||||
this.generatedClassMetaData = generatedClassMetaData;
|
||||
this.requestGivens
|
||||
.addAll(Collections.singletonList(new CustomModeRequestGiven(blockBuilder, generatedClassMetaData)));
|
||||
.addAll(Collections.singletonList(new CustomModeRequestGiven(blockBuilder, generatedClassMetaData)));
|
||||
this.bodyGivens.addAll(Arrays.asList(new CustomModeMethodWithUrlGiven(blockBuilder, bodyParser),
|
||||
new CustomModeQueryParamsGiven(blockBuilder, bodyParser),
|
||||
new CustomModeSchemeProtocolGiven(blockBuilder), new CustomModeHeadersGiven(blockBuilder),
|
||||
@@ -56,10 +56,12 @@ class CustomModeGiven implements Given, BodyMethodVisitor, CustomModeAcceptor {
|
||||
}
|
||||
|
||||
private void addRequestGivenLine(SingleContractMetadata singleContractMetadata) {
|
||||
this.requestGivens.stream().filter(given -> given.accept(singleContractMetadata)).findFirst()
|
||||
.orElseThrow(() -> new IllegalStateException(
|
||||
"No matching request building Given implementation for a custom test mode"))
|
||||
.apply(singleContractMetadata);
|
||||
this.requestGivens.stream()
|
||||
.filter(given -> given.accept(singleContractMetadata))
|
||||
.findFirst()
|
||||
.orElseThrow(() -> new IllegalStateException(
|
||||
"No matching request building Given implementation for a custom test mode"))
|
||||
.apply(singleContractMetadata);
|
||||
}
|
||||
|
||||
@Override
|
||||
|
||||
@@ -58,7 +58,7 @@ class CustomModeHeadersGiven implements Given {
|
||||
private String string(Header header) {
|
||||
return ".header("
|
||||
+ ContentHelper.getTestSideForNonBodyValue(header.getName()) + ", " + ContentHelper
|
||||
.getTestSideForNonBodyValue(MapConverter.getTestSideValuesForNonBody(header.getServerValue()))
|
||||
.getTestSideForNonBodyValue(MapConverter.getTestSideValuesForNonBody(header.getServerValue()))
|
||||
+ ")";
|
||||
}
|
||||
|
||||
|
||||
@@ -57,8 +57,11 @@ class CustomModeQueryParamsGiven implements Given, CustomModeAcceptor, QueryPara
|
||||
}
|
||||
|
||||
private void addQueryParameters(Url buildUrl) {
|
||||
List<QueryParameter> queryParameters = buildUrl.getQueryParameters().getParameters().stream()
|
||||
.filter(this::allowedQueryParameter).collect(Collectors.toList());
|
||||
List<QueryParameter> queryParameters = buildUrl.getQueryParameters()
|
||||
.getParameters()
|
||||
.stream()
|
||||
.filter(this::allowedQueryParameter)
|
||||
.collect(Collectors.toList());
|
||||
Iterator<QueryParameter> iterator = queryParameters.iterator();
|
||||
while (iterator.hasNext()) {
|
||||
QueryParameter parameter = iterator.next();
|
||||
@@ -84,7 +87,7 @@ class CustomModeQueryParamsGiven implements Given, CustomModeAcceptor, QueryPara
|
||||
|
||||
private String addQueryParameter(QueryParameter queryParam) {
|
||||
return "." + "queryParam(" + this.bodyParser.quotedLongText(queryParam.getName()) + "," + this.bodyParser
|
||||
.quotedLongText(resolveParamValue(MapConverter.getTestSideValuesForNonBody(queryParam))) + ")";
|
||||
.quotedLongText(resolveParamValue(MapConverter.getTestSideValuesForNonBody(queryParam))) + ")";
|
||||
}
|
||||
|
||||
@Override
|
||||
|
||||
@@ -33,9 +33,10 @@ class CustomModeStatusCodeThen implements Then {
|
||||
@Override
|
||||
public MethodVisitor<Then> apply(SingleContractMetadata metadata) {
|
||||
Response response = metadata.getContract().getResponse();
|
||||
this.blockBuilder.addIndented(
|
||||
this.comparisonBuilder.assertThat("response.statusCode()", response.getStatus().getServerValue()))
|
||||
.addEndingIfNotPresent();
|
||||
this.blockBuilder
|
||||
.addIndented(
|
||||
this.comparisonBuilder.assertThat("response.statusCode()", response.getStatus().getServerValue()))
|
||||
.addEndingIfNotPresent();
|
||||
return this;
|
||||
}
|
||||
|
||||
|
||||
@@ -45,9 +45,12 @@ class CustomModeWhen implements When, BodyMethodVisitor, CustomModeAcceptor {
|
||||
}
|
||||
|
||||
private void addResponseWhenLine(SingleContractMetadata singleContractMetadata) {
|
||||
this.responseWhens.stream().filter(when -> when.accept(singleContractMetadata)).findFirst().orElseThrow(
|
||||
() -> new IllegalStateException("No matching request building When implementation for Rest Assured"))
|
||||
.apply(singleContractMetadata);
|
||||
this.responseWhens.stream()
|
||||
.filter(when -> when.accept(singleContractMetadata))
|
||||
.findFirst()
|
||||
.orElseThrow(() -> new IllegalStateException(
|
||||
"No matching request building When implementation for Rest Assured"))
|
||||
.apply(singleContractMetadata);
|
||||
}
|
||||
|
||||
@Override
|
||||
|
||||
@@ -41,8 +41,10 @@ class DefaultJsonStaticImports implements Imports {
|
||||
|
||||
@Override
|
||||
public boolean accept() {
|
||||
return this.generatedClassMetaData.listOfFiles.stream().anyMatch(metadata -> metadata
|
||||
.getConvertedContractWithMetadata().stream().anyMatch(SingleContractMetadata::isJson));
|
||||
return this.generatedClassMetaData.listOfFiles.stream()
|
||||
.anyMatch(metadata -> metadata.getConvertedContractWithMetadata()
|
||||
.stream()
|
||||
.anyMatch(SingleContractMetadata::isJson));
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
@@ -49,8 +49,9 @@ class GeneratedClassMetaData {
|
||||
}
|
||||
|
||||
Collection<SingleContractMetadata> toSingleContractMetadata() {
|
||||
return this.listOfFiles.stream().flatMap(metadata -> metadata.getConvertedContractWithMetadata().stream())
|
||||
.collect(Collectors.toList());
|
||||
return this.listOfFiles.stream()
|
||||
.flatMap(metadata -> metadata.getConvertedContractWithMetadata().stream())
|
||||
.collect(Collectors.toList());
|
||||
}
|
||||
|
||||
boolean isAnyJson() {
|
||||
|
||||
@@ -126,11 +126,14 @@ class GeneratedTestClassBuilder {
|
||||
*/
|
||||
GeneratedTestClass build() {
|
||||
// picks a matching class meta data
|
||||
ClassMetaData classMetaData = this.metaData.stream().filter(Acceptor::accept).findFirst()
|
||||
.orElseThrow(() -> new IllegalStateException("There is no matching class meta data"));
|
||||
classMetaData.setupLineEnding().setupLabelPrefix()
|
||||
// package com.example
|
||||
.packageDefinition();
|
||||
ClassMetaData classMetaData = this.metaData.stream()
|
||||
.filter(Acceptor::accept)
|
||||
.findFirst()
|
||||
.orElseThrow(() -> new IllegalStateException("There is no matching class meta data"));
|
||||
classMetaData.setupLineEnding()
|
||||
.setupLabelPrefix()
|
||||
// package com.example
|
||||
.packageDefinition();
|
||||
// \n
|
||||
this.blockBuilder.addEmptyLine();
|
||||
// import ... \n
|
||||
|
||||
@@ -42,11 +42,11 @@ class GenericHttpBodyThen implements Then, BodyMethodVisitor {
|
||||
this.bodyParser = bodyParser;
|
||||
this.comparisonBuilder = comparisonBuilder;
|
||||
this.templateProcessor = new HandlebarsTemplateProcessor();
|
||||
this.thens.addAll(
|
||||
Arrays.asList(new GenericBinaryBodyThen(blockBuilder, metaData, this.bodyParser, comparisonBuilder),
|
||||
new GenericTextBodyThen(blockBuilder, metaData, this.bodyParser, this.comparisonBuilder),
|
||||
new GenericJsonBodyThen(blockBuilder, metaData, this.bodyParser, this.comparisonBuilder),
|
||||
new GenericXmlBodyThen(blockBuilder, this.bodyParser)));
|
||||
this.thens
|
||||
.addAll(Arrays.asList(new GenericBinaryBodyThen(blockBuilder, metaData, this.bodyParser, comparisonBuilder),
|
||||
new GenericTextBodyThen(blockBuilder, metaData, this.bodyParser, this.comparisonBuilder),
|
||||
new GenericJsonBodyThen(blockBuilder, metaData, this.bodyParser, this.comparisonBuilder),
|
||||
new GenericXmlBodyThen(blockBuilder, this.bodyParser)));
|
||||
}
|
||||
|
||||
@Override
|
||||
|
||||
@@ -39,8 +39,9 @@ class JUnit4IgnoreImports implements Imports {
|
||||
public boolean accept() {
|
||||
return this.generatedClassMetaData.configProperties.getTestFramework() == TestFramework.JUNIT
|
||||
&& this.generatedClassMetaData.listOfFiles.stream()
|
||||
.anyMatch(metadata -> metadata.isIgnored() || metadata.getConvertedContractWithMetadata()
|
||||
.stream().anyMatch(m -> m.isIgnored() || m.isInProgress()));
|
||||
.anyMatch(metadata -> metadata.isIgnored() || metadata.getConvertedContractWithMetadata()
|
||||
.stream()
|
||||
.anyMatch(m -> m.isIgnored() || m.isInProgress()));
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
@@ -39,8 +39,9 @@ class JUnit5IgnoreImports implements Imports {
|
||||
public boolean accept() {
|
||||
return this.generatedClassMetaData.configProperties.getTestFramework() == TestFramework.JUNIT5
|
||||
&& this.generatedClassMetaData.listOfFiles.stream()
|
||||
.anyMatch(metadata -> metadata.isIgnored() || metadata.getConvertedContractWithMetadata()
|
||||
.stream().anyMatch(m -> m.isIgnored() || m.isInProgress()));
|
||||
.anyMatch(metadata -> metadata.isIgnored() || metadata.getConvertedContractWithMetadata()
|
||||
.stream()
|
||||
.anyMatch(m -> m.isIgnored() || m.isInProgress()));
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
@@ -47,7 +47,7 @@ class JavaMultipartGiven implements Given, RestAssuredAcceptor {
|
||||
@Override
|
||||
public MethodVisitor<Given> apply(SingleContractMetadata metadata) {
|
||||
getMultipartParameters(metadata).entrySet()
|
||||
.forEach(entry -> this.blockBuilder.addLine(getMultipartParameterLine(metadata, entry)));
|
||||
.forEach(entry -> this.blockBuilder.addLine(getMultipartParameterLine(metadata, entry)));
|
||||
return this;
|
||||
}
|
||||
|
||||
|
||||
@@ -43,8 +43,11 @@ class JaxRsRequestCookiesWhen implements When {
|
||||
}
|
||||
|
||||
private void appendCookies(Request request) {
|
||||
Iterator<Cookie> iterator = request.getCookies().getEntries().stream()
|
||||
.filter(cookie -> !cookieOfAbsentType(cookie)).iterator();
|
||||
Iterator<Cookie> iterator = request.getCookies()
|
||||
.getEntries()
|
||||
.stream()
|
||||
.filter(cookie -> !cookieOfAbsentType(cookie))
|
||||
.iterator();
|
||||
while (iterator.hasNext()) {
|
||||
Cookie cookie = iterator.next();
|
||||
String value = ".cookie(" + this.bodyParser.quotedShortText(cookie.getKey()) + ", "
|
||||
|
||||
@@ -44,8 +44,11 @@ class JaxRsRequestHeadersWhen implements When {
|
||||
}
|
||||
|
||||
private void appendHeaders(Request request) {
|
||||
Iterator<Header> iterator = request.getHeaders().getEntries().stream().filter(header -> !headerToIgnore(header))
|
||||
.iterator();
|
||||
Iterator<Header> iterator = request.getHeaders()
|
||||
.getEntries()
|
||||
.stream()
|
||||
.filter(header -> !headerToIgnore(header))
|
||||
.iterator();
|
||||
while (iterator.hasNext()) {
|
||||
Header header = iterator.next();
|
||||
String text = ".header(\"" + header.getName() + "\", " + headerValue(header) + ")";
|
||||
|
||||
@@ -53,8 +53,12 @@ class JaxRsRequestWhen implements When, JaxRsAcceptor, QueryParamsResolver {
|
||||
if (request.getHeaders() == null || request.getHeaders().getEntries() == null) {
|
||||
return "";
|
||||
}
|
||||
Header foundHeader = request.getHeaders().getEntries().stream().filter(header -> name.equals(header.getName()))
|
||||
.findFirst().orElse(null);
|
||||
Header foundHeader = request.getHeaders()
|
||||
.getEntries()
|
||||
.stream()
|
||||
.filter(header -> name.equals(header.getName()))
|
||||
.findFirst()
|
||||
.orElse(null);
|
||||
if (foundHeader == null) {
|
||||
return "";
|
||||
}
|
||||
|
||||
@@ -33,9 +33,10 @@ class JaxRsStatusCodeThen implements Then {
|
||||
@Override
|
||||
public MethodVisitor<Then> apply(SingleContractMetadata metadata) {
|
||||
Response response = metadata.getContract().getResponse();
|
||||
this.blockBuilder.addIndented(
|
||||
this.comparisonBuilder.assertThat("response.getStatus()", response.getStatus().getServerValue()))
|
||||
.addEndingIfNotPresent();
|
||||
this.blockBuilder
|
||||
.addIndented(
|
||||
this.comparisonBuilder.assertThat("response.getStatus()", response.getStatus().getServerValue()))
|
||||
.addEndingIfNotPresent();
|
||||
return this;
|
||||
}
|
||||
|
||||
|
||||
@@ -71,8 +71,10 @@ class JaxRsUrlPathWhen implements When, JaxRsAcceptor, QueryParamsResolver {
|
||||
return;
|
||||
}
|
||||
this.blockBuilder.addEmptyLine();
|
||||
Iterator<QueryParameter> iterator = queryParameters.getParameters().stream().filter(this::allowedQueryParameter)
|
||||
.iterator();
|
||||
Iterator<QueryParameter> iterator = queryParameters.getParameters()
|
||||
.stream()
|
||||
.filter(this::allowedQueryParameter)
|
||||
.iterator();
|
||||
while (iterator.hasNext()) {
|
||||
QueryParameter param = iterator.next();
|
||||
String queryParamValue = getQueryParamValue(param);
|
||||
|
||||
@@ -37,12 +37,12 @@ class JaxRsWhen implements When, BodyMethodVisitor, JaxRsAcceptor {
|
||||
this.generatedClassMetaData = generatedClassMetaData;
|
||||
this.bodyParser = bodyParser;
|
||||
this.whens
|
||||
.addAll(Arrays.asList(new JaxRsUrlPathWhen(this.blockBuilder, this.generatedClassMetaData, bodyParser),
|
||||
new JaxRsRequestWhen(this.blockBuilder, this.generatedClassMetaData),
|
||||
new JaxRsRequestHeadersWhen(this.blockBuilder, bodyParser),
|
||||
new JaxRsRequestCookiesWhen(this.blockBuilder, bodyParser),
|
||||
new JaxRsRequestMethodWhen(this.blockBuilder, this.generatedClassMetaData),
|
||||
new JaxRsRequestInvokerWhen(this.blockBuilder)));
|
||||
.addAll(Arrays.asList(new JaxRsUrlPathWhen(this.blockBuilder, this.generatedClassMetaData, bodyParser),
|
||||
new JaxRsRequestWhen(this.blockBuilder, this.generatedClassMetaData),
|
||||
new JaxRsRequestHeadersWhen(this.blockBuilder, bodyParser),
|
||||
new JaxRsRequestCookiesWhen(this.blockBuilder, bodyParser),
|
||||
new JaxRsRequestMethodWhen(this.blockBuilder, this.generatedClassMetaData),
|
||||
new JaxRsRequestInvokerWhen(this.blockBuilder)));
|
||||
}
|
||||
|
||||
@Override
|
||||
|
||||
@@ -110,7 +110,7 @@ class JsonBodyVerificationBuilder implements BodyMethodGeneration, ClassVerifier
|
||||
convertedResponseBody = MapConverter.transformValues(convertedResponseBody,
|
||||
returnReferencedEntries(templateModel), parsingFunction);
|
||||
JsonPaths jsonPaths = new JsonToJsonPathsConverter(assertJsonSize)
|
||||
.transformToJsonPathWithTestsSideValues(convertedResponseBody, parsingFunction, includeEmptyCheck);
|
||||
.transformToJsonPathWithTestsSideValues(convertedResponseBody, parsingFunction, includeEmptyCheck);
|
||||
|
||||
DocumentContext finalParsedRequestBody = parsedRequestBody;
|
||||
jsonPaths.forEach(it -> {
|
||||
@@ -214,12 +214,10 @@ class JsonBodyVerificationBuilder implements BodyMethodGeneration, ClassVerifier
|
||||
Object object = parsedRequestBody.read(jsonPathEntry);
|
||||
if (!(object instanceof String)) {
|
||||
return method
|
||||
.replace('"' + contractTemplate.escapedOpeningTemplate(),
|
||||
contractTemplate.escapedOpeningTemplate())
|
||||
.replace(contractTemplate.escapedClosingTemplate() + '"',
|
||||
contractTemplate.escapedClosingTemplate())
|
||||
.replace('"' + contractTemplate.openingTemplate(), contractTemplate.openingTemplate())
|
||||
.replace(contractTemplate.closingTemplate() + '"', contractTemplate.closingTemplate());
|
||||
.replace('"' + contractTemplate.escapedOpeningTemplate(), contractTemplate.escapedOpeningTemplate())
|
||||
.replace(contractTemplate.escapedClosingTemplate() + '"', contractTemplate.escapedClosingTemplate())
|
||||
.replace('"' + contractTemplate.openingTemplate(), contractTemplate.openingTemplate())
|
||||
.replace(contractTemplate.closingTemplate() + '"', contractTemplate.closingTemplate());
|
||||
}
|
||||
}
|
||||
return method;
|
||||
|
||||
@@ -41,8 +41,10 @@ class JsonPathImports implements Imports {
|
||||
|
||||
@Override
|
||||
public boolean accept() {
|
||||
return this.generatedClassMetaData.listOfFiles.stream().anyMatch(metadata -> metadata
|
||||
.getConvertedContractWithMetadata().stream().anyMatch(SingleContractMetadata::isJson));
|
||||
return this.generatedClassMetaData.listOfFiles.stream()
|
||||
.anyMatch(metadata -> metadata.getConvertedContractWithMetadata()
|
||||
.stream()
|
||||
.anyMatch(SingleContractMetadata::isJson));
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
@@ -29,7 +29,7 @@ class MessagingAssertThatThen implements Then {
|
||||
@Override
|
||||
public MethodVisitor<Then> apply(SingleContractMetadata metadata) {
|
||||
this.blockBuilder
|
||||
.addLineWithEnding(metadata.getContract().getOutputMessage().getAssertThat().getExecutionCommand());
|
||||
.addLineWithEnding(metadata.getContract().getOutputMessage().getAssertThat().getExecutionCommand());
|
||||
return this;
|
||||
}
|
||||
|
||||
|
||||
@@ -50,8 +50,9 @@ class MessagingBodyThen implements Then, BodyMethodVisitor {
|
||||
public MethodVisitor<Then> apply(SingleContractMetadata singleContractMetadata) {
|
||||
endBodyBlock(this.blockBuilder);
|
||||
startBodyBlock(this.blockBuilder, "and:");
|
||||
this.thens.stream().filter(then -> then.accept(singleContractMetadata))
|
||||
.forEach(then -> then.apply(singleContractMetadata));
|
||||
this.thens.stream()
|
||||
.filter(then -> then.accept(singleContractMetadata))
|
||||
.forEach(then -> then.apply(singleContractMetadata));
|
||||
return this;
|
||||
}
|
||||
|
||||
|
||||
@@ -42,8 +42,10 @@ class MessagingFields implements Field {
|
||||
|
||||
@Override
|
||||
public boolean accept() {
|
||||
return this.generatedClassMetaData.listOfFiles.stream().anyMatch(metadata -> metadata
|
||||
.getConvertedContractWithMetadata().stream().anyMatch(SingleContractMetadata::isMessaging));
|
||||
return this.generatedClassMetaData.listOfFiles.stream()
|
||||
.anyMatch(metadata -> metadata.getConvertedContractWithMetadata()
|
||||
.stream()
|
||||
.anyMatch(SingleContractMetadata::isMessaging));
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
@@ -52,8 +52,8 @@ class MessagingHeadersThen implements Then, BodyMethodVisitor {
|
||||
}
|
||||
|
||||
private void appendLineWithHeaderNotNull(String property) {
|
||||
this.blockBuilder.addLineWithEnding(
|
||||
this.comparisonBuilder.assertThatIsNotNull("response.getHeader(\"" + property + "\")"));
|
||||
this.blockBuilder
|
||||
.addLineWithEnding(this.comparisonBuilder.assertThatIsNotNull("response.getHeader(\"" + property + "\")"));
|
||||
}
|
||||
|
||||
private void processHeaderElement(String property, Object value) {
|
||||
@@ -79,8 +79,8 @@ class MessagingHeadersThen implements Then, BodyMethodVisitor {
|
||||
|
||||
private void processHeaderElement(String property, Number value) {
|
||||
appendLineWithHeaderNotNull(property);
|
||||
blockBuilder.addLineWithEnding(
|
||||
this.comparisonBuilder.assertThat("response.getHeader(\"" + property + "\")", value));
|
||||
blockBuilder
|
||||
.addLineWithEnding(this.comparisonBuilder.assertThat("response.getHeader(\"" + property + "\")", value));
|
||||
}
|
||||
|
||||
private void processHeaderElement(String property, Pattern pattern) {
|
||||
|
||||
@@ -44,8 +44,10 @@ class MessagingImports implements Imports {
|
||||
|
||||
@Override
|
||||
public boolean accept() {
|
||||
return this.generatedClassMetaData.listOfFiles.stream().anyMatch(metadata -> metadata
|
||||
.getConvertedContractWithMetadata().stream().anyMatch(SingleContractMetadata::isMessaging));
|
||||
return this.generatedClassMetaData.listOfFiles.stream()
|
||||
.anyMatch(metadata -> metadata.getConvertedContractWithMetadata()
|
||||
.stream()
|
||||
.anyMatch(SingleContractMetadata::isMessaging));
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
@@ -43,11 +43,14 @@ class MessagingReceiveMessageThen implements Then, BodyMethodVisitor {
|
||||
OutputMessage outputMessage = singleContractMetadata.getContract().getOutputMessage();
|
||||
this.bodyReader.storeContractAsYaml(singleContractMetadata);
|
||||
this.blockBuilder
|
||||
.addIndented("ContractVerifierMessage response = contractVerifierMessaging.receive("
|
||||
+ sentToValue(outputMessage.getSentTo().getServerValue()) + ",")
|
||||
.addEmptyLine().indent()
|
||||
.addIndented("contract(this, \"" + singleContractMetadata.methodName() + ".yml\"))").unindent()
|
||||
.addEndingIfNotPresent().addEmptyLine();
|
||||
.addIndented("ContractVerifierMessage response = contractVerifierMessaging.receive("
|
||||
+ sentToValue(outputMessage.getSentTo().getServerValue()) + ",")
|
||||
.addEmptyLine()
|
||||
.indent()
|
||||
.addIndented("contract(this, \"" + singleContractMetadata.methodName() + ".yml\"))")
|
||||
.unindent()
|
||||
.addEndingIfNotPresent()
|
||||
.addEmptyLine();
|
||||
this.blockBuilder.addLineWithEnding(this.comparisonBuilder.assertThatIsNotNull("response"));
|
||||
return this;
|
||||
}
|
||||
|
||||
@@ -43,8 +43,10 @@ class MessagingStaticImports implements Imports {
|
||||
|
||||
@Override
|
||||
public boolean accept() {
|
||||
return this.generatedClassMetaData.listOfFiles.stream().anyMatch(metadata -> metadata
|
||||
.getConvertedContractWithMetadata().stream().anyMatch(SingleContractMetadata::isMessaging));
|
||||
return this.generatedClassMetaData.listOfFiles.stream()
|
||||
.anyMatch(metadata -> metadata.getConvertedContractWithMetadata()
|
||||
.stream()
|
||||
.anyMatch(SingleContractMetadata::isMessaging));
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
@@ -29,7 +29,7 @@ class MessagingTriggeredByWhen implements When {
|
||||
@Override
|
||||
public MethodVisitor<When> apply(SingleContractMetadata metadata) {
|
||||
this.blockBuilder.addIndented(metadata.getContract().getInput().getTriggeredBy().getExecutionCommand())
|
||||
.addEndingIfNotPresent();
|
||||
.addEndingIfNotPresent();
|
||||
return this;
|
||||
}
|
||||
|
||||
|
||||
@@ -58,7 +58,7 @@ class MockMvcHeadersGiven implements Given {
|
||||
private String string(Header header) {
|
||||
return ".header("
|
||||
+ ContentHelper.getTestSideForNonBodyValue(header.getName()) + ", " + ContentHelper
|
||||
.getTestSideForNonBodyValue(MapConverter.getTestSideValuesForNonBody(header.getServerValue()))
|
||||
.getTestSideForNonBodyValue(MapConverter.getTestSideValuesForNonBody(header.getServerValue()))
|
||||
+ ")";
|
||||
}
|
||||
|
||||
|
||||
@@ -60,8 +60,11 @@ class MockMvcQueryParamsWhen implements When, MockMvcAcceptor, QueryParamsResolv
|
||||
}
|
||||
|
||||
private void addQueryParameters(Url buildUrl) {
|
||||
List<QueryParameter> queryParameters = buildUrl.getQueryParameters().getParameters().stream()
|
||||
.filter(this::allowedQueryParameter).collect(Collectors.toList());
|
||||
List<QueryParameter> queryParameters = buildUrl.getQueryParameters()
|
||||
.getParameters()
|
||||
.stream()
|
||||
.filter(this::allowedQueryParameter)
|
||||
.collect(Collectors.toList());
|
||||
Iterator<QueryParameter> iterator = queryParameters.iterator();
|
||||
while (iterator.hasNext()) {
|
||||
QueryParameter parameter = iterator.next();
|
||||
|
||||
@@ -40,12 +40,12 @@ class RestAssuredGiven implements Given, BodyMethodVisitor, RestAssuredAcceptor
|
||||
new ExplicitRequestGiven(blockBuilder, generatedClassMetaData),
|
||||
new WebTestClientRequestGiven(blockBuilder, generatedClassMetaData)));
|
||||
this.bodyGivens
|
||||
.addAll(Arrays.asList(new MockMvcHeadersGiven(blockBuilder), new MockMvcCookiesGiven(blockBuilder),
|
||||
new MockMvcBodyGiven(blockBuilder, generatedClassMetaData, bodyParser),
|
||||
new JavaMultipartGiven(blockBuilder, generatedClassMetaData, bodyParser),
|
||||
new SpockMockMvcMultipartGiven(blockBuilder, generatedClassMetaData, bodyParser),
|
||||
new SpockExplicitMultipartGiven(blockBuilder, generatedClassMetaData, bodyParser),
|
||||
new SpockWebTestClientMultipartGiven(blockBuilder, generatedClassMetaData, bodyParser)));
|
||||
.addAll(Arrays.asList(new MockMvcHeadersGiven(blockBuilder), new MockMvcCookiesGiven(blockBuilder),
|
||||
new MockMvcBodyGiven(blockBuilder, generatedClassMetaData, bodyParser),
|
||||
new JavaMultipartGiven(blockBuilder, generatedClassMetaData, bodyParser),
|
||||
new SpockMockMvcMultipartGiven(blockBuilder, generatedClassMetaData, bodyParser),
|
||||
new SpockExplicitMultipartGiven(blockBuilder, generatedClassMetaData, bodyParser),
|
||||
new SpockWebTestClientMultipartGiven(blockBuilder, generatedClassMetaData, bodyParser)));
|
||||
}
|
||||
|
||||
@Override
|
||||
@@ -58,9 +58,12 @@ class RestAssuredGiven implements Given, BodyMethodVisitor, RestAssuredAcceptor
|
||||
}
|
||||
|
||||
private void addRequestGivenLine(SingleContractMetadata singleContractMetadata) {
|
||||
this.requestGivens.stream().filter(given -> given.accept(singleContractMetadata)).findFirst().orElseThrow(
|
||||
() -> new IllegalStateException("No matching request building Given implementation for Rest Assured"))
|
||||
.apply(singleContractMetadata);
|
||||
this.requestGivens.stream()
|
||||
.filter(given -> given.accept(singleContractMetadata))
|
||||
.findFirst()
|
||||
.orElseThrow(() -> new IllegalStateException(
|
||||
"No matching request building Given implementation for Rest Assured"))
|
||||
.apply(singleContractMetadata);
|
||||
}
|
||||
|
||||
@Override
|
||||
|
||||
@@ -33,9 +33,10 @@ class RestAssuredStatusCodeThen implements Then {
|
||||
@Override
|
||||
public MethodVisitor<Then> apply(SingleContractMetadata metadata) {
|
||||
Response response = metadata.getContract().getResponse();
|
||||
this.blockBuilder.addIndented(
|
||||
this.comparisonBuilder.assertThat("response.statusCode()", response.getStatus().getServerValue()))
|
||||
.addEndingIfNotPresent();
|
||||
this.blockBuilder
|
||||
.addIndented(
|
||||
this.comparisonBuilder.assertThat("response.statusCode()", response.getStatus().getServerValue()))
|
||||
.addEndingIfNotPresent();
|
||||
return this;
|
||||
}
|
||||
|
||||
|
||||
@@ -54,9 +54,12 @@ class RestAssuredWhen implements When, BodyMethodVisitor, RestAssuredAcceptor {
|
||||
}
|
||||
|
||||
private void addResponseWhenLine(SingleContractMetadata singleContractMetadata) {
|
||||
this.responseWhens.stream().filter(when -> when.accept(singleContractMetadata)).findFirst().orElseThrow(
|
||||
() -> new IllegalStateException("No matching request building When implementation for Rest Assured"))
|
||||
.apply(singleContractMetadata);
|
||||
this.responseWhens.stream()
|
||||
.filter(when -> when.accept(singleContractMetadata))
|
||||
.findFirst()
|
||||
.orElseThrow(() -> new IllegalStateException(
|
||||
"No matching request building When implementation for Rest Assured"))
|
||||
.apply(singleContractMetadata);
|
||||
}
|
||||
|
||||
@Override
|
||||
|
||||
@@ -90,29 +90,29 @@ class SingleMethodBuilder {
|
||||
|
||||
SingleMethodBuilder restAssured() {
|
||||
return given(new JavaRestAssuredGiven(this.blockBuilder, this.generatedClassMetaData))
|
||||
.given(new SpockRestAssuredGiven(this.blockBuilder, this.generatedClassMetaData))
|
||||
.when(new JavaRestAssuredWhen(this.blockBuilder, this.generatedClassMetaData))
|
||||
.when(new SpockRestAssuredWhen(this.blockBuilder, this.generatedClassMetaData))
|
||||
.then(new JavaRestAssuredThen(this.blockBuilder, this.generatedClassMetaData))
|
||||
.then(new SpockRestAssuredThen(this.blockBuilder, this.generatedClassMetaData))
|
||||
.methodPostProcessor(new TemplateUpdatingMethodPostProcessor(this.blockBuilder));
|
||||
.given(new SpockRestAssuredGiven(this.blockBuilder, this.generatedClassMetaData))
|
||||
.when(new JavaRestAssuredWhen(this.blockBuilder, this.generatedClassMetaData))
|
||||
.when(new SpockRestAssuredWhen(this.blockBuilder, this.generatedClassMetaData))
|
||||
.then(new JavaRestAssuredThen(this.blockBuilder, this.generatedClassMetaData))
|
||||
.then(new SpockRestAssuredThen(this.blockBuilder, this.generatedClassMetaData))
|
||||
.methodPostProcessor(new TemplateUpdatingMethodPostProcessor(this.blockBuilder));
|
||||
}
|
||||
|
||||
SingleMethodBuilder customMode() {
|
||||
return given(new CustomModeGiven(this.blockBuilder, this.generatedClassMetaData, CustomModeBodyParser.INSTANCE))
|
||||
.when(new CustomModeWhen(this.blockBuilder, this.generatedClassMetaData))
|
||||
.then(new CustomModeThen(this.blockBuilder, this.generatedClassMetaData, CustomModeBodyParser.INSTANCE,
|
||||
ComparisonBuilder.JAVA_HTTP_INSTANCE))
|
||||
.methodPostProcessor(new TemplateUpdatingMethodPostProcessor(this.blockBuilder));
|
||||
.when(new CustomModeWhen(this.blockBuilder, this.generatedClassMetaData))
|
||||
.then(new CustomModeThen(this.blockBuilder, this.generatedClassMetaData, CustomModeBodyParser.INSTANCE,
|
||||
ComparisonBuilder.JAVA_HTTP_INSTANCE))
|
||||
.methodPostProcessor(new TemplateUpdatingMethodPostProcessor(this.blockBuilder));
|
||||
}
|
||||
|
||||
SingleMethodBuilder jaxRs() {
|
||||
return given(new JaxRsGiven(this.generatedClassMetaData))
|
||||
.when(new JavaJaxRsWhen(this.blockBuilder, this.generatedClassMetaData))
|
||||
.when(new SpockJaxRsWhen(this.blockBuilder, this.generatedClassMetaData))
|
||||
.then(new JavaJaxRsThen(this.blockBuilder, this.generatedClassMetaData))
|
||||
.then(new SpockJaxRsThen(this.blockBuilder, this.generatedClassMetaData))
|
||||
.methodPostProcessor(new TemplateUpdatingMethodPostProcessor(this.blockBuilder));
|
||||
.when(new JavaJaxRsWhen(this.blockBuilder, this.generatedClassMetaData))
|
||||
.when(new SpockJaxRsWhen(this.blockBuilder, this.generatedClassMetaData))
|
||||
.then(new JavaJaxRsThen(this.blockBuilder, this.generatedClassMetaData))
|
||||
.then(new SpockJaxRsThen(this.blockBuilder, this.generatedClassMetaData))
|
||||
.methodPostProcessor(new TemplateUpdatingMethodPostProcessor(this.blockBuilder));
|
||||
}
|
||||
|
||||
SingleMethodBuilder messaging() {
|
||||
@@ -205,14 +205,17 @@ class SingleMethodBuilder {
|
||||
|
||||
private boolean shouldStopProcessing(SingleContractMetadata metaData) {
|
||||
List<MethodPreProcessor> matchingPreProcessors = this.methodPreProcessors.stream()
|
||||
.filter(m -> m.accept(metaData)).collect(Collectors.toCollection(LinkedList::new));
|
||||
.filter(m -> m.accept(metaData))
|
||||
.collect(Collectors.toCollection(LinkedList::new));
|
||||
matchingPreProcessors.forEach(m -> m.apply(metaData));
|
||||
return matchingPreProcessors.stream().anyMatch(m -> !m.shouldContinue());
|
||||
}
|
||||
|
||||
private MethodMetadata pickMetadatum() {
|
||||
return this.methodMetadata.stream().filter(Acceptor::accept).findFirst()
|
||||
.orElseThrow(() -> new IllegalStateException("No matching method metadata found"));
|
||||
return this.methodMetadata.stream()
|
||||
.filter(Acceptor::accept)
|
||||
.findFirst()
|
||||
.orElseThrow(() -> new IllegalStateException("No matching method metadata found"));
|
||||
}
|
||||
|
||||
private boolean visit(List<? extends MethodVisitor> list, SingleContractMetadata metaData) {
|
||||
@@ -220,8 +223,9 @@ class SingleMethodBuilder {
|
||||
}
|
||||
|
||||
private boolean visit(List<? extends MethodVisitor> list, SingleContractMetadata metaData, boolean addLineEnding) {
|
||||
List<? extends MethodVisitor> visitors = list.stream().filter(o -> o.accept(metaData))
|
||||
.collect(Collectors.toList());
|
||||
List<? extends MethodVisitor> visitors = list.stream()
|
||||
.filter(o -> o.accept(metaData))
|
||||
.collect(Collectors.toList());
|
||||
Iterator<? extends MethodVisitor> iterator = visitors.iterator();
|
||||
while (iterator.hasNext()) {
|
||||
MethodVisitor visitor = iterator.next();
|
||||
|
||||
@@ -30,7 +30,7 @@ class SpockExplicitMultipartGiven implements Given, ExplicitAcceptor {
|
||||
@Override
|
||||
public MethodVisitor<Given> apply(SingleContractMetadata metadata) {
|
||||
getMultipartParameters(metadata).entrySet()
|
||||
.forEach(entry -> this.blockBuilder.addLine(getMultipartParameterLine(metadata, entry)));
|
||||
.forEach(entry -> this.blockBuilder.addLine(getMultipartParameterLine(metadata, entry)));
|
||||
return this;
|
||||
}
|
||||
|
||||
|
||||
@@ -39,8 +39,9 @@ class SpockIgnoreImports implements Imports {
|
||||
public boolean accept() {
|
||||
return this.generatedClassMetaData.configProperties.getTestFramework() == TestFramework.SPOCK
|
||||
&& this.generatedClassMetaData.listOfFiles.stream()
|
||||
.anyMatch(metadata -> metadata.isIgnored() || metadata.getConvertedContractWithMetadata()
|
||||
.stream().anyMatch(m -> m.isIgnored() || m.isInProgress()));
|
||||
.anyMatch(metadata -> metadata.isIgnored() || metadata.getConvertedContractWithMetadata()
|
||||
.stream()
|
||||
.anyMatch(m -> m.isIgnored() || m.isInProgress()));
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
@@ -46,7 +46,7 @@ class SpockMockMvcMultipartGiven implements Given, MockMvcAcceptor {
|
||||
@Override
|
||||
public MethodVisitor<Given> apply(SingleContractMetadata metadata) {
|
||||
getMultipartParameters(metadata).entrySet()
|
||||
.forEach(entry -> this.blockBuilder.addLine(getMultipartParameterLine(metadata, entry)));
|
||||
.forEach(entry -> this.blockBuilder.addLine(getMultipartParameterLine(metadata, entry)));
|
||||
return this;
|
||||
}
|
||||
|
||||
|
||||
@@ -30,7 +30,7 @@ public class SpockWebTestClientMultipartGiven implements Given, WebTestClientAcc
|
||||
@Override
|
||||
public MethodVisitor<Given> apply(SingleContractMetadata metadata) {
|
||||
getMultipartParameters(metadata).entrySet()
|
||||
.forEach(entry -> this.blockBuilder.addLine(getMultipartParameterLine(metadata, entry)));
|
||||
.forEach(entry -> this.blockBuilder.addLine(getMultipartParameterLine(metadata, entry)));
|
||||
return this;
|
||||
}
|
||||
|
||||
|
||||
@@ -133,19 +133,22 @@ public class TestSideRequestTemplateModel {
|
||||
if (!headersEntriesPresent) {
|
||||
return new HashMap<>();
|
||||
}
|
||||
return new HashMap<>(request.getHeaders().getEntries().stream()
|
||||
.collect(Collectors.groupingBy(Header::getName,
|
||||
Collectors.mapping((Function<Object, String>) o -> MapConverter.getTestSideValues(o).toString(),
|
||||
Collectors.toList()))));
|
||||
return new HashMap<>(request.getHeaders()
|
||||
.getEntries()
|
||||
.stream()
|
||||
.collect(Collectors.groupingBy(Header::getName,
|
||||
Collectors.mapping((Function<Object, String>) o -> MapConverter.getTestSideValues(o).toString(),
|
||||
Collectors.toList()))));
|
||||
}
|
||||
|
||||
private static String fullUrl(String url, Map<String, List<Object>> query, boolean queryParamsPresent) {
|
||||
if (queryParamsPresent) {
|
||||
return url;
|
||||
}
|
||||
String joinedParams = query.entrySet().stream().map(
|
||||
entry -> entry.getValue().stream().map(s -> entry.getKey() + "=" + s).collect(Collectors.joining("&")))
|
||||
.collect(Collectors.joining("&"));
|
||||
String joinedParams = query.entrySet()
|
||||
.stream()
|
||||
.map(entry -> entry.getValue().stream().map(s -> entry.getKey() + "=" + s).collect(Collectors.joining("&")))
|
||||
.collect(Collectors.joining("&"));
|
||||
return url + "?" + joinedParams;
|
||||
}
|
||||
|
||||
@@ -153,8 +156,10 @@ public class TestSideRequestTemplateModel {
|
||||
if (queryParameters == null) {
|
||||
return new HashMap<>();
|
||||
}
|
||||
return new HashMap<>(queryParameters.getParameters().stream().collect(Collectors.groupingBy(
|
||||
QueryParameter::getName, Collectors.mapping(MapConverter::getTestSideValues, Collectors.toList()))));
|
||||
return new HashMap<>(queryParameters.getParameters()
|
||||
.stream()
|
||||
.collect(Collectors.groupingBy(QueryParameter::getName,
|
||||
Collectors.mapping(MapConverter::getTestSideValues, Collectors.toList()))));
|
||||
}
|
||||
|
||||
private static List<String> buildPathsFromUrl(String url) {
|
||||
|
||||
Some files were not shown because too many files have changed in this diff Show More
Reference in New Issue
Block a user