Consumer Contracts (#83)

With this functionality you can have one centralized repository containing all contracts. This repo will have to produce a JAR containing all contracts. The layout of the repository can be arbitrary but some sensible defaults are assumed. The producer will be able to then download that JAR and produce tests and stubs from it.

fixes #38
This commit is contained in:
Marcin Grzejszczak
2016-09-23 10:16:51 +02:00
committed by GitHub
parent 93782cb049
commit 01f4ad76be
50 changed files with 1995 additions and 168 deletions

View File

@@ -0,0 +1,127 @@
package org.springframework.cloud.contract.verifier.plugin
import groovy.transform.ToString
import org.springframework.cloud.contract.verifier.config.TestFramework
import org.springframework.cloud.contract.verifier.config.TestMode
/**
* @author Marcin Grzejszczak
*/
@ToString
class ContractVerifierExtension {
/**
* For which unit test library tests should be generated
*/
TestFramework targetFramework = TestFramework.JUNIT
/**
* Which mechanism should be used to invoke REST calls during tests
*/
TestMode testMode = TestMode.MOCKMVC
/**
* Base package for generated tests
*/
String basePackageForTests
/**
* Class which all generated tests should extend
*/
String baseClassForTests
/**
* Suffix for generated test classes, like Spec or Test
*/
String nameSuffixForTests
/**
* Rule class that should be added to generated tests
*/
String ruleClassForTests
/**
* Patterns that should not be taken into account for processing
*/
List<String> excludedFiles = []
/**
* Patterns for which generated tests should be @Ignored
*/
List<String> ignoredFiles = []
/**
* Imports that should be added to generated tests
*/
String[] imports = []
/**
* Static imports that should be added to generated tests
*/
String[] staticImports = []
/**
* Directory containing contracts written using the GroovyDSL
*/
File contractsDslDir
/**
* Test source directory where tests generated from Groovy DSL should be placed
*/
File generatedTestSourcesDir
/**
* Dir where the generated WireMock stubs from Groovy DSL should be placed.
* You can then mention them in your packaging task to create jar with stubs
*/
File stubsOutputDir
/**
* Suffix for the generated Stubs Jar task
*/
String stubsSuffix = 'stubs'
/**
* Incubating feature. You can check the size of JSON arrays. If not turned on
* explicitly will be disabled.
*/
Boolean assertJsonSize = false
/**
* The URL from which a JAR containing the contracts should get downloaded. If not provided
* but artifactid / coordinates notation was provided then the current Maven's build repositories will be
* taken into consideration
*/
String contractsRepositoryUrl
/**
* Dependency that contains packaged contracts
*/
Dependency contractDependency = new Dependency()
/**
* The path in the JAR with all the contracts where contracts for this particular service lay.
* If not provided will be resolved to {@code groupid/artifactid}. Example:
* </p>
* If {@code groupid} is {@code com.example} and {@code artifactid} is {@code service} then the resolved path will be
* {@code /com/example/artifactid}
*/
String contractsPath
/**
* If {@code true} then JAR with contracts will be taken from local maven repository
*/
boolean contractsWorkOffline
void contractDependency(@DelegatesTo(Dependency) Closure closure) {
closure.delegate = contractDependency
closure.call()
}
static class Dependency {
String groupId
String artifactId
String classifier
String version
String stringNotation
}
}

View File

@@ -0,0 +1,31 @@
package org.springframework.cloud.contract.verifier.plugin
import groovy.transform.PackageScope
import org.springframework.cloud.contract.verifier.config.ContractVerifierConfigProperties
/**
* @author Marcin Grzejszczak
*/
@PackageScope
class ExtensionToProperties {
protected static ContractVerifierConfigProperties fromExtension(ContractVerifierExtension extension) {
return new ContractVerifierConfigProperties(
targetFramework: extension.targetFramework,
testMode: extension.testMode,
basePackageForTests: extension.basePackageForTests,
baseClassForTests: extension.baseClassForTests,
nameSuffixForTests: extension.nameSuffixForTests,
ruleClassForTests: extension.ruleClassForTests,
excludedFiles: extension.excludedFiles,
ignoredFiles: extension.ignoredFiles,
imports: extension.imports,
staticImports: extension.staticImports,
contractsDslDir: extension.contractsDslDir,
generatedTestSourcesDir: extension.generatedTestSourcesDir,
stubsOutputDir: extension.stubsOutputDir,
stubsSuffix: extension.stubsSuffix,
assertJsonSize: extension.assertJsonSize
)
}
}

View File

@@ -38,7 +38,7 @@ class GenerateServerTestsTask extends ConventionTask {
File generatedTestSourcesDir
//TODO: How to deal with @Input*, @Output* and that domain object?
ContractVerifierConfigProperties configProperties
ContractVerifierExtension configProperties
@TaskAction
void generate() {
@@ -51,7 +51,9 @@ class GenerateServerTestsTask extends ConventionTask {
try {
//TODO: What with that? How to pass?
TestGenerator generator = new TestGenerator(getConfigProperties())
ContractVerifierConfigProperties props = ExtensionToProperties.fromExtension(getConfigProperties())
props.contractsDslDir = getContractsDslDir()
TestGenerator generator = new TestGenerator(props)
int generatedClasses = generator.generate()
project.logger.info("Generated {} test classes", generatedClasses)
} catch (ContractVerifierException e) {

View File

@@ -38,18 +38,19 @@ class GenerateWireMockClientStubsFromDslTask extends ConventionTask {
@OutputDirectory
File stubsOutputDir
ContractVerifierConfigProperties configProperties
ContractVerifierExtension configProperties
@TaskAction
void generate() {
logger.info("Spring Cloud Contract Verifier Plugin: Invoking DSL to WireMock client stubs conversion")
logger.debug("From '${getContractsDslDir()}' to '${getStubsOutputDir()}'")
ContractVerifierConfigProperties props = getConfigProperties()
ContractVerifierConfigProperties props = ExtensionToProperties.fromExtension(getConfigProperties())
props.contractsDslDir = getContractsDslDir()
File outMappingsDir = props.stubsOutputDir != null ? new File(props.stubsOutputDir, DEFAULT_MAPPINGS_FOLDER)
: new File(project.buildDir, "stubs/$DEFAULT_MAPPINGS_FOLDER")
RecursiveFilesConverter converter = new RecursiveFilesConverter(
new DslToWireMockClientConverter(),
getConfigProperties(), outMappingsDir)
props, outMappingsDir)
converter.processFiles()
}
}

View File

@@ -0,0 +1,82 @@
package org.springframework.cloud.contract.verifier.plugin
import groovy.transform.PackageScope
import org.gradle.api.Project
import org.gradle.api.logging.Logger
import org.springframework.cloud.contract.stubrunner.AetherStubDownloader
import org.springframework.cloud.contract.stubrunner.ContractDownloader
import org.springframework.cloud.contract.stubrunner.StubConfiguration
import org.springframework.cloud.contract.stubrunner.StubRunnerOptionsBuilder
import org.springframework.util.StringUtils
import java.util.concurrent.ConcurrentHashMap
/**
* @author Marcin Grzejszczak
*/
@PackageScope
class GradleContractsDownloader {
private static final String LATEST_VERSION = '+'
private final Project project
private final Logger log
private static final Map<StubConfiguration, File> downloadedContract = new ConcurrentHashMap<>()
GradleContractsDownloader(Project project, Logger log) {
this.project = project
this.log = log
}
File downloadAndUnpackContractsIfRequired(ContractVerifierExtension extension) {
File defaultContractsDir = extension.contractsDslDir
// download contracts, unzip them and pass as output directory
if (shouldDownloadContracts(extension)) {
this.log.info("For project [${this.project.name}] Download dependency is provided - will download contract jars")
StubConfiguration configuration = stubConfiguration(extension.contractDependency)
if (downloadedContract.get(configuration)) {
this.log.info("For project [${this.project.name}] Returning the cached location of the contracts")
return downloadedContract.get(configuration)
}
File downloadedContracts = contractDownloader(extension, configuration).unpackedDownloadedContracts(
ExtensionToProperties.fromExtension(extension))
downloadedContract.put(configuration, downloadedContracts)
return downloadedContracts
}
this.log.info("For project [${this.project.name}] will use contracts provided in the folder [" + defaultContractsDir + "]")
return defaultContractsDir
}
private boolean shouldDownloadContracts(ContractVerifierExtension extension) {
return StringUtils.hasText(extension.contractsRepositoryUrl) &&
(StringUtils.hasText(extension.contractDependency.artifactId) ||
StringUtils.hasText(extension.contractDependency.stringNotation))
}
private ContractDownloader contractDownloader(ContractVerifierExtension extension, StubConfiguration configuration) {
return new ContractDownloader(stubDownloader(extension), configuration,
extension.contractsPath, this.project.group as String, this.project.name)
}
private AetherStubDownloader stubDownloader(ContractVerifierExtension extension) {
return new AetherStubDownloader(
new StubRunnerOptionsBuilder()
.withStubRepositoryRoot(extension.contractsRepositoryUrl)
.withWorkOffline(extension.contractsWorkOffline)
.build())
}
private StubConfiguration stubConfiguration(ContractVerifierExtension.Dependency contractDependency) {
String groupId = contractDependency.groupId
String artifactId = contractDependency.artifactId
String version = StringUtils.hasText(contractDependency.version) ?
contractDependency.version : LATEST_VERSION
String classifier = contractDependency.classifier
String stringNotation = contractDependency.stringNotation
if (StringUtils.hasText(stringNotation)) {
StubConfiguration stubConfiguration = new StubConfiguration(stringNotation)
return new StubConfiguration(stubConfiguration.groupId, stubConfiguration.artifactId,
stubConfiguration.version, contractDependency.classifier)
}
return new StubConfiguration(groupId, artifactId, version, classifier)
}
}

View File

@@ -24,7 +24,6 @@ import org.gradle.api.publish.maven.MavenPublication
import org.gradle.api.publish.maven.plugins.MavenPublishPlugin
import org.gradle.api.tasks.Copy
import org.gradle.jvm.tasks.Jar
import org.springframework.cloud.contract.verifier.config.ContractVerifierConfigProperties
/**
* Gradle plugin for Spring Cloud Contract Verifier that from the DSL contract can
* <ul>
@@ -62,14 +61,15 @@ class SpringCloudContractVerifierGradlePlugin implements Plugin<Project> {
void apply(Project project) {
this.project = project
project.plugins.apply(GroovyPlugin)
ContractVerifierConfigProperties extension = project.extensions.create(EXTENSION_NAME, ContractVerifierConfigProperties)
ContractVerifierExtension extension = project.extensions.create(EXTENSION_NAME, ContractVerifierExtension)
GradleContractsDownloader downloader = new GradleContractsDownloader(this.project, this.project.logger)
project.check.dependsOn(GENERATE_SERVER_TESTS_TASK_NAME)
setConfigurationDefaults(extension)
createGenerateTestsTask(extension)
createAndConfigureGenerateWireMockClientStubsFromDslTask(extension)
createGenerateTestsTask(downloader, extension)
createAndConfigureGenerateWireMockClientStubsFromDslTask(downloader, extension)
Task stubsJar = createAndConfigureStubsJarTasks(extension)
createAndConfigureCopyContractsTask(stubsJar, extension)
createAndConfigureMavenPublishPlugin(stubsJar, extension)
createAndConfigureCopyContractsTask(stubsJar, downloader, extension)
createAndConfigureMavenPublishPlugin(stubsJar)
addProjectDependencies(project)
addIdeaTestSources(project, extension)
}
@@ -94,11 +94,11 @@ class SpringCloudContractVerifierGradlePlugin implements Plugin<Project> {
project.dependencies.add("testCompile", "org.assertj:assertj-core:2.3.0")
}
private void setConfigurationDefaults(ContractVerifierConfigProperties extension) {
private void setConfigurationDefaults(ContractVerifierExtension extension) {
extension.with {
generatedTestSourcesDir = project.file("${project.buildDir}/generated-test-sources/contracts")
contractsDslDir = defaultContractsDir() //TODO: Use sourceset
basePackageForTests = 'org.springframework.cloud.contract.verifier.tests'
generatedTestSourcesDir = generatedTestSourcesDir ?: project.file("${project.buildDir}/generated-test-sources/contracts")
contractsDslDir = contractsDslDir ?: defaultContractsDir() //TODO: Use sourceset
basePackageForTests = basePackageForTests ?: 'org.springframework.cloud.contract.verifier.tests'
stubsOutputDir = stubsOutputDir ?: project.file("${project.buildDir}/stubs")
}
}
@@ -107,29 +107,31 @@ class SpringCloudContractVerifierGradlePlugin implements Plugin<Project> {
return project.file("${project.rootDir}/src/test/resources/contracts")
}
private void createGenerateTestsTask(ContractVerifierConfigProperties extension) {
private void createGenerateTestsTask(GradleContractsDownloader downloader,
ContractVerifierExtension extension) {
Task task = project.tasks.create(GENERATE_SERVER_TESTS_TASK_NAME, GenerateServerTestsTask)
task.description = "Generate server tests from the contracts"
task.group = GROUP_NAME
task.conventionMapping.with {
contractsDslDir = { extension.contractsDslDir }
contractsDslDir = { downloader.downloadAndUnpackContractsIfRequired(extension) }
generatedTestSourcesDir = { extension.generatedTestSourcesDir }
configProperties = { extension }
}
}
private void createAndConfigureGenerateWireMockClientStubsFromDslTask(ContractVerifierConfigProperties extension) {
private void createAndConfigureGenerateWireMockClientStubsFromDslTask(
GradleContractsDownloader downloader, ContractVerifierExtension extension) {
Task task = project.tasks.create(DSL_TO_WIREMOCK_CLIENT_TASK_NAME, GenerateWireMockClientStubsFromDslTask)
task.description = "Generate WireMock client stubs from the contracts"
task.group = GROUP_NAME
task.conventionMapping.with {
contractsDslDir = { extension.contractsDslDir }
contractsDslDir = { downloader.downloadAndUnpackContractsIfRequired(extension) }
stubsOutputDir = { extension.stubsOutputDir }
configProperties = { extension }
}
}
private Task createAndConfigureStubsJarTasks(ContractVerifierConfigProperties extension) {
private Task createAndConfigureStubsJarTasks(ContractVerifierExtension extension) {
Task task = stubsTask()
if (task) {
project.logger.info("Spring Cloud Contract Verifier Plugin: Stubs jar task was present - won't create one. Remember about adding it to artifacts as an archive!")
@@ -158,9 +160,11 @@ class SpringCloudContractVerifierGradlePlugin implements Plugin<Project> {
}
}
private Task createAndConfigureCopyContractsTask(Task stubs, ContractVerifierConfigProperties extension) {
private Task createAndConfigureCopyContractsTask(Task stubs,
GradleContractsDownloader downloader,
ContractVerifierExtension extension) {
Task task = project.tasks.create(type: Copy, name: COPY_CONTRACTS_TASK_NAME) {
from { extension.contractsDslDir }
from { downloader.downloadAndUnpackContractsIfRequired(extension) }
into { extension.stubsOutputDir != null ?
project.file("${extension.stubsOutputDir}/contracts") : project.file("${project.buildDir}/stubs/contracts") }
}
@@ -170,7 +174,7 @@ class SpringCloudContractVerifierGradlePlugin implements Plugin<Project> {
return task
}
private void createAndConfigureMavenPublishPlugin(Task stubsTask, ContractVerifierConfigProperties extension) {
private void createAndConfigureMavenPublishPlugin(Task stubsTask) {
if (!classIsOnClasspath("org.gradle.api.publish.maven.plugins.MavenPublishPlugin")) {
project.logger.debug("Maven Publish Plugin is not present - won't add default publication")
return

View File

@@ -91,7 +91,7 @@ abstract class ContractVerifierIntegrationSpec extends Specification {
}
protected String[] checkAndPublishToMavenLocal() {
String[] args = ["check", "publishToMavenLocal", "--info"] as String[]
String[] args = ["check", "publishToMavenLocal", "--info", "--stacktrace"] as String[]
if (WORK_OFFLINE) args << "--offline"
return args
}

View File

@@ -6,7 +6,6 @@ import org.gradle.api.plugins.GroovyPlugin
import org.gradle.api.publish.PublishingExtension
import org.gradle.api.publish.maven.plugins.MavenPublishPlugin
import org.gradle.testfixtures.ProjectBuilder
import org.springframework.cloud.contract.verifier.config.ContractVerifierConfigProperties
import spock.lang.Specification
class ContractVerifierSpec extends Specification {
@@ -32,7 +31,7 @@ class ContractVerifierSpec extends Specification {
project.plugins.apply(SpringCloudContractVerifierGradlePlugin)
expect:
project.extensions.findByType(ContractVerifierConfigProperties) != null
project.extensions.findByType(ContractVerifierExtension) != null
}
def "should create generateContractTests task"() {

View File

@@ -52,24 +52,10 @@ subprojects {
configure([project(':fraudDetectionService'), project(':loanApplicationService')]) {
apply plugin: 'spring-boot'
apply plugin: 'spring-cloud-contract'
apply plugin: 'maven-publish'
ext {
contractsDir = file("mappings")
stubsOutputDirRoot = file("${project.buildDir}/production/${project.name}-stubs/")
}
ext['jetty.version'] = '9.2.17.v20160517'
contracts {
targetFramework = 'Spock'
testMode = 'JaxRsClient'
baseClassForTests = 'org.springframework.cloud.MvcSpec'
contractsDslDir = file("${project.projectDir.absolutePath}/mappings/")
generatedTestSourcesDir = file("${project.buildDir}/generated-test-sources/")
stubsOutputDir = stubsOutputDirRoot
}
jar {
version = '0.0.1'
}
@@ -114,16 +100,38 @@ configure([project(':fraudDetectionService'), project(':loanApplicationService')
configure(project(':fraudDetectionService')) {
test.dependsOn('generateWireMockClientStubs')
apply plugin: 'spring-cloud-contract'
ext {
contractsDir = file("mappings")
stubsOutputDirRoot = file("${project.buildDir}/production/${project.name}-stubs/")
}
ext['jetty.version'] = '9.2.17.v20160517'
contracts {
targetFramework = 'Spock'
testMode = 'JaxRsClient'
baseClassForTests = 'org.springframework.cloud.MvcSpec'
contractsRepositoryUrl = "file://" + file("${project.rootDir.absolutePath}/m2repo/repository").absolutePath
contractDependency {
stringNotation = "com.example:jersey-contracts"
}
generatedTestSourcesDir = file("${project.buildDir}/generated-test-sources/")
stubsOutputDir = stubsOutputDirRoot
}
}
configure(project(':loanApplicationService')) {
task copyCollaboratorStubs(type: Copy) {
File fraudBuildDir = project(':fraudDetectionService').buildDir
from(new File(fraudBuildDir, "/production/${project(':fraudDetectionService').name}-stubs/"))
into "src/test/resources/"
from(new File(fraudBuildDir, "/production/${project(':fraudDetectionService').name}-stubs/")) {
include '**/*.json'
}
into "src/test/resources/mappings"
}
generateContractTests.dependsOn('copyCollaboratorStubs')
test.dependsOn('copyCollaboratorStubs')
}

View File

@@ -1,48 +0,0 @@
/*
* Copyright 2013-2016 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
import org.springframework.cloud.contract.spec.Contract
Contract.make {
request {
method """PUT"""
url """/fraudcheck"""
body("""
{
"clientPesel":"${value(consumer(regex('[0-9]{10}')), producer('1234567890'))}",
"loanAmount":99999}
"""
)
headers {
header("""Content-Type""", """application/vnd.fraud.v1+json""")
}
}
response {
status 200
body( """{
"fraudCheckStatus": "${value(consumer('FRAUD'), producer(regex('[A-Z]{5}')))}",
"rejectionReason": "Amount too high"
}""")
headers {
header('Content-Type': value(
producer(regex('application/vnd.fraud.v1.json.*')),
consumer('application/vnd.fraud.v1+json'))
)
}
}
}

View File

@@ -1,49 +0,0 @@
/*
* Copyright 2013-2016 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
import org.springframework.cloud.contract.spec.Contract
Contract.make {
request {
method 'PUT'
url '/fraudcheck'
body("""
{
"clientPesel":"${value(consumer(regex('[0-9]{10}')), producer('1234567890'))}",
"loanAmount":123.123
}
"""
)
headers {
header('Content-Type', 'application/vnd.fraud.v1+json')
}
}
response {
status 200
body(
fraudCheckStatus: "OK",
rejectionReason: $(consumer(null), producer(execute('assertThatRejectionReasonIsNull($it)')))
)
headers {
header('Content-Type': value(
producer(regex('application/vnd.fraud.v1.json.*')),
consumer('application/vnd.fraud.v1+json'))
)
}
}
}

View File

@@ -0,0 +1,25 @@
<?xml version="1.0" encoding="UTF-8"?>
<!--
~ Copyright 2013-2016 the original author or authors.
~
~ Licensed under the Apache License, Version 2.0 (the "License");
~ you may not use this file except in compliance with the License.
~ You may obtain a copy of the License at
~
~ http://www.apache.org/licenses/LICENSE-2.0
~
~ Unless required by applicable law or agreed to in writing, software
~ distributed under the License is distributed on an "AS IS" BASIS,
~ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
~ See the License for the specific language governing permissions and
~ limitations under the License.
-->
<project xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd" xmlns="http://maven.apache.org/POM/4.0.0"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">
<modelVersion>4.0.0</modelVersion>
<groupId>com.example</groupId>
<artifactId>jersey-contracts</artifactId>
<version>0.0.1-SNAPSHOT</version>
<packaging>pom</packaging>
</project>

View File

@@ -0,0 +1,24 @@
<?xml version="1.0" encoding="UTF-8"?>
<metadata modelVersion="1.1.0">
<groupId>com.example</groupId>
<artifactId>jersey-contracts</artifactId>
<version>0.0.1-SNAPSHOT</version>
<versioning>
<snapshot>
<localCopy>true</localCopy>
</snapshot>
<lastUpdated>20160916125313</lastUpdated>
<snapshotVersions>
<snapshotVersion>
<extension>jar</extension>
<value>0.0.1-SNAPSHOT</value>
<updated>20160916125313</updated>
</snapshotVersion>
<snapshotVersion>
<extension>pom</extension>
<value>0.0.1-SNAPSHOT</value>
<updated>20160916125313</updated>
</snapshotVersion>
</snapshotVersions>
</versioning>
</metadata>

View File

@@ -0,0 +1,28 @@
<?xml version="1.0" encoding="UTF-8"?>
<!--
~ Copyright 2013-2016 the original author or authors.
~
~ Licensed under the Apache License, Version 2.0 (the "License");
~ you may not use this file except in compliance with the License.
~ You may obtain a copy of the License at
~
~ http://www.apache.org/licenses/LICENSE-2.0
~
~ Unless required by applicable law or agreed to in writing, software
~ distributed under the License is distributed on an "AS IS" BASIS,
~ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
~ See the License for the specific language governing permissions and
~ limitations under the License.
-->
<metadata>
<groupId>com.example</groupId>
<artifactId>jersey-contracts</artifactId>
<version>0.0.1-SNAPSHOT</version>
<versioning>
<versions>
<version>0.0.1-SNAPSHOT</version>
</versions>
<lastUpdated>20160409062112</lastUpdated>
</versioning>
</metadata>