Skip to content

Commit

Permalink
refactor: more some more Groovy code to Kotlin
Browse files Browse the repository at this point in the history
  • Loading branch information
Ronald Holshausen committed Jun 17, 2020
1 parent 68b0d6c commit d7a9b93
Show file tree
Hide file tree
Showing 8 changed files with 103 additions and 42 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -3,9 +3,7 @@ package au.com.dius.pact.consumer.groovy
/**
* Base class for builders
*/
class BaseBuilder extends Matchers {
public static final List COMPACT_MIME_TYPES = ['application/x-thrift+json']

class GroovyBuilder extends BaseBuilder {
def call(Closure closure) {
build(closure)
}
Expand All @@ -15,5 +13,4 @@ class BaseBuilder extends Matchers {
closure.resolveStrategy = Closure.DELEGATE_FIRST
closure.call()
}

}
Original file line number Diff line number Diff line change
Expand Up @@ -18,7 +18,7 @@ import static au.com.dius.pact.core.model.PathExpressionsKt.PATH_SPECIAL_CHARS
/**
* DSL Builder for constructing JSON bodies
*/
class PactBodyBuilder extends BaseBuilder {
class PactBodyBuilder extends GroovyBuilder {

public static final String PATH_SEP = '.'
public static final String START_LIST = '['
Expand All @@ -45,11 +45,7 @@ class PactBodyBuilder extends BaseBuilder {
}

private boolean shouldPrettyPrint() {
prettyPrintBody == null && !compactMimeType() || prettyPrintBody
}

private boolean compactMimeType() {
mimetype in COMPACT_MIME_TYPES
prettyPrintBody == null && (mimetype != null && !isCompactMimeType(mimetype) || mimetype == null) || prettyPrintBody
}

def methodMissing(String name, args) {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -23,7 +23,6 @@ import au.com.dius.pact.core.model.matchingrules.MatchingRules
import au.com.dius.pact.core.model.matchingrules.MatchingRulesImpl
import au.com.dius.pact.core.model.matchingrules.RegexMatcher
import au.com.dius.pact.core.support.expressions.DataType
import groovy.json.JsonBuilder
import groovy.transform.CompileStatic
import org.apache.http.entity.ContentType
import org.apache.http.entity.mime.HttpMultipartMode
Expand All @@ -37,13 +36,7 @@ import static au.com.dius.pact.consumer.ConsumerPactRunnerKt.runConsumerTest
* Builder DSL for Pact tests
*/
@SuppressWarnings('PropertyName')
class PactBuilder extends BaseBuilder {

private static final String CONTENT_TYPE = 'Content-Type'
private static final String JSON = 'application/json'
private static final String BODY = 'body'
private static final String LOCALHOST = 'localhost'
public static final String HEADER = 'header'
class PactBuilder extends GroovyBuilder {

Consumer consumer
Provider provider
Expand Down Expand Up @@ -232,24 +225,6 @@ class PactBuilder extends BaseBuilder {
this
}

private setupBody(Map requestData, Map request) {
if (requestData.containsKey(BODY)) {
def body = requestData.body
if (body instanceof PactBodyBuilder) {
request.body = body.body
request.matchers.addCategory(body.matchers)
request.generators.addGenerators(body.generators)
} else if (body != null && !(body instanceof String)) {

if (requestData.prettyPrint == null && !compactMimeTypes(requestData) || requestData.prettyPrint) {
request.body = new JsonBuilder(body).toPrettyString()
} else {
request.body = new JsonBuilder(body).toString()
}
}
}
}

/**
* Defines the response attributes (body, headers, etc.) that are returned for the request
* @param responseData Map of attributes
Expand All @@ -264,10 +239,6 @@ class PactBuilder extends BaseBuilder {
this
}

private static boolean compactMimeTypes(Map reqResData) {
reqResData.headers && reqResData.headers[CONTENT_TYPE] in COMPACT_MIME_TYPES
}

/**
* Allows the body to be defined using a Groovy builder pattern
* @param options The following options are available:
Expand Down
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
package au.com.dius.pact.consumer.groovy.messaging

import au.com.dius.pact.consumer.PactConsumerConfig
import au.com.dius.pact.consumer.groovy.BaseBuilder
import au.com.dius.pact.consumer.groovy.GroovyBuilder
import au.com.dius.pact.consumer.groovy.Matcher
import au.com.dius.pact.consumer.groovy.PactBodyBuilder
import au.com.dius.pact.core.model.Consumer
Expand All @@ -17,7 +17,7 @@ import au.com.dius.pact.core.model.messaging.MessagePact
/**
* Pact builder for consumer tests for messaging
*/
class PactMessageBuilder extends BaseBuilder {
class PactMessageBuilder extends GroovyBuilder {
Consumer consumer
Provider provider
List<ProviderState> providerStates = []
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,51 @@
package au.com.dius.pact.consumer.groovy

import au.com.dius.pact.core.model.generators.Generators
import au.com.dius.pact.core.model.matchingrules.Category
import au.com.dius.pact.core.model.matchingrules.MatchingRules
import au.com.dius.pact.core.support.property
import groovy.json.JsonBuilder
import mu.KLogging

open class BaseBuilder : Matchers() {
protected fun setupBody(requestData: Map<String, Any>, request: MutableMap<String, Any>) {
if (requestData.containsKey(BODY)) {
val body = requestData[BODY]
if (body != null && body::class.qualifiedName == "au.com.dius.pact.consumer.groovy.PactBodyBuilder") {
request[BODY] = body::class.property(BODY)?.get(body) as Any
val matchers = request["matchers"] as MatchingRules
matchers.addCategory(body::class.property("matchers")?.get(body) as Category)
val generators = request["generators"] as Generators
generators.addGenerators(body::class.property("generators")?.get(body) as Generators)
} else if (body != null && body !is String) {
val prettyPrint = requestData["prettyPrint"] as Boolean?
if (prettyPrint == null && !compactMimeTypes(requestData) || prettyPrint == true) {
request[BODY] = JsonBuilder(body).toPrettyString()
} else {
request[BODY] = JsonBuilder(body).toString()
}
}
}
}

companion object : KLogging() {
const val CONTENT_TYPE = "Content-Type"
const val JSON = "application/json"
const val BODY = "body"
const val LOCALHOST = "localhost"
const val HEADER = "header"

val COMPACT_MIME_TYPES = listOf("application/x-thrift+json")

@JvmStatic
fun compactMimeTypes(reqResData: Map<String, Any>): Boolean {
return if (reqResData.containsKey("headers")) {
val headers = reqResData["headers"] as Map<String, String>
headers.entries.find { it.key == CONTENT_TYPE }?.value in COMPACT_MIME_TYPES
} else false
}

@JvmStatic
fun isCompactMimeType(mimetype: String) = mimetype in COMPACT_MIME_TYPES
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,40 @@
package au.com.dius.pact.consumer.groovy

import au.com.dius.pact.consumer.MockServer
import au.com.dius.pact.consumer.PactVerificationResult
import org.apache.http.client.methods.RequestBuilder
import org.apache.http.impl.client.CloseableHttpClient
import org.apache.http.impl.client.HttpClients
import spock.lang.Ignore
import spock.lang.Specification

@Ignore
class BinaryFileSpec extends Specification {

def 'handles bodies from form posts'() {
given:
def pdf = BinaryFileSpec.getResourceAsStream('/sample.pdf').bytes
def service = new PactBuilder()
service {
serviceConsumer 'Consumer'
hasPactWith 'File Service'
uponReceiving('a multipart file POST')
withAttributes(path: '/get-doco')
willRespondWith(status: 200, body: pdf, headers: ['Content-Type': 'application/pdf'])
}

when:
def result = service.runTest { MockServer mockServer, context ->
CloseableHttpClient httpclient = HttpClients.createDefault()
def response = httpclient.withCloseable {
def request = RequestBuilder.get(mockServer.url + '/get-doco').build()
httpclient.execute(request)
}
assert response.statusLine.statusCode == 200
assert response.entity.contentLength == pdf.size()
}

then:
result instanceof PactVerificationResult.Ok
}
}
Binary file added consumer/groovy/src/test/resources/sample.pdf
Binary file not shown.
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,7 @@ import au.com.dius.pact.provider.junitsupport.Provider
import au.com.dius.pact.provider.junitsupport.loader.PactFolder
import com.github.tomakehurst.wiremock.WireMockServer
import groovy.util.logging.Slf4j
import org.junit.jupiter.api.AfterAll
import org.junit.jupiter.api.BeforeAll
import org.junit.jupiter.api.BeforeEach
import org.junit.jupiter.api.TestTemplate
Expand Down Expand Up @@ -35,6 +36,11 @@ class BinaryFileProviderTest {
System.setProperty('pact.content_type.override.application.pdf', 'text')
}

@AfterAll
static void afterAll() {
System.clearProperty('pact.content_type.override.application.pdf')
}

@BeforeEach
void before(PactVerificationContext context, @WiremockResolver.Wiremock WireMockServer server,
@WiremockUriResolver.WiremockUri String uri) throws MalformedURLException {
Expand Down

0 comments on commit d7a9b93

Please sign in to comment.