Code formatting

This commit is contained in:
Jakub Kubrynski
2015-02-21 12:49:49 +01:00
parent e521511e00
commit 4a5efff48c
41 changed files with 1225 additions and 1208 deletions

View File

@@ -6,7 +6,7 @@ import io.coderate.accurest.AccurestException
@CompileStatic
class ConversionAccurestException extends AccurestException {
ConversionAccurestException(String message, Throwable cause) {
super(message, cause)
}
ConversionAccurestException(String message, Throwable cause) {
super(message, cause)
}
}

View File

@@ -6,8 +6,8 @@ import io.coderate.accurest.dsl.WiremockStubStrategy
@CompileStatic
class DslToWiremockClientConverter extends DslToWiremockConverter {
@Override
String convertContent(String dslBody) {
return new WiremockStubStrategy(createGroovyDSLfromStringContent(dslBody)).toWiremockClientStub()
}
@Override
String convertContent(String dslBody) {
return new WiremockStubStrategy(createGroovyDSLfromStringContent(dslBody)).toWiremockClientStub()
}
}

View File

@@ -6,17 +6,17 @@ import io.coderate.accurest.dsl.GroovyDsl
@CompileStatic
abstract class DslToWiremockConverter implements SingleFileConverter {
@Override
boolean canHandleFileName(String fileName) {
return fileName.endsWith('.groovy')
}
@Override
boolean canHandleFileName(String fileName) {
return fileName.endsWith('.groovy')
}
@Override
String generateOutputFileNameForInput(String inputFileName) {
return inputFileName.replaceAll('.groovy', '.json')
}
@Override
String generateOutputFileNameForInput(String inputFileName) {
return inputFileName.replaceAll('.groovy', '.json')
}
protected GroovyDsl createGroovyDSLfromStringContent(String groovyDslAsString) {
return (GroovyDsl)new GroovyShell(this.class.classLoader).evaluate("$groovyDslAsString")
}
protected GroovyDsl createGroovyDSLfromStringContent(String groovyDslAsString) {
return (GroovyDsl) new GroovyShell(this.class.classLoader).evaluate("$groovyDslAsString")
}
}

View File

@@ -6,8 +6,8 @@ import io.coderate.accurest.dsl.WiremockStubStrategy
@CompileStatic
class DslToWiremockServerConverter extends DslToWiremockConverter {
@Override
String convertContent(String dslBody) {
return new WiremockStubStrategy(createGroovyDSLfromStringContent(dslBody)).toWiremockServerStub()
}
@Override
String convertContent(String dslBody) {
return new WiremockStubStrategy(createGroovyDSLfromStringContent(dslBody)).toWiremockServerStub()
}
}

View File

@@ -12,42 +12,42 @@ import java.nio.file.Paths
@CompileStatic
class RecursiveFilesConverter {
private final SingleFileConverter singleFileConverter
private final File sourceRootDirectory
private final File targetRootDirectory
private final SingleFileConverter singleFileConverter
private final File sourceRootDirectory
private final File targetRootDirectory
RecursiveFilesConverter(SingleFileConverter singleFileConverter, File sourceRootDirectory, File targetRootDirectory) {
this.singleFileConverter = singleFileConverter
this.sourceRootDirectory = sourceRootDirectory
this.targetRootDirectory = targetRootDirectory
}
RecursiveFilesConverter(SingleFileConverter singleFileConverter, File sourceRootDirectory, File targetRootDirectory) {
this.singleFileConverter = singleFileConverter
this.sourceRootDirectory = sourceRootDirectory
this.targetRootDirectory = targetRootDirectory
}
void processFiles() {
sourceRootDirectory.eachFileRecurse(FileType.FILES) { File sourceFile ->
try {
if (!singleFileConverter.canHandleFileName(sourceFile.name)) {
return
}
String convertedContent = singleFileConverter.convertContent(sourceFile.text)
Path absoluteTargetPath = createAndReturnTargetDirectory(sourceFile)
File newGroovyFile = createTargetFileWithProperName(absoluteTargetPath, sourceFile)
newGroovyFile.text = convertedContent
} catch (Exception e) {
throw new ConversionAccurestException("Unable to convertion of ${sourceFile.name}", e)
}
}
}
void processFiles() {
sourceRootDirectory.eachFileRecurse(FileType.FILES) { File sourceFile ->
try {
if (!singleFileConverter.canHandleFileName(sourceFile.name)) {
return
}
String convertedContent = singleFileConverter.convertContent(sourceFile.text)
Path absoluteTargetPath = createAndReturnTargetDirectory(sourceFile)
File newGroovyFile = createTargetFileWithProperName(absoluteTargetPath, sourceFile)
newGroovyFile.text = convertedContent
} catch (Exception e) {
throw new ConversionAccurestException("Unable to convertion of ${sourceFile.name}", e)
}
}
}
private Path createAndReturnTargetDirectory(File sourceFile) {
Path relativePath = Paths.get(sourceRootDirectory.toURI()).relativize(sourceFile.parentFile.toPath())
Path absoluteTargetPath = targetRootDirectory.toPath().resolve(relativePath)
Files.createDirectories(absoluteTargetPath)
absoluteTargetPath
}
private Path createAndReturnTargetDirectory(File sourceFile) {
Path relativePath = Paths.get(sourceRootDirectory.toURI()).relativize(sourceFile.parentFile.toPath())
Path absoluteTargetPath = targetRootDirectory.toPath().resolve(relativePath)
Files.createDirectories(absoluteTargetPath)
absoluteTargetPath
}
private File createTargetFileWithProperName(Path absoluteTargetPath, File sourceFile) {
File newGroovyFile = new File(absoluteTargetPath.toFile(), singleFileConverter.generateOutputFileNameForInput(sourceFile.name))
log.info("Creating new json [$newGroovyFile.path]")
newGroovyFile
}
private File createTargetFileWithProperName(Path absoluteTargetPath, File sourceFile) {
File newGroovyFile = new File(absoluteTargetPath.toFile(), singleFileConverter.generateOutputFileNameForInput(sourceFile.name))
log.info("Creating new json [$newGroovyFile.path]")
newGroovyFile
}
}

View File

@@ -5,9 +5,9 @@ import groovy.transform.CompileStatic
@CompileStatic
interface SingleFileConverter {
boolean canHandleFileName(String fileName)
boolean canHandleFileName(String fileName)
String convertContent(String content)
String convertContent(String content)
String generateOutputFileNameForInput(String inputFileName)
String generateOutputFileNameForInput(String inputFileName)
}

View File

@@ -8,132 +8,137 @@ import groovy.xml.XmlUtil
import static org.apache.commons.lang3.StringEscapeUtils.escapeJava
class WiremockToDslConverter {
static String fromWiremockStub(String wiremockStringStub) {
return new WiremockToDslConverter().convertFromWiremockStub(wiremockStringStub)
}
static String fromWiremockStub(String wiremockStringStub) {
return new WiremockToDslConverter().convertFromWiremockStub(wiremockStringStub)
}
private String convertFromWiremockStub(String wiremockStringStub) {
Object wiremockStub = new JsonSlurper().parseText(wiremockStringStub)
def request = wiremockStub.request
def response = wiremockStub.response
return """\
private String convertFromWiremockStub(String wiremockStringStub) {
Object wiremockStub = new JsonSlurper().parseText(wiremockStringStub)
def request = wiremockStub.request
def response = wiremockStub.response
return """\
request {
${request.method ? "method \"\"\"$request.method\"\"\"" : ""}
${request.url ? "url \"\"\"$request.url\"\"\"" : ""}
${request.urlPattern ? "urlPattern \"\"\"${escapeJava(request.urlPattern)}\"\"\"" : ""}
${request.urlPath ? "urlPath \"\"\"$request.urlPath\"\"\"" : ""}
${request.headers ? """headers {
${request.headers.collect {
def assertion = it.value
String headerName = it.key as String
def entry = assertion.entrySet().first()
"""header(\"\"\"$headerName\"\"\").$entry.key(\"\"\"${escapeJava(entry.value)}\"\"\")\n"""
}.join('')
}
${
request.headers ? """headers {
${
request.headers.collect {
def assertion = it.value
String headerName = it.key as String
def entry = assertion.entrySet().first()
"""header(\"\"\"$headerName\"\"\").$entry.key(\"\"\"${escapeJava(entry.value)}\"\"\")\n"""
}.join('')
}
}
""" : ""}
""" : ""
}
}
response {
${response.status ? "status $response.status" : ""}
${response.body ? "body( ${buildBody(response.body)})" : ""}
${response.headers ? """headers {
${
response.headers ? """headers {
${response.headers.collect { "header('$it.key': '${it.value}')\n" }.join('')}
}
""" : ""}
""" : ""
}
}
"""
}
}
private Object buildBody(Map responseBody) {
return responseBody.entrySet().collectAll(withQuotedMapStringElements()).inject([:], appendToIterable())
}
private Object buildBody(Map responseBody) {
return responseBody.entrySet().collectAll(withQuotedMapStringElements()).inject([:], appendToIterable())
}
private Object buildBody(List responseBody) {
return responseBody.collectAll(withQuotedStringElements()).inject([], appendToIterable())
}
private Object buildBody(List responseBody) {
return responseBody.collectAll(withQuotedStringElements()).inject([], appendToIterable())
}
private Object buildBody(Integer responseBody) {
return responseBody
}
private Object buildBody(Integer responseBody) {
return responseBody
}
private Object buildBody(String responseBody) {
try {
def json = new JsonSlurper().parseText(responseBody)
return wrapWithMultilineGString(JsonOutput.prettyPrint(responseBody))
} catch (Exception jsonException) {
try {
def xml = new XmlSlurper().parseText(responseBody)
return wrapWithMultilineGString(XmlUtil.serialize(responseBody))
} catch (Exception xmlException) {
return wrapWithMultilineGString(responseBody)
}
}
}
private Object buildBody(String responseBody) {
try {
def json = new JsonSlurper().parseText(responseBody)
return wrapWithMultilineGString(JsonOutput.prettyPrint(responseBody))
} catch (Exception jsonException) {
try {
def xml = new XmlSlurper().parseText(responseBody)
return wrapWithMultilineGString(XmlUtil.serialize(responseBody))
} catch (Exception xmlException) {
return wrapWithMultilineGString(responseBody)
}
}
}
private String wrapWithMultilineGString(String string) {
return """\"\"\"$string\"\"\""""
}
private String wrapWithMultilineGString(String string) {
return """\"\"\"$string\"\"\""""
}
private Closure withQuotedMapStringElements() {
return {
[(it.key): convert(it.value)]
}
}
private Closure withQuotedMapStringElements() {
return {
[(it.key): convert(it.value)]
}
}
private Closure withQuotedStringElements() {
return {
convert(it)
}
}
private Closure withQuotedStringElements() {
return {
convert(it)
}
}
private Closure appendToIterable() {
return {
acc, el -> acc << el
}
}
private Closure appendToIterable() {
return {
acc, el -> acc << el
}
}
private Object convert(Object element) {
return element
}
private Object convert(Object element) {
return element
}
private Object convert(String element) {
return quoteString(element)
}
private Object convert(String element) {
return quoteString(element)
}
private String quoteString(String element) {
if (element =~ /^".*"$/) {
return element
}
return """\"\"\"${escapeJava(element)}\"\"\""""
}
private String quoteString(String element) {
if (element =~ /^".*"$/) {
return element
}
return """\"\"\"${escapeJava(element)}\"\"\""""
}
private Object convert(List element) {
return element.collect {
convert(it)
}
}
private Object convert(List element) {
return element.collect {
convert(it)
}
}
private Object convert(Map element) {
return element.collectEntries {
[(it.key) : convert(it.value)]
}
}
private Object convert(Map element) {
return element.collectEntries {
[(it.key): convert(it.value)]
}
}
static void main(String[] args) {
String rootOfFolderWithStubs = args[0]
new File(rootOfFolderWithStubs).eachFileRecurse(FileType.FILES) {
try {
if(!it.name.endsWith('json')) {
return
}
String wiremockStub = fromWiremockStub(it.text)
File newGroovyFile = new File(it.parent, it.name.replaceAll('json', 'groovy'))
println("Creating new groovy file [$newGroovyFile.path]")
newGroovyFile.text = wiremockStub
} catch (Exception e) {
System.err.println(e)
}
static void main(String[] args) {
String rootOfFolderWithStubs = args[0]
new File(rootOfFolderWithStubs).eachFileRecurse(FileType.FILES) {
try {
if (!it.name.endsWith('json')) {
return
}
String wiremockStub = fromWiremockStub(it.text)
File newGroovyFile = new File(it.parent, it.name.replaceAll('json', 'groovy'))
println("Creating new groovy file [$newGroovyFile.path]")
newGroovyFile.text = wiremockStub
} catch (Exception e) {
System.err.println(e)
}
}
}
}
}
}

