Skip to content

Commit d6cb3b4

Browse files
author
Ronald Holshausen
committedFeb 8, 2020
feat: Allow just the changed pact specified in the webhook to be run (JUnit 4) #998
1 parent d21e478 commit d6cb3b4

File tree

9 files changed

+327
-248
lines changed

9 files changed

+327
-248
lines changed
 

‎core/model/src/main/kotlin/au/com/dius/pact/core/model/PactSource.kt

+1-1
Original file line numberDiff line numberDiff line change
@@ -28,7 +28,7 @@ data class PactBrokerSource<I> @JvmOverloads constructor(
2828
val host: String,
2929
val port: String?,
3030
val scheme: String = "http",
31-
val pacts: MutableMap<Consumer, List<Pact<I>>> = mutableMapOf()
31+
val pacts: MutableMap<Consumer, MutableList<Pact<I>>> = mutableMapOf()
3232
) : PactSource()
3333
where I : Interaction
3434

‎provider/pact-jvm-provider-junit/src/main/kotlin/au/com/dius/pact/provider/junit/PactRunner.kt

+36-3
Original file line numberDiff line numberDiff line change
@@ -3,8 +3,11 @@ package au.com.dius.pact.provider.junit
33
import au.com.dius.pact.core.model.Interaction
44
import au.com.dius.pact.core.model.Pact
55
import au.com.dius.pact.core.support.expressions.SystemPropertyResolver
6+
import au.com.dius.pact.core.support.isNotEmpty
7+
import au.com.dius.pact.provider.ProviderVerifier
68
import au.com.dius.pact.provider.junit.JUnitProviderTestSupport.filterPactsByAnnotations
79
import au.com.dius.pact.provider.junit.loader.NoPactsFoundException
10+
import au.com.dius.pact.provider.junit.loader.OverrideablePactLoader
811
import au.com.dius.pact.provider.junit.loader.PactBroker
912
import au.com.dius.pact.provider.junit.loader.PactFolder
1013
import au.com.dius.pact.provider.junit.loader.PactLoader
@@ -146,9 +149,9 @@ open class PactRunner<I>(clazz: Class<*>) : ParentRunner<InteractionRunner<I>>(c
146149
}
147150

