Bumping versions
This commit is contained in:
@@ -66,37 +66,32 @@ public class RecursiveFilesConverter {
|
||||
private final boolean excludeBuildFolders;
|
||||
|
||||
@Deprecated
|
||||
public RecursiveFilesConverter(ContractVerifierConfigProperties props,
|
||||
StubGeneratorProvider holder) {
|
||||
this(props.getStubsOutputDir(), props.getContractsDslDir(),
|
||||
props.getExcludedFiles(), props.getIncludedContracts(),
|
||||
props.getExcludeBuildFolders(), holder);
|
||||
public RecursiveFilesConverter(ContractVerifierConfigProperties props, StubGeneratorProvider holder) {
|
||||
this(props.getStubsOutputDir(), props.getContractsDslDir(), props.getExcludedFiles(),
|
||||
props.getIncludedContracts(), props.getExcludeBuildFolders(), holder);
|
||||
}
|
||||
|
||||
@Deprecated
|
||||
public RecursiveFilesConverter(ContractVerifierConfigProperties props) {
|
||||
this(props.getStubsOutputDir(), props.getContractsDslDir(),
|
||||
props.getExcludedFiles(), props.getIncludedContracts(),
|
||||
props.getExcludeBuildFolders(), null);
|
||||
}
|
||||
|
||||
@Deprecated
|
||||
public RecursiveFilesConverter(ContractVerifierConfigProperties props,
|
||||
File stubsOutputDir) {
|
||||
this(stubsOutputDir, props.getContractsDslDir(), props.getExcludedFiles(),
|
||||
this(props.getStubsOutputDir(), props.getContractsDslDir(), props.getExcludedFiles(),
|
||||
props.getIncludedContracts(), props.getExcludeBuildFolders(), null);
|
||||
}
|
||||
|
||||
@Deprecated
|
||||
public RecursiveFilesConverter(ContractVerifierConfigProperties props,
|
||||
File stubsOutputDir, StubGeneratorProvider holder) {
|
||||
this(stubsOutputDir, props.getContractsDslDir(), props.getExcludedFiles(),
|
||||
props.getIncludedContracts(), props.getExcludeBuildFolders(), holder);
|
||||
public RecursiveFilesConverter(ContractVerifierConfigProperties props, File stubsOutputDir) {
|
||||
this(stubsOutputDir, props.getContractsDslDir(), props.getExcludedFiles(), props.getIncludedContracts(),
|
||||
props.getExcludeBuildFolders(), null);
|
||||
}
|
||||
|
||||
public RecursiveFilesConverter(File stubsOutputDir, File contractsDslDir,
|
||||
List<String> excludedFiles, String includedContracts,
|
||||
boolean excludeBuildFolders, StubGeneratorProvider holder) {
|
||||
@Deprecated
|
||||
public RecursiveFilesConverter(ContractVerifierConfigProperties props, File stubsOutputDir,
|
||||
StubGeneratorProvider holder) {
|
||||
this(stubsOutputDir, props.getContractsDslDir(), props.getExcludedFiles(), props.getIncludedContracts(),
|
||||
props.getExcludeBuildFolders(), holder);
|
||||
}
|
||||
|
||||
public RecursiveFilesConverter(File stubsOutputDir, File contractsDslDir, List<String> excludedFiles,
|
||||
String includedContracts, boolean excludeBuildFolders, StubGeneratorProvider holder) {
|
||||
this.outMappingsDir = stubsOutputDir;
|
||||
this.contractsDslDir = contractsDslDir;
|
||||
this.excludedFiles = excludedFiles;
|
||||
@@ -105,20 +100,16 @@ public class RecursiveFilesConverter {
|
||||
this.holder = holder == null ? new StubGeneratorProvider() : holder;
|
||||
}
|
||||
|
||||
public RecursiveFilesConverter(File stubsOutputDir, File contractsDslDir,
|
||||
List<String> excludedFiles, String includedContracts,
|
||||
boolean excludeBuildFolders) {
|
||||
this(stubsOutputDir, contractsDslDir, excludedFiles, includedContracts,
|
||||
excludeBuildFolders, null);
|
||||
public RecursiveFilesConverter(File stubsOutputDir, File contractsDslDir, List<String> excludedFiles,
|
||||
String includedContracts, boolean excludeBuildFolders) {
|
||||
this(stubsOutputDir, contractsDslDir, excludedFiles, includedContracts, excludeBuildFolders, null);
|
||||
}
|
||||
|
||||
public void processFiles() {
|
||||
ContractFileScanner scanner = new ContractFileScannerBuilder()
|
||||
.baseDir(contractsDslDir).excluded(new HashSet<>(excludedFiles))
|
||||
.ignored(new HashSet<>()).included(new HashSet<>())
|
||||
ContractFileScanner scanner = new ContractFileScannerBuilder().baseDir(contractsDslDir)
|
||||
.excluded(new HashSet<>(excludedFiles)).ignored(new HashSet<>()).included(new HashSet<>())
|
||||
.includeMatcher(includedContracts).build();
|
||||
MultiValueMap<Path, ContractMetadata> contracts = scanner
|
||||
.findContractsRecursively();
|
||||
MultiValueMap<Path, ContractMetadata> contracts = scanner.findContractsRecursively();
|
||||
if (log.isDebugEnabled()) {
|
||||
log.debug("Found the following contracts " + contracts);
|
||||
}
|
||||
@@ -128,14 +119,12 @@ public class RecursiveFilesConverter {
|
||||
log.debug("Will create a stub for contract [" + contract + "]");
|
||||
}
|
||||
File sourceFile = contract.getPath().toFile();
|
||||
Collection<StubGenerator> stubGenerators = contract
|
||||
.getConvertedContract() != null
|
||||
? holder.allOrDefault(new DslToWireMockClientConverter())
|
||||
: holder.converterForName(sourceFile.getName());
|
||||
Collection<StubGenerator> stubGenerators = contract.getConvertedContract() != null
|
||||
? holder.allOrDefault(new DslToWireMockClientConverter())
|
||||
: holder.converterForName(sourceFile.getName());
|
||||
try {
|
||||
String path = sourceFile.getPath();
|
||||
if (excludeBuildFolders && (matchesPath(path, "target")
|
||||
|| matchesPath(path, "build"))) {
|
||||
if (excludeBuildFolders && (matchesPath(path, "target") || matchesPath(path, "build"))) {
|
||||
if (log.isDebugEnabled()) {
|
||||
log.debug("Exclude build folder is set. Path [" + path
|
||||
+ "] contains [target] or [build] in its path");
|
||||
@@ -149,8 +138,8 @@ public class RecursiveFilesConverter {
|
||||
int contractsSize = contract.getConvertedContract().size();
|
||||
Path entryKey = entry.getKey();
|
||||
if (log.isDebugEnabled()) {
|
||||
log.debug("Stub Generators [" + stubGenerators
|
||||
+ "] will convert contents of [" + entryKey + "]");
|
||||
log.debug(
|
||||
"Stub Generators [" + stubGenerators + "] will convert contents of [" + entryKey + "]");
|
||||
}
|
||||
|
||||
for (StubGenerator stubGenerator : stubGenerators) {
|
||||
@@ -159,23 +148,18 @@ public class RecursiveFilesConverter {
|
||||
if (convertedContent == null || convertedContent.isEmpty()) {
|
||||
continue;
|
||||
}
|
||||
Set<Map.Entry<Contract, String>> entrySet = convertedContent
|
||||
.entrySet();
|
||||
Iterator<Map.Entry<Contract, String>> iterator = entrySet
|
||||
.iterator();
|
||||
Set<Map.Entry<Contract, String>> entrySet = convertedContent.entrySet();
|
||||
Iterator<Map.Entry<Contract, String>> iterator = entrySet.iterator();
|
||||
int index = 0;
|
||||
while (iterator.hasNext()) {
|
||||
Map.Entry<Contract, String> content = iterator.next();
|
||||
Contract dsl = content.getKey();
|
||||
String converted = content.getValue();
|
||||
if (StringUtils.hasText(converted)) {
|
||||
Path absoluteTargetPath = createAndReturnTargetDirectory(
|
||||
sourceFile);
|
||||
File newJsonFile = createTargetFileWithProperName(
|
||||
stubGenerator, absoluteTargetPath, sourceFile,
|
||||
contractsSize, index, dsl);
|
||||
Files.write(newJsonFile.toPath(),
|
||||
Collections.singletonList(converted),
|
||||
Path absoluteTargetPath = createAndReturnTargetDirectory(sourceFile);
|
||||
File newJsonFile = createTargetFileWithProperName(stubGenerator, absoluteTargetPath,
|
||||
sourceFile, contractsSize, index, dsl);
|
||||
Files.write(newJsonFile.toPath(), Collections.singletonList(converted),
|
||||
StandardCharsets.UTF_8);
|
||||
}
|
||||
index = index + 1;
|
||||
@@ -198,8 +182,7 @@ public class RecursiveFilesConverter {
|
||||
private static <T> T last(Iterable<T> self) {
|
||||
Iterator<T> iterator = self.iterator();
|
||||
if (!iterator.hasNext()) {
|
||||
throw new NoSuchElementException(
|
||||
"Cannot access last() element from an empty Iterable");
|
||||
throw new NoSuchElementException("Cannot access last() element from an empty Iterable");
|
||||
}
|
||||
T result = null;
|
||||
while (iterator.hasNext()) {
|
||||
@@ -209,8 +192,7 @@ public class RecursiveFilesConverter {
|
||||
}
|
||||
|
||||
private boolean nullOrEmpty(ContractMetadata contract) {
|
||||
return contract.getConvertedContract() == null
|
||||
|| nullOrEmpty(contract.getConvertedContract());
|
||||
return contract.getConvertedContract() == null || nullOrEmpty(contract.getConvertedContract());
|
||||
}
|
||||
|
||||
private boolean nullOrEmpty(Collection collection) {
|
||||
@@ -222,8 +204,7 @@ public class RecursiveFilesConverter {
|
||||
}
|
||||
|
||||
private Path createAndReturnTargetDirectory(File sourceFile) {
|
||||
Path relativePath = Paths.get(contractsDslDir.toURI())
|
||||
.relativize(sourceFile.getParentFile().toPath());
|
||||
Path relativePath = Paths.get(contractsDslDir.toURI()).relativize(sourceFile.getParentFile().toPath());
|
||||
Path absoluteTargetPath = outMappingsDir.toPath().resolve(relativePath);
|
||||
try {
|
||||
Files.createDirectories(absoluteTargetPath);
|
||||
@@ -234,19 +215,16 @@ public class RecursiveFilesConverter {
|
||||
return absoluteTargetPath;
|
||||
}
|
||||
|
||||
private File createTargetFileWithProperName(StubGenerator stubGenerator,
|
||||
Path absoluteTargetPath, File sourceFile, int contractsSize, int index,
|
||||
Contract dsl) {
|
||||
private File createTargetFileWithProperName(StubGenerator stubGenerator, Path absoluteTargetPath, File sourceFile,
|
||||
int contractsSize, int index, Contract dsl) {
|
||||
String name = generateName(dsl, contractsSize, stubGenerator, sourceFile, index);
|
||||
File newJsonFile = new File(absoluteTargetPath.toFile(), name);
|
||||
log.info("Creating new stub [" + newJsonFile.getPath() + "]");
|
||||
return newJsonFile;
|
||||
}
|
||||
|
||||
private String generateName(Contract dsl, int contractsSize, StubGenerator converter,
|
||||
File sourceFile, int index) {
|
||||
String generatedName = converter
|
||||
.generateOutputFileNameForInput(sourceFile.getName());
|
||||
private String generateName(Contract dsl, int contractsSize, StubGenerator converter, File sourceFile, int index) {
|
||||
String generatedName = converter.generateOutputFileNameForInput(sourceFile.getName());
|
||||
boolean hasDot = NamesUtil.hasDot(generatedName);
|
||||
String extension = hasDot ? NamesUtil.afterLastDot(generatedName) : "";
|
||||
if (StringUtils.hasText(dsl.getName()) && StringUtils.hasText(extension)) {
|
||||
|
||||
@@ -55,8 +55,8 @@ 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);
|
||||
}
|
||||
|
||||
@@ -33,8 +33,7 @@ import org.springframework.core.io.support.SpringFactoriesLoader;
|
||||
public class StubGeneratorProvider {
|
||||
|
||||
public StubGeneratorProvider() {
|
||||
this.converters
|
||||
.addAll(SpringFactoriesLoader.loadFactories(StubGenerator.class, null));
|
||||
this.converters.addAll(SpringFactoriesLoader.loadFactories(StubGenerator.class, null));
|
||||
}
|
||||
|
||||
public StubGeneratorProvider(List<StubGenerator> converters) {
|
||||
@@ -42,14 +41,12 @@ public class StubGeneratorProvider {
|
||||
}
|
||||
|
||||
public Collection<StubGenerator> converterForName(final String fileName) {
|
||||
return this.converters.stream()
|
||||
.filter(stubGenerator -> stubGenerator.canHandleFileName(fileName))
|
||||
return this.converters.stream().filter(stubGenerator -> stubGenerator.canHandleFileName(fileName))
|
||||
.collect(Collectors.toList());
|
||||
}
|
||||
|
||||
public Collection<StubGenerator> allOrDefault(StubGenerator defaultStubGenerator) {
|
||||
return this.converters.isEmpty() ? Collections.singletonList(defaultStubGenerator)
|
||||
: this.converters;
|
||||
return this.converters.isEmpty() ? Collections.singletonList(defaultStubGenerator) : this.converters;
|
||||
}
|
||||
|
||||
private final List<StubGenerator> converters = new ArrayList<StubGenerator>();
|
||||
|
||||
@@ -33,8 +33,7 @@ public interface StubPostProcessor<T> {
|
||||
/**
|
||||
* List of registered stub post processors.
|
||||
*/
|
||||
List<StubPostProcessor> PROCESSORS = SpringFactoriesLoader
|
||||
.loadFactories(StubPostProcessor.class, null);
|
||||
List<StubPostProcessor> PROCESSORS = SpringFactoriesLoader.loadFactories(StubPostProcessor.class, null);
|
||||
|
||||
/**
|
||||
* @param stubMapping - generated stub mapping
|
||||
|
||||
@@ -38,10 +38,8 @@ class DefaultWireMockStubPostProcessor implements WireMockStubPostProcessor {
|
||||
|
||||
@Override
|
||||
public StubMapping postProcess(StubMapping stubMapping, Contract contract) {
|
||||
WireMockMetaData wireMockMetaData = WireMockMetaData
|
||||
.fromMetadata(contract.getMetadata());
|
||||
StubMapping stubMappingFromMetadata = stubMappingFromMetadata(
|
||||
wireMockMetaData.getStubMapping());
|
||||
WireMockMetaData wireMockMetaData = WireMockMetaData.fromMetadata(contract.getMetadata());
|
||||
StubMapping stubMappingFromMetadata = stubMappingFromMetadata(wireMockMetaData.getStubMapping());
|
||||
stubMapping.setResponse(mergedResponse(stubMapping, stubMappingFromMetadata));
|
||||
if (stubMappingFromMetadata.getPostServeActions() != null) {
|
||||
setPostServeActions(stubMapping, stubMappingFromMetadata);
|
||||
@@ -52,94 +50,76 @@ class DefaultWireMockStubPostProcessor implements WireMockStubPostProcessor {
|
||||
return stubMapping;
|
||||
}
|
||||
|
||||
public void setPostServeActions(StubMapping stubMapping,
|
||||
StubMapping stubMappingFromMetadata) {
|
||||
public void setPostServeActions(StubMapping stubMapping, StubMapping stubMappingFromMetadata) {
|
||||
Map<String, Parameters> postServeActions = stubMapping.getPostServeActions();
|
||||
postServeActions = postServeActions != null ? postServeActions : new HashMap<>();
|
||||
postServeActions.putAll(stubMappingFromMetadata.getPostServeActions());
|
||||
stubMapping.setPostServeActions(postServeActions);
|
||||
}
|
||||
|
||||
public void setMetadata(StubMapping stubMapping,
|
||||
StubMapping stubMappingFromMetadata) {
|
||||
public void setMetadata(StubMapping stubMapping, StubMapping stubMappingFromMetadata) {
|
||||
Metadata metadata = stubMapping.getMetadata();
|
||||
metadata = metadata != null ? metadata : new Metadata();
|
||||
metadata.putAll(stubMappingFromMetadata.getPostServeActions());
|
||||
stubMapping.setMetadata(metadata);
|
||||
}
|
||||
|
||||
public ResponseDefinition mergedResponse(StubMapping stubMapping,
|
||||
StubMapping stubMappingFromMetadata) {
|
||||
ResponseDefinition responseDefinition = new ResponseDefinition(
|
||||
stubMapping.getResponse().getStatus(),
|
||||
stubMapping.getResponse().getStatusMessage(),
|
||||
stubMapping.getResponse().getBody(),
|
||||
stubMapping.getResponse().getJsonBody(),
|
||||
stubMapping.getResponse().getBase64Body(),
|
||||
stubMapping.getResponse().getBodyFileName(),
|
||||
stubMapping.getResponse().getHeaders(),
|
||||
public ResponseDefinition mergedResponse(StubMapping stubMapping, StubMapping stubMappingFromMetadata) {
|
||||
ResponseDefinition responseDefinition = new ResponseDefinition(stubMapping.getResponse().getStatus(),
|
||||
stubMapping.getResponse().getStatusMessage(), stubMapping.getResponse().getBody(),
|
||||
stubMapping.getResponse().getJsonBody(), stubMapping.getResponse().getBase64Body(),
|
||||
stubMapping.getResponse().getBodyFileName(), stubMapping.getResponse().getHeaders(),
|
||||
stubMapping.getResponse().getAdditionalProxyRequestHeaders(),
|
||||
fixedDelayMilliseconds(stubMapping, stubMappingFromMetadata),
|
||||
delayDistribution(stubMapping, stubMappingFromMetadata),
|
||||
chunkedDribbleDelay(stubMapping, stubMappingFromMetadata),
|
||||
proxyBaseUrl(stubMapping, stubMappingFromMetadata),
|
||||
fault(stubMapping, stubMappingFromMetadata),
|
||||
proxyBaseUrl(stubMapping, stubMappingFromMetadata), fault(stubMapping, stubMappingFromMetadata),
|
||||
transformers(stubMapping, stubMappingFromMetadata),
|
||||
transformerParameters(stubMapping, stubMappingFromMetadata),
|
||||
wasConfigured(stubMapping, stubMappingFromMetadata));
|
||||
return responseDefinition;
|
||||
}
|
||||
|
||||
public Boolean wasConfigured(StubMapping stubMapping,
|
||||
StubMapping stubMappingFromMetadata) {
|
||||
public Boolean wasConfigured(StubMapping stubMapping, StubMapping stubMappingFromMetadata) {
|
||||
return stubMappingFromMetadata.getResponse().isFromConfiguredStub() != null
|
||||
? stubMappingFromMetadata.getResponse().isFromConfiguredStub()
|
||||
: stubMapping.getResponse().isFromConfiguredStub();
|
||||
}
|
||||
|
||||
public Parameters transformerParameters(StubMapping stubMapping,
|
||||
StubMapping stubMappingFromMetadata) {
|
||||
public Parameters transformerParameters(StubMapping stubMapping, StubMapping stubMappingFromMetadata) {
|
||||
return stubMappingFromMetadata.getResponse().getTransformerParameters() != null
|
||||
? stubMappingFromMetadata.getResponse().getTransformerParameters()
|
||||
: stubMapping.getResponse().getTransformerParameters();
|
||||
}
|
||||
|
||||
public List<String> transformers(StubMapping stubMapping,
|
||||
StubMapping stubMappingFromMetadata) {
|
||||
public List<String> transformers(StubMapping stubMapping, StubMapping stubMappingFromMetadata) {
|
||||
return stubMappingFromMetadata.getResponse().getTransformers() != null
|
||||
? stubMappingFromMetadata.getResponse().getTransformers()
|
||||
: stubMapping.getResponse().getTransformers();
|
||||
? stubMappingFromMetadata.getResponse().getTransformers() : stubMapping.getResponse().getTransformers();
|
||||
}
|
||||
|
||||
public Fault fault(StubMapping stubMapping, StubMapping stubMappingFromMetadata) {
|
||||
return stubMappingFromMetadata.getResponse().getFault() != null
|
||||
? stubMappingFromMetadata.getResponse().getFault()
|
||||
: stubMapping.getResponse().getFault();
|
||||
? stubMappingFromMetadata.getResponse().getFault() : stubMapping.getResponse().getFault();
|
||||
}
|
||||
|
||||
public String proxyBaseUrl(StubMapping stubMapping,
|
||||
StubMapping stubMappingFromMetadata) {
|
||||
public String proxyBaseUrl(StubMapping stubMapping, StubMapping stubMappingFromMetadata) {
|
||||
return stubMappingFromMetadata.getResponse().getProxyBaseUrl() != null
|
||||
? stubMappingFromMetadata.getResponse().getProxyBaseUrl()
|
||||
: stubMapping.getResponse().getProxyBaseUrl();
|
||||
? stubMappingFromMetadata.getResponse().getProxyBaseUrl() : stubMapping.getResponse().getProxyBaseUrl();
|
||||
}
|
||||
|
||||
public ChunkedDribbleDelay chunkedDribbleDelay(StubMapping stubMapping,
|
||||
StubMapping stubMappingFromMetadata) {
|
||||
public ChunkedDribbleDelay chunkedDribbleDelay(StubMapping stubMapping, StubMapping stubMappingFromMetadata) {
|
||||
return stubMappingFromMetadata.getResponse().getChunkedDribbleDelay() != null
|
||||
? stubMappingFromMetadata.getResponse().getChunkedDribbleDelay()
|
||||
: stubMapping.getResponse().getChunkedDribbleDelay();
|
||||
}
|
||||
|
||||
public DelayDistribution delayDistribution(StubMapping stubMapping,
|
||||
StubMapping stubMappingFromMetadata) {
|
||||
public DelayDistribution delayDistribution(StubMapping stubMapping, StubMapping stubMappingFromMetadata) {
|
||||
return stubMappingFromMetadata.getResponse().getDelayDistribution() != null
|
||||
? stubMappingFromMetadata.getResponse().getDelayDistribution()
|
||||
: stubMapping.getResponse().getDelayDistribution();
|
||||
}
|
||||
|
||||
public Integer fixedDelayMilliseconds(StubMapping stubMapping,
|
||||
StubMapping stubMappingFromMetadata) {
|
||||
public Integer fixedDelayMilliseconds(StubMapping stubMapping, StubMapping stubMappingFromMetadata) {
|
||||
return stubMappingFromMetadata.getResponse().getFixedDelayMilliseconds() != null
|
||||
? stubMappingFromMetadata.getResponse().getFixedDelayMilliseconds()
|
||||
: stubMapping.getResponse().getFixedDelayMilliseconds();
|
||||
@@ -154,27 +134,22 @@ class DefaultWireMockStubPostProcessor implements WireMockStubPostProcessor {
|
||||
}
|
||||
else if (wiremock instanceof Map) {
|
||||
try {
|
||||
return StubMapping
|
||||
.buildFrom(this.objectMapper.writeValueAsString(wiremock));
|
||||
return StubMapping.buildFrom(this.objectMapper.writeValueAsString(wiremock));
|
||||
}
|
||||
catch (JsonProcessingException e) {
|
||||
throw new IllegalStateException(
|
||||
"Failed to build StubMapping for map [" + wiremock + "]", e);
|
||||
throw new IllegalStateException("Failed to build StubMapping for map [" + wiremock + "]", e);
|
||||
}
|
||||
}
|
||||
throw new UnsupportedOperationException(
|
||||
"Unsupported type for wiremock metadata extension");
|
||||
throw new UnsupportedOperationException("Unsupported type for wiremock metadata extension");
|
||||
}
|
||||
|
||||
@Override
|
||||
public boolean isApplicable(Contract contract) {
|
||||
boolean contains = contract.getMetadata()
|
||||
.containsKey(WireMockMetaData.METADATA_KEY);
|
||||
boolean contains = contract.getMetadata().containsKey(WireMockMetaData.METADATA_KEY);
|
||||
if (!contains) {
|
||||
return false;
|
||||
}
|
||||
Object stubMapping = WireMockMetaData.fromMetadata(contract.getMetadata())
|
||||
.getStubMapping();
|
||||
Object stubMapping = WireMockMetaData.fromMetadata(contract.getMetadata()).getStubMapping();
|
||||
return WireMockMetaData.APPLICABLE_CLASSES.stream()
|
||||
.anyMatch(aClass -> aClass.isAssignableFrom(stubMapping.getClass()));
|
||||
}
|
||||
|
||||
@@ -39,10 +39,8 @@ import org.springframework.util.StringUtils;
|
||||
*/
|
||||
public class DslToWireMockClientConverter extends DslToWireMockConverter {
|
||||
|
||||
private String convertASingleContract(String rootName, ContractMetadata contract,
|
||||
Contract dsl) {
|
||||
StubMapping stubMapping = new WireMockStubStrategy(rootName, contract, dsl)
|
||||
.toWireMockClientStub();
|
||||
private String convertASingleContract(String rootName, ContractMetadata contract, Contract dsl) {
|
||||
StubMapping stubMapping = new WireMockStubStrategy(rootName, contract, dsl).toWireMockClientStub();
|
||||
StubMapping mapping = postProcessStubMapping(stubMapping, dsl);
|
||||
if (mapping == null) {
|
||||
return "";
|
||||
@@ -51,16 +49,14 @@ public class DslToWireMockClientConverter extends DslToWireMockConverter {
|
||||
}
|
||||
|
||||
@Override
|
||||
public StubMapping postProcessStubMapping(StubMapping stubMapping,
|
||||
Contract contract) {
|
||||
public StubMapping postProcessStubMapping(StubMapping stubMapping, Contract contract) {
|
||||
StubMapping mapping = super.postProcessStubMapping(stubMapping, contract);
|
||||
// apply the default WireMock processor as the last one
|
||||
return defaultStubMappingPostProcessing(mapping, contract);
|
||||
}
|
||||
|
||||
@Override
|
||||
public StubMapping defaultStubMappingPostProcessing(StubMapping stubMapping,
|
||||
Contract contract) {
|
||||
public StubMapping defaultStubMappingPostProcessing(StubMapping stubMapping, Contract contract) {
|
||||
DefaultWireMockStubPostProcessor processor = new DefaultWireMockStubPostProcessor();
|
||||
if (processor.isApplicable(contract)) {
|
||||
return processor.postProcess(stubMapping, contract);
|
||||
@@ -69,15 +65,13 @@ public class DslToWireMockClientConverter extends DslToWireMockConverter {
|
||||
}
|
||||
|
||||
@Override
|
||||
public Map<Contract, String> convertContents(String rootName,
|
||||
ContractMetadata contract) {
|
||||
public Map<Contract, String> convertContents(String rootName, ContractMetadata contract) {
|
||||
List<Contract> httpContracts = httpContracts(contract);
|
||||
if (httpContracts.isEmpty()) {
|
||||
return new HashMap<>();
|
||||
}
|
||||
if (contract.getConvertedContract().size() == 1) {
|
||||
return Collections.singletonMap(
|
||||
first((List<Contract>) contract.getConvertedContract()),
|
||||
return Collections.singletonMap(first((List<Contract>) contract.getConvertedContract()),
|
||||
convertASingleContract(rootName, contract,
|
||||
first((List<Contract>) contract.getConvertedContract())));
|
||||
}
|
||||
@@ -85,17 +79,16 @@ 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, List<Contract> contractsWithRequest) {
|
||||
private Map<Contract, String> convertContracts(String rootName, ContractMetadata contract,
|
||||
List<Contract> contractsWithRequest) {
|
||||
Map<Contract, String> convertedContracts = new LinkedHashMap<>();
|
||||
for (int i = 0; i < contractsWithRequest.size(); i++) {
|
||||
Contract dsl = contractsWithRequest.get(i);
|
||||
String name = StringUtils.hasText(dsl.getName())
|
||||
? NamesUtil.convertIllegalPackageChars(dsl.getName())
|
||||
String name = StringUtils.hasText(dsl.getName()) ? NamesUtil.convertIllegalPackageChars(dsl.getName())
|
||||
: rootName + "_" + i;
|
||||
convertedContracts.put(dsl, convertASingleContract(name, contract, dsl));
|
||||
}
|
||||
@@ -104,8 +97,7 @@ public class DslToWireMockClientConverter extends DslToWireMockConverter {
|
||||
|
||||
private static <T> T first(List<T> self) {
|
||||
if (self.isEmpty()) {
|
||||
throw new NoSuchElementException(
|
||||
"Cannot access first() element from an empty List");
|
||||
throw new NoSuchElementException("Cannot access first() element from an empty List");
|
||||
}
|
||||
return self.get(0);
|
||||
}
|
||||
|
||||
@@ -37,8 +37,7 @@ public class WireMockMetaData implements SpringCloudContractMetadata {
|
||||
/**
|
||||
* Applicable classes for Stub Mapping.
|
||||
*/
|
||||
static final List<Class> APPLICABLE_CLASSES = Arrays.asList(String.class,
|
||||
StubMapping.class, Map.class);
|
||||
static final List<Class> APPLICABLE_CLASSES = Arrays.asList(String.class, StubMapping.class, Map.class);
|
||||
|
||||
/**
|
||||
* {@link StubMapping} represented by one of the classes in
|
||||
@@ -55,8 +54,7 @@ public class WireMockMetaData implements SpringCloudContractMetadata {
|
||||
}
|
||||
|
||||
public static WireMockMetaData fromMetadata(Map<String, Object> metadata) {
|
||||
return MetadataUtil.fromMetadata(metadata, WireMockMetaData.METADATA_KEY,
|
||||
new WireMockMetaData());
|
||||
return MetadataUtil.fromMetadata(metadata, WireMockMetaData.METADATA_KEY, new WireMockMetaData());
|
||||
}
|
||||
|
||||
@Override
|
||||
@@ -66,10 +64,8 @@ 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() + "`")
|
||||
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())
|
||||
+ ". Please check "
|
||||
+ "the http://wiremock.org/docs/stubbing/ for more information about the StubMapping class properties.";
|
||||
|
||||
@@ -49,35 +49,25 @@ public class WireMockToDslConverter {
|
||||
|
||||
private static final JsonPointer PRIORITY_POINTER = JsonPointer.compile("/priority");
|
||||
|
||||
private static final JsonPointer REQUEST_METHOD_POINTER = JsonPointer
|
||||
.compile("/request/method");
|
||||
private static final JsonPointer REQUEST_METHOD_POINTER = JsonPointer.compile("/request/method");
|
||||
|
||||
private static final JsonPointer REQUEST_URL_POINTER = JsonPointer
|
||||
.compile("/request/url");
|
||||
private static final JsonPointer REQUEST_URL_POINTER = JsonPointer.compile("/request/url");
|
||||
|
||||
private static final JsonPointer REQUEST_URL_PATH_POINTER = JsonPointer
|
||||
.compile("/request/urlPath");
|
||||
private static final JsonPointer REQUEST_URL_PATH_POINTER = JsonPointer.compile("/request/urlPath");
|
||||
|
||||
private static final JsonPointer REQUEST_URL_PATTERN_POINTER = JsonPointer
|
||||
.compile("/request/urlPattern");
|
||||
private static final JsonPointer REQUEST_URL_PATTERN_POINTER = JsonPointer.compile("/request/urlPattern");
|
||||
|
||||
private static final JsonPointer REQUEST_URL_PATH_PATTERN_POINTER = JsonPointer
|
||||
.compile("/request/urlPathPattern");
|
||||
private static final JsonPointer REQUEST_URL_PATH_PATTERN_POINTER = JsonPointer.compile("/request/urlPathPattern");
|
||||
|
||||
private static final JsonPointer REQUEST_HEADERS_POINTER = JsonPointer
|
||||
.compile("/request/headers");
|
||||
private static final JsonPointer REQUEST_HEADERS_POINTER = JsonPointer.compile("/request/headers");
|
||||
|
||||
private static final JsonPointer REQUEST_BODY_POINTER = JsonPointer
|
||||
.compile("/request/bodyPatterns");
|
||||
private static final JsonPointer REQUEST_BODY_POINTER = JsonPointer.compile("/request/bodyPatterns");
|
||||
|
||||
private static final JsonPointer RESPONSE_STATUS_POINTER = JsonPointer
|
||||
.compile("/response/status");
|
||||
private static final JsonPointer RESPONSE_STATUS_POINTER = JsonPointer.compile("/response/status");
|
||||
|
||||
private static final JsonPointer RESPONSE_BODY_POINTER = JsonPointer
|
||||
.compile("/response/body");
|
||||
private static final JsonPointer RESPONSE_BODY_POINTER = JsonPointer.compile("/response/body");
|
||||
|
||||
private static final JsonPointer RESPONSE_HEADERS_POINTER = JsonPointer
|
||||
.compile("/response/headers");
|
||||
private static final JsonPointer RESPONSE_HEADERS_POINTER = JsonPointer.compile("/response/headers");
|
||||
|
||||
private static final ObjectMapper OBJECT_MAPPER = new ObjectMapper();
|
||||
|
||||
@@ -98,12 +88,10 @@ public class WireMockToDslConverter {
|
||||
|
||||
private String convertFromWireMockStub(String wireMockStringStub) {
|
||||
JsonNode wireMockStub = parseStubDefinition(wireMockStringStub);
|
||||
return buildPriority(wireMockStub) + "request {\n"
|
||||
+ buildRequestMethod(wireMockStub) + buildRequestUrl(wireMockStub)
|
||||
+ buildRequestUrlPattern(wireMockStub)
|
||||
+ buildRequestUrlPathPattern(wireMockStub)
|
||||
+ buildRequestUrlPath(wireMockStub) + buildRequestHeaders(wireMockStub)
|
||||
+ buildRequestBody(wireMockStub) + "}\n" + "response {\n"
|
||||
return buildPriority(wireMockStub) + "request {\n" + buildRequestMethod(wireMockStub)
|
||||
+ buildRequestUrl(wireMockStub) + buildRequestUrlPattern(wireMockStub)
|
||||
+ buildRequestUrlPathPattern(wireMockStub) + buildRequestUrlPath(wireMockStub)
|
||||
+ buildRequestHeaders(wireMockStub) + buildRequestBody(wireMockStub) + "}\n" + "response {\n"
|
||||
+ buildResponseStatus(wireMockStub) + buildResponseBody(wireMockStub)
|
||||
+ buildResponseHeaders(wireMockStub) + "}" + "\n";
|
||||
}
|
||||
@@ -157,10 +145,8 @@ public class WireMockToDslConverter {
|
||||
String requestUrlPattern = "";
|
||||
JsonNode requestUrlPatternNode = wireMockStub.at(REQUEST_URL_PATTERN_POINTER);
|
||||
if (!requestUrlPatternNode.isMissingNode()) {
|
||||
String escapedRequestUrlPatternValue = escapeJava(
|
||||
requestUrlPatternNode.asText());
|
||||
requestUrlPattern = "url $(consumer(regex('" + escapedRequestUrlPatternValue
|
||||
+ "')), producer('"
|
||||
String escapedRequestUrlPatternValue = escapeJava(requestUrlPatternNode.asText());
|
||||
requestUrlPattern = "url $(consumer(regex('" + escapedRequestUrlPatternValue + "')), producer('"
|
||||
+ new Xeger(escapedRequestUrlPatternValue).generate() + "'))\n";
|
||||
}
|
||||
return requestUrlPattern;
|
||||
@@ -168,13 +154,10 @@ public class WireMockToDslConverter {
|
||||
|
||||
private String buildRequestUrlPathPattern(JsonNode wireMockStub) {
|
||||
String requestUrlPathPattern = "";
|
||||
JsonNode requestUrlPathPatternNode = wireMockStub
|
||||
.at(REQUEST_URL_PATH_PATTERN_POINTER);
|
||||
JsonNode requestUrlPathPatternNode = wireMockStub.at(REQUEST_URL_PATH_PATTERN_POINTER);
|
||||
if (!requestUrlPathPatternNode.isMissingNode()) {
|
||||
String escapedRequestUrlPathPatternValue = escapeJava(
|
||||
requestUrlPathPatternNode.asText());
|
||||
requestUrlPathPattern = "urlPath $(consumer(regex('"
|
||||
+ escapedRequestUrlPathPatternValue + "')), producer('"
|
||||
String escapedRequestUrlPathPatternValue = escapeJava(requestUrlPathPatternNode.asText());
|
||||
requestUrlPathPattern = "urlPath $(consumer(regex('" + escapedRequestUrlPathPatternValue + "')), producer('"
|
||||
+ new Xeger(escapedRequestUrlPathPatternValue).generate() + "'))'\n";
|
||||
}
|
||||
return requestUrlPathPattern;
|
||||
@@ -187,14 +170,11 @@ public class WireMockToDslConverter {
|
||||
if (requestHeadersNode.isObject()) {
|
||||
requestHeadersBuilder.append("headers {\n");
|
||||
ObjectNode requestHeadersObjectNode = requestHeadersNode.deepCopy();
|
||||
Iterator<Map.Entry<String, JsonNode>> fields = requestHeadersObjectNode
|
||||
.fields();
|
||||
Iterator<Map.Entry<String, JsonNode>> fields = requestHeadersObjectNode.fields();
|
||||
fields.forEachRemaining(c -> {
|
||||
requestHeadersBuilder.append("header('").append(c.getKey()).append("',");
|
||||
Map.Entry<String, JsonNode> headerValue = c.getValue().deepCopy().fields()
|
||||
.next();
|
||||
String header = buildHeader(headerValue.getKey(),
|
||||
headerValue.getValue().asText());
|
||||
Map.Entry<String, JsonNode> headerValue = c.getValue().deepCopy().fields().next();
|
||||
String header = buildHeader(headerValue.getKey(), headerValue.getValue().asText());
|
||||
requestHeadersBuilder.append(header).append(")").append("\n");
|
||||
});
|
||||
requestHeadersBuilder.append("}");
|
||||
@@ -222,24 +202,17 @@ 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)
|
||||
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()
|
||||
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("'))"));
|
||||
.append(escapeJava(b.getValue().asText())).append("')), producer('")
|
||||
.append(new Xeger(escapeJava(b.getValue().asText())).generate()).append("'))"));
|
||||
}
|
||||
return requestBody.toString();
|
||||
}
|
||||
@@ -258,14 +231,10 @@ public class WireMockToDslConverter {
|
||||
String responseBody = "";
|
||||
JsonNode responseBodyNode = wireMockStub.at(RESPONSE_BODY_POINTER);
|
||||
if (responseBodyNode.isInt()) {
|
||||
responseBody += "body( "
|
||||
+ escapeJava(buildPrettyPrintResponseBody((IntNode) responseBodyNode))
|
||||
+ ")\n";
|
||||
responseBody += "body( " + escapeJava(buildPrettyPrintResponseBody((IntNode) responseBodyNode)) + ")\n";
|
||||
}
|
||||
if (responseBodyNode.isTextual()) {
|
||||
responseBody += "body( \""
|
||||
+ escapeJava(
|
||||
buildPrettyPrintResponseBody((TextNode) responseBodyNode))
|
||||
responseBody += "body( \"" + escapeJava(buildPrettyPrintResponseBody((TextNode) responseBodyNode))
|
||||
+ "\")\n";
|
||||
}
|
||||
return responseBody;
|
||||
@@ -278,8 +247,7 @@ public class WireMockToDslConverter {
|
||||
private String buildPrettyPrintResponseBody(TextNode node) {
|
||||
try {
|
||||
String textNode = node.asText();
|
||||
Object intermediateObjectForPrettyPrinting = OBJECT_MAPPER.reader()
|
||||
.readValue(textNode, Object.class);
|
||||
Object intermediateObjectForPrettyPrinting = OBJECT_MAPPER.reader().readValue(textNode, Object.class);
|
||||
DefaultIndenter customIndenter = new DefaultIndenter(" ", "\n");
|
||||
return OBJECT_MAPPER
|
||||
.writer(new PrivatePrettyPrinter().withArrayIndenter(customIndenter)
|
||||
@@ -287,8 +255,7 @@ public class WireMockToDslConverter {
|
||||
.writeValueAsString(intermediateObjectForPrettyPrinting);
|
||||
}
|
||||
catch (IOException e) {
|
||||
throw new RuntimeException(
|
||||
"WireMock response body could not be pretty printed");
|
||||
throw new RuntimeException("WireMock response body could not be pretty printed");
|
||||
}
|
||||
}
|
||||
|
||||
@@ -299,11 +266,9 @@ public class WireMockToDslConverter {
|
||||
if (requestHeadersNode.isObject()) {
|
||||
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"));
|
||||
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"));
|
||||
responseHeadersBuilder.append("}");
|
||||
}
|
||||
return responseHeadersBuilder.toString();
|
||||
@@ -319,8 +284,7 @@ public class WireMockToDslConverter {
|
||||
@Override
|
||||
public DefaultPrettyPrinter withSeparators(Separators separators) {
|
||||
_separators = separators;
|
||||
_objectFieldValueSeparatorWithSpaces = separators
|
||||
.getObjectFieldValueSeparator() + " ";
|
||||
_objectFieldValueSeparatorWithSpaces = separators.getObjectFieldValueSeparator() + " ";
|
||||
return this;
|
||||
}
|
||||
|
||||
|
||||
@@ -60,8 +60,7 @@ class DefaultWireMockStubPostProcessorTests {
|
||||
|
||||
@Test
|
||||
void should_not_be_applicable_for_missing_metadata_entry() {
|
||||
then(new DefaultWireMockStubPostProcessor().isApplicable(new Contract()))
|
||||
.isFalse();
|
||||
then(new DefaultWireMockStubPostProcessor().isApplicable(new Contract())).isFalse();
|
||||
}
|
||||
|
||||
@Test
|
||||
@@ -100,8 +99,7 @@ class DefaultWireMockStubPostProcessorTests {
|
||||
contract.getMetadata().put("wiremock", map);
|
||||
StubMapping stubMapping = StubMapping.buildFrom(STUB_MAPPING);
|
||||
|
||||
StubMapping result = new DefaultWireMockStubPostProcessor()
|
||||
.postProcess(stubMapping, contract);
|
||||
StubMapping result = new DefaultWireMockStubPostProcessor().postProcess(stubMapping, contract);
|
||||
|
||||
thenPostServerActionWasSet(result);
|
||||
}
|
||||
@@ -114,24 +112,20 @@ class DefaultWireMockStubPostProcessorTests {
|
||||
contract.getMetadata().put("wiremock", map);
|
||||
StubMapping stubMapping = StubMapping.buildFrom(STUB_MAPPING);
|
||||
|
||||
StubMapping result = new DefaultWireMockStubPostProcessor()
|
||||
.postProcess(stubMapping, contract);
|
||||
StubMapping result = new DefaultWireMockStubPostProcessor().postProcess(stubMapping, contract);
|
||||
|
||||
thenPostServerActionWasSet(result);
|
||||
}
|
||||
|
||||
@Test
|
||||
void should_merge_stub_mappings_when_stub_mapping_is_map()
|
||||
throws JsonProcessingException {
|
||||
void should_merge_stub_mappings_when_stub_mapping_is_map() throws JsonProcessingException {
|
||||
Contract contract = new Contract();
|
||||
Map<String, Object> map = new HashMap<>();
|
||||
map.put("stubMapping",
|
||||
new ObjectMapper().readValue(POST_SERVE_ACTION, HashMap.class));
|
||||
map.put("stubMapping", new ObjectMapper().readValue(POST_SERVE_ACTION, HashMap.class));
|
||||
contract.getMetadata().put("wiremock", map);
|
||||
StubMapping stubMapping = StubMapping.buildFrom(STUB_MAPPING);
|
||||
|
||||
StubMapping result = new DefaultWireMockStubPostProcessor()
|
||||
.postProcess(stubMapping, contract);
|
||||
StubMapping result = new DefaultWireMockStubPostProcessor().postProcess(stubMapping, contract);
|
||||
|
||||
thenPostServerActionWasSet(result);
|
||||
}
|
||||
@@ -144,8 +138,7 @@ class DefaultWireMockStubPostProcessorTests {
|
||||
contract.getMetadata().put("wiremock", map);
|
||||
StubMapping stubMapping = StubMapping.buildFrom(STUB_MAPPING);
|
||||
|
||||
StubMapping result = new DefaultWireMockStubPostProcessor()
|
||||
.postProcess(stubMapping, contract);
|
||||
StubMapping result = new DefaultWireMockStubPostProcessor().postProcess(stubMapping, contract);
|
||||
|
||||
then(result.getRequest().getMethod().getName()).isEqualTo("GET");
|
||||
then(result.getResponse().getStatus()).isEqualTo(200);
|
||||
|
||||
@@ -54,29 +54,25 @@ public class BaseClassMapping {
|
||||
return false;
|
||||
}
|
||||
BaseClassMapping that = (BaseClassMapping) o;
|
||||
if (this.contractPackageRegex != null
|
||||
? !this.contractPackageRegex.equals(that.contractPackageRegex)
|
||||
if (this.contractPackageRegex != null ? !this.contractPackageRegex.equals(that.contractPackageRegex)
|
||||
: that.contractPackageRegex != null) {
|
||||
return false;
|
||||
}
|
||||
return this.baseClassFQN != null ? this.baseClassFQN.equals(that.baseClassFQN)
|
||||
: that.baseClassFQN == null;
|
||||
return this.baseClassFQN != null ? this.baseClassFQN.equals(that.baseClassFQN) : that.baseClassFQN == null;
|
||||
|
||||
}
|
||||
|
||||
@Override
|
||||
public int hashCode() {
|
||||
int result = this.contractPackageRegex != null
|
||||
? this.contractPackageRegex.hashCode() : 0;
|
||||
result = 31 * result
|
||||
+ (this.baseClassFQN != null ? this.baseClassFQN.hashCode() : 0);
|
||||
int result = this.contractPackageRegex != null ? this.contractPackageRegex.hashCode() : 0;
|
||||
result = 31 * result + (this.baseClassFQN != null ? this.baseClassFQN.hashCode() : 0);
|
||||
return result;
|
||||
}
|
||||
|
||||
@Override
|
||||
public String toString() {
|
||||
return "BaseClassMapping{" + "contractPackageRegex='" + this.contractPackageRegex
|
||||
+ '\'' + ", baseClassFQN='" + this.baseClassFQN + '\'' + '}';
|
||||
return "BaseClassMapping{" + "contractPackageRegex='" + this.contractPackageRegex + '\'' + ", baseClassFQN='"
|
||||
+ this.baseClassFQN + '\'' + '}';
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
@@ -29,12 +29,10 @@ final class ChangeDetector {
|
||||
private ChangeDetector() {
|
||||
}
|
||||
|
||||
static boolean inputFilesChangeDetected(File contractsDirectory,
|
||||
MojoExecution mojoExecution, MavenSession session)
|
||||
static boolean inputFilesChangeDetected(File contractsDirectory, MojoExecution mojoExecution, MavenSession session)
|
||||
throws MojoExecutionException {
|
||||
|
||||
IncrementalBuildHelper incrementalBuildHelper = new IncrementalBuildHelper(
|
||||
mojoExecution, session);
|
||||
IncrementalBuildHelper incrementalBuildHelper = new IncrementalBuildHelper(mojoExecution, session);
|
||||
|
||||
DirectoryScanner scanner = incrementalBuildHelper.getDirectoryScanner();
|
||||
scanner.setBasedir(contractsDirectory);
|
||||
|
||||
@@ -48,8 +48,7 @@ import static org.springframework.cloud.contract.maven.verifier.ChangeDetector.i
|
||||
*
|
||||
* @author Mariusz Smykula
|
||||
*/
|
||||
@Mojo(name = "convert", requiresProject = false,
|
||||
defaultPhase = LifecyclePhase.PROCESS_TEST_RESOURCES)
|
||||
@Mojo(name = "convert", requiresProject = false, defaultPhase = LifecyclePhase.PROCESS_TEST_RESOURCES)
|
||||
public class ConvertMojo extends AbstractMojo {
|
||||
|
||||
static final String DEFAULT_STUBS_DIR = "${project.build.directory}/stubs/";
|
||||
@@ -222,58 +221,50 @@ public class ConvertMojo extends AbstractMojo {
|
||||
File contractsDirectory = locationOfContracts(config);
|
||||
contractsDirectory = contractSubfolderIfPresent(contractsDirectory);
|
||||
|
||||
if (this.incrementalContractStubs && !inputFilesChangeDetected(contractsDirectory,
|
||||
mojoExecution, session)) {
|
||||
if (this.incrementalContractStubs && !inputFilesChangeDetected(contractsDirectory, mojoExecution, session)) {
|
||||
getLog().info("Nothing to generate - all stubs are up to date");
|
||||
return;
|
||||
}
|
||||
|
||||
File contractsDslDir = contractsDslDir(contractsDirectory);
|
||||
LeftOverPrevention leftOverPrevention = new LeftOverPrevention(
|
||||
this.stubsDirectory, mojoExecution, session);
|
||||
LeftOverPrevention leftOverPrevention = new LeftOverPrevention(this.stubsDirectory, mojoExecution, session);
|
||||
|
||||
File copiedContracts = copyContracts(rootPath, config, contractsDirectory);
|
||||
if (this.convertToYaml) {
|
||||
contractsDslDir = copiedContracts;
|
||||
convertBackedUpDslsToYaml(rootPath, config, contractsDirectory,
|
||||
contractsDslDir);
|
||||
convertBackedUpDslsToYaml(rootPath, config, contractsDirectory, contractsDslDir);
|
||||
}
|
||||
config.setContractsDslDir(contractsDslDir);
|
||||
config.setStubsOutputDir(stubsOutputDir(rootPath));
|
||||
logSetup(config, contractsDslDir);
|
||||
RecursiveFilesConverter converter = new RecursiveFilesConverter(
|
||||
config.getStubsOutputDir(), config.getContractsDslDir(),
|
||||
config.getExcludedFiles(), config.getIncludedContracts(),
|
||||
RecursiveFilesConverter converter = new RecursiveFilesConverter(config.getStubsOutputDir(),
|
||||
config.getContractsDslDir(), config.getExcludedFiles(), config.getIncludedContracts(),
|
||||
config.isExcludeBuildFolders());
|
||||
converter.processFiles();
|
||||
leftOverPrevention.deleteLeftOvers();
|
||||
}
|
||||
|
||||
private void convertBackedUpDslsToYaml(String rootPath,
|
||||
ContractVerifierConfigProperties config, File contractsDirectory,
|
||||
File contractsDslDir) throws MojoExecutionException {
|
||||
private void convertBackedUpDslsToYaml(String rootPath, ContractVerifierConfigProperties config,
|
||||
File contractsDirectory, File contractsDslDir) throws MojoExecutionException {
|
||||
copyOriginals(rootPath, config, contractsDirectory);
|
||||
ToYamlConverter.replaceContractWithYaml(contractsDslDir);
|
||||
getLog().info("Replaced DSL files with their YAML representation at ["
|
||||
+ contractsDslDir + "]");
|
||||
getLog().info("Replaced DSL files with their YAML representation at [" + contractsDslDir + "]");
|
||||
}
|
||||
|
||||
private File copyOriginals(String rootPath, ContractVerifierConfigProperties config,
|
||||
File contractsDirectory) throws MojoExecutionException {
|
||||
File outputFolderWithOriginals = new File(this.stubsDirectory,
|
||||
rootPath + ORIGINAL_PATH);
|
||||
new CopyContracts(this.project, this.mavenSession, this.mavenResourcesFiltering,
|
||||
config).copy(contractsDirectory, outputFolderWithOriginals);
|
||||
private File copyOriginals(String rootPath, ContractVerifierConfigProperties config, File contractsDirectory)
|
||||
throws MojoExecutionException {
|
||||
File outputFolderWithOriginals = new File(this.stubsDirectory, rootPath + ORIGINAL_PATH);
|
||||
new CopyContracts(this.project, this.mavenSession, this.mavenResourcesFiltering, config)
|
||||
.copy(contractsDirectory, outputFolderWithOriginals);
|
||||
return outputFolderWithOriginals;
|
||||
}
|
||||
|
||||
private File copyContracts(String rootPath, ContractVerifierConfigProperties config,
|
||||
File contractsDirectory) throws MojoExecutionException {
|
||||
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);
|
||||
private File copyContracts(String rootPath, ContractVerifierConfigProperties config, File contractsDirectory)
|
||||
throws MojoExecutionException {
|
||||
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);
|
||||
return outputFolderWithContracts;
|
||||
}
|
||||
|
||||
@@ -281,21 +272,17 @@ public class ConvertMojo extends AbstractMojo {
|
||||
if (getLog().isDebugEnabled()) {
|
||||
getLog().debug("The contracts dir equals [" + contractsDslDir + "]");
|
||||
}
|
||||
getLog().info(
|
||||
"Converting from Spring Cloud Contract Verifier contracts to WireMock stubs mappings");
|
||||
getLog().info(String.format(
|
||||
" Spring Cloud Contract Verifier contracts directory: %s",
|
||||
getLog().info("Converting from Spring Cloud Contract Verifier contracts to WireMock stubs mappings");
|
||||
getLog().info(String.format(" Spring Cloud Contract Verifier contracts directory: %s",
|
||||
config.getContractsDslDir()));
|
||||
getLog().info(String.format("Stub Server stubs mappings directory: %s",
|
||||
config.getStubsOutputDir()));
|
||||
getLog().info(String.format("Stub Server stubs mappings directory: %s", config.getStubsOutputDir()));
|
||||
}
|
||||
|
||||
private File contractSubfolderIfPresent(File contractsDirectory) {
|
||||
File contractsSubFolder = new File(contractsDirectory, "contracts");
|
||||
if (contractsSubFolder.exists()) {
|
||||
if (getLog().isDebugEnabled()) {
|
||||
getLog().debug(
|
||||
"The subfolder [contracts] exists, will pick it as a source of contracts");
|
||||
getLog().debug("The subfolder [contracts] exists, will pick it as a source of contracts");
|
||||
}
|
||||
contractsDirectory = contractsSubFolder;
|
||||
}
|
||||
@@ -303,19 +290,15 @@ public class ConvertMojo extends AbstractMojo {
|
||||
}
|
||||
|
||||
private File locationOfContracts(ContractVerifierConfigProperties config) {
|
||||
return new MavenContractsDownloader(this.project, this.contractDependency,
|
||||
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);
|
||||
return new MavenContractsDownloader(this.project, this.contractDependency, 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);
|
||||
}
|
||||
|
||||
private File stubsOutputDir(String rootPath) {
|
||||
return isInsideProject() ? new File(this.stubsDirectory, rootPath + MAPPINGS_PATH)
|
||||
: this.destination;
|
||||
return isInsideProject() ? new File(this.stubsDirectory, rootPath + MAPPINGS_PATH) : this.destination;
|
||||
}
|
||||
|
||||
private File contractsDslDir(File contractsDirectory) {
|
||||
|
||||
@@ -43,8 +43,7 @@ class CopyContracts {
|
||||
|
||||
private final ContractVerifierConfigProperties config;
|
||||
|
||||
CopyContracts(MavenProject project, MavenSession mavenSession,
|
||||
MavenResourcesFiltering mavenResourcesFiltering,
|
||||
CopyContracts(MavenProject project, MavenSession mavenSession, MavenResourcesFiltering mavenResourcesFiltering,
|
||||
ContractVerifierConfigProperties config) {
|
||||
this.project = project;
|
||||
this.mavenSession = mavenSession;
|
||||
@@ -52,18 +51,14 @@ class CopyContracts {
|
||||
this.config = config;
|
||||
}
|
||||
|
||||
public void copy(File contractsDirectory, File outputDirectory)
|
||||
throws MojoExecutionException {
|
||||
log.info("Copying Spring Cloud Contract Verifier contracts to [" + outputDirectory
|
||||
+ "]" + ". Only files matching [" + this.config.getIncludedContracts()
|
||||
+ "] pattern will end up in " + "the final JAR with stubs.");
|
||||
public void copy(File contractsDirectory, File outputDirectory) throws MojoExecutionException {
|
||||
log.info("Copying Spring Cloud Contract Verifier contracts to [" + outputDirectory + "]"
|
||||
+ ". Only files matching [" + this.config.getIncludedContracts() + "] pattern will end up in "
|
||||
+ "the final JAR with stubs.");
|
||||
Resource resource = new Resource();
|
||||
String includedRootFolderAntPattern = this.config
|
||||
.getIncludedRootFolderAntPattern() + "*.*";
|
||||
String slashSeparatedGroupIdAntPattern = slashSeparatedGroupIdAntPattern(
|
||||
includedRootFolderAntPattern);
|
||||
String dotSeparatedGroupIdAntPattern = dotSeparatedGroupIdAntPattern(
|
||||
includedRootFolderAntPattern);
|
||||
String includedRootFolderAntPattern = this.config.getIncludedRootFolderAntPattern() + "*.*";
|
||||
String slashSeparatedGroupIdAntPattern = slashSeparatedGroupIdAntPattern(includedRootFolderAntPattern);
|
||||
String dotSeparatedGroupIdAntPattern = dotSeparatedGroupIdAntPattern(includedRootFolderAntPattern);
|
||||
// by default group id is slash separated...
|
||||
resource.addInclude(slashSeparatedGroupIdAntPattern);
|
||||
if (!slashSeparatedGroupIdAntPattern.equals(dotSeparatedGroupIdAntPattern)) {
|
||||
@@ -101,8 +96,7 @@ class CopyContracts {
|
||||
return includedRootFolderAntPattern;
|
||||
}
|
||||
else if (includedRootFolderAntPattern.contains(dotSeparatedGroupId())) {
|
||||
return includedRootFolderAntPattern.replace(dotSeparatedGroupId(),
|
||||
slashSeparatedGroupId());
|
||||
return includedRootFolderAntPattern.replace(dotSeparatedGroupId(), slashSeparatedGroupId());
|
||||
}
|
||||
return includedRootFolderAntPattern;
|
||||
}
|
||||
@@ -112,8 +106,7 @@ class CopyContracts {
|
||||
return includedRootFolderAntPattern;
|
||||
}
|
||||
else if (includedRootFolderAntPattern.contains(slashSeparatedGroupId())) {
|
||||
return includedRootFolderAntPattern.replace(slashSeparatedGroupId(),
|
||||
dotSeparatedGroupId());
|
||||
return includedRootFolderAntPattern.replace(slashSeparatedGroupId(), dotSeparatedGroupId());
|
||||
}
|
||||
return includedRootFolderAntPattern;
|
||||
}
|
||||
|
||||
@@ -43,20 +43,16 @@ import static org.springframework.cloud.contract.maven.verifier.ChangeDetector.i
|
||||
*
|
||||
* @author Mariusz Smykula
|
||||
*/
|
||||
@Mojo(name = "generateStubs", defaultPhase = LifecyclePhase.PACKAGE,
|
||||
requiresProject = true)
|
||||
@Mojo(name = "generateStubs", defaultPhase = LifecyclePhase.PACKAGE, requiresProject = true)
|
||||
public class GenerateStubsMojo extends AbstractMojo {
|
||||
|
||||
@Parameter(defaultValue = "${project.build.directory}", readonly = true,
|
||||
required = true)
|
||||
@Parameter(defaultValue = "${project.build.directory}", readonly = true, required = true)
|
||||
private File projectBuildDirectory;
|
||||
|
||||
@Parameter(defaultValue = "${project.build.finalName}", readonly = true,
|
||||
required = true)
|
||||
@Parameter(defaultValue = "${project.build.finalName}", readonly = true, required = true)
|
||||
private String projectFinalName;
|
||||
|
||||
@Parameter(property = "stubsDirectory",
|
||||
defaultValue = "${project.build.directory}/stubs")
|
||||
@Parameter(property = "stubsDirectory", defaultValue = "${project.build.directory}/stubs")
|
||||
private File outputDirectory;
|
||||
|
||||
/**
|
||||
@@ -68,8 +64,7 @@ public class GenerateStubsMojo extends AbstractMojo {
|
||||
/**
|
||||
* Set this to "true" to bypass only JAR creation.
|
||||
*/
|
||||
@Parameter(property = "spring.cloud.contract.verifier.jar.skip",
|
||||
defaultValue = "false")
|
||||
@Parameter(property = "spring.cloud.contract.verifier.jar.skip", defaultValue = "false")
|
||||
private boolean jarSkip;
|
||||
|
||||
@Component
|
||||
@@ -112,10 +107,8 @@ public class GenerateStubsMojo extends AbstractMojo {
|
||||
|
||||
public void execute() throws MojoExecutionException, MojoFailureException {
|
||||
if (this.skip || this.jarSkip) {
|
||||
getLog().info(
|
||||
"Skipping Spring Cloud Contract Verifier execution: spring.cloud.contract.verifier.skip="
|
||||
+ this.skip + ", spring.cloud.contract.verifier.jar.skip="
|
||||
+ this.jarSkip);
|
||||
getLog().info("Skipping Spring Cloud Contract Verifier execution: spring.cloud.contract.verifier.skip="
|
||||
+ this.skip + ", spring.cloud.contract.verifier.jar.skip=" + this.jarSkip);
|
||||
return;
|
||||
}
|
||||
else if (stubsOutputMissing(this.outputDirectory) && !this.failOnNoContracts) {
|
||||
@@ -124,44 +117,37 @@ public class GenerateStubsMojo extends AbstractMojo {
|
||||
return;
|
||||
}
|
||||
else if (stubsOutputMissing(this.outputDirectory) && this.failOnNoContracts) {
|
||||
throw new MojoExecutionException("Stubs could not be found: ["
|
||||
+ this.outputDirectory.getAbsolutePath()
|
||||
throw new MojoExecutionException("Stubs could not be found: [" + this.outputDirectory.getAbsolutePath()
|
||||
+ "] .\nPlease make sure that spring-cloud-contract:convert was invoked");
|
||||
}
|
||||
if (this.incrementalContractStubsJar
|
||||
&& !inputFilesChangeDetected(outputDirectory, mojoExecution, session)) {
|
||||
if (this.incrementalContractStubsJar && !inputFilesChangeDetected(outputDirectory, mojoExecution, session)) {
|
||||
getLog().info("Nothing to generate - stubs jar is up to date");
|
||||
return;
|
||||
}
|
||||
File stubsJarFile = createStubJar(this.outputDirectory);
|
||||
this.projectHelper.attachArtifact(this.project, "jar", this.classifier,
|
||||
stubsJarFile);
|
||||
this.projectHelper.attachArtifact(this.project, "jar", this.classifier, stubsJarFile);
|
||||
}
|
||||
|
||||
private File createStubJar(File stubsOutputDir)
|
||||
throws MojoFailureException, MojoExecutionException {
|
||||
private File createStubJar(File stubsOutputDir) throws MojoFailureException, MojoExecutionException {
|
||||
if (!stubsOutputDir.exists()) {
|
||||
throw new MojoExecutionException("Stubs could not be found: ["
|
||||
+ stubsOutputDir.getAbsolutePath()
|
||||
throw new MojoExecutionException("Stubs could not be found: [" + stubsOutputDir.getAbsolutePath()
|
||||
+ "] .\nPlease make sure that spring-cloud-contract:convert was invoked");
|
||||
}
|
||||
String stubArchiveName = this.projectFinalName + "-" + this.classifier + ".jar";
|
||||
File stubsJarFile = new File(this.projectBuildDirectory, stubArchiveName);
|
||||
String[] excludes = excludes();
|
||||
getLog().info("Files matching this pattern will be excluded from "
|
||||
+ "stubs generation " + Arrays.toString(excludes));
|
||||
getLog().info(
|
||||
"Files matching this pattern will be excluded from " + "stubs generation " + Arrays.toString(excludes));
|
||||
try {
|
||||
this.archiver.addDirectory(stubsOutputDir, new String[] { "**/*.*" },
|
||||
excludedFilesEmpty() ? new String[0] : this.excludedFiles);
|
||||
this.archiver.setCompress(true);
|
||||
this.archiver.setDestFile(stubsJarFile);
|
||||
this.archiver
|
||||
.addConfiguredManifest(ManifestCreator.createManifest(this.project));
|
||||
this.archiver.addConfiguredManifest(ManifestCreator.createManifest(this.project));
|
||||
this.archiver.createArchive();
|
||||
}
|
||||
catch (Exception e) {
|
||||
throw new MojoFailureException(
|
||||
"Exception while packaging " + this.classifier + " jar.", e);
|
||||
throw new MojoFailureException("Exception while packaging " + this.classifier + " jar.", e);
|
||||
}
|
||||
return stubsJarFile;
|
||||
}
|
||||
|
||||
@@ -59,12 +59,10 @@ public class GenerateTestsMojo extends AbstractMojo {
|
||||
defaultValue = "${project.basedir}/src/test/resources/contracts")
|
||||
private File contractsDirectory;
|
||||
|
||||
@Parameter(
|
||||
defaultValue = "${project.build.directory}/generated-test-sources/contracts")
|
||||
@Parameter(defaultValue = "${project.build.directory}/generated-test-sources/contracts")
|
||||
private File generatedTestSourcesDir;
|
||||
|
||||
@Parameter(
|
||||
defaultValue = "${project.build.directory}/generated-test-resources/contracts")
|
||||
@Parameter(defaultValue = "${project.build.directory}/generated-test-resources/contracts")
|
||||
private File generatedTestResourcesDir;
|
||||
|
||||
@Parameter
|
||||
@@ -113,8 +111,7 @@ public class GenerateTestsMojo extends AbstractMojo {
|
||||
* Incubating feature. You can check the size of JSON arrays. If not turned on
|
||||
* explicitly will be disabled.
|
||||
*/
|
||||
@Parameter(property = "spring.cloud.contract.verifier.assert.size",
|
||||
defaultValue = "false")
|
||||
@Parameter(property = "spring.cloud.contract.verifier.assert.size", defaultValue = "false")
|
||||
private boolean assertJsonSize;
|
||||
|
||||
/**
|
||||
@@ -264,63 +261,50 @@ public class GenerateTestsMojo extends AbstractMojo {
|
||||
public void execute() throws MojoExecutionException, MojoFailureException {
|
||||
if (this.skip || this.mavenTestSkip || this.skipTests) {
|
||||
if (this.skip) {
|
||||
getLog().info(
|
||||
"Skipping Spring Cloud Contract Verifier execution: spring.cloud.contract.verifier.skip="
|
||||
+ this.skip);
|
||||
getLog().info("Skipping Spring Cloud Contract Verifier execution: spring.cloud.contract.verifier.skip="
|
||||
+ this.skip);
|
||||
}
|
||||
if (this.mavenTestSkip) {
|
||||
getLog().info(
|
||||
"Skipping Spring Cloud Contract Verifier execution: maven.test.skip="
|
||||
+ this.mavenTestSkip);
|
||||
"Skipping Spring Cloud Contract Verifier execution: maven.test.skip=" + this.mavenTestSkip);
|
||||
}
|
||||
if (this.skipTests) {
|
||||
getLog().info(
|
||||
"Skipping Spring Cloud Contract Verifier execution: skipTests"
|
||||
+ this.skipTests);
|
||||
getLog().info("Skipping Spring Cloud Contract Verifier execution: skipTests" + this.skipTests);
|
||||
}
|
||||
return;
|
||||
}
|
||||
getLog().info(
|
||||
"Generating server tests source code for Spring Cloud Contract Verifier contract verification");
|
||||
getLog().info("Generating server tests source code for Spring Cloud Contract Verifier contract verification");
|
||||
final ContractVerifierConfigProperties config = new ContractVerifierConfigProperties();
|
||||
config.setFailOnInProgress(this.failOnInProgress);
|
||||
// download contracts, unzip them and pass as output directory
|
||||
File contractsDirectory = new MavenContractsDownloader(this.project,
|
||||
this.contractDependency, 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);
|
||||
getLog().info(
|
||||
"Directory with contract is present at [" + contractsDirectory + "]");
|
||||
File contractsDirectory = new MavenContractsDownloader(this.project, this.contractDependency,
|
||||
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);
|
||||
getLog().info("Directory with contract is present at [" + contractsDirectory + "]");
|
||||
|
||||
if (this.incrementalContractTests && !ChangeDetector
|
||||
.inputFilesChangeDetected(contractsDirectory, mojoExecution, session)) {
|
||||
if (this.incrementalContractTests
|
||||
&& !ChangeDetector.inputFilesChangeDetected(contractsDirectory, mojoExecution, session)) {
|
||||
getLog().info("Nothing to generate - all classes are up to date");
|
||||
return;
|
||||
}
|
||||
|
||||
setupConfig(config, contractsDirectory);
|
||||
this.project
|
||||
.addTestCompileSourceRoot(this.generatedTestSourcesDir.getAbsolutePath());
|
||||
this.project.addTestCompileSourceRoot(this.generatedTestSourcesDir.getAbsolutePath());
|
||||
Resource resource = new Resource();
|
||||
resource.setDirectory(this.generatedTestResourcesDir.getAbsolutePath());
|
||||
this.project.addTestResource(resource);
|
||||
if (getLog().isInfoEnabled()) {
|
||||
getLog().info("Test Source directory: "
|
||||
+ this.generatedTestSourcesDir.getAbsolutePath() + " added.");
|
||||
getLog().info("Using [" + config.getBaseClassForTests()
|
||||
+ "] as base class for test classes, ["
|
||||
+ config.getBasePackageForTests() + "] as base "
|
||||
+ "package for tests, [" + config.getPackageWithBaseClasses()
|
||||
+ "] as package with " + "base classes, base class mappings "
|
||||
getLog().info("Test Source directory: " + this.generatedTestSourcesDir.getAbsolutePath() + " added.");
|
||||
getLog().info("Using [" + config.getBaseClassForTests() + "] as base class for test classes, ["
|
||||
+ config.getBasePackageForTests() + "] as base " + "package for tests, ["
|
||||
+ config.getPackageWithBaseClasses() + "] as package with " + "base classes, base class mappings "
|
||||
+ this.baseClassMappings);
|
||||
}
|
||||
try {
|
||||
LeftOverPrevention leftOverPrevention = new LeftOverPrevention(
|
||||
this.generatedTestSourcesDir, mojoExecution, session);
|
||||
LeftOverPrevention leftOverPrevention = new LeftOverPrevention(this.generatedTestSourcesDir, mojoExecution,
|
||||
session);
|
||||
TestGenerator generator = new TestGenerator(config);
|
||||
int generatedClasses = generator.generate();
|
||||
getLog().info("Generated " + generatedClasses + " test classes.");
|
||||
@@ -328,14 +312,11 @@ public class GenerateTestsMojo extends AbstractMojo {
|
||||
}
|
||||
catch (ContractVerifierException e) {
|
||||
throw new MojoExecutionException(
|
||||
String.format("Spring Cloud Contract Verifier Plugin exception: %s",
|
||||
e.getMessage()),
|
||||
e);
|
||||
String.format("Spring Cloud Contract Verifier Plugin exception: %s", e.getMessage()), e);
|
||||
}
|
||||
}
|
||||
|
||||
private void setupConfig(ContractVerifierConfigProperties config,
|
||||
File contractsDirectory) {
|
||||
private void setupConfig(ContractVerifierConfigProperties config, File contractsDirectory) {
|
||||
config.setContractsDslDir(contractsDirectory);
|
||||
config.setGeneratedTestSourcesDir(this.generatedTestSourcesDir);
|
||||
config.setGeneratedTestResourcesDir(this.generatedTestResourcesDir);
|
||||
|
||||
@@ -41,19 +41,18 @@ class LeftOverPrevention {
|
||||
|
||||
private final File generatedDirectory;
|
||||
|
||||
LeftOverPrevention(File generatedDirectory, MojoExecution mojoExecution,
|
||||
MavenSession session) throws MojoExecutionException {
|
||||
LeftOverPrevention(File generatedDirectory, MojoExecution mojoExecution, MavenSession session)
|
||||
throws MojoExecutionException {
|
||||
this.generatedDirectory = generatedDirectory;
|
||||
this.incrementalBuildHelper = new IncrementalBuildHelper(mojoExecution, session);
|
||||
this.incrementalBuildHelper.beforeRebuildExecution(
|
||||
new IncrementalBuildHelperRequest().outputDirectory(generatedDirectory));
|
||||
this.incrementalBuildHelper
|
||||
.beforeRebuildExecution(new IncrementalBuildHelperRequest().outputDirectory(generatedDirectory));
|
||||
}
|
||||
|
||||
void deleteLeftOvers() throws MojoExecutionException {
|
||||
if (generatedDirectory.exists()) {
|
||||
incrementalBuildHelper
|
||||
.afterRebuildExecution(new IncrementalBuildHelperRequest()
|
||||
.outputDirectory(generatedDirectory));
|
||||
.afterRebuildExecution(new IncrementalBuildHelperRequest().outputDirectory(generatedDirectory));
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -34,18 +34,15 @@ final class ManifestCreator {
|
||||
Manifest manifest = new Manifest();
|
||||
Plugin verifierMavenPlugin = findMavenPlugin(project.getBuildPlugins());
|
||||
if (verifierMavenPlugin != null) {
|
||||
manifest.addConfiguredAttribute(
|
||||
new Manifest.Attribute("Spring-Cloud-Contract-Maven-Plugin-Version",
|
||||
verifierMavenPlugin.getVersion()));
|
||||
manifest.addConfiguredAttribute(new Manifest.Attribute("Spring-Cloud-Contract-Maven-Plugin-Version",
|
||||
verifierMavenPlugin.getVersion()));
|
||||
}
|
||||
if (verifierMavenPlugin != null
|
||||
&& !verifierMavenPlugin.getDependencies().isEmpty()) {
|
||||
Dependency verifierDependency = findVerifierDependency(
|
||||
verifierMavenPlugin.getDependencies());
|
||||
if (verifierMavenPlugin != null && !verifierMavenPlugin.getDependencies().isEmpty()) {
|
||||
Dependency verifierDependency = findVerifierDependency(verifierMavenPlugin.getDependencies());
|
||||
if (verifierDependency != null) {
|
||||
String verifierVersion = verifierDependency.getVersion();
|
||||
manifest.addConfiguredAttribute(new Manifest.Attribute(
|
||||
"Spring-Cloud-Contract-Verifier-Version", verifierVersion));
|
||||
manifest.addConfiguredAttribute(
|
||||
new Manifest.Attribute("Spring-Cloud-Contract-Verifier-Version", verifierVersion));
|
||||
}
|
||||
}
|
||||
return manifest;
|
||||
|
||||
@@ -73,12 +73,10 @@ class MavenContractsDownloader {
|
||||
|
||||
private final boolean failOnNoStubs;
|
||||
|
||||
MavenContractsDownloader(MavenProject project, Dependency contractDependency,
|
||||
String contractsPath, String contractsRepositoryUrl,
|
||||
StubRunnerProperties.StubsMode stubsMode, Log log, String repositoryUsername,
|
||||
String repositoryPassword, String repositoryProxyHost,
|
||||
Integer repositoryProxyPort, boolean deleteStubsAfterTest,
|
||||
Map<String, String> contractsProperties, boolean failOnNoContracts) {
|
||||
MavenContractsDownloader(MavenProject project, Dependency contractDependency, String contractsPath,
|
||||
String contractsRepositoryUrl, StubRunnerProperties.StubsMode stubsMode, Log log, String repositoryUsername,
|
||||
String repositoryPassword, String repositoryProxyHost, Integer repositoryProxyPort,
|
||||
boolean deleteStubsAfterTest, Map<String, String> contractsProperties, boolean failOnNoContracts) {
|
||||
this.project = project;
|
||||
this.contractDependency = contractDependency;
|
||||
this.contractsPath = contractsPath;
|
||||
@@ -95,54 +93,42 @@ class MavenContractsDownloader {
|
||||
this.failOnNoStubs = failOnNoContracts;
|
||||
}
|
||||
|
||||
File downloadAndUnpackContractsIfRequired(ContractVerifierConfigProperties config,
|
||||
File defaultContractsDir) {
|
||||
String contractsDirFromProp = this.project.getProperties()
|
||||
.getProperty(CONTRACTS_DIRECTORY_PROP);
|
||||
File downloadedContractsDir = StringUtils.hasText(contractsDirFromProp)
|
||||
? new File(contractsDirFromProp) : null;
|
||||
File downloadAndUnpackContractsIfRequired(ContractVerifierConfigProperties config, File defaultContractsDir) {
|
||||
String contractsDirFromProp = this.project.getProperties().getProperty(CONTRACTS_DIRECTORY_PROP);
|
||||
File downloadedContractsDir = StringUtils.hasText(contractsDirFromProp) ? new File(contractsDirFromProp) : null;
|
||||
// reuse downloaded contracts from another mojo
|
||||
if (downloadedContractsDir != null && downloadedContractsDir.exists()) {
|
||||
this.log.info(
|
||||
"Another mojo has downloaded the contracts - will reuse them from ["
|
||||
+ downloadedContractsDir + "]");
|
||||
this.log.info("Another mojo has downloaded the contracts - will reuse them from [" + downloadedContractsDir
|
||||
+ "]");
|
||||
final ContractDownloader.InclusionProperties inclusionProperties = contractDownloader()
|
||||
.createNewInclusionProperties(downloadedContractsDir);
|
||||
config.setIncludedContracts(inclusionProperties.getIncludedContracts());
|
||||
config.setIncludedRootFolderAntPattern(
|
||||
inclusionProperties.getIncludedRootFolderAntPattern());
|
||||
config.setIncludedRootFolderAntPattern(inclusionProperties.getIncludedRootFolderAntPattern());
|
||||
return downloadedContractsDir;
|
||||
}
|
||||
else if (shouldDownloadContracts()) {
|
||||
this.log.info(
|
||||
"Download dependency is provided - will retrieve contracts from a remote location");
|
||||
this.log.info("Download dependency is provided - will retrieve contracts from a remote location");
|
||||
final ContractDownloader contractDownloader = contractDownloader();
|
||||
final File downloadedContracts = contractDownloader
|
||||
.unpackAndDownloadContracts();
|
||||
final File downloadedContracts = contractDownloader.unpackAndDownloadContracts();
|
||||
final ContractDownloader.InclusionProperties inclusionProperties = contractDownloader
|
||||
.createNewInclusionProperties(downloadedContracts);
|
||||
config.setIncludedContracts(inclusionProperties.getIncludedContracts());
|
||||
config.setIncludedRootFolderAntPattern(
|
||||
inclusionProperties.getIncludedRootFolderAntPattern());
|
||||
this.project.getProperties().setProperty(CONTRACTS_DIRECTORY_PROP,
|
||||
downloadedContracts.getAbsolutePath());
|
||||
config.setIncludedRootFolderAntPattern(inclusionProperties.getIncludedRootFolderAntPattern());
|
||||
this.project.getProperties().setProperty(CONTRACTS_DIRECTORY_PROP, downloadedContracts.getAbsolutePath());
|
||||
return downloadedContracts;
|
||||
}
|
||||
this.log.info("Will use contracts provided in the folder [" + defaultContractsDir
|
||||
+ "]");
|
||||
this.log.info("Will use contracts provided in the folder [" + defaultContractsDir + "]");
|
||||
return defaultContractsDir;
|
||||
}
|
||||
|
||||
private boolean shouldDownloadContracts() {
|
||||
return this.contractDependency != null
|
||||
&& StringUtils.hasText(this.contractDependency.getArtifactId())
|
||||
return this.contractDependency != null && StringUtils.hasText(this.contractDependency.getArtifactId())
|
||||
|| StringUtils.hasText(this.contractsRepositoryUrl);
|
||||
}
|
||||
|
||||
private ContractDownloader contractDownloader() {
|
||||
return new ContractDownloader(stubDownloader(), stubConfiguration(),
|
||||
this.contractsPath, this.project.getGroupId(),
|
||||
this.project.getArtifactId(), this.project.getVersion());
|
||||
return new ContractDownloader(stubDownloader(), stubConfiguration(), this.contractsPath,
|
||||
this.project.getGroupId(), this.project.getArtifactId(), this.project.getVersion());
|
||||
}
|
||||
|
||||
private StubDownloader stubDownloader() {
|
||||
@@ -152,11 +138,9 @@ 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)
|
||||
.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);
|
||||
|
||||
@@ -40,12 +40,10 @@ import org.springframework.util.StringUtils;
|
||||
@Mojo(name = "pushStubsToScm")
|
||||
public class PushStubsToScmMojo extends AbstractMojo {
|
||||
|
||||
@Parameter(defaultValue = "${project.build.directory}", readonly = true,
|
||||
required = true)
|
||||
@Parameter(defaultValue = "${project.build.directory}", readonly = true, required = true)
|
||||
private File projectBuildDirectory;
|
||||
|
||||
@Parameter(property = "stubsDirectory",
|
||||
defaultValue = "${project.build.directory}/stubs")
|
||||
@Parameter(property = "stubsDirectory", defaultValue = "${project.build.directory}/stubs")
|
||||
private File outputDirectory;
|
||||
|
||||
/**
|
||||
@@ -57,8 +55,7 @@ public class PushStubsToScmMojo extends AbstractMojo {
|
||||
/**
|
||||
* Set this to "true" to bypass only JAR creation.
|
||||
*/
|
||||
@Parameter(property = "spring.cloud.contract.verifier.publish-stubs-to-scm.skip",
|
||||
defaultValue = "false")
|
||||
@Parameter(property = "spring.cloud.contract.verifier.publish-stubs-to-scm.skip", defaultValue = "false")
|
||||
private boolean taskSkip;
|
||||
|
||||
@Parameter(defaultValue = "${project}", readonly = true)
|
||||
@@ -107,34 +104,27 @@ public class PushStubsToScmMojo extends AbstractMojo {
|
||||
@Override
|
||||
public void execute() {
|
||||
if (this.skip || this.taskSkip) {
|
||||
getLog().info(
|
||||
"Skipping Spring Cloud Contract Verifier execution: spring.cloud.contract.verifier.skip="
|
||||
+ this.skip
|
||||
+ ", spring.cloud.contract.verifier.publish-stubs-to-scm.skip="
|
||||
+ this.taskSkip);
|
||||
getLog().info("Skipping Spring Cloud Contract Verifier execution: spring.cloud.contract.verifier.skip="
|
||||
+ this.skip + ", spring.cloud.contract.verifier.publish-stubs-to-scm.skip=" + this.taskSkip);
|
||||
return;
|
||||
}
|
||||
if (StringUtils.isEmpty(this.contractsRepositoryUrl) || !ScmStubDownloaderBuilder
|
||||
.isProtocolAccepted(this.contractsRepositoryUrl)) {
|
||||
if (StringUtils.isEmpty(this.contractsRepositoryUrl)
|
||||
|| !ScmStubDownloaderBuilder.isProtocolAccepted(this.contractsRepositoryUrl)) {
|
||||
getLog().info("Skipping pushing stubs to scm since your "
|
||||
+ "[contractsRepositoryUrl] property doesn't match any of the accepted protocols");
|
||||
return;
|
||||
}
|
||||
String projectName = this.project.getGroupId() + ":"
|
||||
+ this.project.getArtifactId() + ":" + this.project.getVersion();
|
||||
String projectName = this.project.getGroupId() + ":" + this.project.getArtifactId() + ":"
|
||||
+ this.project.getVersion();
|
||||
getLog().info("Pushing Stubs to SCM for project [" + projectName + "]");
|
||||
new ContractProjectUpdater(buildOptions()).updateContractProject(projectName,
|
||||
this.outputDirectory.toPath());
|
||||
new ContractProjectUpdater(buildOptions()).updateContractProject(projectName, this.outputDirectory.toPath());
|
||||
}
|
||||
|
||||
StubRunnerOptions buildOptions() {
|
||||
StubRunnerOptionsBuilder builder = new StubRunnerOptionsBuilder()
|
||||
.withOptions(StubRunnerOptions.fromSystemProps())
|
||||
.withStubRepositoryRoot(this.contractsRepositoryUrl)
|
||||
.withStubsMode(this.contractsMode)
|
||||
.withUsername(this.contractsRepositoryUsername)
|
||||
.withPassword(this.contractsRepositoryPassword)
|
||||
.withDeleteStubsAfterTest(this.deleteStubsAfterTest)
|
||||
.withOptions(StubRunnerOptions.fromSystemProps()).withStubRepositoryRoot(this.contractsRepositoryUrl)
|
||||
.withStubsMode(this.contractsMode).withUsername(this.contractsRepositoryUsername)
|
||||
.withPassword(this.contractsRepositoryPassword).withDeleteStubsAfterTest(this.deleteStubsAfterTest)
|
||||
.withProperties(this.contractsProperties);
|
||||
return builder.build();
|
||||
}
|
||||
|
||||
@@ -45,8 +45,7 @@ import org.springframework.util.StringUtils;
|
||||
* @author Mariusz Smykula
|
||||
* @author Eddú Meléndez
|
||||
*/
|
||||
@Mojo(name = "run", requiresProject = false,
|
||||
requiresDependencyResolution = ResolutionScope.RUNTIME)
|
||||
@Mojo(name = "run", requiresProject = false, requiresDependencyResolution = ResolutionScope.RUNTIME)
|
||||
public class RunMojo extends AbstractMojo {
|
||||
|
||||
private final LocalStubRunner localStubRunner;
|
||||
@@ -65,8 +64,7 @@ public class RunMojo extends AbstractMojo {
|
||||
/**
|
||||
* HTTP port for the WireMock server that serves stubs.
|
||||
*/
|
||||
@Parameter(property = "spring.cloud.contract.verifier.http.port",
|
||||
defaultValue = "8080")
|
||||
@Parameter(property = "spring.cloud.contract.verifier.http.port", defaultValue = "8080")
|
||||
private int httpPort;
|
||||
|
||||
/**
|
||||
@@ -78,8 +76,7 @@ public class RunMojo extends AbstractMojo {
|
||||
/**
|
||||
* Set this to "true" to bypass verifier test generation.
|
||||
*/
|
||||
@Parameter(property = "spring.cloud.contract.verifier.skipTestOnly",
|
||||
defaultValue = "false")
|
||||
@Parameter(property = "spring.cloud.contract.verifier.skipTestOnly", defaultValue = "false")
|
||||
private boolean skipTestOnly;
|
||||
|
||||
/**
|
||||
@@ -91,22 +88,19 @@ public class RunMojo extends AbstractMojo {
|
||||
/**
|
||||
* Minimal port at which the stub should start.
|
||||
*/
|
||||
@Parameter(property = "spring.cloud.contract.verifier.http.minPort",
|
||||
defaultValue = "10000")
|
||||
@Parameter(property = "spring.cloud.contract.verifier.http.minPort", defaultValue = "10000")
|
||||
private int minPort;
|
||||
|
||||
/**
|
||||
* Maximal port at which the stub should start.
|
||||
*/
|
||||
@Parameter(property = "spring.cloud.contract.verifier.http.maxPort",
|
||||
defaultValue = "15000")
|
||||
@Parameter(property = "spring.cloud.contract.verifier.http.maxPort", defaultValue = "15000")
|
||||
private int maxPort;
|
||||
|
||||
/**
|
||||
* Should the plugin wait for the user to press the key after starting the stubs.
|
||||
*/
|
||||
@Parameter(property = "spring.cloud.contract.verifier.wait-for-key-pressed",
|
||||
defaultValue = "true")
|
||||
@Parameter(property = "spring.cloud.contract.verifier.wait-for-key-pressed", defaultValue = "true")
|
||||
private boolean waitForKeyPressed;
|
||||
|
||||
/**
|
||||
@@ -133,24 +127,19 @@ public class RunMojo extends AbstractMojo {
|
||||
@Override
|
||||
public void execute() throws MojoExecutionException, MojoFailureException {
|
||||
if (this.skip || this.skipTestOnly) {
|
||||
getLog().info(
|
||||
"Skipping verifier execution: spring.cloud.contract.verifier.skip="
|
||||
+ this.skip);
|
||||
getLog().info("Skipping verifier execution: spring.cloud.contract.verifier.skip=" + this.skip);
|
||||
return;
|
||||
}
|
||||
BatchStubRunner batchStubRunner = null;
|
||||
StubRunnerOptionsBuilder optionsBuilder = new StubRunnerOptionsBuilder()
|
||||
.withStubsClassifier(this.stubsClassifier);
|
||||
if (StringUtils.isEmpty(this.stubs)) {
|
||||
StubRunnerOptions options = optionsBuilder
|
||||
.withMinMaxPort(this.httpPort, this.httpPort).build();
|
||||
StubRunner stubRunner = this.localStubRunner
|
||||
.run(resolveStubsDirectory().getAbsolutePath(), options);
|
||||
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)
|
||||
StubRunnerOptions options = optionsBuilder.withStubs(this.stubs).withMinMaxPort(this.minPort, this.maxPort)
|
||||
.withServerId(this.serverId).build();
|
||||
batchStubRunner = this.remoteStubRunner.run(options, this.repoSession);
|
||||
}
|
||||
|
||||
@@ -53,8 +53,7 @@ public class AetherStubDownloaderFactory {
|
||||
private final Settings settings;
|
||||
|
||||
@Inject
|
||||
public AetherStubDownloaderFactory(RepositorySystem repoSystem, MavenProject project,
|
||||
Settings settings) {
|
||||
public AetherStubDownloaderFactory(RepositorySystem repoSystem, MavenProject project, Settings settings) {
|
||||
this.repoSystem = repoSystem;
|
||||
this.project = project;
|
||||
this.settings = settings;
|
||||
@@ -64,13 +63,10 @@ public class AetherStubDownloaderFactory {
|
||||
return new StubDownloaderBuilder() {
|
||||
@Override
|
||||
public StubDownloader build(StubRunnerOptions stubRunnerOptions) {
|
||||
log.info(
|
||||
"Will download contracts using current build's Maven repository setup");
|
||||
return new AetherStubDownloader(
|
||||
AetherStubDownloaderFactory.this.repoSystem,
|
||||
AetherStubDownloaderFactory.this.project
|
||||
.getRemoteProjectRepositories(),
|
||||
repoSession, AetherStubDownloaderFactory.this.settings);
|
||||
log.info("Will download contracts using current build's Maven repository setup");
|
||||
return new AetherStubDownloader(AetherStubDownloaderFactory.this.repoSystem,
|
||||
AetherStubDownloaderFactory.this.project.getRemoteProjectRepositories(), repoSession,
|
||||
AetherStubDownloaderFactory.this.settings);
|
||||
}
|
||||
|
||||
@Override
|
||||
|
||||
@@ -37,8 +37,7 @@ public class LocalStubRunner {
|
||||
|
||||
public StubRunner run(final String contractsDir, StubRunnerOptions options) {
|
||||
log.info("Launching StubRunner with contracts from " + contractsDir);
|
||||
StubRunner stubRunner = new StubRunner(options, contractsDir,
|
||||
new StubConfiguration(contractsDir));
|
||||
StubRunner stubRunner = new StubRunner(options, contractsDir, new StubConfiguration(contractsDir));
|
||||
stubRunner.runStubs();
|
||||
return stubRunner;
|
||||
}
|
||||
|
||||
@@ -46,23 +46,19 @@ public class RemoteStubRunner {
|
||||
this.aetherStubDownloaderFactory = aetherStubDownloaderFactory;
|
||||
}
|
||||
|
||||
public BatchStubRunner run(StubRunnerOptions options,
|
||||
RepositorySystemSession repositorySystemSession) {
|
||||
StubDownloader stubDownloader = this.aetherStubDownloaderFactory
|
||||
.build(repositorySystemSession).build(options);
|
||||
public BatchStubRunner run(StubRunnerOptions options, RepositorySystemSession repositorySystemSession) {
|
||||
StubDownloader stubDownloader = this.aetherStubDownloaderFactory.build(repositorySystemSession).build(options);
|
||||
try {
|
||||
if (log.isDebugEnabled()) {
|
||||
log.debug("Launching StubRunner with args: " + options);
|
||||
}
|
||||
BatchStubRunner stubRunner = new BatchStubRunnerFactory(options,
|
||||
stubDownloader).buildBatchStubRunner();
|
||||
BatchStubRunner stubRunner = new BatchStubRunnerFactory(options, stubDownloader).buildBatchStubRunner();
|
||||
RunningStubs runningCollaborators = stubRunner.runStubs();
|
||||
log.info(runningCollaborators.toString());
|
||||
return stubRunner;
|
||||
}
|
||||
catch (Exception e) {
|
||||
log.error("An exception occurred while trying to execute the stubs: "
|
||||
+ e.getMessage());
|
||||
log.error("An exception occurred while trying to execute the stubs: " + e.getMessage());
|
||||
throw e;
|
||||
}
|
||||
|
||||
|
||||
@@ -63,8 +63,7 @@ public abstract class AbstractMojoTest {
|
||||
return new File(this.tmpFolder, name);
|
||||
}
|
||||
|
||||
protected void executeMojo(File baseDir, String goal, Xpp3Dom... parameters)
|
||||
throws Exception {
|
||||
protected void executeMojo(File baseDir, String goal, Xpp3Dom... parameters) throws Exception {
|
||||
MavenProject mavenProject = rule.readMavenProject(baseDir);
|
||||
MavenSession mavenSession = rule.newMavenSession(mavenProject);
|
||||
rule.executeMojo(mavenSession, mavenProject, goal, parameters);
|
||||
|
||||
@@ -43,15 +43,13 @@ public class PluginUnitTest extends AbstractMojoTest {
|
||||
}
|
||||
|
||||
private Xpp3Dom defaultPackageForTests() {
|
||||
return newParameter("basePackageForTests",
|
||||
"org.springframework.cloud.contract.verifier.tests");
|
||||
return newParameter("basePackageForTests", "org.springframework.cloud.contract.verifier.tests");
|
||||
}
|
||||
|
||||
@Test
|
||||
public void shouldGenerateWireMockFromStubsDirectory() throws Exception {
|
||||
File basedir = getBasedir("withStubs");
|
||||
executeMojo(basedir, "convert",
|
||||
newParameter("contractsDirectory", "src/test/resources/stubs"));
|
||||
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));
|
||||
@@ -80,8 +78,7 @@ public class PluginUnitTest extends AbstractMojoTest {
|
||||
@Test
|
||||
public void shouldGenerateContractSpecificationInDefaultLocation() throws Exception {
|
||||
File basedir = getBasedir("basic");
|
||||
executeMojo(basedir, "generateTests", defaultPackageForTests(),
|
||||
newParameter("testFramework", "SPOCK"));
|
||||
executeMojo(basedir, "generateTests", defaultPackageForTests(), newParameter("testFramework", "SPOCK"));
|
||||
String path = "target/generated-test-sources/contracts/org/springframework/cloud/contract/verifier/tests/ContractVerifierSpec.groovy";
|
||||
assertFilesPresent(basedir, path);
|
||||
File test = new File(basedir, path);
|
||||
@@ -99,8 +96,7 @@ public class PluginUnitTest extends AbstractMojoTest {
|
||||
@Test
|
||||
public void shouldGenerateContractTestsWithCustomImports() throws Exception {
|
||||
File basedir = getBasedir("basic");
|
||||
executeMojo(basedir, "generateTests", defaultPackageForTests(),
|
||||
newParameter("imports", ""));
|
||||
executeMojo(basedir, "generateTests", defaultPackageForTests(), newParameter("imports", ""));
|
||||
assertFilesPresent(basedir,
|
||||
"target/generated-test-sources/contracts/org/springframework/cloud/contract/verifier/tests/ContractVerifierTest.java");
|
||||
}
|
||||
@@ -119,8 +115,7 @@ public class PluginUnitTest extends AbstractMojoTest {
|
||||
@Test
|
||||
public void shouldGenerateContractTestsWithArraySize() throws Exception {
|
||||
File basedir = getBasedir("basic");
|
||||
executeMojo(basedir, "generateTests", defaultPackageForTests(),
|
||||
newParameter("assertJsonSize", "true"));
|
||||
executeMojo(basedir, "generateTests", defaultPackageForTests(), newParameter("assertJsonSize", "true"));
|
||||
assertFilesPresent(basedir,
|
||||
"target/generated-test-sources/contracts/org/springframework/cloud/contract/verifier/tests/ContractVerifierTest.java");
|
||||
File test = new File(basedir,
|
||||
@@ -153,24 +148,17 @@ 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");
|
||||
}
|
||||
|
||||
@Test
|
||||
public void shouldGenerateStubsByDownloadingContractsFromARepoWhenCustomPathIsProvided()
|
||||
throws Exception {
|
||||
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,
|
||||
@@ -188,8 +176,7 @@ public class PluginUnitTest extends AbstractMojoTest {
|
||||
}
|
||||
|
||||
@Test
|
||||
public void shouldGenerateOutputWhenCalledGenerateTestsFromRootProject()
|
||||
throws Exception {
|
||||
public void shouldGenerateOutputWhenCalledGenerateTestsFromRootProject() throws Exception {
|
||||
File basedir = getBasedir("different-module-configuration");
|
||||
executeMojo(basedir, "generateTests", defaultPackageForTests());
|
||||
assertFilesPresent(basedir,
|
||||
@@ -200,38 +187,30 @@ 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");
|
||||
}
|
||||
|
||||
@Test
|
||||
public void shouldGenerateTestsByDownloadingContractsFromARepoWhenCustomPathIsProvided()
|
||||
throws Exception {
|
||||
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,
|
||||
"target/generated-test-sources/contracts/org/springframework/cloud/contract/verifier/tests/com/foo/bar/BazTest.java");
|
||||
assertFilesNotPresent(basedir,
|
||||
"target/stubs/contracts/com/foo/bar/baz/shouldBeIgnoredByPlugin.groovy");
|
||||
assertFilesNotPresent(basedir, "target/stubs/contracts/com/foo/bar/baz/shouldBeIgnoredByPlugin.groovy");
|
||||
}
|
||||
|
||||
@Test
|
||||
public void shouldGenerateContractTestsWithBaseClassResolvedFromConvention()
|
||||
throws Exception {
|
||||
public void shouldGenerateContractTestsWithBaseClassResolvedFromConvention() throws Exception {
|
||||
File basedir = getBasedir("basic-generated-baseclass");
|
||||
|
||||
executeMojo(basedir, "generateTests", defaultPackageForTests(),
|
||||
newParameter("testFramework", "JUNIT"));
|
||||
executeMojo(basedir, "generateTests", defaultPackageForTests(), newParameter("testFramework", "JUNIT"));
|
||||
|
||||
String path = "target/generated-test-sources/contracts/org/springframework/cloud/contract/verifier/tests/hello/V1Test.java";
|
||||
assertFilesPresent(basedir, path);
|
||||
@@ -241,12 +220,10 @@ public class PluginUnitTest extends AbstractMojoTest {
|
||||
}
|
||||
|
||||
@Test
|
||||
public void shouldGenerateContractTestsWithBaseClassResolvedFromConventionForSpock()
|
||||
throws Exception {
|
||||
public void shouldGenerateContractTestsWithBaseClassResolvedFromConventionForSpock() throws Exception {
|
||||
File basedir = getBasedir("basic-generated-baseclass");
|
||||
|
||||
executeMojo(basedir, "generateTests", defaultPackageForTests(),
|
||||
newParameter("testFramework", "SPOCK"));
|
||||
executeMojo(basedir, "generateTests", defaultPackageForTests(), newParameter("testFramework", "SPOCK"));
|
||||
|
||||
String path = "target/generated-test-sources/contracts/org/springframework/cloud/contract/verifier/tests/hello/V1Spec.groovy";
|
||||
assertFilesPresent(basedir, path);
|
||||
@@ -256,12 +233,10 @@ public class PluginUnitTest extends AbstractMojoTest {
|
||||
}
|
||||
|
||||
@Test
|
||||
public void shouldGenerateContractTestsWithBaseClassResolvedFromMapping()
|
||||
throws Exception {
|
||||
public void shouldGenerateContractTestsWithBaseClassResolvedFromMapping() throws Exception {
|
||||
File basedir = getBasedir("basic-baseclass-from-mappings");
|
||||
|
||||
executeMojo(basedir, "generateTests", defaultPackageForTests(),
|
||||
newParameter("testFramework", "JUNIT"));
|
||||
executeMojo(basedir, "generateTests", defaultPackageForTests(), newParameter("testFramework", "JUNIT"));
|
||||
|
||||
String path = "target/generated-test-sources/contracts/org/springframework/cloud/contract/verifier/tests/com/hello/V1Test.java";
|
||||
assertFilesPresent(basedir, path);
|
||||
@@ -271,12 +246,10 @@ public class PluginUnitTest extends AbstractMojoTest {
|
||||
}
|
||||
|
||||
@Test
|
||||
public void shouldGenerateContractTestsWithBaseClassResolvedFromMappingNameForSpock()
|
||||
throws Exception {
|
||||
public void shouldGenerateContractTestsWithBaseClassResolvedFromMappingNameForSpock() throws Exception {
|
||||
File basedir = getBasedir("basic-baseclass-from-mappings");
|
||||
|
||||
executeMojo(basedir, "generateTests", defaultPackageForTests(),
|
||||
newParameter("testFramework", "SPOCK"));
|
||||
executeMojo(basedir, "generateTests", defaultPackageForTests(), newParameter("testFramework", "SPOCK"));
|
||||
|
||||
String path = "target/generated-test-sources/contracts/org/springframework/cloud/contract/verifier/tests/com/hello/V1Spec.groovy";
|
||||
assertFilesPresent(basedir, path);
|
||||
@@ -286,12 +259,10 @@ public class PluginUnitTest extends AbstractMojoTest {
|
||||
}
|
||||
|
||||
@Test
|
||||
public void shouldGenerateContractTestsWithAFileContainingAListOfContracts()
|
||||
throws Exception {
|
||||
public void shouldGenerateContractTestsWithAFileContainingAListOfContracts() throws Exception {
|
||||
File basedir = getBasedir("multiple-contracts");
|
||||
|
||||
executeMojo(basedir, "generateTests", defaultPackageForTests(),
|
||||
newParameter("testFramework", "JUNIT"));
|
||||
executeMojo(basedir, "generateTests", defaultPackageForTests(), newParameter("testFramework", "JUNIT"));
|
||||
|
||||
String path = "target/generated-test-sources/contracts/org/springframework/cloud/contract/verifier/tests/com/hello/V1Test.java";
|
||||
assertFilesPresent(basedir, path);
|
||||
@@ -302,8 +273,7 @@ public class PluginUnitTest extends AbstractMojoTest {
|
||||
}
|
||||
|
||||
@Test
|
||||
public void shouldGenerateStubsWithAFileContainingAListOfContracts()
|
||||
throws Exception {
|
||||
public void shouldGenerateStubsWithAFileContainingAListOfContracts() throws Exception {
|
||||
File basedir = getBasedir("multiple-contracts");
|
||||
|
||||
executeMojo(basedir, "convert", newParameter("stubsDirectory", "target/foo"));
|
||||
@@ -347,8 +317,7 @@ public class PluginUnitTest extends AbstractMojoTest {
|
||||
File test = new File(basedir,
|
||||
"target/generated-test-sources/contracts/org/springframework/cloud/contract/verifier/tests/ContractVerifierTest.java");
|
||||
String testContents = readFileToString(test, defaultCharset());
|
||||
int countOccurrencesOf = StringUtils.countOccurrencesOf(testContents,
|
||||
"\t\tMockMvcRequestSpecification");
|
||||
int countOccurrencesOf = StringUtils.countOccurrencesOf(testContents, "\t\tMockMvcRequestSpecification");
|
||||
then(countOccurrencesOf).isEqualTo(4);
|
||||
}
|
||||
|
||||
@@ -358,8 +327,7 @@ public class PluginUnitTest extends AbstractMojoTest {
|
||||
|
||||
executeMojo(basedir, "pushStubsToScm");
|
||||
|
||||
then(this.capture.toString())
|
||||
.contains("Skipping pushing stubs to scm since your");
|
||||
then(this.capture.toString()).contains("Skipping pushing stubs to scm since your");
|
||||
}
|
||||
|
||||
@Test
|
||||
@@ -367,10 +335,8 @@ 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,
|
||||
|
||||
@@ -62,8 +62,7 @@ import org.springframework.util.StringUtils;
|
||||
*/
|
||||
public final class PactStubDownloaderBuilder implements StubDownloaderBuilder {
|
||||
|
||||
private static final List<String> ACCEPTABLE_PROTOCOLS = Collections
|
||||
.singletonList("pact");
|
||||
private static final List<String> ACCEPTABLE_PROTOCOLS = Collections.singletonList("pact");
|
||||
|
||||
/**
|
||||
* Does any of the accepted protocols matches the URL of the repository.
|
||||
@@ -149,11 +148,9 @@ class PactStubDownloader implements StubDownloader {
|
||||
}
|
||||
|
||||
@Override
|
||||
public Map.Entry<StubConfiguration, File> downloadAndUnpackStubJar(
|
||||
StubConfiguration stubConfiguration) {
|
||||
public Map.Entry<StubConfiguration, File> downloadAndUnpackStubJar(StubConfiguration stubConfiguration) {
|
||||
String version = stubConfiguration.version;
|
||||
final FromPropsThenFromSysEnv resolver = new FromPropsThenFromSysEnv(
|
||||
this.stubRunnerOptions);
|
||||
final FromPropsThenFromSysEnv resolver = new FromPropsThenFromSysEnv(this.stubRunnerOptions);
|
||||
List<String> tags = tags(version, resolver);
|
||||
try {
|
||||
PactLoader loader = pactBrokerLoader(resolver, tags);
|
||||
@@ -161,16 +158,14 @@ class PactStubDownloader implements StubDownloader {
|
||||
List<Pact> pacts = loader.load(providerName);
|
||||
if (pacts.isEmpty()) {
|
||||
if (log.isWarnEnabled()) {
|
||||
log.warn("No pact definitions found for provider [" + providerName
|
||||
+ "]");
|
||||
log.warn("No pact definitions found for provider [" + providerName + "]");
|
||||
}
|
||||
return null;
|
||||
}
|
||||
File tmpDirWhereStubsWillBeUnzipped = TemporaryFileStorage
|
||||
.createTempDir(TEMP_DIR_PREFIX);
|
||||
File tmpDirWhereStubsWillBeUnzipped = TemporaryFileStorage.createTempDir(TEMP_DIR_PREFIX);
|
||||
// make the groupid / artifactid folders
|
||||
String coordinatesFolderName = stubConfiguration.getGroupId().replace(".",
|
||||
File.separator) + File.separator + stubConfiguration.getArtifactId();
|
||||
String coordinatesFolderName = stubConfiguration.getGroupId().replace(".", File.separator) + File.separator
|
||||
+ stubConfiguration.getArtifactId();
|
||||
File contractsFolder = new File(tmpDirWhereStubsWillBeUnzipped,
|
||||
coordinatesFolderName + File.separator + "contracts");
|
||||
File mappingsFolder = new File(tmpDirWhereStubsWillBeUnzipped,
|
||||
@@ -178,25 +173,21 @@ class PactStubDownloader implements StubDownloader {
|
||||
boolean createdContractsDirs = contractsFolder.mkdirs();
|
||||
boolean createdMappingsDirs = mappingsFolder.mkdirs();
|
||||
if (!createdContractsDirs || !createdMappingsDirs) {
|
||||
throw new IllegalStateException(
|
||||
"Failed to create mandatory [contracts] or [mappings] folders under ["
|
||||
+ coordinatesFolderName + "]");
|
||||
throw new IllegalStateException("Failed to create mandatory [contracts] or [mappings] folders under ["
|
||||
+ coordinatesFolderName + "]");
|
||||
}
|
||||
storePacts(providerName, pacts, contractsFolder, mappingsFolder);
|
||||
return new AbstractMap.SimpleEntry<>(stubConfiguration,
|
||||
tmpDirWhereStubsWillBeUnzipped);
|
||||
return new AbstractMap.SimpleEntry<>(stubConfiguration, tmpDirWhereStubsWillBeUnzipped);
|
||||
}
|
||||
catch (IOException e) {
|
||||
throw new IllegalStateException(e);
|
||||
}
|
||||
}
|
||||
|
||||
private void storePacts(String providerName, List<Pact> pacts, File contractsFolder,
|
||||
File mappingsFolder) {
|
||||
private void storePacts(String providerName, List<Pact> pacts, File contractsFolder, File mappingsFolder) {
|
||||
for (int i = 0; i < pacts.size(); i++) {
|
||||
String json = toJson(pacts.get(i).toMap(PactSpecVersion.V3));
|
||||
File file = new File(contractsFolder,
|
||||
i + "_" + providerName.replace(":", "_") + "_pact.json");
|
||||
File file = new File(contractsFolder, i + "_" + providerName.replace(":", "_") + "_pact.json");
|
||||
storeFile(file.toPath(), json.getBytes());
|
||||
try {
|
||||
storeMapping(mappingsFolder, file);
|
||||
@@ -210,8 +201,7 @@ class PactStubDownloader implements StubDownloader {
|
||||
private void storeMapping(File mappingsFolder, File file) {
|
||||
Collection<Contract> contracts = new PactContractConverter().convertFrom(file);
|
||||
if (log.isDebugEnabled()) {
|
||||
log.debug("Converted pact file [" + file + "] to [" + contracts.size()
|
||||
+ "] contracts");
|
||||
log.debug("Converted pact file [" + file + "] to [" + contracts.size() + "] contracts");
|
||||
}
|
||||
MappingGenerator.toMappings(file, contracts, mappingsFolder);
|
||||
}
|
||||
@@ -231,18 +221,15 @@ class PactStubDownloader implements StubDownloader {
|
||||
|
||||
private String providerName(StubConfiguration stubConfiguration) {
|
||||
boolean providerNameWithGroupId = Boolean.parseBoolean(StubRunnerPropertyUtils
|
||||
.getProperty(this.stubRunnerOptions.getProperties(),
|
||||
PROVIDER_NAME_WITH_GROUP_ID));
|
||||
.getProperty(this.stubRunnerOptions.getProperties(), PROVIDER_NAME_WITH_GROUP_ID));
|
||||
if (providerNameWithGroupId) {
|
||||
return stubConfiguration.getGroupId() + ":"
|
||||
+ stubConfiguration.getArtifactId();
|
||||
return stubConfiguration.getGroupId() + ":" + stubConfiguration.getArtifactId();
|
||||
}
|
||||
return stubConfiguration.getArtifactId();
|
||||
}
|
||||
|
||||
@NotNull
|
||||
PactLoader pactBrokerLoader(ValueResolver resolver, List<String> tags)
|
||||
throws IOException {
|
||||
PactLoader pactBrokerLoader(ValueResolver resolver, List<String> tags) throws IOException {
|
||||
Resource repo = this.stubRunnerOptions.getStubRepositoryRoot();
|
||||
String schemeSpecificPart = schemeSpecificPart(repo.getURI());
|
||||
URI pactBrokerUrl = URI.create(schemeSpecificPart);
|
||||
@@ -257,20 +244,17 @@ class PactStubDownloader implements StubDownloader {
|
||||
|
||||
@Override
|
||||
public String host() {
|
||||
return resolver
|
||||
.resolveValue("pactbroker.host:" + pactBrokerUrl.getHost());
|
||||
return resolver.resolveValue("pactbroker.host:" + pactBrokerUrl.getHost());
|
||||
}
|
||||
|
||||
@Override
|
||||
public String port() {
|
||||
return resolver
|
||||
.resolveValue("pactbroker.port:" + pactBrokerUrl.getPort());
|
||||
return resolver.resolveValue("pactbroker.port:" + pactBrokerUrl.getPort());
|
||||
}
|
||||
|
||||
@Override
|
||||
public String scheme() {
|
||||
return resolver
|
||||
.resolveValue("pactbroker.protocol:" + pactBrokerUrl.getScheme());
|
||||
return resolver.resolveValue("pactbroker.protocol:" + pactBrokerUrl.getScheme());
|
||||
}
|
||||
|
||||
@Override
|
||||
@@ -298,14 +282,12 @@ class PactStubDownloader implements StubDownloader {
|
||||
|
||||
@Override
|
||||
public String username() {
|
||||
return resolver.resolveValue(
|
||||
"pactbroker.auth.username:" + stubRunnerUsername);
|
||||
return resolver.resolveValue("pactbroker.auth.username:" + stubRunnerUsername);
|
||||
}
|
||||
|
||||
@Override
|
||||
public String password() {
|
||||
return resolver.resolveValue(
|
||||
"pactbroker.auth.password:" + stubRunnerPassword);
|
||||
return resolver.resolveValue("pactbroker.auth.password:" + stubRunnerPassword);
|
||||
}
|
||||
|
||||
@Override
|
||||
@@ -332,10 +314,9 @@ class PactStubDownloader implements StubDownloader {
|
||||
|
||||
@NotNull
|
||||
private List<String> tags(String version, ValueResolver resolver) {
|
||||
String defaultTag = StubConfiguration.DEFAULT_VERSION.equals(version) ? "latest"
|
||||
: version;
|
||||
return new ArrayList<>(Arrays.asList(StringUtils.commaDelimitedListToStringArray(
|
||||
resolver.resolveValue("pactbroker.tags:" + defaultTag + ""))));
|
||||
String defaultTag = StubConfiguration.DEFAULT_VERSION.equals(version) ? "latest" : version;
|
||||
return new ArrayList<>(Arrays.asList(StringUtils
|
||||
.commaDelimitedListToStringArray(resolver.resolveValue("pactbroker.tags:" + defaultTag + ""))));
|
||||
}
|
||||
|
||||
private String toJson(Map map) {
|
||||
@@ -348,8 +329,8 @@ class PactStubDownloader implements StubDownloader {
|
||||
}
|
||||
|
||||
private void registerShutdownHook() {
|
||||
Runtime.getRuntime().addShutdownHook(new Thread(() -> TemporaryFileStorage
|
||||
.cleanup(PactStubDownloader.this.deleteStubsAfterTest)));
|
||||
Runtime.getRuntime().addShutdownHook(
|
||||
new Thread(() -> TemporaryFileStorage.cleanup(PactStubDownloader.this.deleteStubsAfterTest)));
|
||||
}
|
||||
|
||||
}
|
||||
@@ -368,8 +349,7 @@ class FromPropsThenFromSysEnv implements ValueResolver {
|
||||
public String resolveValue(String expression) {
|
||||
PropertyValueTuple tuple = new PropertyValueTuple(expression).invoke();
|
||||
String propertyName = tuple.getPropertyName();
|
||||
String property = StubRunnerPropertyUtils
|
||||
.getProperty(this.options.getProperties(), propertyName);
|
||||
String property = StubRunnerPropertyUtils.getProperty(this.options.getProperties(), propertyName);
|
||||
if (StringUtils.hasText(property)) {
|
||||
return property;
|
||||
}
|
||||
@@ -380,8 +360,7 @@ class FromPropsThenFromSysEnv implements ValueResolver {
|
||||
public boolean propertyDefined(String property) {
|
||||
PropertyValueTuple tuple = new PropertyValueTuple(property).invoke();
|
||||
String propertyName = tuple.getPropertyName();
|
||||
boolean hasProperty = StubRunnerPropertyUtils
|
||||
.hasProperty(this.options.getProperties(), propertyName);
|
||||
boolean hasProperty = StubRunnerPropertyUtils.hasProperty(this.options.getProperties(), propertyName);
|
||||
if (hasProperty) {
|
||||
return true;
|
||||
}
|
||||
@@ -406,8 +385,7 @@ class PropertyValueTuple {
|
||||
|
||||
PropertyValueTuple invoke() {
|
||||
if (this.propertyName.contains(":")) {
|
||||
String[] kv = org.apache.commons.lang3.StringUtils
|
||||
.splitPreserveAllTokens(this.propertyName, ':');
|
||||
String[] kv = org.apache.commons.lang3.StringUtils.splitPreserveAllTokens(this.propertyName, ':');
|
||||
this.propertyName = kv[0];
|
||||
}
|
||||
return this;
|
||||
|
||||
Reference in New Issue
Block a user