View File

@@ -5,11 +5,11 @@ import spock.lang.Specification
class DslToWiremockClientConverterSpec extends Specification {
def "should convert DSL file to Wiremock JSON"() {
given:
def converter = new DslToWiremockClientConverter()
and:
String dslBody = """
def "should convert DSL file to Wiremock JSON"() {
given:
def converter = new DslToWiremockClientConverter()
and:
String dslBody = """
io.coderate.accurest.dsl.GroovyDsl.make {
request {
method('PUT')
@@ -20,10 +20,10 @@ class DslToWiremockClientConverterSpec extends Specification {
}
}
"""
when:
String json = converter.convertContent(dslBody)
then:
new JsonSlurper().parseText(json) == new JsonSlurper().parseText("""
when:
String json = converter.convertContent(dslBody)
then:
new JsonSlurper().parseText(json) == new JsonSlurper().parseText("""
{"request":{"method":"PUT","urlPattern":"/[0-9]{2}"},"response":{"status":200}}""")
}
}
}

View File

@@ -5,11 +5,11 @@ import spock.lang.Specification
class DslToWiremockServerConverterSpec extends Specification {
def "should convert DSL file to Wiremock JSON"() {
given:
def converter = new DslToWiremockServerConverter()
and:
String dslBody = """
def "should convert DSL file to Wiremock JSON"() {
given:
def converter = new DslToWiremockServerConverter()
and:
String dslBody = """
io.coderate.accurest.dsl.GroovyDsl.make {
request {
method('PUT')
@@ -20,10 +20,10 @@ class DslToWiremockServerConverterSpec extends Specification {
}
}
"""
when:
String json = converter.convertContent(dslBody)
then:
new JsonSlurper().parseText(json) == new JsonSlurper().parseText("""
when:
String json = converter.convertContent(dslBody)
then:
new JsonSlurper().parseText(json) == new JsonSlurper().parseText("""
{"request":{"method":"PUT","urlPattern":"/12"},"response":{"status":200}}""")
}
}
}

View File

@@ -11,55 +11,57 @@ import java.nio.file.Paths
class RecursiveFilesConverterSpec extends Specification {
private static final Set<String> EXPECTED_TARGET_FILES = ["dslRoot.json", "dir1/dsl1.json", "dir1/dsl1b.json", "dir2/dsl2.json"]
private static
final Set<String> EXPECTED_TARGET_FILES = ["dslRoot.json", "dir1/dsl1.json", "dir1/dsl1b.json", "dir2/dsl2.json"]
@Rule
public TemporaryFolder tmpFolder = new TemporaryFolder();
@Rule
public TemporaryFolder tmpFolder = new TemporaryFolder();
def "should recursively convert all matching files"() {
given:
File originalSourceRootDirectory = new File(this.getClass().getResource("/converter/source").toURI())
File sourceRootDirectory = tmpFolder.newFolder("source")
File targetRootDirectory = tmpFolder.newFolder("target")
FileUtils.copyDirectory(originalSourceRootDirectory, sourceRootDirectory)
and:
def singleFileConverterStub = Stub(SingleFileConverter)
singleFileConverterStub.canHandleFileName(_) >> { String fileName -> fileName.endsWith(".groovy") }
singleFileConverterStub.convertContent(_) >> { "converted" }
singleFileConverterStub.generateOutputFileNameForInput(_) >> { String inputFileName -> inputFileName.replaceAll('.groovy', '.json') }
RecursiveFilesConverter recursiveFilesConverter = new RecursiveFilesConverter(singleFileConverterStub, sourceRootDirectory, targetRootDirectory)
when:
recursiveFilesConverter.processFiles()
then:
Collection<File> createdFiles = FileUtils.listFiles(targetRootDirectory, TrueFileFilter.INSTANCE, TrueFileFilter.INSTANCE)
Set<String> relativizedCreatedFiles = getRelativePathsForFilesInDirectory(createdFiles, targetRootDirectory)
EXPECTED_TARGET_FILES == relativizedCreatedFiles
and:
createdFiles.each { it.text == "converted" }
}
def "should recursively convert all matching files"() {
given:
File originalSourceRootDirectory = new File(this.getClass().getResource("/converter/source").toURI())
File sourceRootDirectory = tmpFolder.newFolder("source")
File targetRootDirectory = tmpFolder.newFolder("target")
FileUtils.copyDirectory(originalSourceRootDirectory, sourceRootDirectory)
and:
def singleFileConverterStub = Stub(SingleFileConverter)
singleFileConverterStub.canHandleFileName(_) >> { String fileName -> fileName.endsWith(".groovy") }
singleFileConverterStub.convertContent(_) >> { "converted" }
singleFileConverterStub.generateOutputFileNameForInput(_) >> { String inputFileName -> inputFileName.replaceAll('.groovy', '.json') }
RecursiveFilesConverter recursiveFilesConverter = new RecursiveFilesConverter(singleFileConverterStub, sourceRootDirectory, targetRootDirectory)
when:
recursiveFilesConverter.processFiles()
then:
Collection<File> createdFiles = FileUtils.listFiles(targetRootDirectory, TrueFileFilter.INSTANCE, TrueFileFilter.INSTANCE)
Set<String> relativizedCreatedFiles = getRelativePathsForFilesInDirectory(createdFiles, targetRootDirectory)
EXPECTED_TARGET_FILES == relativizedCreatedFiles
and:
createdFiles.each { it.text == "converted" }
}
def "on failure should break processing and throw meaningful exception"() {
given:
def sourceFile = tmpFolder.newFile()
and:
def singleFileConverterStub = Stub(SingleFileConverter)
singleFileConverterStub.canHandleFileName(_) >> { true }
singleFileConverterStub.convertContent(_) >> { throw new NullPointerException("Test conversion error") }
singleFileConverterStub.generateOutputFileNameForInput(_) >> { String inputFileName -> "${inputFileName}2" }
RecursiveFilesConverter recursiveFilesConverter = new RecursiveFilesConverter(singleFileConverterStub, tmpFolder.root, tmpFolder.root)
when:
recursiveFilesConverter.processFiles()
then:
def e = thrown(ConversionAccurestException)
e.message?.contains(sourceFile.name)
e.cause?.message == "Test conversion error"
}
def "on failure should break processing and throw meaningful exception"() {
given:
def sourceFile = tmpFolder.newFile()
and:
def singleFileConverterStub = Stub(SingleFileConverter)
singleFileConverterStub.canHandleFileName(_) >> { true }
singleFileConverterStub.convertContent(_) >> { throw new NullPointerException("Test conversion error") }
singleFileConverterStub.generateOutputFileNameForInput(_) >> { String inputFileName -> "${inputFileName}2" }
RecursiveFilesConverter recursiveFilesConverter = new RecursiveFilesConverter(singleFileConverterStub, tmpFolder.root, tmpFolder.root)
when:
recursiveFilesConverter.processFiles()
then:
def e = thrown(ConversionAccurestException)
e.message?.contains(sourceFile.name)
e.cause?.message == "Test conversion error"
}
private static Set<String> getRelativePathsForFilesInDirectory(Collection<File> createdFiles, File targetRootDirectory) {
Path rootSourcePath = Paths.get(targetRootDirectory.toURI())
Set<String> relativizedCreatedFiles = createdFiles.collect { File file ->
rootSourcePath.relativize(Paths.get(file.toURI())).toString()
}
relativizedCreatedFiles
}
private
static Set<String> getRelativePathsForFilesInDirectory(Collection<File> createdFiles, File targetRootDirectory) {
Path rootSourcePath = Paths.get(targetRootDirectory.toURI())
Set<String> relativizedCreatedFiles = createdFiles.collect { File file ->
rootSourcePath.relativize(Paths.get(file.toURI())).toString()
}
relativizedCreatedFiles
}
}

View File