148151
try {
149-
if (pactSource != null) {
152+
val loader = if (pactSource != null) {
150153
val pactLoaderClass = pactSource.value
151-
return try {
154+
try {
152155
// Checks if there is a constructor with one argument of type Class.
153156
val constructorWithClass = pactLoaderClass.java.getDeclaredConstructor(Class::class.java)
154157
if (constructorWithClass != null) {
@@ -163,15 +166,45 @@ open class PactRunner<I>(clazz: Class<*>) : ParentRunner<InteractionRunner<I>>(c
163166
}
164167
} else {
165168
val annotation = pactLoaders.first()
166-
return annotation.annotationClass.findAnnotation<PactSource>()!!.value.java
169+
annotation.annotationClass.findAnnotation<PactSource>()!!.value.java
167170
.getConstructor(annotation.annotationClass.java).newInstance(annotation)
168171
}
172+
173+
checkForOverriddenPactUrl(clazz, loader)
174+
175+
return loader
169176
} catch (e: ReflectiveOperationException) {
170177
logger.error(e) { "Error while creating pact source" }
171178
throw InitializationError(e)
172179
}
173180
}
174181

182+
private fun checkForOverriddenPactUrl(clazz: TestClass, loader: PactLoader?) {
183+
val overridePactUrl: AllowOverridePactUrl? = clazz.getAnnotation(AllowOverridePactUrl::class.java)
184+
var pactUrl = System.getProperty(ProviderVerifier.PACT_FILTER_PACTURL)
185+
if (pactUrl.isNullOrEmpty()) {
186+
pactUrl = System.getenv(ProviderVerifier.PACT_FILTER_PACTURL)
187+
}
188+
189+
if (loader is OverrideablePactLoader && overridePactUrl != null && pactUrl.isNotEmpty()) {
190+
val consumer = clazz.getAnnotation(Consumer::class.java)
191+
var consumerProperty = System.getProperty(ProviderVerifier.PACT_FILTER_CONSUMERS)
192+
if (consumerProperty.isNullOrEmpty()) {
193+
consumerProperty = System.getenv(ProviderVerifier.PACT_FILTER_CONSUMERS)
194+
}
195+
when {
196+
consumerProperty.isNotEmpty() -> loader.overridePactUrl(pactUrl, consumerProperty)
197+
consumer != null -> loader.overridePactUrl(pactUrl, consumer.value)
198+
else -> {
199+
logger.warn {
200+
"The property ${ProviderVerifier.PACT_FILTER_PACTURL} has been set, but no consumer filter" +
201+
" or @Consumer annotation has been provided, Ignoring"
202+
}
203+
}
204+
}
205+
}
206+
}
207+
175208
companion object : KLogging() {
176209
const val WARNING_ON_IGNORED_IOERROR = """
177210
---------------------------------------------------------------------------

‎provider/pact-jvm-provider-junit/src/test/groovy/au/com/dius/pact/provider/junit/loader/PactBrokerLoaderSpec.groovy

+19-2
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,7 @@
11
package au.com.dius.pact.provider.junit.loader
22

33
import au.com.dius.pact.core.model.Pact
4+
import au.com.dius.pact.core.model.UrlSource
45
import au.com.dius.pact.core.pactbroker.IHalClient
56
import au.com.dius.pact.core.pactbroker.InvalidHalResponse
67
import au.com.dius.pact.core.pactbroker.PactBrokerClient
@@ -36,7 +37,7 @@ class PactBrokerLoaderSpec extends Specification {
3637
mockPact = Mock(Pact)
3738

3839
pactBrokerLoader = { boolean failIfNoPactsFound = true ->
39-
def loader = new PactBrokerLoader(host, port, protocol, tags, consumers) {
40+
def loader = new PactBrokerLoader(host, port, protocol, tags, consumers, failIfNoPactsFound, null, null, null) {
4041
@Override
4142
PactBrokerClient newPactBrokerClient(URI url, ValueResolver resolver) {
4243
brokerClient
@@ -47,7 +48,6 @@ class PactBrokerLoaderSpec extends Specification {
4748
mockPact
4849
}
4950
}
50-
loader.failIfNoPactsFound = failIfNoPactsFound
5151
loader
5252
}
5353
}
@@ -356,6 +356,23 @@ class PactBrokerLoaderSpec extends Specification {
356356
result.size() == 3
357357
}
358358

359+
def 'use the overridden pact URL'() {
360+
given:
361+
consumers = ['a', 'b', 'c']
362+
tags = ['demo']
363+
PactBrokerLoader loader = Spy(pactBrokerLoader())
364+
loader.overridePactUrl('http://overridden.com', 'overridden')
365+
def consumer = new ConsumerInfo('overridden', null, true, [], null, new UrlSource('http://overridden.com'))
366+
367+
when:
368+
def result = loader.load('test')
369+
370+
then:
371+
1 * loader.loadPact(consumer, _) >> Stub(Pact)
372+
0 * brokerClient._
373+
result.size() == 1
374+
}
375+
359376
def 'does not fail if the port is not provided'() {
360377
when:
361378
port = null

‎provider/pact-jvm-provider/src/main/java/au/com/dius/pact/provider/junit/loader/PactBrokerLoader.java

-226
This file was deleted.

‎provider/pact-jvm-provider/src/main/kotlin/au/com/dius/pact/provider/ProviderVerifier.kt

+27-15
Original file line numberDiff line numberDiff line change
@@ -377,8 +377,8 @@ open class ProviderVerifier @JvmOverloads constructor (
377377
val s = " generates a message which"
378378
result = result.merge(displayBodyResult(failures, comparison.bodyMismatches,
379379
interactionMessage + s, message.interactionId.orEmpty()))
380-
.merge(displayMetadataResult(messageMetadata ?: emptyMap(), failures, comparison.metadataMismatches,
381-
interactionMessage + s, message.interactionId.orEmpty()))
380+
.merge(displayMetadataResult(messageMetadata ?: emptyMap(), failures,
381+
comparison.metadataMismatches, interactionMessage + s, message.interactionId.orEmpty()))
382382
}
383383
return result
384384
}
@@ -431,8 +431,8 @@ open class ProviderVerifier @JvmOverloads constructor (
431431
var interactionMessage = "Verifying a pact between ${consumer.name} and ${provider.name}" +
432432
" - ${interaction.description} "
433433

434-
val stateChangeResult = stateChangeHandler.executeStateChange(this, provider, consumer, interaction, interactionMessage,
435-
failures, providerClient)
434+
val stateChangeResult = stateChangeHandler.executeStateChange(this, provider, consumer,
435+
interaction, interactionMessage, failures, providerClient)
436436
if (stateChangeResult.stateChangeResult is Ok) {
437437
interactionMessage = stateChangeResult.message
438438
reportInteractionDescription(interaction)
@@ -442,7 +442,8 @@ open class ProviderVerifier @JvmOverloads constructor (
442442
"interaction" to interaction
443443
)
444444

445-
val result = if (ProviderUtils.verificationType(provider, consumer) == PactVerification.REQUEST_RESPONSE) {
445+
val result = if (ProviderUtils.verificationType(provider, consumer) ==
446+
PactVerification.REQUEST_RESPONSE) {
446447
logger.debug { "Verifying via request/response" }
447448
verifyResponseFromProvider(provider, interaction as RequestResponseInteraction, interactionMessage, failures,
448449
providerClient, context)
@@ -481,9 +482,12 @@ open class ProviderVerifier @JvmOverloads constructor (
481482
reporters.forEach { it.returnsAResponseWhich() }
482483

483484
val s = " returns a response which"
484-
return displayStatusResult(failures, expectedResponse.status, comparison.statusMismatch, interactionMessage + s, interactionId)
485-
.merge(displayHeadersResult(failures, expectedResponse.headers, comparison.headerMismatches, interactionMessage + s, interactionId))
486-
.merge(displayBodyResult(failures, comparison.bodyMismatches, interactionMessage + s, interactionId))
485+
return displayStatusResult(failures, expectedResponse.status, comparison.statusMismatch,
486+
interactionMessage + s, interactionId)
487+
.merge(displayHeadersResult(failures, expectedResponse.headers, comparison.headerMismatches,
488+
interactionMessage + s, interactionId))
489+
.merge(displayBodyResult(failures, comparison.bodyMismatches,
490+
interactionMessage + s, interactionId))
487491
}
488492

489493
fun displayStatusResult(
@@ -524,7 +528,8 @@ open class ProviderVerifier @JvmOverloads constructor (
524528
reporters.forEach { it.headerComparisonFailed(key, expectedHeaderValue!!, headerComparison) }
525529
failures["$comparisonDescription includes headers \"$key\" with value \"$expectedHeaderValue\""] =
526530
headerComparison.joinToString(", ") { it.description() }
527-
result = result.merge(TestResult.Failed(headerComparison.map { it.toMap() }, "Headers had differences"))
531+
result = result.merge(TestResult.Failed(headerComparison.map { it.toMap() },
532+
"Headers had differences"))
528533
}
529534
}
530535
result
@@ -598,7 +603,8 @@ open class ProviderVerifier @JvmOverloads constructor (
598603
consumer: IConsumerInfo,
599604
client: PactBrokerClient? = null
600605
) {
601-
val pact = FilteredPact(loadPactFileForConsumer(consumer), Predicate { filterInteractions(it) })
606+
val pact = FilteredPact(loadPactFileForConsumer(consumer),
607+
Predicate { filterInteractions(it) })
602608
reportVerificationForConsumer(consumer, provider, pact.source)
603609
if (pact.interactions.isEmpty()) {
604610
reporters.forEach { it.warnPactFileHasNoInteractions(pact as Pact<Interaction>) }
@@ -607,10 +613,15 @@ open class ProviderVerifier @JvmOverloads constructor (
607613
verifyInteraction(provider, consumer, failures, it)
608614
}.reduce { acc, result -> acc.merge(result) }
609615
when {
610-
pact.isFiltered() -> logger.warn { "Skipping publishing of verification results as the interactions have been filtered" }
611-
publishingResultsDisabled() -> logger.warn { "Skipping publishing of verification results as it has been disabled " +
612-
"($PACT_VERIFIER_PUBLISH_RESULTS is not 'true')" }
613-
else -> verificationReporter.reportResults(pact, result, providerVersion.get() ?: "0.0.0", client, providerTag?.get())
616+
pact.isFiltered() -> logger.warn {
617+
"Skipping publishing of verification results as the interactions have been filtered"
618+
}
619+
publishingResultsDisabled() -> logger.warn {
620+
"Skipping publishing of verification results as it has been disabled " +
621+
"($PACT_VERIFIER_PUBLISH_RESULTS is not 'true')"
622+
}
623+
else -> verificationReporter.reportResults(pact, result, providerVersion.get() ?: "0.0.0", client,
624+
providerTag?.get())
614625
}
615626
}
616627
}
@@ -683,7 +694,8 @@ open class ProviderVerifier @JvmOverloads constructor (
683694
}
684695

685696
fun filterInteractions(interaction: Interaction): Boolean {
686-
return if (projectHasProperty.apply(PACT_FILTER_DESCRIPTION) && projectHasProperty.apply(PACT_FILTER_PROVIDERSTATE)) {
697+
return if (projectHasProperty.apply(PACT_FILTER_DESCRIPTION) &&
698+
projectHasProperty.apply(PACT_FILTER_PROVIDERSTATE)) {
687699
matchDescription(interaction) && matchState(interaction)
688700
} else if (projectHasProperty.apply(PACT_FILTER_DESCRIPTION)) {
689701
matchDescription(interaction)
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,12 @@
1+
package au.com.dius.pact.provider.junit
2+
3+
import java.lang.annotation.Inherited
4+
5+
/**
6+
* This will mark the test to use any pact URL from the Java system properties `pact.filter.pacturl` and either the
7+
* `pact.filter.consumers` system property or the @Consumer annotation.
8+
*/
9+
@Retention(AnnotationRetention.RUNTIME)
10+
@Target(AnnotationTarget.CLASS, AnnotationTarget.FILE)
11+
@Inherited
12+
annotation class AllowOverridePactUrl

‎provider/pact-jvm-provider/src/main/kotlin/au/com/dius/pact/provider/junit/JUnitProviderTestSupport.kt

+1-1
Original file line numberDiff line numberDiff line change
@@ -11,7 +11,7 @@ import java.util.function.Predicate
1111
object JUnitProviderTestSupport {
1212
fun <I> filterPactsByAnnotations(pacts: List<Pact<I>>, testClass: Class<*>): List<Pact<I>> where I : Interaction {
1313
val pactFilterValues = testClass.getAnnotation(PactFilter::class.java)?.value
14-
return if (pactFilterValues != null && pactFilterValues.any { !it.isEmpty() }) {
14+
return if (pactFilterValues != null && pactFilterValues.any { it.isNotEmpty() }) {
1515
pacts.map { pact ->
1616
FilteredPact(pact, Predicate { interaction ->
1717
pactFilterValues.any { value -> interaction.providerStates.any { it.matches(value) } }
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,8 @@
1+
package au.com.dius.pact.provider.junit.loader
2+
3+
/**
4+
* Allows the Pact URL to be overridden (for example, when verifying a Pact from a Webhook call)
5+
*/
6+
interface OverrideablePactLoader : PactLoader {
7+
fun overridePactUrl(pactUrl: String, consumer: String)
8+
}
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,223 @@
1+
package au.com.dius.pact.provider.junit.loader
2+
3+
import au.com.dius.pact.core.model.DefaultPactReader
4+
import au.com.dius.pact.core.model.Interaction
5+
import au.com.dius.pact.core.model.Pact
6+
import au.com.dius.pact.core.model.PactBrokerSource
7+
import au.com.dius.pact.core.model.PactReader
8+
import au.com.dius.pact.core.model.UrlSource
9+
import au.com.dius.pact.core.pactbroker.PactBrokerClient
10+
import au.com.dius.pact.core.support.expressions.ExpressionParser.parseExpression
11+
import au.com.dius.pact.core.support.expressions.ExpressionParser.parseListExpression
12+
import au.com.dius.pact.core.support.expressions.SystemPropertyResolver
13+
import au.com.dius.pact.core.support.expressions.ValueResolver
14+
import au.com.dius.pact.core.support.isNotEmpty
15+
import au.com.dius.pact.provider.ConsumerInfo
16+
import mu.KLogging
17+
import org.apache.http.client.utils.URIBuilder
18+
import java.io.IOException
19+
import java.net.URI
20+
import java.net.URISyntaxException
21+
import kotlin.reflect.KClass
22+
23+
/**
24+
* Out-of-the-box implementation of {@link PactLoader} that downloads pacts from Pact broker
25+
*/
26+
open class PactBrokerLoader(
27+
val pactBrokerHost: String,
28+
val pactBrokerPort: String?,
29+
val pactBrokerScheme: String,
30+
val pactBrokerTags: List<String>? = listOf("latest"),
31+
val pactBrokerConsumers: List<String> = emptyList(),
32+
var failIfNoPactsFound: Boolean = true,
33+
var authentication: PactBrokerAuth?,
34+
var valueResolverClass: KClass<out ValueResolver>?,
35+
valueResolver: ValueResolver? = null
36+
) : OverrideablePactLoader {
37+
38+
private var _pactSource: PactBrokerSource<Interaction> = PactBrokerSource(
39+
pactBrokerHost, pactBrokerPort, pactBrokerScheme)
40+
private var resolver: ValueResolver? = valueResolver
41+
private var overriddenPactUrl: String? = null
42+
private var overriddenConsumer: String? = null
43+
44+
var pactReader: PactReader = DefaultPactReader
45+
46+
constructor(pactBroker: PactBroker) : this(
47+
pactBroker.host,
48+
pactBroker.port,
49+
pactBroker.scheme,
50+
pactBroker.tags.toList(),
51+
pactBroker.consumers.toList(),
52+
true,
53+
pactBroker.authentication,
54+
pactBroker.valueResolver
55+
)
56+
57+
override fun overridePactUrl(pactUrl: String, consumer: String) {
58+
overriddenPactUrl = pactUrl
59+
overriddenConsumer = consumer
60+
}
61+
62+
override fun load(providerName: String): List<Pact<Interaction>> {
63+
val resolver = setupValueResolver()
64+
val pacts = when {
65+
overriddenPactUrl.isNotEmpty() -> {
66+
val pactBrokerClient = newPactBrokerClient(brokerUrl(resolver).build(), resolver)
67+
val pactSource = UrlSource<Interaction>(overriddenPactUrl!!)
68+
pactSource.encodePath = false
69+
listOf(loadPact(ConsumerInfo(name = overriddenConsumer!!, pactSource = pactSource),
70+
pactBrokerClient.options))
71+
}
72+
pactBrokerTags.isNullOrEmpty() -> loadPactsForProvider(providerName, null, resolver)
73+
else -> {
74+
pactBrokerTags.flatMap { parseListExpression(it, resolver) }.flatMap {
75+
try {
76+
loadPactsForProvider(providerName, it, resolver)
77+
} catch (e: NoPactsFoundException) {
78+
// Ignoring exception at this point, it will be handled at a higher level
79+
emptyList<Pact<Interaction>>()
80+
}
81+
}
82+
}
83+
}
84+
return pacts
85+
}
86+
87+
private fun setupValueResolver(): ValueResolver {
88+
var valueResolver: ValueResolver = SystemPropertyResolver()
89+
if (resolver != null) {
90+
valueResolver = resolver!!
91+
} else if (valueResolverClass != null) {
92+
try {
93+
valueResolver = valueResolverClass!!.java.newInstance()
94+
} catch (e: InstantiationException) {
95+
logger.warn(e) { "Failed to instantiate the value resolver, using the default" }
96+
} catch (e: IllegalAccessException) {
97+
logger.warn(e) { "Failed to instantiate the value resolver, using the default" }
98+
}
99+
}
100+
return valueResolver
101+
}
102+
103+
override fun getPactSource() = _pactSource
104+
105+
override fun setValueResolver(valueResolver: ValueResolver) {
106+
this.resolver = valueResolver
107+
}
108+
109+
@Throws(IOException::class, IllegalArgumentException::class)
110+
private fun loadPactsForProvider(
111+
providerName: String,
112+
tag: String?,
113+
resolver: ValueResolver
114+
): List<Pact<Interaction>> {
115+
logger.debug { "Loading pacts from pact broker for provider $providerName and tag $tag" }
116+
val uriBuilder = brokerUrl(resolver)
117+
try {
118+
var consumers: List<ConsumerInfo>
119+
val pactBrokerClient = newPactBrokerClient(uriBuilder.build(), resolver)
120+
consumers = if (tag.isNullOrEmpty() || tag == "latest") {
121+
pactBrokerClient.fetchConsumers(providerName).map { ConsumerInfo.from(it) }
122+
} else {
123+
pactBrokerClient.fetchConsumersWithTag(providerName, tag).map { ConsumerInfo.from(it) }
124+
}
125+
126+
if (failIfNoPactsFound && consumers.isEmpty()) {
127+
throw NoPactsFoundException("No consumer pacts were found for provider '" + providerName + "' and tag '" +
128+
tag + "'. (URL " + getUrlForProvider(providerName, tag.orEmpty(), pactBrokerClient) + ")")
129+
}
130+
131+
if (pactBrokerConsumers.isNotEmpty()) {
132+
val consumerInclusions = pactBrokerConsumers.flatMap { parseListExpression(it, resolver) }
133+
consumers = consumers.filter { consumerInclusions.isEmpty() || consumerInclusions.contains(it.name) }
134+
}
135+
136+
return consumers.map { loadPact(it, pactBrokerClient.options) }
137+
} catch (e: URISyntaxException) {
138+
throw IOException("Was not able load pacts from broker as the broker URL was invalid", e)
139+
}
140+
}
141+
142+
private fun brokerUrl(resolver: ValueResolver): URIBuilder {
143+
val scheme = parseExpression(pactBrokerScheme, resolver)
144+
val host = parseExpression(pactBrokerHost, resolver)
145+
val port = parseExpression(pactBrokerPort, resolver)
146+
147+
if (host.isNullOrEmpty()) {
148+
throw IllegalArgumentException(String.format("Invalid pact broker host specified ('%s'). " +
149+
"Please provide a valid host or specify the system property 'pactbroker.host'.", pactBrokerHost))
150+
}
151+
152+
if (port.isNotEmpty() && !port!!.matches(Regex("^[0-9]+"))) {
153+
throw IllegalArgumentException(String.format("Invalid pact broker port specified ('%s'). " +
154+
"Please provide a valid port number or specify the system property 'pactbroker.port'.", pactBrokerPort))
155+
}
156+
157+
val uriBuilder = URIBuilder().setScheme(scheme).setHost(host)
158+
if (port.isNotEmpty()) {
159+
uriBuilder.port = Integer.parseInt(port)
160+
}
161+
return uriBuilder
162+
}
163+
164+
private fun getUrlForProvider(providerName: String, tag: String, pactBrokerClient: PactBrokerClient): String {
165+
return try {
166+
pactBrokerClient.getUrlForProvider(providerName, tag)!!
167+
} catch (e: Exception) {
168+
logger.debug(e) { "Failed to get provider URL from the pact broker" }
169+
"Unknown"
170+
}
171+
}
172+
173+
open fun loadPact(consumer: ConsumerInfo, options: Map<String, Any>): Pact<Interaction> {
174+
val pact = pactReader.loadPact(consumer.pactSource!!, options) as Pact<Interaction>
175+
val pacts = this.pactSource.pacts
176+
val pactConsumer = consumer.toPactConsumer()
177+
val pactList = pacts.getOrDefault(pactConsumer, mutableListOf())
178+
pactList.add(pact)
179+
pacts[pactConsumer] = pactList
180+
return pact
181+
}
182+
183+
open fun newPactBrokerClient(url: URI, resolver: ValueResolver): PactBrokerClient {
184+
if (authentication == null || authentication!!.scheme.equals("none", ignoreCase = true)) {
185+
logger.debug { "Authentication: None" }
186+
return PactBrokerClient(url.toString(), emptyMap())
187+
}
188+
189+
val scheme = parseExpression(authentication!!.scheme, resolver)
190+
if (scheme.isNotEmpty()) {
191+
// Legacy behavior (before support for bearer token was added):
192+
// If scheme was not explicitly set, basic was always used.
193+
// If it was explicitly set, the given value was used together with username and password
194+
val schemeToUse = if (scheme.equals("legacy")) "basic" else scheme
195+
logger.debug { "Authentication: $schemeToUse" }
196+
val options = mapOf("authentication" to listOf(schemeToUse,
197+
parseExpression(authentication!!.username, resolver),
198+
parseExpression(authentication!!.password, resolver)))
199+
return PactBrokerClient(url.toString(), options)
200+
}
201+
202+
// Check if username is set. If yes, use basic auth.
203+
val username = parseExpression(authentication!!.username, resolver)
204+
if (username.isNotEmpty()) {
205+
logger.debug { "Authentication: Basic" }
206+
val options = mapOf("authentication" to listOf("basic", username,
207+
parseExpression(authentication!!.password, resolver)))
208+
return PactBrokerClient(url.toString(), options)
209+
}
210+
211+
// Check if token is set. If yes, use bearer auth.
212+
val token = parseExpression(authentication!!.token, resolver)
213+
if (token.isNotEmpty()) {
214+
logger.debug { "Authentication: Bearer" }
215+
val options = mapOf("authentication" to listOf("bearer", token))
216+
return PactBrokerClient(url.toString(), options)
217+
}
218+
219+
throw IllegalArgumentException("Invalid pact authentication specified. Either username or token must be set.")
220+
}
221+
222+
companion object : KLogging()
223+
}

0 commit comments

Comments
 (0)
Please sign in to comment.