@@ -5,9 +5,9 @@ import spock.lang.Specification
class WiremockToDslConverterSpec extends Specification {
def 'should produce a Groovy DSL from Wiremock stub'() {
given:
String wiremockStub = '''\
def 'should produce a Groovy DSL from Wiremock stub'() {
given:
String wiremockStub = '''\
{
"request": {
"method": "GET",
@@ -40,44 +40,44 @@ class WiremockToDslConverterSpec extends Specification {
}
}
'''
and:
GroovyDsl expectedGroovyDsl = GroovyDsl.make {
request {
method 'GET'
urlPattern '/[0-9]{2}'
headers {
header('Accept').matches('text/.*')
header('etag').doesNotMatch('abcd.*')
header('X-Custom-Header').contains('2134')
}
}
response {
status 200
body (
id : [value: '132'],
surname : 'Kowalsky',
name: 'Jan',
created : '2014-02-02 12:23:43'
)
headers {
header 'Content-Type': 'text/plain'
and:
GroovyDsl expectedGroovyDsl = GroovyDsl.make {
request {
method 'GET'
urlPattern '/[0-9]{2}'
headers {
header('Accept').matches('text/.*')
header('etag').doesNotMatch('abcd.*')
header('X-Custom-Header').contains('2134')
}
}
response {
status 200
body(
id: [value: '132'],
surname: 'Kowalsky',
name: 'Jan',
created: '2014-02-02 12:23:43'
)
headers {
header 'Content-Type': 'text/plain'
}
}
}
when:
String groovyDsl = WiremockToDslConverter.fromWiremockStub(wiremockStub)
then:
new GroovyShell(this.class.classLoader).evaluate(
""" io.coderate.accurest.dsl.GroovyDsl.make {
}
}
}
when:
String groovyDsl = WiremockToDslConverter.fromWiremockStub(wiremockStub)
then:
new GroovyShell(this.class.classLoader).evaluate(
""" io.coderate.accurest.dsl.GroovyDsl.make {
$groovyDsl
}""") == expectedGroovyDsl
}
}
def 'should convert Wiremock stub with body containing simple JSON'() {
given:
String wiremockStub = '''\
def 'should convert Wiremock stub with body containing simple JSON'() {
given:
String wiremockStub = '''\
{
"request": {
"method": "DELETE",
@@ -97,38 +97,38 @@ class WiremockToDslConverterSpec extends Specification {
}
}
'''
and:
GroovyDsl expectedGroovyDsl = GroovyDsl.make {
request {
method 'DELETE'
urlPattern '/credit-card-verification-data/[0-9]+'
headers {
header('Content-Type').equalTo('application/vnd.mymoid-adapter.v2+json; charset=UTF-8')
}
}
response {
status 200
body ("""{
and:
GroovyDsl expectedGroovyDsl = GroovyDsl.make {
request {
method 'DELETE'
urlPattern '/credit-card-verification-data/[0-9]+'
headers {
header('Content-Type').equalTo('application/vnd.mymoid-adapter.v2+json; charset=UTF-8')
}
}
response {
status 200
body("""{
"status": "OK"
}""")
headers {
header 'Content-Type': 'application/json'
headers {
header 'Content-Type': 'application/json'
}
}
}
when:
String groovyDsl = WiremockToDslConverter.fromWiremockStub(wiremockStub)
then:
new GroovyShell(this.class.classLoader).evaluate(
""" io.coderate.accurest.dsl.GroovyDsl.make {
}
}
}
when:
String groovyDsl = WiremockToDslConverter.fromWiremockStub(wiremockStub)
then:
new GroovyShell(this.class.classLoader).evaluate(
""" io.coderate.accurest.dsl.GroovyDsl.make {
$groovyDsl
}""") == expectedGroovyDsl
}
}
def 'should convert Wiremock stub with body containing integer'() {
given:
String wiremockStub = '''\
def 'should convert Wiremock stub with body containing integer'() {
given:
String wiremockStub = '''\
{
"request": {
"method": "POST",
@@ -148,36 +148,36 @@ class WiremockToDslConverterSpec extends Specification {
}
}
'''
and:
GroovyDsl expectedGroovyDsl = GroovyDsl.make {
request {
method 'POST'
url '/charge/count'
headers {
header('Content-Type').equalTo('application/vnd.creditcard-reporter.v1+json')
}
}
response {
status 200
body ( 200 )
headers {
header 'Content-Type': 'application/json'
and:
GroovyDsl expectedGroovyDsl = GroovyDsl.make {
request {
method 'POST'
url '/charge/count'
headers {
header('Content-Type').equalTo('application/vnd.creditcard-reporter.v1+json')
}
}
response {
status 200
body(200)
headers {
header 'Content-Type': 'application/json'
}
}
}
when:
String groovyDsl = WiremockToDslConverter.fromWiremockStub(wiremockStub)
then:
new GroovyShell(this.class.classLoader).evaluate(
""" io.coderate.accurest.dsl.GroovyDsl.make {
}
}
}
when:
String groovyDsl = WiremockToDslConverter.fromWiremockStub(wiremockStub)
then:
new GroovyShell(this.class.classLoader).evaluate(
""" io.coderate.accurest.dsl.GroovyDsl.make {
$groovyDsl
}""") == expectedGroovyDsl
}
}
def 'should convert Wiremock stub with body as a list'() {
given:
String wiremockStub = '''\
def 'should convert Wiremock stub with body as a list'() {
given:
String wiremockStub = '''\
{
"request": {
"method": "POST",
@@ -201,41 +201,41 @@ class WiremockToDslConverterSpec extends Specification {
}
}
'''
and:
GroovyDsl expectedGroovyDsl = GroovyDsl.make {
request {
method 'POST'
url '/charge/count'
headers {
header('Content-Type').equalTo('application/vnd.creditcard-reporter.v1+json')
}
}
response {
status 200
body ([
[a: 1, c: '3'],
'b',
'a'
])
headers {
header 'Content-Type': 'application/json'
and:
GroovyDsl expectedGroovyDsl = GroovyDsl.make {
request {
method 'POST'
url '/charge/count'
headers {
header('Content-Type').equalTo('application/vnd.creditcard-reporter.v1+json')
}
}
response {
status 200
body([
[a: 1, c: '3'],
'b',
'a'
])
headers {
header 'Content-Type': 'application/json'
}
}
}
when:
String groovyDsl = WiremockToDslConverter.fromWiremockStub(wiremockStub)
then:
new GroovyShell(this.class.classLoader).evaluate(
""" io.coderate.accurest.dsl.GroovyDsl.make {
}
}
}
when:
String groovyDsl = WiremockToDslConverter.fromWiremockStub(wiremockStub)
then:
new GroovyShell(this.class.classLoader).evaluate(
""" io.coderate.accurest.dsl.GroovyDsl.make {
$groovyDsl
}""") == expectedGroovyDsl
}
}
def 'should convert Wiremock stub with body containing a nested list'() {
given:
String wiremockStub = '''\
def 'should convert Wiremock stub with body containing a nested list'() {
given:
String wiremockStub = '''\
{
"request": {
"method": "POST",
@@ -252,18 +252,18 @@ class WiremockToDslConverterSpec extends Specification {
}
}
'''
and:
GroovyDsl expectedGroovyDsl = GroovyDsl.make {
request {
method 'POST'
url '/charge/search?pageNumber=0&size=2147483647'
headers {
header('Content-Type').equalTo('application/vnd.creditcard-reporter.v1+json')
}
}
response {
status 200
body ("""[
and:
GroovyDsl expectedGroovyDsl = GroovyDsl.make {
request {
method 'POST'
url '/charge/search?pageNumber=0&size=2147483647'
headers {
header('Content-Type').equalTo('application/vnd.creditcard-reporter.v1+json')
}
}
response {
status 200
body("""[
{
"amount": 1.01,
"name": "Name",
@@ -285,15 +285,15 @@ class WiremockToDslConverterSpec extends Specification {
"user": null
}
]""")
}
}
when:
String groovyDsl = WiremockToDslConverter.fromWiremockStub(wiremockStub)
then:
new GroovyShell(this.class.classLoader).evaluate(
""" io.coderate.accurest.dsl.GroovyDsl.make {
}
}
when:
String groovyDsl = WiremockToDslConverter.fromWiremockStub(wiremockStub)
then:
new GroovyShell(this.class.classLoader).evaluate(
""" io.coderate.accurest.dsl.GroovyDsl.make {
$groovyDsl
}""") == expectedGroovyDsl
}
}
}

View File

@@ -1,12 +1,12 @@
io.coderate.accurest.dsl.GroovyDsl.make {
request {
method('PUT')
headers {
header 'Content-Type': 'application/json'
}
urlPattern $(client('/[0-9]{2}'), server('/12'))
}
response {
status 200
}
request {
method('PUT')
headers {
header 'Content-Type': 'application/json'
}
urlPattern $(client('/[0-9]{2}'), server('/12'))
}
response {
status 200
}
}

View File

@@ -1,12 +1,12 @@
io.coderate.accurest.dsl.GroovyDsl.make {
request {
method('PUT')
headers {
header 'Content-Type': 'application/json'
}
urlPattern $(client('/[0-9]{2}'), server('/12'))
}
response {
status 200
}
request {
method('PUT')
headers {
header 'Content-Type': 'application/json'
}
urlPattern $(client('/[0-9]{2}'), server('/12'))
}
response {
status 200
}
}

View File

@@ -1,12 +1,12 @@
io.coderate.accurest.dsl.GroovyDsl.make {
request {
method('PUT')
headers {
header 'Content-Type': 'application/json'
}
urlPattern $(client('/[0-9]{2}'), server('/12'))
}
response {
status 200
}
request {
method('PUT')
headers {
header 'Content-Type': 'application/json'
}
urlPattern $(client('/[0-9]{2}'), server('/12'))
}
response {
status 200
}
}

View File

@@ -1,12 +1,12 @@
io.coderate.accurest.dsl.GroovyDsl.make {
request {
method('PUT')
headers {
header 'Content-Type': 'application/json'
}
urlPattern $(client('/[0-9]{2}'), server('/12'))
}
response {
status 200
}
request {
method('PUT')
headers {
header 'Content-Type': 'application/json'
}
urlPattern $(client('/[0-9]{2}'), server('/12'))
}
response {
status 200
}
}

View File

@@ -13,28 +13,28 @@ import static io.coderate.accurest.util.NamesUtil.capitalize
@CompileStatic
class FileSaver {
File targetDirectory
TestFramework framework
File targetDirectory
TestFramework framework
FileSaver(File targetDirectory, TestFramework framework) {
this.targetDirectory = targetDirectory
this.framework = framework
}
FileSaver(File targetDirectory, TestFramework framework) {
this.targetDirectory = targetDirectory
this.framework = framework
}
void saveClassFile(String fileName, String packageName, byte[] classBytes) {
void saveClassFile(String fileName, String packageName, byte[] classBytes) {
def testBaseDir = Paths.get(targetDirectory.absolutePath, NamesUtil.packageToDirectory(packageName))
Files.createDirectories(testBaseDir)
def classPath = Paths.get(testBaseDir.toString(), capitalize(fileName) + getTestClassSuffix() + getTestClassExtension())
.toAbsolutePath()
Files.write(classPath, classBytes, StandardOpenOption.CREATE, StandardOpenOption.TRUNCATE_EXISTING)
}
def testBaseDir = Paths.get(targetDirectory.absolutePath, NamesUtil.packageToDirectory(packageName))
Files.createDirectories(testBaseDir)
def classPath = Paths.get(testBaseDir.toString(), capitalize(fileName) + getTestClassSuffix() + getTestClassExtension())
.toAbsolutePath()
Files.write(classPath, classBytes, StandardOpenOption.CREATE, StandardOpenOption.TRUNCATE_EXISTING)
}
private String getTestClassSuffix() {
return framework == TestFramework.SPOCK ? 'Spec' : 'Test'
}
private String getTestClassSuffix() {
return framework == TestFramework.SPOCK ? 'Spec' : 'Test'
}
private String getTestClassExtension() {
return framework == TestFramework.SPOCK ? '.groovy' : '.java'
}
private String getTestClassExtension() {
return framework == TestFramework.SPOCK ? '.groovy' : '.java'
}
}

View File

@@ -11,50 +11,50 @@ import static io.coderate.accurest.builder.MethodBuilder.createTestMethod
import static io.coderate.accurest.util.NamesUtil.capitalize
class SingleTestGenerator {
private final AccurestConfigProperties configProperties
private final AccurestConfigProperties configProperties
SingleTestGenerator(AccurestConfigProperties configProperties) {
this.configProperties = configProperties
}
this.configProperties = configProperties
}
@PackageScope
String buildClass(List<File> listOfFiles, String className, String classPackage) {
ClassBuilder clazz = createClass(capitalize(className), classPackage,
configProperties)
@PackageScope
String buildClass(List<File> listOfFiles, String className, String classPackage) {
ClassBuilder clazz = createClass(capitalize(className), classPackage,
configProperties)
if (configProperties.imports) {
configProperties.imports.each {
clazz.addImport(it)
}
}
if (configProperties.imports) {
configProperties.imports.each {
clazz.addImport(it)
}
}
if (configProperties.staticImports) {
configProperties.staticImports.each {
clazz.addStaticImport(it)
}
}
if (configProperties.staticImports) {
configProperties.staticImports.each {
clazz.addStaticImport(it)
}
}
if (configProperties.testMode == TestMode.MOCKMVC) {
clazz.addStaticImport('com.jayway.restassured.module.mockmvc.RestAssuredMockMvc.*')
} else {
clazz.addStaticImport('com.jayway.restassured.RestAssured.*')
}
if (configProperties.testMode == TestMode.MOCKMVC) {
clazz.addStaticImport('com.jayway.restassured.module.mockmvc.RestAssuredMockMvc.*')
} else {
clazz.addStaticImport('com.jayway.restassured.RestAssured.*')
}
if (configProperties.targetFramework == TestFramework.JUNIT) {
clazz.addImport('org.junit.Test')
} else {
clazz.addImport('groovy.json.JsonSlurper')
}
if (configProperties.targetFramework == TestFramework.JUNIT) {
clazz.addImport('org.junit.Test')
} else {
clazz.addImport('groovy.json.JsonSlurper')
}
if (configProperties.ruleClassForTests) {
clazz.addImport('org.junit.Rule')
.addRule(configProperties.ruleClassForTests)
}
if (configProperties.ruleClassForTests) {
clazz.addImport('org.junit.Rule')
.addRule(configProperties.ruleClassForTests)
}
listOfFiles.each {
clazz.addMethod(createTestMethod(it, configProperties.targetFramework))
}
return clazz.build()
}
listOfFiles.each {
clazz.addMethod(createTestMethod(it, configProperties.targetFramework))
}
return clazz.build()
}
}

View File

@@ -13,60 +13,60 @@ import static io.coderate.accurest.util.NamesUtil.afterLast
*/
class TestGenerator {
private final AccurestConfigProperties configProperties
private AtomicInteger counter = new AtomicInteger()
private SingleTestGenerator generator
private FileSaver saver
private DirectoryScanner directoryScanner
private final AccurestConfigProperties configProperties
private AtomicInteger counter = new AtomicInteger()
private SingleTestGenerator generator
private FileSaver saver
private DirectoryScanner directoryScanner
TestGenerator(AccurestConfigProperties accurestConfigProperties) {
this(accurestConfigProperties, new SingleTestGenerator(accurestConfigProperties),
new FileSaver(accurestConfigProperties.generatedTestSourcesDir, accurestConfigProperties.targetFramework))
}
TestGenerator(AccurestConfigProperties accurestConfigProperties) {
this(accurestConfigProperties, new SingleTestGenerator(accurestConfigProperties),
new FileSaver(accurestConfigProperties.generatedTestSourcesDir, accurestConfigProperties.targetFramework))
}
TestGenerator(AccurestConfigProperties configProperties, SingleTestGenerator generator, FileSaver saver) {
this.configProperties = configProperties
if (configProperties.stubsBaseDirectory == null) {
throw new AccurestException("Stubs directory not found under " + configProperties.stubsBaseDirectory)
}
this.generator = generator
this.saver = saver
this.directoryScanner = new DirectoryScanner()
directoryScanner.setExcludes(configProperties.getIgnoredFiles() as String[])
directoryScanner.setBasedir(configProperties.stubsBaseDirectory)
}
TestGenerator(AccurestConfigProperties configProperties, SingleTestGenerator generator, FileSaver saver) {
this.configProperties = configProperties
if (configProperties.stubsBaseDirectory == null) {
throw new AccurestException("Stubs directory not found under " + configProperties.stubsBaseDirectory)
}
this.generator = generator
this.saver = saver
this.directoryScanner = new DirectoryScanner()
directoryScanner.setExcludes(configProperties.getIgnoredFiles() as String[])
directoryScanner.setBasedir(configProperties.stubsBaseDirectory)
}
int generate() {
generateTestClasses(configProperties.basePackageForTests)
return counter.get()
}
int generate() {
generateTestClasses(configProperties.basePackageForTests)
return counter.get()
}
@PackageScope
void generateTestClasses(final String packageName) {
directoryScanner.scan()
directoryScanner.getIncludedDirectories()
.each { String includedDirectoryRelativePath ->
processIncludedDirectory(includedDirectoryRelativePath, packageName)
@PackageScope
void generateTestClasses(final String packageName) {
directoryScanner.scan()
directoryScanner.getIncludedDirectories()
.each { String includedDirectoryRelativePath ->
processIncludedDirectory(includedDirectoryRelativePath, packageName)
}
}
}
}
private void processIncludedDirectory(
final String includedDirectoryRelativePath, final String packageNameForClass) {
if (!includedDirectoryRelativePath.isEmpty()) {
List<File> filesToClass = directoryScanner.includedFiles.
grep { String includedFile ->
return includedFile.matches(includedDirectoryRelativePath + File.separator + "[A-Za-z0-9]*\\.json")
}
.collect {
return new File(configProperties.stubsBaseDirectory, it)
}
if (filesToClass.size()) {
def className = afterLast(includedDirectoryRelativePath, File.separator)
def classBytes = generator.buildClass(filesToClass, className, packageNameForClass).bytes
saver.saveClassFile(className, packageNameForClass, classBytes)
counter.incrementAndGet()
}
}
}
private void processIncludedDirectory(
final String includedDirectoryRelativePath, final String packageNameForClass) {
if (!includedDirectoryRelativePath.isEmpty()) {
List<File> filesToClass = directoryScanner.includedFiles.
grep { String includedFile ->
return includedFile.matches(includedDirectoryRelativePath + File.separator + "[A-Za-z0-9]*\\.json")
}
.collect {
return new File(configProperties.stubsBaseDirectory, it)
}
if (filesToClass.size()) {
def className = afterLast(includedDirectoryRelativePath, File.separator)
def classBytes = generator.buildClass(filesToClass, className, packageNameForClass).bytes
saver.saveClassFile(className, packageNameForClass, classBytes)
counter.incrementAndGet()
}
}
}
}

View File

@@ -1,6 +1,5 @@
package io.coderate.accurest.builder
import groovy.json.JsonOutput
import groovy.transform.PackageScope
/**

View File

@@ -1,4 +1,5 @@
package io.coderate.accurest.dsl
import groovy.transform.CompileStatic
import io.coderate.accurest.dsl.internal.DslProperty
import io.coderate.accurest.dsl.internal.Headers
@@ -6,50 +7,50 @@ import io.coderate.accurest.dsl.internal.WithValuePattern
@CompileStatic
abstract class BaseWiremockStubStrategy {
protected Map buildClientHeadersSection(Headers headers) {
if (!headers) {
return null
}
return withAssertionHeaders(headers) {
Map.Entry<String, WithValuePattern> entry -> [(entry.key): buildClientHeaderFromValuePattern(entry.value)]
} << headers.valueHeaders()
}
protected Map buildClientHeadersSection(Headers headers) {
if (!headers) {
return null
}
return withAssertionHeaders(headers) {
Map.Entry<String, WithValuePattern> entry -> [(entry.key): buildClientHeaderFromValuePattern(entry.value)]
} << headers.valueHeaders()
}
protected Map buildServerHeadersSection(Headers headers) {
if (!headers) {
return null
}
return withAssertionHeaders(headers) {
Map.Entry<String, WithValuePattern> entry -> [(entry.key): buildServerHeaderFromValuePattern(entry.value)]
} << headers.valueHeaders()
}
protected Map buildServerHeadersSection(Headers headers) {
if (!headers) {
return null
}
return withAssertionHeaders(headers) {
Map.Entry<String, WithValuePattern> entry -> [(entry.key): buildServerHeaderFromValuePattern(entry.value)]
} << headers.valueHeaders()
}
private Map withAssertionHeaders(Headers headers, Closure closure) {
return headers?.assertionEntries()?.collectEntries(closure)
}
private Map withAssertionHeaders(Headers headers, Closure closure) {
return headers?.assertionEntries()?.collectEntries(closure)
}
private Map buildClientHeaderFromValuePattern(WithValuePattern valuePattern) {
return getValuePatternSection(valuePattern)
.findAll { it.value }
.collectEntries { [(it.key): it.value.clientValue] }
}
private Map buildClientHeaderFromValuePattern(WithValuePattern valuePattern) {
return getValuePatternSection(valuePattern)
.findAll { it.value }
.collectEntries { [(it.key): it.value.clientValue] }
}
private Map buildServerHeaderFromValuePattern(WithValuePattern valuePattern) {
return getValuePatternSection(valuePattern)
.findAll { it.value }
.collectEntries { [(it.key): it.value.serverValue] }
}
private Map buildServerHeaderFromValuePattern(WithValuePattern valuePattern) {
return getValuePatternSection(valuePattern)
.findAll { it.value }
.collectEntries { [(it.key): it.value.serverValue] }
}
private Map<String, DslProperty> getValuePatternSection(WithValuePattern valuePattern) {
return [equalToJson : valuePattern.equalToJson,
equalToXml : valuePattern.equalToXml,
matchesXPath : valuePattern.matchesXPath,
jsonCompareMode: valuePattern.jsonCompareMode,
equalTo : valuePattern.equalTo,
contains : valuePattern.contains,
matches : valuePattern.matches,
doesNotMatch : valuePattern.doesNotMatch,
absent : valuePattern.absent,
matchesJsonPath: valuePattern.matchesJsonPath]
}
private Map<String, DslProperty> getValuePatternSection(WithValuePattern valuePattern) {
return [equalToJson : valuePattern.equalToJson,
equalToXml : valuePattern.equalToXml,
matchesXPath : valuePattern.matchesXPath,
jsonCompareMode: valuePattern.jsonCompareMode,
equalTo : valuePattern.equalTo,
contains : valuePattern.contains,
matches : valuePattern.matches,
doesNotMatch : valuePattern.doesNotMatch,
absent : valuePattern.absent,
matchesJsonPath: valuePattern.matchesJsonPath]
}
}

View File

@@ -11,26 +11,26 @@ import io.coderate.accurest.dsl.internal.Response
@ToString(includeFields = true, includePackage = false)
class GroovyDsl {
Request request
Response response
Request request
Response response
static GroovyDsl make(Closure closure) {
GroovyDsl dsl = new GroovyDsl()
closure.delegate = dsl
closure()
return dsl
}
static GroovyDsl make(Closure closure) {
GroovyDsl dsl = new GroovyDsl()
closure.delegate = dsl
closure()
return dsl
}
void request(@DelegatesTo(Request) Closure closure) {
this.request = new Request()
closure.delegate = request
closure()
}
void request(@DelegatesTo(Request) Closure closure) {
this.request = new Request()
closure.delegate = request
closure()
}
void response(@DelegatesTo(Response) Closure closure) {
this.response = new Response()
closure.delegate = response
closure()
}
void response(@DelegatesTo(Response) Closure closure) {
this.response = new Response()
closure.delegate = response
closure()
}
}

View File

@@ -10,33 +10,35 @@ import io.coderate.accurest.dsl.internal.ServerRequest
@PackageScope
class WiremockRequestStubStrategy extends BaseWiremockStubStrategy {
private final Request request
private final Request request
WiremockRequestStubStrategy(GroovyDsl groovyDsl) {
this.request = groovyDsl.request
}
WiremockRequestStubStrategy(GroovyDsl groovyDsl) {
this.request = groovyDsl.request
}
@PackageScope Map buildClientRequestContent() {
return buildRequestContent(new ClientRequest(request))
}
@PackageScope
Map buildClientRequestContent() {
return buildRequestContent(new ClientRequest(request))
}
@PackageScope Map buildServerRequestContent() {
return buildRequestContent(new ServerRequest(request))
}
@PackageScope
Map buildServerRequestContent() {
return buildRequestContent(new ServerRequest(request))
}
private Map<String, Object> buildRequestContent(ClientRequest request) {
return [method : request?.method?.clientValue,
url : request?.url?.clientValue,
urlPattern: request?.urlPattern?.clientValue,
urlPath : request?.urlPath?.clientValue,
headers : buildClientHeadersSection(request.headers)].findAll { it.value }
}
private Map<String, Object> buildRequestContent(ClientRequest request) {
return [method : request?.method?.clientValue,
url : request?.url?.clientValue,
urlPattern: request?.urlPattern?.clientValue,
urlPath : request?.urlPath?.clientValue,
headers : buildClientHeadersSection(request.headers)].findAll { it.value }
}
private Map<String, Object> buildRequestContent(ServerRequest request) {
return [method : request?.method?.serverValue,
url : request?.url?.serverValue,
urlPattern: request?.urlPattern?.serverValue,
urlPath : request?.urlPath?.serverValue,
headers : buildServerHeadersSection(request.headers)].findAll { it.value }
}
private Map<String, Object> buildRequestContent(ServerRequest request) {
return [method : request?.method?.serverValue,
url : request?.url?.serverValue,
urlPattern: request?.urlPattern?.serverValue,
urlPath : request?.urlPath?.serverValue,
headers : buildServerHeadersSection(request.headers)].findAll { it.value }
}
}

View File

@@ -10,30 +10,32 @@ import io.coderate.accurest.dsl.internal.ServerResponse
@PackageScope
class WiremockResponseStubStrategy extends BaseWiremockStubStrategy {
private final Response response
private final Response response
WiremockResponseStubStrategy(GroovyDsl groovyDsl) {
this.response = groovyDsl.response
}
WiremockResponseStubStrategy(GroovyDsl groovyDsl) {
this.response = groovyDsl.response
}
@PackageScope Map buildClientResponseContent() {
return buildResponseContent(new ClientResponse(response))
}
@PackageScope
Map buildClientResponseContent() {
return buildResponseContent(new ClientResponse(response))
}
@PackageScope Map buildServerResponseContent() {
return buildResponseContent(new ServerResponse(response))
}
@PackageScope
Map buildServerResponseContent() {
return buildResponseContent(new ServerResponse(response))
}
private Map<String, Object> buildResponseContent(ClientResponse response) {
return [status : response?.status?.clientValue,
body : response?.body?.forClientSide(),
headers: buildClientHeadersSection(response.headers)].findAll { it.value }
}
private Map<String, Object> buildResponseContent(ClientResponse response) {
return [status : response?.status?.clientValue,
body : response?.body?.forClientSide(),
headers: buildClientHeadersSection(response.headers)].findAll { it.value }
}
private Map<String, Object> buildResponseContent(ServerResponse response) {
return [status : response?.status?.serverValue,
body : response?.body?.forServerSide(),
headers: buildServerHeadersSection(response.headers)].findAll { it.value }
}
private Map<String, Object> buildResponseContent(ServerResponse response) {
return [status : response?.status?.serverValue,
body : response?.body?.forServerSide(),
headers: buildServerHeadersSection(response.headers)].findAll { it.value }
}
}

View File

@@ -6,21 +6,21 @@ import groovy.transform.CompileStatic
@CompileStatic
class WiremockStubStrategy {
private final WiremockRequestStubStrategy wiremockRequestStubStrategy
private final WiremockResponseStubStrategy wiremockResponseStubStrategy
private final WiremockRequestStubStrategy wiremockRequestStubStrategy
private final WiremockResponseStubStrategy wiremockResponseStubStrategy
WiremockStubStrategy(GroovyDsl groovyDsl) {
this.wiremockRequestStubStrategy = new WiremockRequestStubStrategy(groovyDsl)
this.wiremockResponseStubStrategy = new WiremockResponseStubStrategy(groovyDsl)
}
WiremockStubStrategy(GroovyDsl groovyDsl) {
this.wiremockRequestStubStrategy = new WiremockRequestStubStrategy(groovyDsl)
this.wiremockResponseStubStrategy = new WiremockResponseStubStrategy(groovyDsl)
}
String toWiremockClientStub() {
return JsonOutput.prettyPrint(JsonOutput.toJson([request: wiremockRequestStubStrategy.buildClientRequestContent(),
response: wiremockResponseStubStrategy.buildClientResponseContent()]))
}
String toWiremockClientStub() {
return JsonOutput.prettyPrint(JsonOutput.toJson([request : wiremockRequestStubStrategy.buildClientRequestContent(),
response: wiremockResponseStubStrategy.buildClientResponseContent()]))
}
String toWiremockServerStub() {
return JsonOutput.prettyPrint(JsonOutput.toJson([request: wiremockRequestStubStrategy.buildServerRequestContent(),
response: wiremockResponseStubStrategy.buildServerResponseContent()]))
}
String toWiremockServerStub() {
return JsonOutput.prettyPrint(JsonOutput.toJson([request : wiremockRequestStubStrategy.buildServerRequestContent(),
response: wiremockResponseStubStrategy.buildServerResponseContent()]))
}
}

View File

@@ -9,65 +9,65 @@ import org.codehaus.groovy.runtime.GStringImpl
@EqualsAndHashCode(includeFields = true)
class Body {
private Map<String, DslProperty> body
private DslProperty bodyAsValue
private List<DslProperty> bodyAsList
private Map<String, DslProperty> body
private DslProperty bodyAsValue
private List<DslProperty> bodyAsList
Body() {
this.body = [:]
}
Body() {
this.body = [:]
}
Body(Map<String, DslProperty> body) {
this.body = body
}
Body(Map<String, DslProperty> body) {
this.body = body
}
Body(List bodyAsList) {
this.bodyAsList = bodyAsList
}
Body(List bodyAsList) {
this.bodyAsList = bodyAsList
}
Body(Object bodyAsValue) {
this.bodyAsValue = new DslProperty(bodyAsValue)
}
Body(Object bodyAsValue) {
this.bodyAsValue = new DslProperty(bodyAsValue)
}
Body(GString bodyAsValue) {
this.bodyAsValue = new DslProperty(getClientValue(bodyAsValue), getServerValue(bodyAsValue))
}
Body(GString bodyAsValue) {
this.bodyAsValue = new DslProperty(getClientValue(bodyAsValue), getServerValue(bodyAsValue))
}
private Map getClientValue(GString bodyAsValue) {
GString clientGString = new GStringImpl(bodyAsValue.values.clone(), bodyAsValue.strings.clone())
Object[] clientValues = bodyAsValue.values.collect { it instanceof DslProperty ? it.clientValue : it } as Object[]
return new JsonSlurper().parseText(new GStringImpl(clientValues, clientGString.strings).toString())
}
private Map getClientValue(GString bodyAsValue) {
GString clientGString = new GStringImpl(bodyAsValue.values.clone(), bodyAsValue.strings.clone())
Object[] clientValues = bodyAsValue.values.collect { it instanceof DslProperty ? it.clientValue : it } as Object[]
return new JsonSlurper().parseText(new GStringImpl(clientValues, clientGString.strings).toString())
}
private Map getServerValue(GString bodyAsValue) {
GString clientGString = new GStringImpl(bodyAsValue.values.clone(), bodyAsValue.strings.clone())
Object[] serverValues = bodyAsValue.values.collect { it instanceof DslProperty ? it.serverValue: it } as Object[]
return new JsonSlurper().parseText(new GStringImpl(serverValues, clientGString.strings).toString())
}
private Map getServerValue(GString bodyAsValue) {
GString clientGString = new GStringImpl(bodyAsValue.values.clone(), bodyAsValue.strings.clone())
Object[] serverValues = bodyAsValue.values.collect { it instanceof DslProperty ? it.serverValue : it } as Object[]
return new JsonSlurper().parseText(new GStringImpl(serverValues, clientGString.strings).toString())
}
Body(DslProperty bodyAsValue) {
this.bodyAsValue = bodyAsValue
}
Body(DslProperty bodyAsValue) {
this.bodyAsValue = bodyAsValue
}
Object forClientSide() {
if(bodyAsValue) {
return bodyAsValue.clientValue
} else if(bodyAsList) {
bodyAsList.collect { it.clientValue }
}
return body.collectEntries { Map.Entry<String, DslProperty> entry ->
[(entry.key) : entry.value.clientValue]
} as Map<String, Object>
}
Object forClientSide() {
if (bodyAsValue) {
return bodyAsValue.clientValue
} else if (bodyAsList) {
bodyAsList.collect { it.clientValue }
}
return body.collectEntries { Map.Entry<String, DslProperty> entry ->
[(entry.key): entry.value.clientValue]
} as Map<String, Object>
}
Object forServerSide() {
if(bodyAsValue) {
return bodyAsValue.serverValue
} else if(bodyAsList) {
bodyAsList.collect { it.serverValue }
}
return body.collectEntries { Map.Entry<String, DslProperty> entry ->
[(entry.key) : entry.value.serverValue]
} as Map<String, Object>
}
Object forServerSide() {
if (bodyAsValue) {
return bodyAsValue.serverValue
} else if (bodyAsList) {
bodyAsList.collect { it.serverValue }
}
return body.collectEntries { Map.Entry<String, DslProperty> entry ->
[(entry.key): entry.value.serverValue]
} as Map<String, Object>
}
}

View File

@@ -1,10 +1,11 @@
package io.coderate.accurest.dsl.internal
import groovy.transform.CompileStatic
@CompileStatic
class ClientDslProperty extends DslProperty {
ClientDslProperty(Object singleValue) {
super(singleValue)
}
ClientDslProperty(Object singleValue) {
super(singleValue)
}
}

View File

@@ -11,60 +11,60 @@ import groovy.transform.TypeChecked
@PackageScope
class Common {
Map<String, DslProperty> convertObjectsToDslProperties(Map<String, Object> body) {
return body.collectEntries {
Map.Entry<String, Object> entry ->
[(entry.key): toDslProperty(entry.value)]
} as Map<String, DslProperty>
}
Map<String, DslProperty> convertObjectsToDslProperties(Map<String, Object> body) {
return body.collectEntries {
Map.Entry<String, Object> entry ->
[(entry.key): toDslProperty(entry.value)]
} as Map<String, DslProperty>
}
List convertObjectsToDslProperties(List body) {
return body.collect {
Object element -> toDslProperty(element)
} as List
}
List convertObjectsToDslProperties(List body) {
return body.collect {
Object element -> toDslProperty(element)
} as List
}
DslProperty toDslProperty(Object property) {
return new DslProperty(property)
}
DslProperty toDslProperty(Object property) {
return new DslProperty(property)
}
DslProperty toDslProperty(Map property) {
return new DslProperty(property.collectEntries {
[(it.key) : toDslProperty(it.value)]
})
}
DslProperty toDslProperty(Map property) {
return new DslProperty(property.collectEntries {
[(it.key): toDslProperty(it.value)]
})
}
DslProperty toDslProperty(List property) {
return new DslProperty(property.collect {
toDslProperty(it)
})
}
DslProperty toDslProperty(List property) {
return new DslProperty(property.collect {
toDslProperty(it)
})
}
DslProperty toDslProperty(DslProperty property) {
return property
}
DslProperty toDslProperty(DslProperty property) {
return property
}
DslProperty value(ClientDslProperty client, ServerDslProperty server) {
return new DslProperty(client.clientValue, server.serverValue)
}
DslProperty value(ClientDslProperty client, ServerDslProperty server) {
return new DslProperty(client.clientValue, server.serverValue)
}
DslProperty value(ServerDslProperty server, ClientDslProperty client) {
return new DslProperty(client.clientValue, server.serverValue)
}
DslProperty value(ServerDslProperty server, ClientDslProperty client) {
return new DslProperty(client.clientValue, server.serverValue)
}
DslProperty $(ClientDslProperty client, ServerDslProperty server) {
return value(client, server)
}
DslProperty $(ClientDslProperty client, ServerDslProperty server) {
return value(client, server)
}
DslProperty $(ServerDslProperty server, ClientDslProperty client) {
return value(server, client)
}
DslProperty $(ServerDslProperty server, ClientDslProperty client) {
return value(server, client)
}
ClientDslProperty client(Object clientValue) {
return new ClientDslProperty(clientValue)
}
ClientDslProperty client(Object clientValue) {
return new ClientDslProperty(clientValue)
}
ServerDslProperty server(Object serverValue) {
return new ServerDslProperty(serverValue)
}
ServerDslProperty server(Object serverValue) {
return new ServerDslProperty(serverValue)
}
}

View File

@@ -9,16 +9,16 @@ import groovy.transform.ToString
@ToString(includePackage = false)
class DslProperty<T> {
final T clientValue
final T serverValue
final T clientValue
final T serverValue
DslProperty(T clientValue, T serverValue) {
this.clientValue = clientValue
this.serverValue = serverValue
}
DslProperty(T clientValue, T serverValue) {
this.clientValue = clientValue
this.serverValue = serverValue
}
DslProperty(T singleValue) {
this.clientValue = singleValue
this.serverValue = singleValue
}
DslProperty(T singleValue) {
this.clientValue = singleValue
this.serverValue = singleValue
}
}

View File

@@ -7,26 +7,26 @@ import groovy.transform.ToString
@ToString(includePackage = false, includeFields = true, ignoreNulls = true)
class Headers {
private Map<String, WithValuePattern> assertionHeaders = [:]
private Map<String, String> valueHeaders = [:]
private Map<String, WithValuePattern> assertionHeaders = [:]
private Map<String, String> valueHeaders = [:]
WithValuePattern header(String headerName) {
WithValuePattern withValuePattern = new WithValuePattern()
assertionHeaders[headerName] = withValuePattern
return withValuePattern
}
WithValuePattern header(String headerName) {
WithValuePattern withValuePattern = new WithValuePattern()
assertionHeaders[headerName] = withValuePattern
return withValuePattern
}
void header(Map<String, String> singleHeader) {
Map.Entry<String, String> first = singleHeader.entrySet().first()
valueHeaders[first?.key] = first?.value
}
void header(Map<String, String> singleHeader) {
Map.Entry<String, String> first = singleHeader.entrySet().first()
valueHeaders[first?.key] = first?.value
}
Map<String, String> valueHeaders() {
return Collections.unmodifiableMap(valueHeaders)
}
Map<String, String> valueHeaders() {
return Collections.unmodifiableMap(valueHeaders)
}
Set<Map.Entry<String, WithValuePattern>> assertionEntries() {
return Collections.unmodifiableSet(assertionHeaders.entrySet())
}
Set<Map.Entry<String, WithValuePattern>> assertionEntries() {
return Collections.unmodifiableSet(assertionHeaders.entrySet())
}
}

View File

@@ -1,5 +1,5 @@
package io.coderate.accurest.dsl.internal
enum JSONCompareMode {
STRICT, LENIENT, NON_EXTENSIBLE, STRICT_ORDER
STRICT, LENIENT, NON_EXTENSIBLE, STRICT_ORDER
}

View File

@@ -1,4 +1,5 @@
package io.coderate.accurest.dsl.internal
import groovy.transform.CompileStatic
import groovy.transform.EqualsAndHashCode
import groovy.transform.ToString
@@ -9,76 +10,76 @@ import groovy.transform.TypeChecked
@ToString(includePackage = false)
class Request extends Common {
DslProperty method
DslProperty url
DslProperty urlPattern
DslProperty urlPath
Headers headers
DslProperty method
DslProperty url
DslProperty urlPattern
DslProperty urlPath
Headers headers
Request() {
}
Request() {
}
Request(Request request) {
this.method = request.method
this.url = request.url
this.urlPattern = request.urlPattern
this.urlPath = request.urlPath
this.headers = request.headers
}
Request(Request request) {
this.method = request.method
this.url = request.url
this.urlPattern = request.urlPattern
this.urlPath = request.urlPath
this.headers = request.headers
}
void method(String method) {
this.method = toDslProperty(method)
}
void method(String method) {
this.method = toDslProperty(method)
}
void method(DslProperty method) {
this.method = toDslProperty(method)
}
void method(DslProperty method) {
this.method = toDslProperty(method)
}
void url(String url) {
this.url = toDslProperty(url)
}
void url(String url) {
this.url = toDslProperty(url)
}
void url(DslProperty url) {
this.url = toDslProperty(url)
}
void url(DslProperty url) {
this.url = toDslProperty(url)
}
void urlPattern(String urlPattern) {
this.urlPattern = toDslProperty(urlPattern)
}
void urlPattern(String urlPattern) {
this.urlPattern = toDslProperty(urlPattern)
}
void urlPattern(DslProperty urlPattern) {
this.urlPattern = toDslProperty(urlPattern)
}
void urlPattern(DslProperty urlPattern) {
this.urlPattern = toDslProperty(urlPattern)
}
void headers(@DelegatesTo(Headers) Closure closure) {
this.headers = new Headers()
closure.delegate = headers
closure()
}
void headers(@DelegatesTo(Headers) Closure closure) {
this.headers = new Headers()
closure.delegate = headers
closure()
}
void urlPath(String urlPath) {
this.urlPath = toDslProperty(urlPath)
}
void urlPath(String urlPath) {
this.urlPath = toDslProperty(urlPath)
}
void urlPath(DslProperty urlPath) {
this.urlPath = toDslProperty(urlPath)
}
void urlPath(DslProperty urlPath) {
this.urlPath = toDslProperty(urlPath)
}
}
@CompileStatic
@EqualsAndHashCode(includeFields = true)
@ToString(includePackage = false)
class ServerRequest extends Request {
ServerRequest(Request request) {
super(request)
}
ServerRequest(Request request) {
super(request)
}
}
@CompileStatic
@EqualsAndHashCode(includeFields = true)
@ToString(includePackage = false)
class ClientRequest extends Request {
ClientRequest(Request request) {
super(request)
}
ClientRequest(Request request) {
super(request)
}
}

View File

@@ -10,72 +10,72 @@ import groovy.transform.TypeChecked
@ToString(includePackage = false, includeFields = true)
class Response extends Common {
private DslProperty status
private Headers headers
private Body body = new Body()
private DslProperty status
private Headers headers
private Body body = new Body()
Response() {
}
Response() {
}
Response(Response response) {
this.status = response.status
this.headers = response.headers
this.body = response.body
}
Response(Response response) {
this.status = response.status
this.headers = response.headers
this.body = response.body
}
void status(int status) {
this.status = toDslProperty(status)
}
void status(int status) {
this.status = toDslProperty(status)
}
void status(DslProperty status) {
this.status = toDslProperty(status)
}
void status(DslProperty status) {
this.status = toDslProperty(status)
}
void headers(@DelegatesTo(Headers) Closure closure) {
this.headers = new Headers()
closure.delegate = headers
closure()
}
void headers(@DelegatesTo(Headers) Closure closure) {
this.headers = new Headers()
closure.delegate = headers
closure()
}
void body(Map<String, Object> body) {
this.body = new Body(convertObjectsToDslProperties(body))
}
void body(Map<String, Object> body) {
this.body = new Body(convertObjectsToDslProperties(body))
}
void body(List body) {
this.body = new Body(convertObjectsToDslProperties(body))
}
void body(List body) {
this.body = new Body(convertObjectsToDslProperties(body))
}
void body(Object bodyAsValue) {
this.body = new Body(bodyAsValue)
}
void body(Object bodyAsValue) {
this.body = new Body(bodyAsValue)
}
Body getBody() {
return body
}
Body getBody() {
return body
}
DslProperty getStatus() {
return status
}
DslProperty getStatus() {
return status
}
Headers getHeaders() {
return headers
}
Headers getHeaders() {
return headers
}
}
@CompileStatic
@EqualsAndHashCode(includeFields = true)
@ToString(includePackage = false)
class ServerResponse extends Response {
ServerResponse(Response request) {
super(request)
}
ServerResponse(Response request) {
super(request)
}
}
@CompileStatic
@EqualsAndHashCode(includeFields = true)
@ToString(includePackage = false)
class ClientResponse extends Response {
ClientResponse(Response request) {
super(request)
}
ClientResponse(Response request) {
super(request)
}
}

View File

@@ -9,7 +9,7 @@ import groovy.transform.ToString
@ToString(includePackage = false)
class ServerDslProperty extends DslProperty {
ServerDslProperty(Object singleValue) {
super(singleValue)
}
ServerDslProperty(Object singleValue) {
super(singleValue)
}
}

View File

@@ -9,94 +9,94 @@ import groovy.transform.TypeChecked
@ToString(includePackage = false)
class WithValuePattern {
DslProperty<String> equalTo
DslProperty<String> equalToJson
DslProperty<String> equalToXml
DslProperty<String> matchesXPath
DslProperty<JSONCompareMode> jsonCompareMode
DslProperty<String> contains
DslProperty<String> matches
DslProperty<String> doesNotMatch
DslProperty<String> absent
DslProperty<String> matchesJsonPath
DslProperty<String> equalTo
DslProperty<String> equalToJson
DslProperty<String> equalToXml
DslProperty<String> matchesXPath
DslProperty<JSONCompareMode> jsonCompareMode
DslProperty<String> contains
DslProperty<String> matches
DslProperty<String> doesNotMatch
DslProperty<String> absent
DslProperty<String> matchesJsonPath
void equalTo(String equalTo) {
this.equalTo = new DslProperty<String>(equalTo)
}
void equalTo(String equalTo) {
this.equalTo = new DslProperty<String>(equalTo)
}
void equalTo(DslProperty equalTo) {
this.equalTo = equalTo
}
void equalTo(DslProperty equalTo) {
this.equalTo = equalTo
}
void equalToJson(String equalToJson) {
this.equalToJson = new DslProperty<String>(equalToJson)
}
void equalToJson(String equalToJson) {
this.equalToJson = new DslProperty<String>(equalToJson)
}
void equalToJson(DslProperty equalToJson) {
this.equalToJson = equalToJson
}
void equalToJson(DslProperty equalToJson) {
this.equalToJson = equalToJson
}
void equalToXml(String equalToXml) {
this.equalToXml = new DslProperty<String>(equalToXml)
}
void equalToXml(String equalToXml) {
this.equalToXml = new DslProperty<String>(equalToXml)
}
void equalToXml(DslProperty equalToXml) {
this.equalToXml = equalToXml
}
void equalToXml(DslProperty equalToXml) {
this.equalToXml = equalToXml
}
void matchesXPath(String matchesXPath) {
this.matchesXPath = new DslProperty<String>(matchesXPath)
}
void matchesXPath(String matchesXPath) {
this.matchesXPath = new DslProperty<String>(matchesXPath)
}
void matchesXPath(DslProperty matchesXPath) {
this.matchesXPath = matchesXPath
}
void matchesXPath(DslProperty matchesXPath) {
this.matchesXPath = matchesXPath
}
void jsonCompareMode(JSONCompareMode jsonCompareMode) {
this.jsonCompareMode = new DslProperty<JSONCompareMode>(jsonCompareMode)
}
void jsonCompareMode(JSONCompareMode jsonCompareMode) {
this.jsonCompareMode = new DslProperty<JSONCompareMode>(jsonCompareMode)
}
void jsonCompareMode(DslProperty jsonCompareMode) {
this.jsonCompareMode = jsonCompareMode
}
void jsonCompareMode(DslProperty jsonCompareMode) {
this.jsonCompareMode = jsonCompareMode
}
void contains(String contains) {
this.contains = new DslProperty<String>(contains)
}
void contains(String contains) {
this.contains = new DslProperty<String>(contains)
}
void contains(DslProperty contains) {
this.contains = contains
}
void contains(DslProperty contains) {
this.contains = contains
}
void matches(String matches) {
this.matches = new DslProperty<String>(matches)
}
void matches(String matches) {
this.matches = new DslProperty<String>(matches)
}
void matches(DslProperty matches) {
this.matches = matches
}
void matches(DslProperty matches) {
this.matches = matches
}
void doesNotMatch(String doesNotMatch) {
this.doesNotMatch = new DslProperty<String>(doesNotMatch)
}
void doesNotMatch(String doesNotMatch) {
this.doesNotMatch = new DslProperty<String>(doesNotMatch)
}
void doesNotMatch(DslProperty doesNotMatch) {
this.doesNotMatch = doesNotMatch
}
void doesNotMatch(DslProperty doesNotMatch) {
this.doesNotMatch = doesNotMatch
}
void absent(String absent) {
this.absent = new DslProperty<String>(absent)
}
void absent(String absent) {
this.absent = new DslProperty<String>(absent)
}
void absent(DslProperty absent) {
this.absent = absent
}
void absent(DslProperty absent) {
this.absent = absent
}
void matchesJsonPath(String matchesJsonPath) {
this.matchesJsonPath = new DslProperty<String>(matchesJsonPath)
}
void matchesJsonPath(String matchesJsonPath) {
this.matchesJsonPath = new DslProperty<String>(matchesJsonPath)
}
void matchesJsonPath(DslProperty matchesJsonPath) {
this.matchesJsonPath = matchesJsonPath
}
void matchesJsonPath(DslProperty matchesJsonPath) {
this.matchesJsonPath = matchesJsonPath
}
}

View File

@@ -9,7 +9,7 @@
},
"bodyPatterns": [
{
"matches": "\\{\"clientPesel\":\"1234567890\",\"loanAmount\":123.123\\}"
"matches": "\\{\"clientPesel\":\"1234567890\",\"loanAmount\":123.123\\}"
}
]
},

View File

@@ -11,7 +11,7 @@ class MainTest {
stubsBaseDirectory: '/home/devel/projects/codearte/accurest/accurest-core/src/main/resources/stubs',
generatedTestSourcesDir: '/tmp/accurest',
targetFramework: TestFramework.SPOCK, testMode: TestMode.MOCKMVC, basePackageForTests: 'io.test',
staticImports: ['com.pupablada.Test.*'], imports: ['org.innapypa.Test'], ignoredFiles: ["**/other"])
staticImports: ['com.pupablada.Test.*'], imports: ['org.innapypa.Test'], ignoredFiles: ["**/other"])
println new TestGenerator(properties).generate()
}
}

View File

@@ -10,7 +10,7 @@ class TestGeneratorSpec extends Specification {
private SingleTestGenerator classGenerator = Mock(SingleTestGenerator)
def "should find all .json files and generate 3 classes for them"() {
def "should find all .json files and generate 3 classes for them"() {
given:
File resource = new File(this.getClass().getResource("/directory/with/stubs/stubsRepositoryIndicator").toURI())
AccurestConfigProperties properties = new AccurestConfigProperties()
@@ -22,7 +22,7 @@ class TestGeneratorSpec extends Specification {
3 * classGenerator.buildClass(_, _, _) >> "qwerty"
}
def "should filter other directory"() {
def "should filter other directory"() {
given:
File resource = new File(this.getClass().getResource("/directory/with/stubs/stubsRepositoryIndicator").toURI())
AccurestConfigProperties properties = new AccurestConfigProperties()
@@ -35,7 +35,7 @@ class TestGeneratorSpec extends Specification {
1 * classGenerator.buildClass(_, 'different', _) >> "qwerty"
}
def "should ignore file"() {
def "should ignore file"() {
given:
File resource = new File(this.getClass().getResource("/directory/with/stubs/stubsRepositoryIndicator").toURI())
AccurestConfigProperties properties = new AccurestConfigProperties()

View File

@@ -7,42 +7,42 @@ import spock.lang.Specification
class WiremockGroovyDslResponseSpec extends Specification {
def 'should generate response without body for #side side'() {
given:
GroovyDsl dsl = GroovyDsl.make {
response {
status 200
}
}
expect:
new WiremockResponseStubStrategy(dsl)."build${side}ResponseContent"() == new JsonSlurper().parseText(expectedStub)
where:
side << ['Client', 'Server']
expectedStub << ['''
def 'should generate response without body for #side side'() {
given:
GroovyDsl dsl = GroovyDsl.make {
response {
status 200
}
}
expect:
new WiremockResponseStubStrategy(dsl)."build${side}ResponseContent"() == new JsonSlurper().parseText(expectedStub)
where:
side << ['Client', 'Server']
expectedStub << ['''
{
"status": 200
}
''',
'''
'''
{
"status": 200
}
''']
}
}
def 'should generate headers for response for client side'() {
given:
GroovyDsl dsl = GroovyDsl.make {
response {
headers {
header('Content-Type').matches $(client('text/xml'), server('text/*'))
}
status 200
}
}
expect:
new WiremockResponseStubStrategy(dsl).buildClientResponseContent() == new JsonSlurper().parseText('''
def 'should generate headers for response for client side'() {
given:
GroovyDsl dsl = GroovyDsl.make {
response {
headers {
header('Content-Type').matches $(client('text/xml'), server('text/*'))
}
status 200
}
}
expect:
new WiremockResponseStubStrategy(dsl).buildClientResponseContent() == new JsonSlurper().parseText('''
{
"headers": {
"Content-Type": {
@@ -52,20 +52,20 @@ class WiremockGroovyDslResponseSpec extends Specification {
"status": 200
}
''')
}
}
def 'should generate headers for response for server side'() {
given:
GroovyDsl dsl = GroovyDsl.make {
response {
status 200
headers {
header('Content-Type').matches $(client('text/xml'), server('text/*'))
}
}
}
expect:
new WiremockResponseStubStrategy(dsl).buildServerResponseContent() == new JsonSlurper().parseText('''
def 'should generate headers for response for server side'() {
given:
GroovyDsl dsl = GroovyDsl.make {
response {
status 200
headers {
header('Content-Type').matches $(client('text/xml'), server('text/*'))
}
}
}
expect:
new WiremockResponseStubStrategy(dsl).buildServerResponseContent() == new JsonSlurper().parseText('''
{
"status": 200,
"headers": {
@@ -75,20 +75,20 @@ class WiremockGroovyDslResponseSpec extends Specification {
}
}
''')
}
}
def 'should generate an exact header for response for both sides '() {
given:
GroovyDsl dsl = GroovyDsl.make {
response {
status 200
headers {
header 'Content-Type': 'text/xml'
}
}
}
expect:
new WiremockResponseStubStrategy(dsl).buildServerResponseContent() == new JsonSlurper().parseText('''
def 'should generate an exact header for response for both sides '() {
given:
GroovyDsl dsl = GroovyDsl.make {
response {
status 200
headers {
header 'Content-Type': 'text/xml'
}
}
}
expect:
new WiremockResponseStubStrategy(dsl).buildServerResponseContent() == new JsonSlurper().parseText('''
{
"status": 200,
"headers": {
@@ -96,5 +96,5 @@ class WiremockGroovyDslResponseSpec extends Specification {
}
}
''')
}
}
}

View File

@@ -9,36 +9,36 @@ import spock.lang.Specification
class WiremockGroovyDslSpec extends Specification {
def 'should convert groovy dsl stub to wiremock stub for the client side'() {
given:
GroovyDsl groovyDsl = GroovyDsl.make {
request {
method('GET')
urlPattern $(client('/[0-9]{2}'), server('/12'))
}
response {
status 200
body (
id : value(
client('123'),
server({ regex('[0-9]+') })
),
surname : $(
client('Kowalsky'),
server('Lewandowski')
),
name: 'Jan',
created : $(client('2014-02-02 12:23:43'), server({ currentDate(it) }))
)
headers {
header 'Content-Type': 'text/plain'
}
}
}
when:
String wiremockStub = new WiremockStubStrategy(groovyDsl).toWiremockClientStub()
then:
new JsonSlurper().parseText(wiremockStub) == new JsonSlurper().parseText('''
def 'should convert groovy dsl stub to wiremock stub for the client side'() {
given:
GroovyDsl groovyDsl = GroovyDsl.make {
request {
method('GET')
urlPattern $(client('/[0-9]{2}'), server('/12'))
}
response {
status 200
body(
id: value(
client('123'),
server({ regex('[0-9]+') })
),
surname: $(
client('Kowalsky'),
server('Lewandowski')
),
name: 'Jan',
created: $(client('2014-02-02 12:23:43'), server({ currentDate(it) }))
)
headers {
header 'Content-Type': 'text/plain'
}
}
}
when:
String wiremockStub = new WiremockStubStrategy(groovyDsl).toWiremockClientStub()
then:
new JsonSlurper().parseText(wiremockStub) == new JsonSlurper().parseText('''
{
"request": {
"method": "GET",
@@ -58,35 +58,35 @@ class WiremockGroovyDslSpec extends Specification {
}
}
''')
}
}
def 'should convert groovy dsl stub with Body as String to wiremock stub for the client side'() {
given:
GroovyDsl groovyDsl = GroovyDsl.make {
request {
method('GET')
urlPattern $(client('/[0-9]{2}'), server('/12'))
}
response {
status 200
body ("""\
def 'should convert groovy dsl stub with Body as String to wiremock stub for the client side'() {
given:
GroovyDsl groovyDsl = GroovyDsl.make {
request {
method('GET')
urlPattern $(client('/[0-9]{2}'), server('/12'))
}
response {
status 200
body("""\
{
"id": "${value(client('123'),server('321'))}",
"surname": "${value(client('Kowalsky'),server('Lewandowski'))}",
"id": "${value(client('123'), server('321'))}",
"surname": "${value(client('Kowalsky'), server('Lewandowski'))}",
"name": "Jan",
"created" : "${$(client('2014-02-02 12:23:43'), server('2999-09-09 01:23:45'))}"
}
"""
)
headers {
header 'Content-Type': 'text/plain'
}
}
}
when:
String wiremockStub = new WiremockStubStrategy(groovyDsl).toWiremockClientStub()
then:
new JsonSlurper().parseText(wiremockStub) == new JsonSlurper().parseText('''
)
headers {
header 'Content-Type': 'text/plain'
}
}
}
when:
String wiremockStub = new WiremockStubStrategy(groovyDsl).toWiremockClientStub()
then:
new JsonSlurper().parseText(wiremockStub) == new JsonSlurper().parseText('''
{
"request": {
"method": "GET",
@@ -106,35 +106,35 @@ class WiremockGroovyDslSpec extends Specification {
}
}
''')
}
}
def 'should convert groovy dsl stub with Body as String to wiremock stub for the server side'() {
given:
GroovyDsl groovyDsl = GroovyDsl.make {
request {
method('GET')
urlPattern $(client('/[0-9]{2}'), server('/12'))
}
response {
status 200
body ("""\
def 'should convert groovy dsl stub with Body as String to wiremock stub for the server side'() {
given:
GroovyDsl groovyDsl = GroovyDsl.make {
request {
method('GET')
urlPattern $(client('/[0-9]{2}'), server('/12'))
}
response {
status 200
body("""\
{
"id": "${value(client('123'),server('321'))}",
"surname": "${value(client('Kowalsky'),server('Lewandowski'))}",
"id": "${value(client('123'), server('321'))}",
"surname": "${value(client('Kowalsky'), server('Lewandowski'))}",
"name": "Jan",
"created" : "${$(client('2014-02-02 12:23:43'), server('2999-09-09 01:23:45'))}"
}
"""
)
headers {
header 'Content-Type': 'text/plain'
}
}
}
when:
String wiremockStub = new WiremockStubStrategy(groovyDsl).toWiremockServerStub()
then:
new JsonSlurper().parseText(wiremockStub) == new JsonSlurper().parseText('''
)
headers {
header 'Content-Type': 'text/plain'
}
}
}
when:
String wiremockStub = new WiremockStubStrategy(groovyDsl).toWiremockServerStub()
then:
new JsonSlurper().parseText(wiremockStub) == new JsonSlurper().parseText('''
{
"request": {
"method": "GET",
@@ -154,38 +154,38 @@ class WiremockGroovyDslSpec extends Specification {
}
}
''')
}
}
def 'should convert groovy dsl stub to wiremock stub for the server side'() {
given:
GroovyDsl groovyDsl = GroovyDsl.make {
request {
method('GET')
urlPattern $(client('/[0-9]{2}'), server('/12'))
}
response {
status(200)
body (
id : value(
client('123'),
server('321')
),
surname : $(
client('Kowalsky'),
server('Lewandowski')
),
name: 'Jan',
created : $(client('2014-02-02 12:23:43'), server('1999-01-01 01:23:45'))
)
headers {
header('Content-Type': 'text/plain')
}
}
}
when:
String wiremockStub = new WiremockStubStrategy(groovyDsl).toWiremockServerStub()
then:
new JsonSlurper().parseText(wiremockStub) == new JsonSlurper().parseText('''
def 'should convert groovy dsl stub to wiremock stub for the server side'() {
given:
GroovyDsl groovyDsl = GroovyDsl.make {
request {
method('GET')
urlPattern $(client('/[0-9]{2}'), server('/12'))
}
response {
status(200)
body(
id: value(
client('123'),
server('321')
),
surname: $(
client('Kowalsky'),
server('Lewandowski')
),
name: 'Jan',
created: $(client('2014-02-02 12:23:43'), server('1999-01-01 01:23:45'))
)
headers {
header('Content-Type': 'text/plain')
}
}
}
when:
String wiremockStub = new WiremockStubStrategy(groovyDsl).toWiremockServerStub()
then:
new JsonSlurper().parseText(wiremockStub) == new JsonSlurper().parseText('''
{
"request": {
"method": "GET",
@@ -205,129 +205,129 @@ class WiremockGroovyDslSpec extends Specification {
}
}
''')
}
}
def "should generate stub with GET"() {
given:
GroovyDsl groovyDsl = GroovyDsl.make {
request {
method("GET")
}
}
expect:
new WiremockRequestStubStrategy(groovyDsl).buildClientRequestContent() == new JsonSlurper().parseText('''
def "should generate stub with GET"() {
given:
GroovyDsl groovyDsl = GroovyDsl.make {
request {
method("GET")
}
}
expect:
new WiremockRequestStubStrategy(groovyDsl).buildClientRequestContent() == new JsonSlurper().parseText('''
{
"method":"GET"
}
''')
}
}
def "should generate request when two elements are provided "() {
given:
GroovyDsl groovyDsl = GroovyDsl.make {
request {
method("GET")
url("/sth")
}
}
expect:
new WiremockRequestStubStrategy(groovyDsl).buildClientRequestContent() == new JsonSlurper().parseText('''
def "should generate request when two elements are provided "() {
given:
GroovyDsl groovyDsl = GroovyDsl.make {
request {
method("GET")
url("/sth")
}
}
expect:
new WiremockRequestStubStrategy(groovyDsl).buildClientRequestContent() == new JsonSlurper().parseText('''
{
"method":"GET",
"url":"/sth"
}
''')
}
}
def "should generate request with urlPattern for client side"() {
given:
GroovyDsl groovyDsl = GroovyDsl.make {
request {
urlPattern $(
client('/^[0-9]{2}$'),
server('/12')
)
}
}
expect:
new WiremockRequestStubStrategy(groovyDsl).buildClientRequestContent() == new JsonSlurper().parseText('''
def "should generate request with urlPattern for client side"() {
given:
GroovyDsl groovyDsl = GroovyDsl.make {
request {
urlPattern $(
client('/^[0-9]{2}$'),
server('/12')
)
}
}
expect:
new WiremockRequestStubStrategy(groovyDsl).buildClientRequestContent() == new JsonSlurper().parseText('''
{
"urlPattern":"/^[0-9]{2}$"
}
''')
}
}
def "should generate stub with urlPattern for server side"() {
given:
GroovyDsl groovyDsl = GroovyDsl.make {
request {
urlPattern $(
client('/[0-9]{2}'),
server('/12')
)
}
}
expect:
new WiremockRequestStubStrategy(groovyDsl).buildServerRequestContent() == new JsonSlurper().parseText('''
def "should generate stub with urlPattern for server side"() {
given:
GroovyDsl groovyDsl = GroovyDsl.make {
request {
urlPattern $(
client('/[0-9]{2}'),
server('/12')
)
}
}
expect:
new WiremockRequestStubStrategy(groovyDsl).buildServerRequestContent() == new JsonSlurper().parseText('''
{
"urlPattern":"/12"
}
''')
}
}
def "should generate stub with urlPath for client side"() {
given:
GroovyDsl groovyDsl = GroovyDsl.make {
request {
urlPath ('/12')
}
}
expect:
new WiremockRequestStubStrategy(groovyDsl).buildClientRequestContent() == new JsonSlurper().parseText('''
def "should generate stub with urlPath for client side"() {
given:
GroovyDsl groovyDsl = GroovyDsl.make {
request {
urlPath('/12')
}
}
expect:
new WiremockRequestStubStrategy(groovyDsl).buildClientRequestContent() == new JsonSlurper().parseText('''
{
"urlPath":"/12"
}
''')
}
}
def "should generate stub with urlPath for server side"() {
given:
GroovyDsl groovyDsl = GroovyDsl.make {
request {
urlPath ('/12')
}
}
expect:
new WiremockRequestStubStrategy(groovyDsl).buildClientRequestContent() == new JsonSlurper().parseText('''
def "should generate stub with urlPath for server side"() {
given:
GroovyDsl groovyDsl = GroovyDsl.make {
request {
urlPath('/12')
}
}
expect:
new WiremockRequestStubStrategy(groovyDsl).buildClientRequestContent() == new JsonSlurper().parseText('''
{
"urlPath":"/12"
}
''')
}
}
def "should generate stub with some headers section for client side"() {
given:
GroovyDsl groovyDsl = GroovyDsl.make {
request {
headers {
header('Content-Type').equalTo('text/xml')
header('Accept').matches $(
client('text/.*'),
server('text/plain')
)
header('etag').doesNotMatch $(
client('abcd.*'),
server('abcdef')
)
header('X-Custom-Header').contains $(
client('2134'),
server('121345')
)
}
}
}
expect:
new WiremockRequestStubStrategy(groovyDsl).buildClientRequestContent() == new JsonSlurper().parseText('''
def "should generate stub with some headers section for client side"() {
given:
GroovyDsl groovyDsl = GroovyDsl.make {
request {
headers {
header('Content-Type').equalTo('text/xml')
header('Accept').matches $(
client('text/.*'),
server('text/plain')
)
header('etag').doesNotMatch $(
client('abcd.*'),
server('abcdef')
)
header('X-Custom-Header').contains $(
client('2134'),
server('121345')
)
}
}
}
expect:
new WiremockRequestStubStrategy(groovyDsl).buildClientRequestContent() == new JsonSlurper().parseText('''
{
"headers": {
"Content-Type": {
@@ -345,31 +345,31 @@ class WiremockGroovyDslSpec extends Specification {
}
}
''')
}
}
def "should generate stub with some headers section for server side"() {
given:
GroovyDsl groovyDsl = GroovyDsl.make {
request {
headers {
header('Content-Type').equalTo('text/xml')
header('Accept').matches $(
client('text/.*'),
server('text/plain')
)
header('etag').doesNotMatch $(
client('abcd.*'),
server('abcdef')
)
header('X-Custom-Header').contains $(
client('2134'),
server('121345')
)
}
}
}
expect:
new WiremockRequestStubStrategy(groovyDsl).buildServerRequestContent() == new JsonSlurper().parseText('''
def "should generate stub with some headers section for server side"() {
given:
GroovyDsl groovyDsl = GroovyDsl.make {
request {
headers {
header('Content-Type').equalTo('text/xml')
header('Accept').matches $(
client('text/.*'),
server('text/plain')
)
header('etag').doesNotMatch $(
client('abcd.*'),
server('abcdef')
)
header('X-Custom-Header').contains $(
client('2134'),
server('121345')
)
}
}
}
expect:
new WiremockRequestStubStrategy(groovyDsl).buildServerRequestContent() == new JsonSlurper().parseText('''
{
"headers": {
"Content-Type": {
@@ -387,11 +387,11 @@ class WiremockGroovyDslSpec extends Specification {
}
}
''')
}
}
@Ignore("Not implemented yet")
def "should generate stub with request body matching for server side"() {}
@Ignore("Not implemented yet")
def "should generate stub with request body matching for server side"() {}
@Ignore("Not implemented yet")
def "should generate stub with request query parameter matching for server side"() {}
@Ignore("Not implemented yet")
def "should generate stub with request query parameter matching for server side"() {}
}

View File

@@ -11,8 +11,10 @@ import org.gradle.api.tasks.TaskAction
class GenerateServerTestsTask extends DefaultTask {
@InputDirectory File groovyDslDir
@OutputDirectory File generatedTestSourcesDir
@InputDirectory
File groovyDslDir
@OutputDirectory
File generatedTestSourcesDir
//TODO: How to deal with @Input*, @Output* and that domain object?
AccurestConfigProperties configProperties

View File

@@ -9,8 +9,10 @@ import org.gradle.api.tasks.TaskAction
//TODO: Implement as an incremental task: https://gradle.org/docs/current/userguide/custom_tasks.html#incremental_tasks ?
class GenerateWiremockClientStubsFromDslTask extends DefaultTask {
@InputDirectory File groovyDslDir
@InputDirectory File generatedWiremockClientStubsDir
@InputDirectory
File groovyDslDir
@InputDirectory
File generatedWiremockClientStubsDir
@TaskAction
void generate() {