diff --git a/buildSrc/src/main/groovy/au.com.dius.pact.kotlin-common-conventions.gradle b/buildSrc/src/main/groovy/au.com.dius.pact.kotlin-common-conventions.gradle index b2c04b524d..f56e6b16b9 100644 --- a/buildSrc/src/main/groovy/au.com.dius.pact.kotlin-common-conventions.gradle +++ b/buildSrc/src/main/groovy/au.com.dius.pact.kotlin-common-conventions.gradle @@ -36,8 +36,6 @@ dependencies { implementation 'io.github.microutils:kotlin-logging:2.1.23' implementation 'org.apache.httpcomponents.client5:httpclient5:5.1.1' implementation 'org.apache.httpcomponents.client5:httpclient5-fluent:5.1.1' - implementation 'com.michael-bull.kotlin-result:kotlin-result:1.1.16' - implementation 'com.michael-bull.kotlin-result:kotlin-result-jvm:1.1.16' implementation 'com.google.guava:guava:30.1.1-jre' implementation 'org.slf4j:slf4j-api:1.7.32' implementation 'io.ktor:ktor-http-jvm:1.6.8' diff --git a/consumer/build.gradle b/consumer/build.gradle index 09618676c3..3b8f659a74 100644 --- a/consumer/build.gradle +++ b/consumer/build.gradle @@ -19,13 +19,14 @@ dependencies { implementation 'org.slf4j:slf4j-api' implementation 'io.ktor:ktor-server-netty' implementation 'io.ktor:ktor-network-tls-certificates' - implementation('io.pact.plugin.driver:core:0.1.7') { + implementation('io.pact.plugin.driver:core:0.1.8') { exclude group: 'au.com.dius.pact.core' } implementation 'org.apache.commons:commons-lang3' implementation 'com.github.mifmif:generex:1.0.2' implementation 'org.apache.commons:commons-io:1.3.2' implementation 'org.apache.commons:commons-text:1.9' + implementation 'com.michael-bull.kotlin-result:kotlin-result:1.1.14' testImplementation 'org.hamcrest:hamcrest' testImplementation 'org.spockframework:spock-core' diff --git a/consumer/groovy/build.gradle b/consumer/groovy/build.gradle index d751e97753..3c63cdfcb7 100644 --- a/consumer/groovy/build.gradle +++ b/consumer/groovy/build.gradle @@ -14,7 +14,7 @@ dependencies { implementation 'com.github.mifmif:generex:1.0.2' implementation 'org.apache.commons:commons-lang3' implementation 'org.apache.commons:commons-collections4' - implementation('io.pact.plugin.driver:core:0.1.7') { + implementation('io.pact.plugin.driver:core:0.1.8') { exclude group: 'au.com.dius.pact.core' } diff --git a/consumer/junit/src/main/java/au/com/dius/pact/consumer/junit/BaseProviderRule.java b/consumer/junit/src/main/java/au/com/dius/pact/consumer/junit/BaseProviderRule.java index 75ac8e27e5..10f36f369f 100644 --- a/consumer/junit/src/main/java/au/com/dius/pact/consumer/junit/BaseProviderRule.java +++ b/consumer/junit/src/main/java/au/com/dius/pact/consumer/junit/BaseProviderRule.java @@ -94,7 +94,7 @@ public void evaluate() throws Throwable { } if (config.getPactVersion() == PactSpecVersion.V4) { - pact.get().asV4Pact().component1().getInteractions() + pact.get().asV4Pact().get().getInteractions() .forEach(i -> i.getComments().put("testname", Json.toJson(description.getDisplayName()))); } diff --git a/consumer/junit5/src/main/kotlin/au/com/dius/pact/consumer/junit5/PactConsumerTestExt.kt b/consumer/junit5/src/main/kotlin/au/com/dius/pact/consumer/junit5/PactConsumerTestExt.kt index d23e339693..63aad1ec21 100644 --- a/consumer/junit5/src/main/kotlin/au/com/dius/pact/consumer/junit5/PactConsumerTestExt.kt +++ b/consumer/junit5/src/main/kotlin/au/com/dius/pact/consumer/junit5/PactConsumerTestExt.kt @@ -29,7 +29,6 @@ import au.com.dius.pact.core.support.MetricEvent import au.com.dius.pact.core.support.Metrics import au.com.dius.pact.core.support.expressions.DataType import au.com.dius.pact.core.support.expressions.ExpressionParser -import com.github.michaelbull.result.unwrap import mu.KLogging import org.junit.jupiter.api.Disabled import org.junit.jupiter.api.Nested diff --git a/consumer/src/main/kotlin/au/com/dius/pact/consumer/ConsumerPactRunner.kt b/consumer/src/main/kotlin/au/com/dius/pact/consumer/ConsumerPactRunner.kt index f0fdc502be..7d9855ccc1 100644 --- a/consumer/src/main/kotlin/au/com/dius/pact/consumer/ConsumerPactRunner.kt +++ b/consumer/src/main/kotlin/au/com/dius/pact/consumer/ConsumerPactRunner.kt @@ -6,11 +6,7 @@ import au.com.dius.pact.core.model.Interaction import au.com.dius.pact.core.model.InvalidPactException import au.com.dius.pact.core.model.Pact import au.com.dius.pact.core.model.PactSpecVersion -import au.com.dius.pact.core.model.RequestResponsePact -import au.com.dius.pact.core.model.messaging.Message -import au.com.dius.pact.core.model.messaging.MessagePact import au.com.dius.pact.core.support.V4PactFeaturesException -import com.github.michaelbull.result.expect interface PactTestRun { @Throws(Throwable::class) diff --git a/consumer/src/main/kotlin/au/com/dius/pact/consumer/KTorMockServer.kt b/consumer/src/main/kotlin/au/com/dius/pact/consumer/KTorMockServer.kt index 22143d07ee..d0489a3e5f 100644 --- a/consumer/src/main/kotlin/au/com/dius/pact/consumer/KTorMockServer.kt +++ b/consumer/src/main/kotlin/au/com/dius/pact/consumer/KTorMockServer.kt @@ -8,10 +8,8 @@ import au.com.dius.pact.core.model.IResponse import au.com.dius.pact.core.model.OptionalBody import au.com.dius.pact.core.model.Pact import au.com.dius.pact.core.model.Request -import au.com.dius.pact.core.model.RequestResponsePact import au.com.dius.pact.core.model.Response -import com.github.michaelbull.result.Err -import com.github.michaelbull.result.Ok +import au.com.dius.pact.core.support.Result import io.ktor.application.ApplicationCall import io.ktor.application.ApplicationCallPipeline import io.ktor.application.install @@ -127,13 +125,13 @@ class KTorMockServer( override fun updatePact(pact: Pact): Pact { return if (pact.isV4Pact()) { when (val p = pact.asV4Pact()) { - is Ok -> { + is Result.Ok -> { for (interaction in p.value.interactions) { interaction.asV4Interaction().transport = if (config is MockHttpsProviderConfig) "https" else "http" } p.value } - is Err -> pact + is Result.Err -> pact } } else { pact diff --git a/consumer/src/main/kotlin/au/com/dius/pact/consumer/MockHttpServer.kt b/consumer/src/main/kotlin/au/com/dius/pact/consumer/MockHttpServer.kt index 3cce86da54..4ea19141b8 100755 --- a/consumer/src/main/kotlin/au/com/dius/pact/consumer/MockHttpServer.kt +++ b/consumer/src/main/kotlin/au/com/dius/pact/consumer/MockHttpServer.kt @@ -20,6 +20,7 @@ import au.com.dius.pact.core.model.Response import au.com.dius.pact.core.model.V4Pact import au.com.dius.pact.core.model.generators.GeneratorTestMode import au.com.dius.pact.core.model.queryStringToMap +import au.com.dius.pact.core.support.Result import au.com.dius.pact.core.support.unwrap import com.github.michaelbull.result.Err import com.github.michaelbull.result.Ok @@ -354,13 +355,13 @@ open class MockHttpServer(pact: BasePact, config: MockProviderConfig) : override fun updatePact(pact: Pact): Pact { return if (pact.isV4Pact()) { when (val p = pact.asV4Pact()) { - is Ok -> { + is Result.Ok -> { for (interaction in p.value.interactions) { interaction.asV4Interaction().transport = "https" } p.value } - is Err -> pact + is Result.Err -> pact } } else { pact @@ -373,13 +374,13 @@ open class MockHttpsServer(pact: BasePact, config: MockProviderConfig) : override fun updatePact(pact: Pact): Pact { return if (pact.isV4Pact()) { when (val p = pact.asV4Pact()) { - is Ok -> { + is Result.Ok -> { for (interaction in p.value.interactions) { interaction.asV4Interaction().transport = "https" } p.value } - is Err -> pact + is Result.Err -> pact } } else { pact diff --git a/consumer/src/main/kotlin/au/com/dius/pact/consumer/PluginMockServer.kt b/consumer/src/main/kotlin/au/com/dius/pact/consumer/PluginMockServer.kt index 4fb65297ff..b5247f4e22 100644 --- a/consumer/src/main/kotlin/au/com/dius/pact/consumer/PluginMockServer.kt +++ b/consumer/src/main/kotlin/au/com/dius/pact/consumer/PluginMockServer.kt @@ -6,8 +6,7 @@ import au.com.dius.pact.core.model.BasePact import au.com.dius.pact.core.model.Pact import au.com.dius.pact.core.support.contains import au.com.dius.pact.core.support.isNotEmpty -import com.github.michaelbull.result.Err -import com.github.michaelbull.result.Ok +import au.com.dius.pact.core.support.Result import io.pact.plugins.jvm.core.CatalogueEntry import io.pact.plugins.jvm.core.CatalogueManager import io.pact.plugins.jvm.core.DefaultPluginManager @@ -67,13 +66,13 @@ class PluginMockServer(pact: BasePact, config: MockProviderConfig) : BaseMockSer override fun updatePact(pact: Pact): Pact { return if (pact.isV4Pact()) { when (val p = pact.asV4Pact()) { - is Ok -> { + is Result.Ok -> { for (interaction in p.value.interactions) { interaction.asV4Interaction().transport = transportEntry.key } p.value } - is Err -> pact + is Result.Err -> pact } } else { pact diff --git a/consumer/src/main/kotlin/au/com/dius/pact/consumer/dsl/PactBuilder.kt b/consumer/src/main/kotlin/au/com/dius/pact/consumer/dsl/PactBuilder.kt index 2ffe533c02..a8fe66394b 100644 --- a/consumer/src/main/kotlin/au/com/dius/pact/consumer/dsl/PactBuilder.kt +++ b/consumer/src/main/kotlin/au/com/dius/pact/consumer/dsl/PactBuilder.kt @@ -28,6 +28,7 @@ import au.com.dius.pact.core.support.isNotEmpty import au.com.dius.pact.core.support.json.JsonValue import com.github.michaelbull.result.Err import com.github.michaelbull.result.Ok +import au.com.dius.pact.core.support.Result import io.pact.plugins.jvm.core.CatalogueEntry import io.pact.plugins.jvm.core.CatalogueEntryProviderType import io.pact.plugins.jvm.core.CatalogueEntryType @@ -233,7 +234,7 @@ open class PactBuilder( val contentMatcher = MatchingConfig.lookupContentMatcher(contentType) if (contentMatcher != null) { when (val result = contentMatcher.setupBodyFromConfig(bodyConfig)) { - is Ok -> { + is Result.Ok -> { result.value.map { val (partName, body, rules, generators, _, _, interactionMarkup, interactionMarkupType) = it val matchingRules = MatchingRulesImpl() @@ -244,7 +245,7 @@ open class PactBuilder( InteractionMarkup(interactionMarkup, interactionMarkupType) } } - is Err -> throw InteractionConfigurationError("Failed to set the interaction: " + result.error) + is Result.Err -> throw InteractionConfigurationError("Failed to set the interaction: " + result.error) } } else { listOf( @@ -303,7 +304,7 @@ open class PactBuilder( val contentMatcher = MatchingConfig.lookupContentMatcher(contentType) if (contentMatcher != null) { when (val result = contentMatcher.setupBodyFromConfig(bodyConfig)) { - is Ok -> { + is Result.Ok -> { if (result.value.size > 1) { logger.warn { "Plugin returned multiple contents, will only use the first" } } @@ -316,7 +317,7 @@ open class PactBuilder( part.generators.addGenerators(generators) } } - is Err -> throw InteractionConfigurationError("Failed to set the interaction: " + result.error) + is Result.Err -> throw InteractionConfigurationError("Failed to set the interaction: " + result.error) } } else { part.body = OptionalBody.body(toJson(bodyConfig).serialise().toByteArray(), ContentType(contentType)) diff --git a/core/matchers/build.gradle b/core/matchers/build.gradle index 7b9b17d219..d55dacb7a2 100644 --- a/core/matchers/build.gradle +++ b/core/matchers/build.gradle @@ -20,9 +20,10 @@ dependencies { implementation 'org.atteo:evo-inflector:1.3' implementation 'com.github.ajalt:mordant:1.2.1' implementation 'com.github.zafarkhaja:java-semver:0.9.0' - implementation('io.pact.plugin.driver:core:0.1.7') { + implementation('io.pact.plugin.driver:core:0.1.8') { exclude group: 'au.com.dius.pact.core' } + implementation 'com.michael-bull.kotlin-result:kotlin-result:1.1.14' testImplementation 'org.apache.groovy:groovy' testImplementation 'org.apache.groovy:groovy-xml' diff --git a/core/matchers/src/main/kotlin/au/com/dius/pact/core/matchers/ContentMatcher.kt b/core/matchers/src/main/kotlin/au/com/dius/pact/core/matchers/ContentMatcher.kt index e543e44aab..cc610b03ac 100644 --- a/core/matchers/src/main/kotlin/au/com/dius/pact/core/matchers/ContentMatcher.kt +++ b/core/matchers/src/main/kotlin/au/com/dius/pact/core/matchers/ContentMatcher.kt @@ -1,7 +1,7 @@ package au.com.dius.pact.core.matchers import au.com.dius.pact.core.model.OptionalBody -import com.github.michaelbull.result.Result +import au.com.dius.pact.core.support.Result import io.pact.plugins.jvm.core.InteractionContents interface ContentMatcher { diff --git a/core/matchers/src/main/kotlin/au/com/dius/pact/core/matchers/FormPostContentMatcher.kt b/core/matchers/src/main/kotlin/au/com/dius/pact/core/matchers/FormPostContentMatcher.kt index 3f8a6b2131..c0c8703a65 100755 --- a/core/matchers/src/main/kotlin/au/com/dius/pact/core/matchers/FormPostContentMatcher.kt +++ b/core/matchers/src/main/kotlin/au/com/dius/pact/core/matchers/FormPostContentMatcher.kt @@ -2,10 +2,7 @@ package au.com.dius.pact.core.matchers import au.com.dius.pact.core.model.ContentType import au.com.dius.pact.core.model.OptionalBody -import au.com.dius.pact.core.model.generators.Generators -import au.com.dius.pact.core.model.matchingrules.MatchingRuleCategory -import com.github.michaelbull.result.Ok -import com.github.michaelbull.result.Result +import au.com.dius.pact.core.support.Result import io.pact.plugins.jvm.core.InteractionContents import mu.KLogging import org.apache.hc.core5.http.NameValuePair @@ -36,7 +33,7 @@ class FormPostContentMatcher : ContentMatcher { override fun setupBodyFromConfig( bodyConfig: Map ): Result, String> { - return Ok(listOf(InteractionContents("", OptionalBody.body( + return Result.Ok(listOf(InteractionContents("", OptionalBody.body( bodyConfig["body"].toString().toByteArray(), ContentType("application/x-www-form-urlencoded") )))) diff --git a/core/matchers/src/main/kotlin/au/com/dius/pact/core/matchers/JsonContentMatcher.kt b/core/matchers/src/main/kotlin/au/com/dius/pact/core/matchers/JsonContentMatcher.kt index bcf0dfd34f..1fd926a2a3 100644 --- a/core/matchers/src/main/kotlin/au/com/dius/pact/core/matchers/JsonContentMatcher.kt +++ b/core/matchers/src/main/kotlin/au/com/dius/pact/core/matchers/JsonContentMatcher.kt @@ -6,10 +6,9 @@ import au.com.dius.pact.core.model.ContentType import au.com.dius.pact.core.model.OptionalBody import au.com.dius.pact.core.model.constructPath import au.com.dius.pact.core.support.Json.toJson +import au.com.dius.pact.core.support.Result import au.com.dius.pact.core.support.json.JsonParser import au.com.dius.pact.core.support.json.JsonValue -import com.github.michaelbull.result.Ok -import com.github.michaelbull.result.Result import io.pact.plugins.jvm.core.InteractionContents import mu.KLogging @@ -43,7 +42,7 @@ object JsonContentMatcher : ContentMatcher, KLogging() { override fun setupBodyFromConfig( bodyConfig: Map ): Result, String> { - return Ok(listOf(InteractionContents("", + return Result.Ok(listOf(InteractionContents("", OptionalBody.body( toJson(bodyConfig["body"]).serialise().toByteArray(), ContentType("application/json") diff --git a/core/matchers/src/main/kotlin/au/com/dius/pact/core/matchers/KafkaJsonSchemaContentMatcher.kt b/core/matchers/src/main/kotlin/au/com/dius/pact/core/matchers/KafkaJsonSchemaContentMatcher.kt index 344547b06d..c678b77e24 100644 --- a/core/matchers/src/main/kotlin/au/com/dius/pact/core/matchers/KafkaJsonSchemaContentMatcher.kt +++ b/core/matchers/src/main/kotlin/au/com/dius/pact/core/matchers/KafkaJsonSchemaContentMatcher.kt @@ -3,11 +3,10 @@ package au.com.dius.pact.core.matchers import au.com.dius.pact.core.model.ContentType import au.com.dius.pact.core.model.OptionalBody import au.com.dius.pact.core.support.Json +import au.com.dius.pact.core.support.Result import au.com.dius.pact.core.support.json.JsonException import au.com.dius.pact.core.support.json.JsonParser import au.com.dius.pact.core.support.json.KafkaSchemaRegistryWireFormatter -import com.github.michaelbull.result.Ok -import com.github.michaelbull.result.Result import io.pact.plugins.jvm.core.InteractionContents import mu.KLogging @@ -57,7 +56,7 @@ class KafkaJsonSchemaContentMatcher : ContentMatcher { override fun setupBodyFromConfig( bodyConfig: Map ): Result, String> { - return Ok(listOf(InteractionContents("", + return Result.Ok(listOf(InteractionContents("", OptionalBody.body( Json.toJson(bodyConfig["body"]).serialise().toByteArray(), ContentType.KAFKA_SCHEMA_REGISTRY_JSON diff --git a/core/matchers/src/main/kotlin/au/com/dius/pact/core/matchers/MultipartMessageContentMatcher.kt b/core/matchers/src/main/kotlin/au/com/dius/pact/core/matchers/MultipartMessageContentMatcher.kt index 0fbc107408..9429995f7b 100755 --- a/core/matchers/src/main/kotlin/au/com/dius/pact/core/matchers/MultipartMessageContentMatcher.kt +++ b/core/matchers/src/main/kotlin/au/com/dius/pact/core/matchers/MultipartMessageContentMatcher.kt @@ -2,10 +2,7 @@ package au.com.dius.pact.core.matchers import au.com.dius.pact.core.model.ContentType import au.com.dius.pact.core.model.OptionalBody -import au.com.dius.pact.core.model.generators.Generators -import au.com.dius.pact.core.model.matchingrules.MatchingRuleCategory -import com.github.michaelbull.result.Ok -import com.github.michaelbull.result.Result +import au.com.dius.pact.core.support.Result import io.pact.plugins.jvm.core.InteractionContents import mu.KLogging import java.util.Enumeration @@ -39,7 +36,7 @@ class MultipartMessageContentMatcher : ContentMatcher { override fun setupBodyFromConfig( bodyConfig: Map ): Result, String> { - return Ok(listOf(InteractionContents("", + return Result.Ok(listOf(InteractionContents("", OptionalBody.body( bodyConfig["body"].toString().toByteArray(), ContentType("multipart/form-data") diff --git a/core/matchers/src/main/kotlin/au/com/dius/pact/core/matchers/PlainTextContentMatcher.kt b/core/matchers/src/main/kotlin/au/com/dius/pact/core/matchers/PlainTextContentMatcher.kt index ab58e33a6e..9e52e74a20 100644 --- a/core/matchers/src/main/kotlin/au/com/dius/pact/core/matchers/PlainTextContentMatcher.kt +++ b/core/matchers/src/main/kotlin/au/com/dius/pact/core/matchers/PlainTextContentMatcher.kt @@ -3,8 +3,7 @@ package au.com.dius.pact.core.matchers import au.com.dius.pact.core.model.ContentType import au.com.dius.pact.core.model.OptionalBody import au.com.dius.pact.core.model.matchingrules.RegexMatcher -import com.github.michaelbull.result.Ok -import com.github.michaelbull.result.Result +import au.com.dius.pact.core.support.Result import io.pact.plugins.jvm.core.InteractionContents import mu.KLogging @@ -56,7 +55,7 @@ class PlainTextContentMatcher : ContentMatcher { override fun setupBodyFromConfig( bodyConfig: Map ): Result, String> { - return Ok(listOf(InteractionContents("", + return Result.Ok(listOf(InteractionContents("", OptionalBody.body( bodyConfig["body"].toString().toByteArray(), ContentType("text/plain") diff --git a/core/matchers/src/main/kotlin/au/com/dius/pact/core/matchers/PluginContentMatcher.kt b/core/matchers/src/main/kotlin/au/com/dius/pact/core/matchers/PluginContentMatcher.kt index 72c3946c1f..3755d58f7b 100644 --- a/core/matchers/src/main/kotlin/au/com/dius/pact/core/matchers/PluginContentMatcher.kt +++ b/core/matchers/src/main/kotlin/au/com/dius/pact/core/matchers/PluginContentMatcher.kt @@ -2,7 +2,9 @@ package au.com.dius.pact.core.matchers import au.com.dius.pact.core.model.ContentType import au.com.dius.pact.core.model.OptionalBody -import com.github.michaelbull.result.Result +import au.com.dius.pact.core.support.Result +import com.github.michaelbull.result.Err +import com.github.michaelbull.result.Ok import io.pact.plugins.jvm.core.InteractionContents import mu.KLogging @@ -28,7 +30,10 @@ class PluginContentMatcher( override fun setupBodyFromConfig( bodyConfig: Map ): Result, String> { - return contentMatcher.configureContent(contentType.toString(), bodyConfig) + return when (val result = contentMatcher.configureContent(contentType.toString(), bodyConfig)) { + is Ok -> Result.Ok(result.value) + is Err -> Result.Err(result.error) + } } companion object : KLogging() diff --git a/core/matchers/src/main/kotlin/au/com/dius/pact/core/matchers/XmlContentMatcher.kt b/core/matchers/src/main/kotlin/au/com/dius/pact/core/matchers/XmlContentMatcher.kt index 04378f0380..46ab91cb2a 100755 --- a/core/matchers/src/main/kotlin/au/com/dius/pact/core/matchers/XmlContentMatcher.kt +++ b/core/matchers/src/main/kotlin/au/com/dius/pact/core/matchers/XmlContentMatcher.kt @@ -2,11 +2,8 @@ package au.com.dius.pact.core.matchers import au.com.dius.pact.core.model.ContentType import au.com.dius.pact.core.model.OptionalBody -import au.com.dius.pact.core.model.generators.Generators -import au.com.dius.pact.core.model.matchingrules.MatchingRuleCategory +import au.com.dius.pact.core.support.Result import au.com.dius.pact.core.support.zipAll -import com.github.michaelbull.result.Ok -import com.github.michaelbull.result.Result import io.pact.plugins.jvm.core.InteractionContents import mu.KLogging import org.apache.xerces.dom.TextImpl @@ -46,7 +43,7 @@ object XmlContentMatcher : ContentMatcher, KLogging() { override fun setupBodyFromConfig( bodyConfig: Map ): Result, String> { - return Ok(listOf(InteractionContents("", + return Result.Ok(listOf(InteractionContents("", OptionalBody.body( bodyConfig["body"].toString().toByteArray(), ContentType("application/xml") diff --git a/core/model/src/main/kotlin/au/com/dius/pact/core/model/BasePact.kt b/core/model/src/main/kotlin/au/com/dius/pact/core/model/BasePact.kt index ba06119650..1548450969 100644 --- a/core/model/src/main/kotlin/au/com/dius/pact/core/model/BasePact.kt +++ b/core/model/src/main/kotlin/au/com/dius/pact/core/model/BasePact.kt @@ -1,11 +1,9 @@ package au.com.dius.pact.core.model import au.com.dius.pact.core.support.Json +import au.com.dius.pact.core.support.Result import au.com.dius.pact.core.support.Utils import au.com.dius.pact.core.support.json.JsonValue -import com.github.michaelbull.result.Err -import com.github.michaelbull.result.Ok -import com.github.michaelbull.result.Result import mu.KLogging import java.io.File import java.util.Collections @@ -30,11 +28,11 @@ abstract class BasePact @JvmOverloads constructor( override fun compatibleTo(other: Pact): Result { return if (provider != other.provider) { - Err("Provider names are different: '$provider' and '${other.provider}'") + Result.Err("Provider names are different: '$provider' and '${other.provider}'") } else if (!this::class.java.isAssignableFrom(other::class.java)) { - Err("Pact types different: '${other::class.simpleName}' can not be assigned to '${this::class.simpleName}'") + Result.Err("Pact types different: '${other::class.simpleName}' can not be assigned to '${this::class.simpleName}'") } else { - Ok(true) + Result.Ok(true) } } diff --git a/core/model/src/main/kotlin/au/com/dius/pact/core/model/Pact.kt b/core/model/src/main/kotlin/au/com/dius/pact/core/model/Pact.kt index 64bd7ff606..63780cdaec 100644 --- a/core/model/src/main/kotlin/au/com/dius/pact/core/model/Pact.kt +++ b/core/model/src/main/kotlin/au/com/dius/pact/core/model/Pact.kt @@ -3,8 +3,8 @@ package au.com.dius.pact.core.model import au.com.dius.pact.core.model.messaging.Message import au.com.dius.pact.core.model.messaging.MessagePact import au.com.dius.pact.core.support.Json +import au.com.dius.pact.core.support.Result import au.com.dius.pact.core.support.json.JsonValue -import com.github.michaelbull.result.Result /** * Pact Provider diff --git a/core/model/src/main/kotlin/au/com/dius/pact/core/model/PactMerge.kt b/core/model/src/main/kotlin/au/com/dius/pact/core/model/PactMerge.kt index ebd4452836..a1dc5fd657 100644 --- a/core/model/src/main/kotlin/au/com/dius/pact/core/model/PactMerge.kt +++ b/core/model/src/main/kotlin/au/com/dius/pact/core/model/PactMerge.kt @@ -1,6 +1,6 @@ package au.com.dius.pact.core.model -import com.github.michaelbull.result.Err +import au.com.dius.pact.core.support.Result import mu.KLogging data class MergeResult(val ok: Boolean, val message: String, val result: Pact? = null) @@ -13,7 +13,7 @@ object PactMerge : KLogging() { @JvmStatic fun merge(newPact: Pact, existing: Pact): MergeResult { val compatibleTo = newPact.compatibleTo(existing) - if (compatibleTo is Err) { + if (compatibleTo is Result.Err) { return MergeResult(false, "Cannot merge pacts as they are not compatible - ${compatibleTo.error}") } diff --git a/core/model/src/main/kotlin/au/com/dius/pact/core/model/PactReader.kt b/core/model/src/main/kotlin/au/com/dius/pact/core/model/PactReader.kt index d3accd94d0..9856217d18 100644 --- a/core/model/src/main/kotlin/au/com/dius/pact/core/model/PactReader.kt +++ b/core/model/src/main/kotlin/au/com/dius/pact/core/model/PactReader.kt @@ -4,13 +4,15 @@ import au.com.dius.pact.core.model.messaging.MessagePact import au.com.dius.pact.core.pactbroker.PactBrokerClient import au.com.dius.pact.core.pactbroker.PactBrokerClientConfig import au.com.dius.pact.core.pactbroker.PactBrokerResult -import au.com.dius.pact.core.support.HttpClientUtils -import au.com.dius.pact.core.support.HttpClientUtils.isJsonResponse import au.com.dius.pact.core.support.Auth -import au.com.dius.pact.core.support.Utils import au.com.dius.pact.core.support.HttpClient +import au.com.dius.pact.core.support.HttpClientUtils +import au.com.dius.pact.core.support.HttpClientUtils.isJsonResponse import au.com.dius.pact.core.support.Json +import au.com.dius.pact.core.support.Result +import au.com.dius.pact.core.support.Utils import au.com.dius.pact.core.support.Version +import au.com.dius.pact.core.support.handleWith import au.com.dius.pact.core.support.json.JsonException import au.com.dius.pact.core.support.json.JsonParser import au.com.dius.pact.core.support.json.JsonValue @@ -18,11 +20,6 @@ import au.com.dius.pact.core.support.json.map import au.com.dius.pact.core.support.jsonArray import au.com.dius.pact.core.support.jsonObject import au.com.dius.pact.core.support.unwrap -import com.github.michaelbull.result.Err -import com.github.michaelbull.result.Ok -import com.github.michaelbull.result.Result -import com.github.michaelbull.result.expect -import com.github.michaelbull.result.runCatching import mu.KLogging import mu.KotlinLogging import org.apache.hc.client5.http.auth.AuthScope @@ -45,7 +42,6 @@ import java.net.URI import java.net.URL import java.net.URLDecoder import kotlin.collections.set -import kotlin.text.isNotEmpty private val logger = KotlinLogging.logger {} @@ -65,12 +61,12 @@ fun loadPactFromUrl( pactResponse.pactFile to source.copy(attributes = pactResponse.links, options = options, tag = source.tag) } else -> when (val jsonResource = fetchJsonResource(http, source)) { - is Ok -> if (jsonResource.value.first is JsonValue.Object) { + is Result.Ok -> if (jsonResource.value.first is JsonValue.Object) { jsonResource.value.first.asObject()!! to jsonResource.value.second } else { throw UnsupportedOperationException("Was expected a JSON document, got ${jsonResource.value}") } - is Err -> throw jsonResource.error + is Result.Err -> throw jsonResource.error } } } @@ -79,7 +75,7 @@ fun loadPactFromUrl( fun fetchJsonResource(http: CloseableHttpClient, source: UrlPactSource): Result, Throwable> { val url = URL(source.url) - return runCatching { + return handleWith { when (url.protocol) { "file" -> JsonParser.parseString(URL(source.url).readText()) to source else -> { diff --git a/core/model/src/main/kotlin/au/com/dius/pact/core/model/PactWriter.kt b/core/model/src/main/kotlin/au/com/dius/pact/core/model/PactWriter.kt index 08ef15973c..d733673591 100644 --- a/core/model/src/main/kotlin/au/com/dius/pact/core/model/PactWriter.kt +++ b/core/model/src/main/kotlin/au/com/dius/pact/core/model/PactWriter.kt @@ -1,12 +1,9 @@ package au.com.dius.pact.core.model import au.com.dius.pact.core.support.Json -import au.com.dius.pact.core.support.json.JsonException +import au.com.dius.pact.core.support.Result import au.com.dius.pact.core.support.json.JsonParser import au.com.dius.pact.core.support.json.JsonValue -import com.github.michaelbull.result.Ok -import com.github.michaelbull.result.Result -import com.github.michaelbull.result.expect import mu.KLogging import java.io.ByteArrayOutputStream import java.io.File @@ -66,7 +63,7 @@ object DefaultPactWriter : PactWriter, KLogging() { Json.prettyPrint(pact.sortInteractions().toMap(pactSpecVersion)) } writer.println(json) - return Ok(json.toByteArray().size) + return Result.Ok(json.toByteArray().size) } /** @@ -104,7 +101,7 @@ object DefaultPactWriter : PactWriter, KLogging() { val bytes = swriter.toString().toByteArray() raf.setLength(bytes.size.toLong()) raf.write(bytes) - Ok(bytes.size) + Result.Ok(bytes.size) } finally { lock.release() raf.close() diff --git a/core/model/src/main/kotlin/au/com/dius/pact/core/model/RequestResponsePact.kt b/core/model/src/main/kotlin/au/com/dius/pact/core/model/RequestResponsePact.kt index 43e5839e80..1d643c49ea 100644 --- a/core/model/src/main/kotlin/au/com/dius/pact/core/model/RequestResponsePact.kt +++ b/core/model/src/main/kotlin/au/com/dius/pact/core/model/RequestResponsePact.kt @@ -1,10 +1,8 @@ package au.com.dius.pact.core.model import au.com.dius.pact.core.support.Json +import au.com.dius.pact.core.support.Result import au.com.dius.pact.core.support.jsonObject -import com.github.michaelbull.result.Err -import com.github.michaelbull.result.Ok -import com.github.michaelbull.result.Result /** * Pact between a consumer and a provider @@ -42,12 +40,12 @@ class RequestResponsePact @JvmOverloads constructor( override fun isRequestResponsePact() = true - override fun asRequestResponsePact() = Ok(this) + override fun asRequestResponsePact() = Result.Ok(this) - override fun asMessagePact() = Err("A V3 Request/Response Pact can not be converted to a Message Pact") + override fun asMessagePact() = Result.Err("A V3 Request/Response Pact can not be converted to a Message Pact") override fun asV4Pact(): Result { - return Ok(V4Pact(consumer, provider, interactions.map { it.asV4Interaction() }.toMutableList(), metadata)) + return Result.Ok(V4Pact(consumer, provider, interactions.map { it.asV4Interaction() }.toMutableList(), metadata)) } fun interactionFor(description: String, providerState: String): SynchronousRequestResponse? { diff --git a/core/model/src/main/kotlin/au/com/dius/pact/core/model/V4Pact.kt b/core/model/src/main/kotlin/au/com/dius/pact/core/model/V4Pact.kt index 203c8e1932..9bf25c5f25 100644 --- a/core/model/src/main/kotlin/au/com/dius/pact/core/model/V4Pact.kt +++ b/core/model/src/main/kotlin/au/com/dius/pact/core/model/V4Pact.kt @@ -6,14 +6,12 @@ import au.com.dius.pact.core.model.messaging.MessagePact import au.com.dius.pact.core.model.v4.MessageContents import au.com.dius.pact.core.model.v4.V4InteractionType import au.com.dius.pact.core.support.Json +import au.com.dius.pact.core.support.Result import au.com.dius.pact.core.support.deepMerge import au.com.dius.pact.core.support.isNotEmpty import au.com.dius.pact.core.support.json.JsonValue import au.com.dius.pact.core.support.json.map import au.com.dius.pact.core.support.jsonObject -import com.github.michaelbull.result.Err -import com.github.michaelbull.result.Ok -import com.github.michaelbull.result.Result import mu.KLogging import mu.KotlinLogging import org.apache.commons.lang3.builder.HashCodeBuilder @@ -473,7 +471,7 @@ sealed class V4Interaction( return if (json.has("type")) { val type = Json.toString(json["type"]) when (val result = V4InteractionType.fromString(type)) { - is Ok -> { + is Result.Ok -> { val id = json["_id"].asString() val key = Json.toString(json["key"]) val description = Json.toString(json["description"]) @@ -517,14 +515,14 @@ sealed class V4Interaction( when (result.value) { V4InteractionType.SynchronousHTTP -> { - Ok(SynchronousHttp( + Result.Ok(SynchronousHttp( key, description, providerStates, HttpRequest.fromJson(json["request"]), HttpResponse.fromJson(json["response"]), id, comments, pending, pluginConfiguration.toMutableMap(), interactionMarkup, transport )) } V4InteractionType.AsynchronousMessages -> { - Ok(AsynchronousMessage(key, description, MessageContents.fromJson(json), id, + Result.Ok(AsynchronousMessage(key, description, MessageContents.fromJson(json), id, providerStates, comments, pending, pluginConfiguration.toMutableMap(), interactionMarkup, transport)) } V4InteractionType.SynchronousMessages -> { @@ -534,21 +532,21 @@ sealed class V4Interaction( val response = if (json.has("response")) json["response"].asArray().map { MessageContents.fromJson(it) } else listOf() - Ok(SynchronousMessages(key, description, id, providerStates, comments, pending, request, + Result.Ok(SynchronousMessages(key, description, id, providerStates, comments, pending, request, response.toMutableList(), pluginConfiguration.toMutableMap(), interactionMarkup, transport)) } } } - is Err -> { + is Result.Err -> { val message = "Interaction $index has invalid type attribute '$type'. It will be ignored. Source: $source" logger.warn(message) - Err(message) + Result.Err(message) } } } else { val message = "Interaction $index has no type attribute. It will be ignored. Source: $source" logger.warn(message) - Err(message) + Result.Err(message) } } } @@ -589,28 +587,28 @@ open class V4Pact @JvmOverloads constructor( } override fun asRequestResponsePact(): Result { - return Ok(RequestResponsePact(provider, consumer, + return Result.Ok(RequestResponsePact(provider, consumer, interactions.filterIsInstance() .map { it.asV3Interaction() }.toMutableList())) } override fun asMessagePact(): Result { - return Ok(MessagePact(provider, consumer, + return Result.Ok(MessagePact(provider, consumer, interactions.filterIsInstance() .map { it.asV3Interaction() }.toMutableList())) } override fun isV4Pact() = true - override fun asV4Pact() = Ok(this) + override fun asV4Pact() = Result.Ok(this) override fun isRequestResponsePact() = interactions.any { it is V4Interaction.SynchronousHttp } override fun compatibleTo(other: Pact): Result { return if (provider != other.provider) { - Err("Provider names are different: '$provider' and '${other.provider}'") + Result.Err("Provider names are different: '$provider' and '${other.provider}'") } else { - Ok(true) + Result.Ok(true) } } diff --git a/core/model/src/main/kotlin/au/com/dius/pact/core/model/generators/DateExpression.kt b/core/model/src/main/kotlin/au/com/dius/pact/core/model/generators/DateExpression.kt index 671b2456a5..f2b837517e 100644 --- a/core/model/src/main/kotlin/au/com/dius/pact/core/model/generators/DateExpression.kt +++ b/core/model/src/main/kotlin/au/com/dius/pact/core/model/generators/DateExpression.kt @@ -1,8 +1,6 @@ package au.com.dius.pact.core.model.generators -import com.github.michaelbull.result.Err -import com.github.michaelbull.result.Ok -import com.github.michaelbull.result.Result +import au.com.dius.pact.core.support.Result import au.com.dius.pact.core.support.generators.expressions.Adjustment import au.com.dius.pact.core.support.generators.expressions.DateBase import au.com.dius.pact.core.support.generators.expressions.DateExpressionLexer @@ -22,8 +20,8 @@ object DateExpression : KLogging() { fun executeDateExpression(base: OffsetDateTime, expression: String?): Result { return if (!expression.isNullOrEmpty()) { return when (val result = parseDateExpression(expression)) { - is Err -> result - is Ok -> { + is Result.Err -> result + is Result.Ok -> { var date = baseDate(result, base) result.value.adjustments.forEach { date = when (it.operation) { @@ -32,11 +30,11 @@ object DateExpression : KLogging() { } } - Ok(date) + Result.Ok(date) } } } else { - Ok(base) + Result.Ok(base) } } @@ -98,7 +96,7 @@ object DateExpression : KLogging() { } } - private fun baseDate(result: Ok, base: OffsetDateTime): OffsetDateTime { + private fun baseDate(result: Result.Ok, base: OffsetDateTime): OffsetDateTime { return when (result.value.base) { DateBase.NOW, DateBase.TODAY -> base DateBase.YESTERDAY -> base.minusDays(1) @@ -144,8 +142,8 @@ object DateExpression : KLogging() { val lexer = DateExpressionLexer(expression) val parser = DateExpressionParser(lexer) return when (val result = parser.expression()) { - is Err -> Err("Error parsing expression: ${result.error}") - is Ok -> Ok(ParsedDateExpression(result.value.first, result.value.second.toMutableList())) + is Result.Err -> Result.Err("Error parsing expression: ${result.error}") + is Result.Ok -> Result.Ok(ParsedDateExpression(result.value.first, result.value.second.toMutableList())) } } } diff --git a/core/model/src/main/kotlin/au/com/dius/pact/core/model/generators/DateTimeExpression.kt b/core/model/src/main/kotlin/au/com/dius/pact/core/model/generators/DateTimeExpression.kt index 82c81d02f5..1c18fb7b40 100644 --- a/core/model/src/main/kotlin/au/com/dius/pact/core/model/generators/DateTimeExpression.kt +++ b/core/model/src/main/kotlin/au/com/dius/pact/core/model/generators/DateTimeExpression.kt @@ -1,9 +1,7 @@ package au.com.dius.pact.core.model.generators -import com.github.michaelbull.result.Err -import com.github.michaelbull.result.Ok -import com.github.michaelbull.result.Result -import com.github.michaelbull.result.mapError +import au.com.dius.pact.core.support.Result +import au.com.dius.pact.core.support.mapError import mu.KLogging import java.lang.Integer.parseInt import java.time.OffsetDateTime @@ -14,19 +12,19 @@ object DateTimeExpression : KLogging() { val split = expression.split("@", limit = 2) if (split.size > 1) { val datePart = DateExpression.executeDateExpression(base, split[0]) - val timePart = if (datePart is Ok) + val timePart = if (datePart is Result.Ok) TimeExpression.executeTimeExpression(datePart.value, split[1]) else TimeExpression.executeTimeExpression(base, split[1]) when { - datePart is Err && timePart is Err -> datePart.mapError { "$it, " + + datePart is Result.Err && timePart is Result.Err -> datePart.mapError { "$it, " + Regex("index (\\d+)").replace(timePart.error) { mr -> val pos = parseInt(mr.groupValues[1]) "index ${pos + split[0].length + 1}" } } - datePart is Err -> datePart - timePart is Err -> timePart.mapError { + datePart is Result.Err -> datePart + timePart is Result.Err -> timePart.mapError { Regex("index (\\d+)").replace(timePart.error) { mr -> val pos = parseInt(mr.groupValues[1]) "index ${pos + split[0].length + 1}" @@ -38,7 +36,7 @@ object DateTimeExpression : KLogging() { DateExpression.executeDateExpression(base, split[0]) } } else { - Ok(base) + Result.Ok(base) } } } diff --git a/core/model/src/main/kotlin/au/com/dius/pact/core/model/generators/Generator.kt b/core/model/src/main/kotlin/au/com/dius/pact/core/model/generators/Generator.kt index f2cd8e3969..92ec009148 100755 --- a/core/model/src/main/kotlin/au/com/dius/pact/core/model/generators/Generator.kt +++ b/core/model/src/main/kotlin/au/com/dius/pact/core/model/generators/Generator.kt @@ -1,17 +1,14 @@ package au.com.dius.pact.core.model.generators -import com.github.michaelbull.result.Result -import com.github.michaelbull.result.getOr import au.com.dius.pact.core.model.PactSpecVersion import au.com.dius.pact.core.model.matchingrules.MatchingRuleCategory import au.com.dius.pact.core.support.Json +import au.com.dius.pact.core.support.Result import au.com.dius.pact.core.support.expressions.DataType import au.com.dius.pact.core.support.expressions.ExpressionParser import au.com.dius.pact.core.support.expressions.MapValueResolver +import au.com.dius.pact.core.support.getOr import au.com.dius.pact.core.support.json.JsonValue -import com.github.michaelbull.result.Err -import com.github.michaelbull.result.Ok -import com.github.michaelbull.result.get import com.mifmif.common.regex.Generex import mu.KLogging import mu.KotlinLogging @@ -296,11 +293,11 @@ enum class UuidFormat { companion object : KLogging() { fun fromString(s: String?): Result { return when(s) { - "simple" -> Ok(Simple) - null, "lower-case-hyphenated" -> Ok(LowerCaseHyphenated) - "upper-case-hyphenated" -> Ok(UpperCaseHyphenated) - "URN" -> Ok(Urn) - else -> Err("'$s' is not a valid UUID format") + "simple" -> Result.Ok(Simple) + null, "lower-case-hyphenated" -> Result.Ok(LowerCaseHyphenated) + "upper-case-hyphenated" -> Result.Ok(UpperCaseHyphenated) + "URN" -> Result.Ok(Urn) + else -> Result.Err("'$s' is not a valid UUID format") } } } @@ -368,7 +365,7 @@ data class DateGenerator @JvmOverloads constructor( override fun generate(context: MutableMap, exampleValue: Any?): Any { val base = if (context.containsKey("baseDate")) context["baseDate"] as OffsetDateTime else OffsetDateTime.now() - val date = DateExpression.executeDateExpression(base, expression).getOr { base } + val date = DateExpression.executeDateExpression(base, expression).getOr(base) return if (!format.isNullOrEmpty()) { date.format(DateTimeFormatter.ofPattern(format)) } else { @@ -409,7 +406,7 @@ data class TimeGenerator @JvmOverloads constructor( override fun generate(context: MutableMap, exampleValue: Any?): Any { val base = if (context.containsKey("baseTime")) context["baseTime"] as OffsetDateTime else OffsetDateTime.now() - val time = TimeExpression.executeTimeExpression(base, expression).getOr { base } + val time = TimeExpression.executeTimeExpression(base, expression).getOr(base) return if (!format.isNullOrEmpty()) { time.format(DateTimeFormatter.ofPattern(format)) } else { @@ -451,7 +448,7 @@ data class DateTimeGenerator @JvmOverloads constructor( override fun generate(context: MutableMap, exampleValue: Any?): Any { val base = if (context.containsKey("baseDateTime")) context["baseDateTime"] as OffsetDateTime else OffsetDateTime.now() - val datetime = DateTimeExpression.executeExpression(base, expression).getOr { base } + val datetime = DateTimeExpression.executeExpression(base, expression).getOr(base) return if (!format.isNullOrEmpty()) { datetime.toZonedDateTime().format(DateTimeFormatter.ofPattern(format).withZone(ZoneId.systemDefault())) } else { diff --git a/core/model/src/main/kotlin/au/com/dius/pact/core/model/generators/TimeExpression.kt b/core/model/src/main/kotlin/au/com/dius/pact/core/model/generators/TimeExpression.kt index fe8a8fb89a..aac60b3da1 100644 --- a/core/model/src/main/kotlin/au/com/dius/pact/core/model/generators/TimeExpression.kt +++ b/core/model/src/main/kotlin/au/com/dius/pact/core/model/generators/TimeExpression.kt @@ -1,14 +1,12 @@ package au.com.dius.pact.core.model.generators +import au.com.dius.pact.core.support.Result import au.com.dius.pact.core.support.generators.expressions.Adjustment import au.com.dius.pact.core.support.generators.expressions.Operation import au.com.dius.pact.core.support.generators.expressions.TimeBase import au.com.dius.pact.core.support.generators.expressions.TimeExpressionLexer import au.com.dius.pact.core.support.generators.expressions.TimeExpressionParser import au.com.dius.pact.core.support.generators.expressions.TimeOffsetType -import com.github.michaelbull.result.Err -import com.github.michaelbull.result.Ok -import com.github.michaelbull.result.Result import mu.KLogging import java.time.LocalTime import java.time.OffsetDateTime @@ -22,8 +20,8 @@ object TimeExpression : KLogging() { fun executeTimeExpression(base: OffsetDateTime, expression: String?): Result { return if (!expression.isNullOrEmpty()) { return when (val result = parseTimeExpression(expression)) { - is Err -> result - is Ok -> { + is Result.Err -> result + is Result.Ok -> { val midnight = OffsetDateTime.of(base.toLocalDate(), LocalTime.MIDNIGHT, ZoneOffset.from(base)) val noon = OffsetDateTime.of(base.toLocalDate(), LocalTime.NOON, ZoneOffset.from(base)) var time = when (val valBase = result.value.base) { @@ -58,11 +56,11 @@ object TimeExpression : KLogging() { } } - Ok(time) + Result.Ok(time) } } } else { - Ok(base) + Result.Ok(base) } } @@ -70,8 +68,8 @@ object TimeExpression : KLogging() { val lexer = TimeExpressionLexer(expression) val parser = TimeExpressionParser(lexer) return when (val result = parser.expression()) { - is Err -> Err("Error parsing expression: ${result.error}") - is Ok -> Ok(ParsedTimeExpression(result.value.first, result.value.second.toMutableList())) + is Result.Err -> Result.Err("Error parsing expression: ${result.error}") + is Result.Ok -> Result.Ok(ParsedTimeExpression(result.value.first, result.value.second.toMutableList())) } } } diff --git a/core/model/src/main/kotlin/au/com/dius/pact/core/model/matchingrules/expressions/MatcherDefinition.kt b/core/model/src/main/kotlin/au/com/dius/pact/core/model/matchingrules/expressions/MatcherDefinition.kt index 34ae3ecd9f..a19d62cebb 100644 --- a/core/model/src/main/kotlin/au/com/dius/pact/core/model/matchingrules/expressions/MatcherDefinition.kt +++ b/core/model/src/main/kotlin/au/com/dius/pact/core/model/matchingrules/expressions/MatcherDefinition.kt @@ -17,11 +17,9 @@ import au.com.dius.pact.core.model.matchingrules.TimeMatcher import au.com.dius.pact.core.model.matchingrules.TimestampMatcher import au.com.dius.pact.core.model.matchingrules.TypeMatcher import au.com.dius.pact.core.support.Either +import au.com.dius.pact.core.support.Result import au.com.dius.pact.core.support.isNotEmpty import au.com.dius.pact.core.support.parsers.StringLexer -import com.github.michaelbull.result.Err -import com.github.michaelbull.result.Ok -import com.github.michaelbull.result.Result class MatcherDefinitionLexer(expression: String): StringLexer(expression) { fun matchDecimal() = matchRegex(DECIMAL_LITERAL).isNotEmpty() @@ -60,7 +58,7 @@ class MatcherDefinitionParser(private val lexer: MatcherDefinitionLexer) { @Suppress("ReturnCount") fun matchingDefinition(): Result { val definition = when (val result = matchingDefinitionExp()) { - is Ok -> { + is Result.Ok -> { var definitions = result.value lexer.skipWhitespace() if (lexer.peekNextChar() == ',') { @@ -68,11 +66,11 @@ class MatcherDefinitionParser(private val lexer: MatcherDefinitionLexer) { lexer.advance() lexer.skipWhitespace() when (val additionalResult = matchingDefinitionExp()) { - is Ok -> { + is Result.Ok -> { definitions = definitions.merge(additionalResult.value) lexer.skipWhitespace() } - is Err -> return additionalResult + is Result.Err -> return additionalResult } } definitions @@ -80,13 +78,13 @@ class MatcherDefinitionParser(private val lexer: MatcherDefinitionLexer) { definitions } } - is Err -> return result + is Result.Err -> return result } return if (lexer.empty) { - Ok(definition) + Result.Ok(definition) } else { - Err("Error parsing expression: Unexpected characters '${lexer.remainder}' at ${lexer.index}") + Result.Err("Error parsing expression: Unexpected characters '${lexer.remainder}' at ${lexer.index}") } } @@ -114,17 +112,17 @@ class MatcherDefinitionParser(private val lexer: MatcherDefinitionLexer) { lexer.matchString("matching") -> { if (matchChar('(')) { when (val matchingRuleResult = matchingRule()) { - is Ok -> { + is Result.Ok -> { if (matchChar(')')) { if (matchingRuleResult.value.reference != null) { - Ok( + Result.Ok( MatchingRuleDefinition( matchingRuleResult.value.value, matchingRuleResult.value.reference!!, matchingRuleResult.value.generator ) ) } else { - Ok( + Result.Ok( MatchingRuleDefinition( matchingRuleResult.value.value, matchingRuleResult.value.rule, matchingRuleResult.value.generator @@ -132,66 +130,66 @@ class MatcherDefinitionParser(private val lexer: MatcherDefinitionLexer) { ) } } else { - Err("Was expecting a ')' at index ${lexer.index}") + Result.Err("Was expecting a ')' at index ${lexer.index}") } } - is Err -> return matchingRuleResult + is Result.Err -> return matchingRuleResult } } else { - Err("Was expecting a '(' at index ${lexer.index}") + Result.Err("Was expecting a '(' at index ${lexer.index}") } } lexer.matchString("notEmpty") -> { if (matchChar('(')) { when (val primitiveValueResult = primitiveValue()) { - is Ok -> { + is Result.Ok -> { if (matchChar(')')) { - Ok(MatchingRuleDefinition(primitiveValueResult.value.first, NotEmptyMatcher, null) + Result.Ok(MatchingRuleDefinition(primitiveValueResult.value.first, NotEmptyMatcher, null) .withType(primitiveValueResult.value.second)) } else { - Err("Was expecting a ')' at index ${lexer.index}") + Result.Err("Was expecting a ')' at index ${lexer.index}") } } - is Err -> return primitiveValueResult + is Result.Err -> return primitiveValueResult } } else { - Err("Was expecting a '(' at index ${lexer.index}") + Result.Err("Was expecting a '(' at index ${lexer.index}") } } lexer.matchString("eachKey") -> { if (matchChar('(')) { when (val definitionResult = matchingDefinitionExp()) { - is Ok -> { + is Result.Ok -> { if (matchChar(')')) { - Ok(MatchingRuleDefinition(null, EachKeyMatcher(definitionResult.value), null)) + Result.Ok(MatchingRuleDefinition(null, EachKeyMatcher(definitionResult.value), null)) } else { - Err("Was expecting a ')' at index ${lexer.index}") + Result.Err("Was expecting a ')' at index ${lexer.index}") } } - is Err -> return definitionResult + is Result.Err -> return definitionResult } } else { - Err("Was expecting a '(' at index ${lexer.index}") + Result.Err("Was expecting a '(' at index ${lexer.index}") } } lexer.matchString("eachValue") -> { if (matchChar('(')) { when (val definitionResult = matchingDefinitionExp()) { - is Ok -> { + is Result.Ok -> { if (matchChar(')')) { - Ok(MatchingRuleDefinition(null, ValueType.Unknown, + Result.Ok(MatchingRuleDefinition(null, ValueType.Unknown, listOf(Either.A(EachValueMatcher(definitionResult.value))), null)) } else { - Err("Was expecting a ')' at index ${lexer.index}") + Result.Err("Was expecting a ')' at index ${lexer.index}") } } - is Err -> return definitionResult + is Result.Err -> return definitionResult } } else { - Err("Was expecting a '(' at index ${lexer.index}") + Result.Err("Was expecting a '(' at index ${lexer.index}") } } - else -> Err("Was expecting a matching rule definition type at index ${lexer.index}") + else -> Result.Err("Was expecting a matching rule definition type at index ${lexer.index}") } } @@ -236,41 +234,41 @@ class MatcherDefinitionParser(private val lexer: MatcherDefinitionLexer) { lexer.matchString("semver") -> matchSemver() lexer.matchString("contentType") -> matchContentType() lexer.peekNextChar() == '$' -> matchReference() - else -> Err("Was expecting a matching rule definition at index ${lexer.index}") + else -> Result.Err("Was expecting a matching rule definition at index ${lexer.index}") } } private fun matchRegex() = if (matchChar(',')) { when (val regexResult = string()) { - is Ok -> { + is Result.Ok -> { if (regexResult.value != null) { if (matchChar(',')) { when (val stringResult = string()) { - is Ok -> Ok( + is Result.Ok -> Result.Ok( MatchingRuleResult(stringResult.value, ValueType.String, RegexMatcher(regexResult.value!!)) ) - is Err -> stringResult + is Result.Err -> stringResult } } else { - Err("Was expecting a ',' at index ${lexer.index}") + Result.Err("Was expecting a ',' at index ${lexer.index}") } } else { - Err("Regex can not be null (at index ${lexer.index})") + Result.Err("Regex can not be null (at index ${lexer.index})") } } - is Err -> regexResult + is Result.Err -> regexResult } } else { - Err("Was expecting a ',' at index ${lexer.index}") + Result.Err("Was expecting a ',' at index ${lexer.index}") } private fun matchDateTime(): Result { val type = lexer.lastMatch return if (matchChar(',')) { when (val formatResult = string()) { - is Ok -> { + is Result.Ok -> { val matcher = when (type) { "date" -> if (formatResult.value != null) DateMatcher(formatResult.value!!) else DateMatcher() "time" -> if (formatResult.value != null) TimeMatcher(formatResult.value!!) else TimeMatcher() @@ -278,80 +276,80 @@ class MatcherDefinitionParser(private val lexer: MatcherDefinitionLexer) { } if (matchChar(',')) { when (val stringResult = string()) { - is Ok -> Ok(MatchingRuleResult(stringResult.value, ValueType.String, matcher)) - is Err -> stringResult + is Result.Ok -> Result.Ok(MatchingRuleResult(stringResult.value, ValueType.String, matcher)) + is Result.Err -> stringResult } } else { - Err("Was expecting a ',' at index ${lexer.index}") + Result.Err("Was expecting a ',' at index ${lexer.index}") } } - is Err -> formatResult + is Result.Err -> formatResult } } else { - Err("Was expecting a ',' at index ${lexer.index}") + Result.Err("Was expecting a ',' at index ${lexer.index}") } } private fun matchDecimal() = if (matchChar(',')) { lexer.skipWhitespace() when { - lexer.matchDecimal() -> Ok( + lexer.matchDecimal() -> Result.Ok( MatchingRuleResult( lexer.lastMatch, ValueType.Decimal, NumberTypeMatcher(NumberTypeMatcher.NumberType.DECIMAL) ) ) - else -> Err("Was expecting a decimal number at index ${lexer.index}") + else -> Result.Err("Was expecting a decimal number at index ${lexer.index}") } } else { - Err("Was expecting a ',' at index ${lexer.index}") + Result.Err("Was expecting a ',' at index ${lexer.index}") } private fun matchInteger() = if (matchChar(',')) { lexer.skipWhitespace() when { - lexer.matchInteger() -> Ok( + lexer.matchInteger() -> Result.Ok( MatchingRuleResult( lexer.lastMatch, ValueType.Integer, NumberTypeMatcher(NumberTypeMatcher.NumberType.INTEGER) ) ) - else -> Err("Was expecting an integer at index ${lexer.index}") + else -> Result.Err("Was expecting an integer at index ${lexer.index}") } } else { - Err("Was expecting a ',' at index ${lexer.index}") + Result.Err("Was expecting a ',' at index ${lexer.index}") } private fun matchNumber() = if (matchChar(',')) { lexer.skipWhitespace() when { - lexer.matchDecimal() -> Ok( + lexer.matchDecimal() -> Result.Ok( MatchingRuleResult( lexer.lastMatch, ValueType.Number, NumberTypeMatcher(NumberTypeMatcher.NumberType.NUMBER) ) ) - lexer.matchInteger() -> Ok( + lexer.matchInteger() -> Result.Ok( MatchingRuleResult( lexer.lastMatch, ValueType.Number, NumberTypeMatcher(NumberTypeMatcher.NumberType.NUMBER) ) ) - else -> Err("Was expecting a number at index ${lexer.index}") + else -> Result.Err("Was expecting a number at index ${lexer.index}") } } else { - Err("Was expecting a ',' at index ${lexer.index}") + Result.Err("Was expecting a ',' at index ${lexer.index}") } private fun matchEqualOrType(equalTo: Boolean) = if (matchChar(',')) { when (val primitiveValueResult = primitiveValue()) { - is Ok -> { - Ok( + is Result.Ok -> { + Result.Ok( MatchingRuleResult( primitiveValueResult.value.first, primitiveValueResult.value.second, if (equalTo) EqualsMatcher else TypeMatcher @@ -359,81 +357,81 @@ class MatcherDefinitionParser(private val lexer: MatcherDefinitionLexer) { ) } - is Err -> primitiveValueResult + is Result.Err -> primitiveValueResult } } else { - Err("Was expecting a ',' at index ${lexer.index}") + Result.Err("Was expecting a ',' at index ${lexer.index}") } // 'include' COMMA s=string { $rule = new IncludeMatcher($s.contents); $value = $s.contents; $type = ValueType.String; } private fun matchInclude() = if (matchChar(',')) { when (val stringResult = string()) { - is Ok -> Ok(MatchingRuleResult(stringResult.value, ValueType.String, IncludeMatcher(stringResult.value.toString()))) - is Err -> stringResult + is Result.Ok -> Result.Ok(MatchingRuleResult(stringResult.value, ValueType.String, IncludeMatcher(stringResult.value.toString()))) + is Result.Err -> stringResult } } else { - Err("Was expecting a ',' at index ${lexer.index}") + Result.Err("Was expecting a ',' at index ${lexer.index}") } // 'boolean' COMMA BOOLEAN_LITERAL { $rule = BooleanMatcher.INSTANCE; $value = $BOOLEAN_LITERAL.getText(); $type = ValueType.Boolean; } private fun matchBoolean() = if (matchChar(',')) { lexer.skipWhitespace() if (lexer.matchBoolean()) { - Ok(MatchingRuleResult(lexer.lastMatch, ValueType.Boolean, BooleanMatcher)) + Result.Ok(MatchingRuleResult(lexer.lastMatch, ValueType.Boolean, BooleanMatcher)) } else { - Err("Was expecting a boolean value at index ${lexer.index}") + Result.Err("Was expecting a boolean value at index ${lexer.index}") } } else { - Err("Was expecting a ',' at index ${lexer.index}") + Result.Err("Was expecting a ',' at index ${lexer.index}") } // 'semver' COMMA s=string { $rule = SemverMatcher.INSTANCE; $value = $s.contents; $type = ValueType.String; } private fun matchSemver() = if (matchChar(',')) { when (val stringResult = string()) { - is Ok -> Ok(MatchingRuleResult(stringResult.value, ValueType.String, SemverMatcher)) - is Err -> stringResult + is Result.Ok -> Result.Ok(MatchingRuleResult(stringResult.value, ValueType.String, SemverMatcher)) + is Result.Err -> stringResult } } else { - Err("Was expecting a ',' at index ${lexer.index}") + Result.Err("Was expecting a ',' at index ${lexer.index}") } // 'contentType' COMMA ct=string COMMA s=string { $rule = new ContentTypeMatcher($ct.contents); $value = $s.contents; $type = ValueType.Unknown; } private fun matchContentType() = if (matchChar(',')) { when (val ctResult = string()) { - is Ok -> { + is Result.Ok -> { if (ctResult.value != null) { if (matchChar(',')) { when (val stringResult = string()) { - is Ok -> Ok( + is Result.Ok -> Result.Ok( MatchingRuleResult(stringResult.value, ValueType.Unknown, ContentTypeMatcher(ctResult.value!!)) ) - is Err -> stringResult + is Result.Err -> stringResult } } else { - Err("Was expecting a ',' at index ${lexer.index}") + Result.Err("Was expecting a ',' at index ${lexer.index}") } } else { - Err("Content type can not be null (at index ${lexer.index})") + Result.Err("Content type can not be null (at index ${lexer.index})") } } - is Err -> ctResult + is Result.Err -> ctResult } } else { - Err("Was expecting a ',' at index ${lexer.index}") + Result.Err("Was expecting a ',' at index ${lexer.index}") } // DOLLAR ref=string { $reference = new MatchingReference($ref.contents); $type = ValueType.Unknown; } private fun matchReference() = if (matchChar('$')) { when (val stringResult = string()) { - is Ok -> if (stringResult.value != null) { - Ok(MatchingRuleResult(null, ValueType.Unknown, null, null, MatchingReference(stringResult.value!!))) + is Result.Ok -> if (stringResult.value != null) { + Result.Ok(MatchingRuleResult(null, ValueType.Unknown, null, null, MatchingReference(stringResult.value!!))) } else { - Err("Matching reference value must not be null (at index ${lexer.index})") + Result.Err("Matching reference value must not be null (at index ${lexer.index})") } - is Err -> stringResult + is Result.Err -> stringResult } } else { - Err("Was expecting a '$' at index ${lexer.index}") + Result.Err("Was expecting a '$' at index ${lexer.index}") } // primitiveValue returns [ String value, ValueType type ] : @@ -447,15 +445,15 @@ class MatcherDefinitionParser(private val lexer: MatcherDefinitionLexer) { return when { lexer.peekNextChar() == '\'' -> { when (val stringResult = string()) { - is Ok -> Ok(stringResult.value to ValueType.String) - is Err -> stringResult + is Result.Ok -> Result.Ok(stringResult.value to ValueType.String) + is Result.Err -> stringResult } } - lexer.matchString("null") -> Ok(null to ValueType.String) - lexer.matchDecimal() -> Ok(lexer.lastMatch to ValueType.Decimal) - lexer.matchInteger() -> Ok(lexer.lastMatch to ValueType.Decimal) - lexer.matchBoolean() -> Ok(lexer.lastMatch to ValueType.Boolean) - else -> Err("Was expecting a primitive value at index ${lexer.index}") + lexer.matchString("null") -> Result.Ok(null to ValueType.String) + lexer.matchDecimal() -> Result.Ok(lexer.lastMatch to ValueType.Decimal) + lexer.matchInteger() -> Result.Ok(lexer.lastMatch to ValueType.Decimal) + lexer.matchBoolean() -> Result.Ok(lexer.lastMatch to ValueType.Boolean) + else -> Result.Err("Was expecting a primitive value at index ${lexer.index}") } } @@ -479,12 +477,12 @@ class MatcherDefinitionParser(private val lexer: MatcherDefinitionLexer) { if (ch == '\'') { lexer.advance() - Ok(stringResult) + Result.Ok(stringResult) } else { - Err("Unterminated string found at index ${lexer.index}") + Result.Err("Unterminated string found at index ${lexer.index}") } } else { - Err("Was expecting a string at index ${lexer.index}") + Result.Err("Was expecting a string at index ${lexer.index}") } } } diff --git a/core/model/src/main/kotlin/au/com/dius/pact/core/model/matchingrules/expressions/MatchingRuleDefinition.kt b/core/model/src/main/kotlin/au/com/dius/pact/core/model/matchingrules/expressions/MatchingRuleDefinition.kt index e4d12bfe06..d66208a2f5 100644 --- a/core/model/src/main/kotlin/au/com/dius/pact/core/model/matchingrules/expressions/MatchingRuleDefinition.kt +++ b/core/model/src/main/kotlin/au/com/dius/pact/core/model/matchingrules/expressions/MatchingRuleDefinition.kt @@ -3,10 +3,8 @@ package au.com.dius.pact.core.model.matchingrules.expressions import au.com.dius.pact.core.model.generators.Generator import au.com.dius.pact.core.model.matchingrules.MatchingRule import au.com.dius.pact.core.support.Either +import au.com.dius.pact.core.support.Result import au.com.dius.pact.core.support.isNotEmpty -import com.github.michaelbull.result.Err -import com.github.michaelbull.result.Ok -import com.github.michaelbull.result.Result import mu.KLogging data class MatchingReference( @@ -125,12 +123,12 @@ data class MatchingRuleDefinition( val lexer = MatcherDefinitionLexer(expression) val parser = MatcherDefinitionParser(lexer) return when (val result = parser.matchingDefinition()) { - is Ok -> if (result.value == null) { - Err("Error parsing expression") + is Result.Ok -> if (result.value == null) { + Result.Err("Error parsing expression") } else { - Ok(result.value!!) + Result.Ok(result.value!!) } - is Err -> Err("Error parsing expression: ${result.error}") + is Result.Err -> Result.Err("Error parsing expression: ${result.error}") } } } diff --git a/core/model/src/main/kotlin/au/com/dius/pact/core/model/messaging/MessagePact.kt b/core/model/src/main/kotlin/au/com/dius/pact/core/model/messaging/MessagePact.kt index 6a1fd4a58c..16bb72358f 100644 --- a/core/model/src/main/kotlin/au/com/dius/pact/core/model/messaging/MessagePact.kt +++ b/core/model/src/main/kotlin/au/com/dius/pact/core/model/messaging/MessagePact.kt @@ -13,13 +13,11 @@ import au.com.dius.pact.core.model.UnknownPactSource import au.com.dius.pact.core.model.V4Pact import au.com.dius.pact.core.support.Json import au.com.dius.pact.core.support.Json.extractFromJson +import au.com.dius.pact.core.support.Result import au.com.dius.pact.core.support.Utils.extractFromMap import au.com.dius.pact.core.support.json.JsonParser import au.com.dius.pact.core.support.json.JsonValue import au.com.dius.pact.core.support.jsonObject -import com.github.michaelbull.result.Err -import com.github.michaelbull.result.Ok -import com.github.michaelbull.result.Result import mu.KLogging import java.io.File @@ -80,12 +78,12 @@ class MessagePact @JvmOverloads constructor ( override fun isRequestResponsePact() = false override fun asRequestResponsePact() = - Err("A V3 Message Pact can not be converted to a V3 Request/Response Pact") + Result.Err("A V3 Message Pact can not be converted to a V3 Request/Response Pact") - override fun asMessagePact() = Ok(this) + override fun asMessagePact() = Result.Ok(this) override fun asV4Pact(): Result { - return Ok(V4Pact(consumer, provider, interactions.map { it.asV4Interaction() }.toMutableList(), metadata)) + return Result.Ok(V4Pact(consumer, provider, interactions.map { it.asV4Interaction() }.toMutableList(), metadata)) } override val interactions: MutableList diff --git a/core/model/src/main/kotlin/au/com/dius/pact/core/model/v4/V4InteractionType.kt b/core/model/src/main/kotlin/au/com/dius/pact/core/model/v4/V4InteractionType.kt index 0814ba7cfd..d783ad129e 100644 --- a/core/model/src/main/kotlin/au/com/dius/pact/core/model/v4/V4InteractionType.kt +++ b/core/model/src/main/kotlin/au/com/dius/pact/core/model/v4/V4InteractionType.kt @@ -1,8 +1,6 @@ package au.com.dius.pact.core.model.v4 -import com.github.michaelbull.result.Err -import com.github.michaelbull.result.Ok -import com.github.michaelbull.result.Result +import au.com.dius.pact.core.support.Result enum class V4InteractionType { SynchronousHTTP, @@ -20,10 +18,10 @@ enum class V4InteractionType { companion object { fun fromString(str: String): Result { return when (str) { - "Synchronous/HTTP" -> Ok(SynchronousHTTP) - "Asynchronous/Messages" -> Ok(AsynchronousMessages) - "Synchronous/Messages" -> Ok(SynchronousMessages) - else -> Err("'$str' is not a valid V4 interaction type") + "Synchronous/HTTP" -> Result.Ok(SynchronousHTTP) + "Asynchronous/Messages" -> Result.Ok(AsynchronousMessages) + "Synchronous/Messages" -> Result.Ok(SynchronousMessages) + else -> Result.Err("'$str' is not a valid V4 interaction type") } } } diff --git a/core/model/src/test/groovy/au/com/dius/pact/core/model/V3PactSpec.groovy b/core/model/src/test/groovy/au/com/dius/pact/core/model/V3PactSpec.groovy index daf4625cc0..b71e825a21 100644 --- a/core/model/src/test/groovy/au/com/dius/pact/core/model/V3PactSpec.groovy +++ b/core/model/src/test/groovy/au/com/dius/pact/core/model/V3PactSpec.groovy @@ -2,9 +2,8 @@ package au.com.dius.pact.core.model import au.com.dius.pact.core.model.messaging.MessagePact import au.com.dius.pact.core.support.Json +import au.com.dius.pact.core.support.Result import au.com.dius.pact.core.support.json.JsonParser -import com.github.michaelbull.result.Err -import com.github.michaelbull.result.Result import org.jetbrains.annotations.NotNull import spock.lang.Specification @@ -122,17 +121,17 @@ class V3PactSpec extends Specification { @Override Result asRequestResponsePact() { - new Err('Not implemented') + new Result.Err('Not implemented') } @Override Result asMessagePact() { - new Err('Not implemented') + new Result.Err('Not implemented') } @Override Result asV4Pact() { - new Err('Not implemented') + new Result.Err('Not implemented') } @Override @@ -188,17 +187,17 @@ class V3PactSpec extends Specification { @Override Result asRequestResponsePact() { - new Err('Not implemented') + new Result.Err('Not implemented') } @Override Result asMessagePact() { - new Err('Not implemented') + new Result.Err('Not implemented') } @Override Result asV4Pact() { - new Err('Not implemented') + new Result.Err('Not implemented') } @Override diff --git a/core/model/src/test/groovy/au/com/dius/pact/core/model/matchingrules/expressions/MatchingDefinitionParserSpec.groovy b/core/model/src/test/groovy/au/com/dius/pact/core/model/matchingrules/expressions/MatchingDefinitionParserSpec.groovy index 54e6942c6d..d1d298b727 100644 --- a/core/model/src/test/groovy/au/com/dius/pact/core/model/matchingrules/expressions/MatchingDefinitionParserSpec.groovy +++ b/core/model/src/test/groovy/au/com/dius/pact/core/model/matchingrules/expressions/MatchingDefinitionParserSpec.groovy @@ -12,14 +12,14 @@ import au.com.dius.pact.core.model.matchingrules.TimeMatcher import au.com.dius.pact.core.model.matchingrules.TimestampMatcher import au.com.dius.pact.core.model.matchingrules.TypeMatcher import au.com.dius.pact.core.support.Either -import com.github.michaelbull.result.Err +import au.com.dius.pact.core.support.Result import spock.lang.Specification @SuppressWarnings('LineLength') class MatchingDefinitionParserSpec extends Specification { def 'if the string does not start with a valid matching definition'() { expect: - MatchingRuleDefinition.parseMatchingRuleDefinition(expression) instanceof Err + MatchingRuleDefinition.parseMatchingRuleDefinition(expression) instanceof Result.Err where: @@ -32,7 +32,7 @@ class MatchingDefinitionParserSpec extends Specification { def 'parse type matcher'() { expect: - MatchingRuleDefinition.parseMatchingRuleDefinition(expression).component1() == + MatchingRuleDefinition.parseMatchingRuleDefinition(expression).value == new MatchingRuleDefinition('Name', TypeMatcher.INSTANCE, null) where: @@ -45,7 +45,7 @@ class MatchingDefinitionParserSpec extends Specification { def 'parse number matcher'() { expect: - MatchingRuleDefinition.parseMatchingRuleDefinition(expression).component1() == + MatchingRuleDefinition.parseMatchingRuleDefinition(expression).value == new MatchingRuleDefinition(value, new NumberTypeMatcher(matcher), null) where: @@ -60,7 +60,7 @@ class MatchingDefinitionParserSpec extends Specification { def 'invalid number matcher'() { expect: - MatchingRuleDefinition.parseMatchingRuleDefinition(expression) instanceof Err + MatchingRuleDefinition.parseMatchingRuleDefinition(expression) instanceof Result.Err where: @@ -71,7 +71,7 @@ class MatchingDefinitionParserSpec extends Specification { def 'parse datetime matcher'() { expect: - MatchingRuleDefinition.parseMatchingRuleDefinition(expression).component1() == + MatchingRuleDefinition.parseMatchingRuleDefinition(expression).value == new MatchingRuleDefinition(value, matcherClass.newInstance(format), null) where: @@ -85,7 +85,7 @@ class MatchingDefinitionParserSpec extends Specification { def 'parse regex matcher'() { expect: - MatchingRuleDefinition.parseMatchingRuleDefinition(expression).component1() == + MatchingRuleDefinition.parseMatchingRuleDefinition(expression).value == new MatchingRuleDefinition(value, new RegexMatcher(regex), null) where: @@ -97,7 +97,7 @@ class MatchingDefinitionParserSpec extends Specification { def 'invalid regex matcher'() { expect: - MatchingRuleDefinition.parseMatchingRuleDefinition(expression) instanceof Err + MatchingRuleDefinition.parseMatchingRuleDefinition(expression) instanceof Result.Err where: @@ -106,7 +106,7 @@ class MatchingDefinitionParserSpec extends Specification { def 'parse include matcher'() { expect: - MatchingRuleDefinition.parseMatchingRuleDefinition(expression).component1() == + MatchingRuleDefinition.parseMatchingRuleDefinition(expression).value == new MatchingRuleDefinition(value, new IncludeMatcher(value), null) where: @@ -118,7 +118,7 @@ class MatchingDefinitionParserSpec extends Specification { def 'parse boolean matcher'() { expect: - MatchingRuleDefinition.parseMatchingRuleDefinition(expression).component1() == + MatchingRuleDefinition.parseMatchingRuleDefinition(expression).value == new MatchingRuleDefinition(value, BooleanMatcher.INSTANCE, null) where: @@ -130,7 +130,7 @@ class MatchingDefinitionParserSpec extends Specification { def 'each key and value'() { expect: - MatchingRuleDefinition.parseMatchingRuleDefinition(expression).component1() == + MatchingRuleDefinition.parseMatchingRuleDefinition(expression).value == new MatchingRuleDefinition(null, ValueType.Unknown, value, null) where: @@ -143,7 +143,7 @@ class MatchingDefinitionParserSpec extends Specification { def 'invalid each key and value'() { expect: - MatchingRuleDefinition.parseMatchingRuleDefinition(expression) instanceof Err + MatchingRuleDefinition.parseMatchingRuleDefinition(expression) instanceof Result.Err where: @@ -155,7 +155,7 @@ class MatchingDefinitionParserSpec extends Specification { def 'parse notEmpty matcher'() { expect: - MatchingRuleDefinition.parseMatchingRuleDefinition(expression).component1() == + MatchingRuleDefinition.parseMatchingRuleDefinition(expression).value == new MatchingRuleDefinition(value, type, [ Either.a(NotEmptyMatcher.INSTANCE) ], null) where: diff --git a/core/pactbroker/build.gradle b/core/pactbroker/build.gradle index 5e274affe3..7d48830ab7 100644 --- a/core/pactbroker/build.gradle +++ b/core/pactbroker/build.gradle @@ -12,7 +12,6 @@ dependencies { implementation 'com.google.guava:guava' api 'io.github.microutils:kotlin-logging' api 'org.apache.httpcomponents.client5:httpclient5' - api 'com.michael-bull.kotlin-result:kotlin-result' implementation 'org.slf4j:slf4j-api' testImplementation 'org.apache.groovy:groovy' diff --git a/core/pactbroker/src/main/kotlin/au/com/dius/pact/core/pactbroker/HalClient.kt b/core/pactbroker/src/main/kotlin/au/com/dius/pact/core/pactbroker/HalClient.kt index 0fcab88959..06f28de22b 100644 --- a/core/pactbroker/src/main/kotlin/au/com/dius/pact/core/pactbroker/HalClient.kt +++ b/core/pactbroker/src/main/kotlin/au/com/dius/pact/core/pactbroker/HalClient.kt @@ -1,11 +1,12 @@ package au.com.dius.pact.core.pactbroker -import au.com.dius.pact.core.support.HttpClientUtils.buildUrl -import au.com.dius.pact.core.support.HttpClientUtils.isJsonResponse import au.com.dius.pact.core.support.Auth import au.com.dius.pact.core.support.HttpClient +import au.com.dius.pact.core.support.HttpClientUtils.buildUrl +import au.com.dius.pact.core.support.HttpClientUtils.isJsonResponse import au.com.dius.pact.core.support.Json import au.com.dius.pact.core.support.Json.fromJson +import au.com.dius.pact.core.support.Result import au.com.dius.pact.core.support.handleWith import au.com.dius.pact.core.support.isNotEmpty import au.com.dius.pact.core.support.json.JsonParser @@ -13,9 +14,6 @@ import au.com.dius.pact.core.support.json.JsonValue import au.com.dius.pact.core.support.json.get import au.com.dius.pact.core.support.jsonObject import au.com.dius.pact.core.support.unwrap -import com.github.michaelbull.result.Err -import com.github.michaelbull.result.Ok -import com.github.michaelbull.result.Result import com.google.common.net.UrlEscapers import mu.KLogging import org.apache.hc.client5.http.classic.methods.HttpGet @@ -207,7 +205,7 @@ open class HalClient @JvmOverloads constructor( handler(it.code, it) } else if (it.code >= 300) { logger.error { "PUT JSON request failed with status ${it.code} ${it.reasonPhrase}" } - Err(RequestFailedException(it.code, if (it.entity != null) EntityUtils.toString(it.entity) else null)) + Result.Err(RequestFailedException(it.code, if (it.entity != null) EntityUtils.toString(it.entity) else null)) } else { true } @@ -244,8 +242,8 @@ open class HalClient @JvmOverloads constructor( @Throws(InvalidNavigationRequest::class) override fun navigate(): IHalClient { when (val result = fetch(ROOT)) { - is Ok -> pathInfo = result.value - is Err -> { + is Result.Ok -> pathInfo = result.value + is Result.Err -> { logger.warn { "Failed to fetch the root HAL document" } throw InvalidNavigationRequest("Failed to fetch the root HAL document", result.error) } @@ -269,11 +267,11 @@ open class HalClient @JvmOverloads constructor( lastUrl = path logger.debug { "Fetching: $path" } return when (val result = getJson(path, encodePath)) { - is Ok -> when (result.value) { - is JsonValue.Object -> Ok(result.value) - else -> Err(RuntimeException("Expected a JSON document, but found a ${result.value}")) + is Result.Ok -> when (result.value) { + is JsonValue.Object -> Result.Ok(result.value) + else -> Result.Err(RuntimeException("Expected a JSON document, but found a ${result.value}")) } - is Err -> result + is Result.Err -> result } as Result } @@ -326,16 +324,16 @@ open class HalClient @JvmOverloads constructor( return if (response.code < 300) { val contentType = ContentType.parseLenient(response.entity.contentType) if (isJsonResponse(contentType)) { - Ok(JsonParser.parseString(EntityUtils.toString(response.entity))) + Result.Ok(JsonParser.parseString(EntityUtils.toString(response.entity))) } else { - Err(InvalidHalResponse("Expected a HAL+JSON response from the pact broker, but got '$contentType'")) + Result.Err(InvalidHalResponse("Expected a HAL+JSON response from the pact broker, but got '$contentType'")) } } else { when (response.code) { - 404 -> Err(NotFoundHalResponse("No HAL document found at path '$path'")) + 404 -> Result.Err(NotFoundHalResponse("No HAL document found at path '$path'")) else -> { val body = if (response.entity != null) EntityUtils.toString(response.entity) else null - Err(RequestFailedException(response.code, body, + Result.Err(RequestFailedException(response.code, body, "Request to path '$path' failed with response ${response.code}")) } } @@ -496,7 +494,7 @@ open class HalClient @JvmOverloads constructor( it.code < 300 -> if (it.entity != null) EntityUtils.toString(it.entity) else null else -> { logger.error { "PUT JSON request failed with status ${it.code} ${it.reasonPhrase}" } - Err(RequestFailedException(it.code, if (it.entity != null) EntityUtils.toString(it.entity) else null)) + Result.Err(RequestFailedException(it.code, if (it.entity != null) EntityUtils.toString(it.entity) else null)) } } } diff --git a/core/pactbroker/src/main/kotlin/au/com/dius/pact/core/pactbroker/PactBrokerClient.kt b/core/pactbroker/src/main/kotlin/au/com/dius/pact/core/pactbroker/PactBrokerClient.kt index 5dfceae924..2c67425784 100644 --- a/core/pactbroker/src/main/kotlin/au/com/dius/pact/core/pactbroker/PactBrokerClient.kt +++ b/core/pactbroker/src/main/kotlin/au/com/dius/pact/core/pactbroker/PactBrokerClient.kt @@ -1,6 +1,7 @@ package au.com.dius.pact.core.pactbroker import au.com.dius.pact.core.support.Json +import au.com.dius.pact.core.support.Result import au.com.dius.pact.core.support.Utils import au.com.dius.pact.core.support.Utils.lookupEnvironmentValue import au.com.dius.pact.core.support.handleWith @@ -11,15 +12,10 @@ import au.com.dius.pact.core.support.json.JsonValue import au.com.dius.pact.core.support.json.map import au.com.dius.pact.core.support.jsonArray import au.com.dius.pact.core.support.jsonObject +import au.com.dius.pact.core.support.mapOk +import au.com.dius.pact.core.support.mapError import au.com.dius.pact.core.support.toJson -import com.github.michaelbull.result.Err -import com.github.michaelbull.result.Ok -import com.github.michaelbull.result.Result -import com.github.michaelbull.result.map -import com.github.michaelbull.result.mapError -import com.github.michaelbull.result.unwrap import com.google.common.net.UrlEscapers.urlFormParameterEscaper -import com.google.common.net.UrlEscapers.urlPathSegmentEscaper import mu.KLogging import java.io.File import java.io.IOException @@ -491,8 +487,8 @@ open class PactBrokerClient( includeWipPactsSince: String? ): Result, Exception> { val halClient = when (val navigateResult = handleWith { newHalClient().navigate() }) { - is Err -> return navigateResult - is Ok -> navigateResult.value + is Result.Err -> return navigateResult + is Result.Ok -> navigateResult.value } val pactsForVerification = when { halClient.linkUrl(PROVIDER_PACTS_FOR_VERIFICATION) != null -> PROVIDER_PACTS_FOR_VERIFICATION @@ -586,7 +582,7 @@ open class PactBrokerClient( } return handleWith { - halClient.postJson(pactsForVerification, mapOf("provider" to providerName), body.serialise()).map { result -> + halClient.postJson(pactsForVerification, mapOf("provider" to providerName), body.serialise()).mapOk { result -> result["_embedded"]["pacts"].asArray().map { pactJson -> val selfLink = pactJson["_links"]["self"] val href = Json.toString(selfLink["href"]) @@ -630,8 +626,8 @@ open class PactBrokerClient( val publishContractsLink = halClient.linkUrl(PUBLISH_CONTRACTS_LINK) return if (publishContractsLink != null) { when (val result = publishContract(halClient, providerName, consumerName, config, pactText)) { - is Ok -> Ok("OK") - is Err -> result + is Result.Ok -> Result.Ok("OK") + is Result.Err -> result } } else { if (config.tags.isNotEmpty()) { @@ -684,15 +680,15 @@ open class PactBrokerClient( val body = JsonValue.Object(bodyValues) return when (val result = halClient.postJson(PUBLISH_CONTRACTS_LINK, mapOf(), body.serialise())) { - is Ok -> { + is Result.Ok -> { displayNotices(result.value) result } - is Err -> { + is Result.Err -> { val error = result.error if (error is RequestFailedException && error.body != null) { when (val json = handleWith { JsonParser.parseString(error.body) }) { - is Ok -> if (json.value is JsonValue.Object) { + is Result.Ok -> if (json.value is JsonValue.Object) { val body: JsonValue.Object = json.value.downcast() displayNotices(body) if (error.status == 400) { @@ -701,7 +697,7 @@ open class PactBrokerClient( } else { logger.error { "Response from Pact Broker was not in correct JSON format: got ${json.value}" } } - is Err -> { + is Result.Err -> { logger.error { "Response from Pact Broker was not in JSON format: ${json.error}" } } } @@ -797,20 +793,20 @@ open class PactBrokerClient( buildUrl: String? ): Result { val halClient = newHalClient() - val publishLink = docAttributes.mapKeys { it.key.toLowerCase() } ["pb:publish-verification-results"] + val publishLink = docAttributes.mapKeys { it.key.lowercase() } ["pb:publish-verification-results"] return if (publishLink is Map<*, *>) { val jsonObject = buildPayload(result, version, buildUrl) - val lowercaseMap = publishLink.mapKeys { it.key.toString().toLowerCase() } + val lowercaseMap = publishLink.mapKeys { it.key.toString().lowercase() } if (lowercaseMap.containsKey("href")) { halClient.postJson(lowercaseMap["href"].toString(), jsonObject.serialise()).mapError { logger.error(it) { "Publishing verification results failed with an exception" } "Publishing verification results failed with an exception: ${it.message}" } } else { - Err("Unable to publish verification results as there is no pb:publish-verification-results link") + Result.Err("Unable to publish verification results as there is no pb:publish-verification-results link") } } else { - Err("Unable to publish verification results as there is no pb:publish-verification-results link") + Result.Err("Unable to publish verification results as there is no pb:publish-verification-results link") } } @@ -919,8 +915,8 @@ open class PactBrokerClient( private fun logPublishingResults(halClient: IHalClient, version: String, tag: String, name: String) { when (val result = halClient.putJson(PROVIDER_TAG_VERSION, mapOf("version" to version, "tag" to tag), "{}")) { - is Ok<*> -> logger.debug { "Pushed tag $tag for provider $name and version $version" } - is Err -> logger.error(result.error) { + is Result.Ok -> logger.debug { "Pushed tag $tag for provider $name and version $version" } + is Result.Err -> logger.error(result.error) { "Failed to push tag $tag for provider $name and version $version" } } @@ -936,28 +932,28 @@ open class PactBrokerClient( val halClient = newHalClient() .withDocContext(docAttributes) .navigate(PROVIDER) - val initial: Result> = Ok(true) + val initial: Result> = Result.Ok(true) return tags.map { tagName -> val result = halClient.putJson(PROVIDER_TAG_VERSION, mapOf("version" to version, "tag" to tagName), "{}") when (result) { - is Ok<*> -> logger.debug { "Pushed tag $tagName for provider $name and version $version" } - is Err -> logger.error(result.error) { + is Result.Ok -> logger.debug { "Pushed tag $tagName for provider $name and version $version" } + is Result.Err -> logger.error(result.error) { "Failed to push tag $tagName for provider $name and version $version" } } result.mapError { err -> "Publishing tag '$tagName' failed: ${err.message ?: err.toString()}" } }.fold(initial) { result, v -> when { - result is Ok && v is Ok -> result - result is Ok && v is Err -> Err(listOf(v.error)) - result is Err && v is Ok -> result - result is Err && v is Err -> Err(result.error + v.error) + result is Result.Ok && v is Result.Ok -> result + result is Result.Ok && v is Result.Err -> Result.Err(listOf(v.error)) + result is Result.Err && v is Result.Ok -> result + result is Result.Err && v is Result.Err -> Result.Err(result.error + v.error) else -> result } } } catch (e: NotFoundHalResponse) { logger.error(e) { "Could not tag provider $name, link was missing" } - return Err(listOf("Could not tag provider $name, link was missing")) + return Result.Err(listOf("Could not tag provider $name, link was missing")) } } @@ -974,20 +970,20 @@ open class PactBrokerClient( val result = halClient.putJson(PROVIDER_BRANCH_VERSION, mapOf("version" to version, "branch" to branch), "{}") return when (result) { - is Ok<*> -> { + is Result.Ok<*> -> { logger.debug { "Pushed branch $branch for provider $name and version $version" } - Ok(true) + Result.Ok(true) } - is Err -> { + is Result.Err -> { logger.error(result.error) { "Failed to push branch $branch for provider $name and version $version" } - Err("Publishing branch '$branch' failed: ${result.error.message ?: result.error.toString()}") + Result.Err("Publishing branch '$branch' failed: ${result.error.message ?: result.error.toString()}") } } } catch (e: NotFoundHalResponse) { val message = "Could not create branch for provider $name, link was missing. It looks like your Pact Broker " + "does not support branches, please update to Pact Broker version 2.86.0 or later for branch support" logger.error(e) { message } - return Err(message) + return Result.Err(message) } } @@ -1009,7 +1005,7 @@ open class PactBrokerClient( { result -> !result.ok && result.unknown != null && result.unknown > 0 } ) { when (val result = halClient.getJson(path, false)) { - is Ok -> { + is Result.Ok -> { val summary: JsonValue.Object = result.value["summary"].downcast() val verificationResultUrl = result.value["matrix"].asArray() ?.get(0)?.asObject() @@ -1021,7 +1017,7 @@ open class PactBrokerClient( CanIDeployResult(Json.toBoolean(summary["deployable"]), "", Json.toString(summary["reason"]), Json.toInteger(summary["unknown"]), verificationResultUrl) } - is Err -> { + is Result.Err -> { logger.error(result.error) { "Pact broker matrix query failed: ${result.error.message}" } CanIDeployResult(false, result.error.message.toString(), "") } @@ -1061,7 +1057,7 @@ open class PactBrokerClient( tags: List ): Result { halClient.navigate() - var result = Ok("") as Result + var result = Result.Ok("") as Result tags.forEach { result = uploadTag(halClient, consumerName, version, it) } @@ -1080,7 +1076,7 @@ open class PactBrokerClient( "tag" to it ), "{}") - if (result is Err) { + if (result is Result.Err) { logger.error(result.error) { "Failed to push tag $it for consumer $consumerName and version $version" } } diff --git a/core/pactbroker/src/test/groovy/au/com/dius/pact/core/pactbroker/HalClientSpec.groovy b/core/pactbroker/src/test/groovy/au/com/dius/pact/core/pactbroker/HalClientSpec.groovy index 34b5470981..06e274b64d 100644 --- a/core/pactbroker/src/test/groovy/au/com/dius/pact/core/pactbroker/HalClientSpec.groovy +++ b/core/pactbroker/src/test/groovy/au/com/dius/pact/core/pactbroker/HalClientSpec.groovy @@ -1,8 +1,7 @@ package au.com.dius.pact.core.pactbroker +import au.com.dius.pact.core.support.Result import au.com.dius.pact.core.support.json.JsonParser -import com.github.michaelbull.result.Err -import com.github.michaelbull.result.Ok import org.apache.hc.client5.http.classic.methods.HttpPost import org.apache.hc.client5.http.impl.auth.BasicScheme import org.apache.hc.client5.http.impl.auth.SystemDefaultCredentialsProvider @@ -226,7 +225,7 @@ class HalClientSpec extends Specification { then: 1 * mockClient.execute({ it.uri.path == '/' }, _, _) >> { r, c, handler -> handler.handleResponse(mockResponse) } - result instanceof Ok + result instanceof Result.Ok } def 'uploading a JSON doc returns an error'() { @@ -243,7 +242,7 @@ class HalClientSpec extends Specification { then: 1 * mockClient.execute({ it.uri.path == '/' }, _, _) >> { r, c, handler -> handler.handleResponse(mockResponse) } - result instanceof Err + result instanceof Result.Err } def 'uploading a JSON doc unsuccessful due to 409'() { @@ -260,7 +259,7 @@ class HalClientSpec extends Specification { then: 1 * mockClient.execute({ it.uri.path == '/' }, _, _) >> { r, c, handler -> handler.handleResponse(mockResponse) } - result instanceof Err + result instanceof Result.Err } @Unroll @@ -302,8 +301,8 @@ class HalClientSpec extends Specification { where: success | status | expectedResult - 'success' | 200 | Ok - 'failure' | 400 | Err + 'success' | 200 | Result.Ok + 'failure' | 400 | Result.Err } def 'post URL returns a failure result if an exception is thrown'() { @@ -316,7 +315,7 @@ class HalClientSpec extends Specification { then: 1 * mockClient.execute(_, _, _) >> { throw new IOException('Boom!') } - result instanceof Err + result instanceof Result.Err } @SuppressWarnings('UnnecessaryGetter') diff --git a/core/pactbroker/src/test/groovy/au/com/dius/pact/core/pactbroker/PactBrokerClientSpec.groovy b/core/pactbroker/src/test/groovy/au/com/dius/pact/core/pactbroker/PactBrokerClientSpec.groovy index c62ef2d532..a58546680e 100644 --- a/core/pactbroker/src/test/groovy/au/com/dius/pact/core/pactbroker/PactBrokerClientSpec.groovy +++ b/core/pactbroker/src/test/groovy/au/com/dius/pact/core/pactbroker/PactBrokerClientSpec.groovy @@ -2,10 +2,9 @@ package au.com.dius.pact.core.pactbroker import au.com.dius.pact.core.support.Auth import au.com.dius.pact.core.support.Json +import au.com.dius.pact.core.support.Result import au.com.dius.pact.core.support.json.JsonParser import au.com.dius.pact.core.support.json.JsonValue -import com.github.michaelbull.result.Err -import com.github.michaelbull.result.Ok import kotlin.Pair import kotlin.collections.MapsKt import spock.lang.Issue @@ -226,7 +225,7 @@ class PactBrokerClientSpec extends Specification { then: 1 * halClient.putJson('pb:publish-pact', ['provider': 'Provider', 'consumer': 'Foo Consumer', 'consumerApplicationVersion': '10.0.0'], - pactContents) >> new Ok(false) + pactContents) >> new Result.Ok(false) !result.value } @@ -257,7 +256,7 @@ class PactBrokerClientSpec extends Specification { then: 1 * halClient.putJson('pb:publish-pact', ['provider': 'Provider/A', 'consumer': 'Foo Consumer/A', - 'consumerApplicationVersion': '10.0.0/B'], pactContents) >> new Ok(true) + 'consumerApplicationVersion': '10.0.0/B'], pactContents) >> new Result.Ok(true) 1 * halClient.putJson('pb:pacticipant-version-tag', ['pacticipant': 'Foo Consumer/A', 'version': '10.0.0/B', 'tag': 'A/B'], '{}') } @@ -289,12 +288,12 @@ class PactBrokerClientSpec extends Specification { then: 1 * halClient.putJson('pb:pacticipant-version-tag', - ['pacticipant': 'Foo Consumer/A', 'version': '10.0.0/B', 'tag': 'A/B'], '{}') >> new Ok(true) + ['pacticipant': 'Foo Consumer/A', 'version': '10.0.0/B', 'tag': 'A/B'], '{}') >> new Result.Ok(true) then: 1 * halClient.putJson('pb:publish-pact', ['provider': 'Provider/A', 'consumer': 'Foo Consumer/A', - 'consumerApplicationVersion': '10.0.0/B'], pactContents) >> new Ok(true) + 'consumerApplicationVersion': '10.0.0/B'], pactContents) >> new Result.Ok(true) } @Unroll @@ -305,7 +304,7 @@ class PactBrokerClientSpec extends Specification { PactBrokerClient client = Spy(PactBrokerClient, constructorArgs: ['baseUrl']) { newHalClient() >> halClient } - halClient.postJson('URL', _) >> new Ok(true) + halClient.postJson('URL', _) >> new Result.Ok(true) expect: client.publishVerificationResults(attributes, new TestResult.Ok(), '0', null).class.simpleName == result @@ -313,10 +312,10 @@ class PactBrokerClientSpec extends Specification { where: reason | attributes | result - 'there is no verification link' | [:] | Err.simpleName - 'the verification link has no href' | ['pb:publish-verification-results': [:]] | Err.simpleName - 'the broker client returns success' | ['pb:publish-verification-results': [href: 'URL']] | Ok.simpleName - 'the links have different case' | ['pb:Publish-Verification-Results': [HREF: 'URL']] | Ok.simpleName + 'there is no verification link' | [:] | Result.Err.simpleName + 'the verification link has no href' | ['pb:publish-verification-results': [:]] | Result.Err.simpleName + 'the broker client returns success' | ['pb:publish-verification-results': [href: 'URL']] | Result.Ok.simpleName + 'the links have different case' | ['pb:Publish-Verification-Results': [HREF: 'URL']] | Result.Ok.simpleName } def 'when fetching a pact, return the results as a Map'() { @@ -342,7 +341,7 @@ class PactBrokerClientSpec extends Specification { def result = client.fetchPact(url, true) then: - 1 * halClient.fetch(url, _) >> new Ok(json) + 1 * halClient.fetch(url, _) >> new Result.Ok(json) result.pactFile == Json.INSTANCE.toJson([a: 'a', b: 100, _links: [:], c: [true, 10.2, 'test']]) } @@ -352,7 +351,7 @@ class PactBrokerClientSpec extends Specification { PactBrokerClient client = Spy(PactBrokerClient, constructorArgs: ['baseUrl']) { newHalClient() >> halClient } - def uploadResult = new Ok(true) + def uploadResult = new Result.Ok(true) halClient.postJson(_, _) >> uploadResult def result = new TestResult.Failed([ [exception: new AssertionError('boom')] @@ -404,8 +403,8 @@ class PactBrokerClientSpec extends Specification { then: 1 * halClient.navigate() >> halClient 1 * halClient.linkUrl('pb:provider-pacts-for-verification') >> 'URL' - 1 * halClient.postJson('pb:provider-pacts-for-verification', [provider: 'provider'], json) >> new Ok(jsonResult) - result instanceof Ok + 1 * halClient.postJson('pb:provider-pacts-for-verification', [provider: 'provider'], json) >> new Result.Ok(jsonResult) + result instanceof Result.Ok result.value.first() == new PactBrokerResult('Pact between Foo Web Client (1.0.2) and Activity Service', 'https://test.pact.dius.com.au/pacts/provider/Activity%20Service/consumer/Foo%20Web%20Client/pact-version/384826ff3a2856e28dfae553efab302863dcd727', 'baseUrl', [], [ @@ -438,8 +437,8 @@ class PactBrokerClientSpec extends Specification { 1 * halClient.navigate() >> halClient 1 * halClient.linkUrl('pb:provider-pacts-for-verification') >> null 1 * halClient.linkUrl('beta:provider-pacts-for-verification') >> 'URL' - 1 * halClient.postJson('beta:provider-pacts-for-verification', _, _) >> new Ok(jsonResult) - result instanceof Ok + 1 * halClient.postJson('beta:provider-pacts-for-verification', _, _) >> new Result.Ok(jsonResult) + result instanceof Result.Ok } def 'fetching pacts with selectors falls back to the previous implementation if no link is available'() { @@ -458,7 +457,7 @@ class PactBrokerClientSpec extends Specification { 1 * halClient.linkUrl('beta:provider-pacts-for-verification') >> null 0 * halClient.postJson(_, _, _) 1 * client.fetchConsumers('provider') >> [] - result instanceof Ok + result instanceof Result.Ok } def 'fetching pacts with selectors does not include wip pacts when pending parameter is false'() { @@ -483,8 +482,8 @@ class PactBrokerClientSpec extends Specification { then: 1 * halClient.navigate() >> halClient 1 * halClient.linkUrl('pb:provider-pacts-for-verification') >> 'URL' - 1 * halClient.postJson('pb:provider-pacts-for-verification', [provider: 'provider'], json) >> new Ok(jsonResult) - result instanceof Ok + 1 * halClient.postJson('pb:provider-pacts-for-verification', [provider: 'provider'], json) >> new Result.Ok(jsonResult) + result instanceof Result.Ok } def 'fetching pacts with selectors includes wip pacts when parameter not blank'() { @@ -510,8 +509,8 @@ class PactBrokerClientSpec extends Specification { then: 1 * halClient.navigate() >> halClient 1 * halClient.linkUrl('pb:provider-pacts-for-verification') >> 'URL' - 1 * halClient.postJson('pb:provider-pacts-for-verification', [provider: 'provider'], json) >> new Ok(jsonResult) - result instanceof Ok + 1 * halClient.postJson('pb:provider-pacts-for-verification', [provider: 'provider'], json) >> new Result.Ok(jsonResult) + result instanceof Result.Ok } @Issue('#1227') @@ -532,7 +531,7 @@ class PactBrokerClientSpec extends Specification { 1 * halClient.linkUrl('beta:provider-pacts-for-verification') >> null 0 * halClient.postJson(_, _, _) 1 * client.fetchConsumers('provider') >> [] - result instanceof Ok + result instanceof Result.Ok } @Issue('#1241') @@ -564,7 +563,7 @@ class PactBrokerClientSpec extends Specification { def result = client.canIDeploy('test', '1.2.3', new Latest.UseLatest(true), '') then: - 3 * halClient.getJson(_, _) >> new Ok(json1) >> new Ok(json1) >> new Ok(json2) + 3 * halClient.getJson(_, _) >> new Result.Ok(json1) >> new Result.Ok(json1) >> new Result.Ok(json2) result.ok } @@ -589,7 +588,7 @@ class PactBrokerClientSpec extends Specification { 0 * halClient.postJson(_, _, _) 1 * client.fetchConsumersWithTag('provider', 'DEV') >> [] 1 * client.fetchConsumersWithTag('provider', 'MASTER') >> [] - result instanceof Ok + result instanceof Result.Ok } @Issue('#1322') @@ -612,8 +611,8 @@ class PactBrokerClientSpec extends Specification { new SSLHandshakeException('PKIX path building failed')) } notThrown(SSLHandshakeException) - result instanceof Err - result.component2() instanceof InvalidNavigationRequest + result instanceof Result.Err + result.error instanceof InvalidNavigationRequest } def 'when publishing provider tags, return an Ok result if it succeeds'() { @@ -625,10 +624,10 @@ class PactBrokerClientSpec extends Specification { newHalClient() >> halClient } def attributes = [:] - halClient.putJson('pb:version-tag', _, _) >> new Ok(true) + halClient.putJson('pb:version-tag', _, _) >> new Result.Ok(true) expect: - client.publishProviderTags(attributes, 'provider', ['0'], 'null') == new Ok(true) + client.publishProviderTags(attributes, 'provider', ['0'], 'null') == new Result.Ok(true) } def 'when publishing provider tags, return an error result if any tag fails'() { @@ -644,10 +643,10 @@ class PactBrokerClientSpec extends Specification { def result = client.publishProviderTags([:], 'provider', ['0', '1', '2'], 'null') then: - 1 * halClient.putJson('pb:version-tag', [version: 'null', tag: '0'], _) >> new Ok(true) - 1 * halClient.putJson('pb:version-tag', [version: 'null', tag: '1'], _) >> new Err(new RuntimeException('failed')) - 1 * halClient.putJson('pb:version-tag', [version: 'null', tag: '2'], _) >> new Ok(true) - result == new Err(["Publishing tag '1' failed: failed"]) + 1 * halClient.putJson('pb:version-tag', [version: 'null', tag: '0'], _) >> new Result.Ok(true) + 1 * halClient.putJson('pb:version-tag', [version: 'null', tag: '1'], _) >> new Result.Err(new RuntimeException('failed')) + 1 * halClient.putJson('pb:version-tag', [version: 'null', tag: '2'], _) >> new Result.Ok(true) + result == new Result.Err(["Publishing tag '1' failed: failed"]) } @RestoreSystemProperties @@ -714,7 +713,7 @@ class PactBrokerClientSpec extends Specification { pactBrokerClient.publishContract(mockHalClient, providerName, consumerName, config, pactText) then: - 1 * mockHalClient.postJson(PactBrokerClient.PUBLISH_CONTRACTS_LINK, [:], jsonBody) >> new Ok(new JsonValue.Object([:])) + 1 * mockHalClient.postJson(PactBrokerClient.PUBLISH_CONTRACTS_LINK, [:], jsonBody) >> new Result.Ok(new JsonValue.Object([:])) } @RestoreSystemProperties @@ -734,7 +733,7 @@ class PactBrokerClientSpec extends Specification { pactBrokerClient.publishContract(mockHalClient, providerName, consumerName, config, pactText) then: - 1 * mockHalClient.postJson(PactBrokerClient.PUBLISH_CONTRACTS_LINK, [:], jsonBody) >> new Ok(new JsonValue.Object([:])) + 1 * mockHalClient.postJson(PactBrokerClient.PUBLISH_CONTRACTS_LINK, [:], jsonBody) >> new Result.Ok(new JsonValue.Object([:])) } @RestoreSystemProperties @@ -755,7 +754,7 @@ class PactBrokerClientSpec extends Specification { pactBrokerClient.publishContract(mockHalClient, providerName, consumerName, config, pactText) then: - 1 * mockHalClient.postJson(PactBrokerClient.PUBLISH_CONTRACTS_LINK, [:], jsonBody) >> new Ok(new JsonValue.Object([:])) + 1 * mockHalClient.postJson(PactBrokerClient.PUBLISH_CONTRACTS_LINK, [:], jsonBody) >> new Result.Ok(new JsonValue.Object([:])) } @Issue('#1525') @@ -788,7 +787,7 @@ class PactBrokerClientSpec extends Specification { def result = client.canIDeploy('test', '1.2.3', new Latest.UseLatest(true), '') then: - 1 * halClient.getJson(_, _) >> new Ok(json) + 1 * halClient.getJson(_, _) >> new Result.Ok(json) result.ok result.verificationResultUrl == 'verificationResultUrl' } diff --git a/core/support/build.gradle b/core/support/build.gradle index 8dc1ea4a50..58b3aae5f8 100644 --- a/core/support/build.gradle +++ b/core/support/build.gradle @@ -9,7 +9,6 @@ dependencies { api 'io.github.microutils:kotlin-logging' api 'org.apache.httpcomponents.client5:httpclient5' api 'org.apache.httpcomponents.client5:httpclient5-fluent' - api 'com.michael-bull.kotlin-result:kotlin-result-jvm' implementation 'org.apache.commons:commons-text' diff --git a/core/support/src/main/java/au/com/dius/pact/core/support/json/BaseJsonLexer.java b/core/support/src/main/java/au/com/dius/pact/core/support/json/BaseJsonLexer.java index 0198616542..2294c4d3b2 100644 --- a/core/support/src/main/java/au/com/dius/pact/core/support/json/BaseJsonLexer.java +++ b/core/support/src/main/java/au/com/dius/pact/core/support/json/BaseJsonLexer.java @@ -1,8 +1,6 @@ package au.com.dius.pact.core.support.json; -import com.github.michaelbull.result.Err; -import com.github.michaelbull.result.Ok; -import com.github.michaelbull.result.Result; +import au.com.dius.pact.core.support.Result; import org.apache.commons.lang3.ArrayUtils; import java.util.function.Predicate; @@ -42,51 +40,51 @@ protected Result scanString() { case 'u': { Character u1 = json.nextChar(); if (u1 == null) { - return new Err(new JsonException(String.format( + return new Result.Err(new JsonException(String.format( "Invalid JSON (%s), Unicode characters require 4 hex digits", json.documentPointer()))); } else if (invalidHex(u1)) { - return new Err(new JsonException(String.format( + return new Result.Err(new JsonException(String.format( "Invalid JSON (%s), '%c' is not a valid hex code character", json.documentPointer(), u1))); } Character u2 = json.nextChar(); if (u2 == null) { - return new Err(new JsonException(String.format( + return new Result.Err(new JsonException(String.format( "Invalid JSON (%s), Unicode characters require 4 hex digits", json.documentPointer()))); } else if (invalidHex(u2)) { - return new Err(new JsonException(String.format( + return new Result.Err(new JsonException(String.format( "Invalid JSON (%s), '%c' is not a valid hex code character", json.documentPointer(), u2))); } Character u3 = json.nextChar(); if (u3 == null) { - return new Err(new JsonException(String.format( + return new Result.Err(new JsonException(String.format( "Invalid JSON (%s), Unicode characters require 4 hex digits", json.documentPointer()))); } else if (invalidHex(u3)) { - return new Err(new JsonException(String.format( + return new Result.Err(new JsonException(String.format( "Invalid JSON (%s), '%c' is not a valid hex code character", json.documentPointer(), u3))); } Character u4 = json.nextChar(); if (u4 == null) { - return new Err(new JsonException(String.format( + return new Result.Err(new JsonException(String.format( "Invalid JSON (%s), Unicode characters require 4 hex digits", json.documentPointer()))); } else if (invalidHex(u4)) { - return new Err(new JsonException(String.format( + return new Result.Err(new JsonException(String.format( "Invalid JSON (%s), '%c' is not a valid hex code character", json.documentPointer(), u4))); } int hex = Integer.parseInt(new String(new char[]{u1, u2, u3, u4}), 16); if (index >= buffer.length) { buffer = allocate(buffer); }; buffer[index++] = (char) hex; break; } - default: return new Err(new JsonException(String.format( + default: return new Result.Err(new JsonException(String.format( "Invalid JSON (%s), '%c' is not a valid escape code", json.documentPointer(), escapeCode))); } } else if (next == null) { - return new Err(new JsonException(String.format("Invalid JSON (%s), End of document scanning for string terminator", + return new Result.Err(new JsonException(String.format("Invalid JSON (%s), End of document scanning for string terminator", json.documentPointer()))); } else if (next != '"') { if (index >= buffer.length) { buffer = allocate(buffer); }; buffer[index++] = next; } } while (next != '"'); - return new Ok(new JsonToken.StringValue(ArrayUtils.subarray(buffer, 0, index))); + return new Result.Ok(new JsonToken.StringValue(ArrayUtils.subarray(buffer, 0, index))); } private char[] allocate(char[] buffer) { @@ -139,14 +137,14 @@ protected char[] consumeChars(Character first, Predicate predicate) { protected Result scanNumber(Character next) { char[] buffer = consumeChars(next, Character::isDigit); if (next == '-' && buffer.length == 1) { - return new Err(new JsonException(String.format( + return new Result.Err(new JsonException(String.format( "Invalid JSON (%s), found a '%c' that was not followed by any digits", json.documentPointer(), next))); } Character ch = json.peekNextChar(); if (ch != null && (ch == '.' || ch == 'e' || ch == 'E')) { return scanDecimalNumber(buffer); } else { - return new Ok(new JsonToken.Integer(buffer)); + return new Result.Ok(new JsonToken.Integer(buffer)); } } @@ -159,7 +157,7 @@ protected Result scanDecimalNumber(char[] buffer) { System.arraycopy(digits, 0, buffer, index, digits.length); index += digits.length; if (!Character.isDigit(buffer[index - 1])) { - return new Err(new JsonException(String.format("Invalid JSON (%s), '%s' is not a valid number", + return new Result.Err(new JsonException(String.format("Invalid JSON (%s), '%s' is not a valid number", json.documentPointer(), new String(ArrayUtils.subarray(buffer, 0, index))))); } next = json.peekNextChar(); @@ -175,10 +173,10 @@ protected Result scanDecimalNumber(char[] buffer) { System.arraycopy(digits, 0, buffer, index, digits.length); index += digits.length; if (!Character.isDigit(buffer[index - 1])) { - return new Err(new JsonException(String.format("Invalid JSON (%s), '%s' is not a valid number", + return new Result.Err(new JsonException(String.format("Invalid JSON (%s), '%s' is not a valid number", json.documentPointer(), new String(ArrayUtils.subarray(buffer, 0, index))))); } } - return new Ok(new JsonToken.Decimal(ArrayUtils.subarray(buffer, 0, index))); + return new Result.Ok(new JsonToken.Decimal(ArrayUtils.subarray(buffer, 0, index))); } } diff --git a/core/support/src/main/kotlin/au/com/dius/pact/core/support/KotlinLanguageSupport.kt b/core/support/src/main/kotlin/au/com/dius/pact/core/support/KotlinLanguageSupport.kt index a7601b4c6f..85feec1429 100644 --- a/core/support/src/main/kotlin/au/com/dius/pact/core/support/KotlinLanguageSupport.kt +++ b/core/support/src/main/kotlin/au/com/dius/pact/core/support/KotlinLanguageSupport.kt @@ -1,10 +1,6 @@ package au.com.dius.pact.core.support import au.com.dius.pact.core.support.json.JsonValue -import com.github.michaelbull.result.Err -import com.github.michaelbull.result.Ok -import com.github.michaelbull.result.Result -import com.github.michaelbull.result.UnwrapException import java.lang.Integer.max import java.net.URL import kotlin.reflect.KProperty1 @@ -37,21 +33,21 @@ public fun String?.toUrl() = if (this.isNullOrEmpty()) { public fun handleWith(f: () -> Any?): Result { return try { val result = f() - if (result is Result<*, *>) result as Result else Ok(result as F) + if (result is Result<*, *>) result as Result else Result.Ok(result as F) } catch (ex: Exception) { - Err(ex) + Result.Err(ex) } catch (ex: Throwable) { - Err(RuntimeException(ex)) + Result.Err(RuntimeException(ex)) } } public fun Result.unwrap(): A { when (this) { - is Err<*> -> when (error) { + is Result.Err<*> -> when (error) { is Throwable -> throw error as Throwable else -> throw UnwrapException(error.toString()) } - is Ok<*> -> return value as A + is Result.Ok<*> -> return value as A } } diff --git a/core/support/src/main/kotlin/au/com/dius/pact/core/support/Result.kt b/core/support/src/main/kotlin/au/com/dius/pact/core/support/Result.kt new file mode 100644 index 0000000000..c30132d843 --- /dev/null +++ b/core/support/src/main/kotlin/au/com/dius/pact/core/support/Result.kt @@ -0,0 +1,75 @@ +package au.com.dius.pact.core.support + +sealed class Result { + data class Ok(val value: V): Result() + data class Err(val error: E): Result() + + fun unwrap(): V { + when (this) { + is Ok -> return value + is Err -> if (error is Throwable) { + throw error + } else { + throw UnwrapException("Tried to unwrap an Err value $error") + } + } + } + + fun expect(function: () -> String): V { + when (this) { + is Ok -> return value + is Err -> throw UnwrapException(function()) + } + } + + fun get(): V? { + return when (this) { + is Err -> null + is Ok -> value + } + } + + fun errorValue(): E? { + return when (this) { + is Err -> error + is Ok -> null + } + } +} + +fun Result.mapOk(transform: (V1) -> V2): Result { + return when (this) { + is Result.Ok -> Result.Ok(transform(value)) + is Result.Err -> this + } +} + +fun Result.mapError(transform: (E1) -> E2): Result { + return when (this) { + is Result.Ok -> this + is Result.Err -> Result.Err(transform(error)) + } +} + +fun Result.mapEither(successFn: (V1) -> V2, errorFn: (E1) -> E2): Result { + return when (this) { + is Result.Err -> Result.Err(errorFn(error)) + is Result.Ok -> Result.Ok(successFn(value)) + } +} + +fun Result.getOr(default: V): V { + return when (this) { + is Result.Err -> default + is Result.Ok -> value + } +} + +fun Result.getOrElse(function: (E) -> V): V { + return when (this) { + is Result.Err -> function(error) + is Result.Ok -> value + } +} + +class UnwrapException(message: String): RuntimeException(message) diff --git a/core/support/src/main/kotlin/au/com/dius/pact/core/support/Utils.kt b/core/support/src/main/kotlin/au/com/dius/pact/core/support/Utils.kt index 3f774b2e94..fe72bfb9ec 100644 --- a/core/support/src/main/kotlin/au/com/dius/pact/core/support/Utils.kt +++ b/core/support/src/main/kotlin/au/com/dius/pact/core/support/Utils.kt @@ -1,8 +1,5 @@ package au.com.dius.pact.core.support -import com.github.michaelbull.result.Err -import com.github.michaelbull.result.Ok -import com.github.michaelbull.result.Result import mu.KLogging import org.apache.commons.lang3.RandomUtils import java.io.IOException @@ -169,12 +166,12 @@ object Utils : KLogging() { return if (matchResult != null) { val unitPower = DATA_SIZES.indexOf(matchResult.groupValues[2]) if (unitPower >= 0) { - Ok(Integer.parseInt(matchResult.groupValues[1]) * 1024.0.pow(unitPower).toInt()) + Result.Ok(Integer.parseInt(matchResult.groupValues[1]) * 1024.0.pow(unitPower).toInt()) } else { - Err("'$value' is not a valid data size") + Result.Err("'$value' is not a valid data size") } } else { - Err("'$value' is not a valid data size") + Result.Err("'$value' is not a valid data size") } } diff --git a/core/support/src/main/kotlin/au/com/dius/pact/core/support/Version.kt b/core/support/src/main/kotlin/au/com/dius/pact/core/support/Version.kt index 55720e5499..c5ec97d412 100644 --- a/core/support/src/main/kotlin/au/com/dius/pact/core/support/Version.kt +++ b/core/support/src/main/kotlin/au/com/dius/pact/core/support/Version.kt @@ -1,9 +1,6 @@ package au.com.dius.pact.core.support import au.com.dius.pact.core.support.parsers.StringLexer -import com.github.michaelbull.result.Err -import com.github.michaelbull.result.Ok -import com.github.michaelbull.result.Result data class Version( var major: Int, @@ -25,34 +22,34 @@ data class Version( val lexer = StringLexer(version) val major = when (val result = lexer.parseInt()) { - is Ok -> result.value - is Err -> return result + is Result.Ok -> result.value + is Result.Err -> return result } val err = parseChar('.', lexer) if (err != null) { - return Err(err) + return Result.Err(err) } val minor = when (val result = lexer.parseInt()) { - is Ok -> result.value - is Err -> return result + is Result.Ok -> result.value + is Result.Err -> return result } return when { lexer.peekNextChar() == '.' -> { lexer.advance() when (val result = lexer.parseInt()) { - is Ok -> if (lexer.empty) { - Ok(Version(major, minor, result.value)) + is Result.Ok -> if (lexer.empty) { + Result.Ok(Version(major, minor, result.value)) } else { - Err("Unexpected characters '${lexer.remainder}' at index ${lexer.index}") + Result.Err("Unexpected characters '${lexer.remainder}' at index ${lexer.index}") } - is Err -> result + is Result.Err -> result } } - lexer.empty -> Ok(Version(major, minor)) - else -> Err("Unexpected characters '${lexer.remainder}' at index ${lexer.index}") + lexer.empty -> Result.Ok(Version(major, minor)) + else -> Result.Err("Unexpected characters '${lexer.remainder}' at index ${lexer.index}") } } diff --git a/core/support/src/main/kotlin/au/com/dius/pact/core/support/generators/expressions/DateExpression.kt b/core/support/src/main/kotlin/au/com/dius/pact/core/support/generators/expressions/DateExpression.kt index 457439b963..1c467deae2 100644 --- a/core/support/src/main/kotlin/au/com/dius/pact/core/support/generators/expressions/DateExpression.kt +++ b/core/support/src/main/kotlin/au/com/dius/pact/core/support/generators/expressions/DateExpression.kt @@ -1,9 +1,7 @@ package au.com.dius.pact.core.support.generators.expressions +import au.com.dius.pact.core.support.Result import au.com.dius.pact.core.support.parsers.StringLexer -import com.github.michaelbull.result.Err -import com.github.michaelbull.result.Ok -import com.github.michaelbull.result.Result class DateExpressionLexer(expression: String): StringLexer(expression) { fun parseDateBase(): DateBase? { @@ -64,46 +62,46 @@ class DateExpressionParser(private val lexer: DateExpressionLexer) { val baseResult = base() if (baseResult != null) { return when (val opResult = parseOp()) { - is Ok -> if (opResult.value != null) { - Ok(baseResult to opResult.value!!) + is Result.Ok -> if (opResult.value != null) { + Result.Ok(baseResult to opResult.value!!) } else { - Ok(baseResult to emptyList()) + Result.Ok(baseResult to emptyList()) } - is Err -> opResult + is Result.Err -> opResult } } when (val opResult = parseOp()) { - is Ok -> if (opResult.value != null) { - return Ok(dateBase to opResult.value!!) + is Result.Ok -> if (opResult.value != null) { + return Result.Ok(dateBase to opResult.value!!) } - is Err -> return opResult + is Result.Err -> return opResult } val nextOrLastResult = parseNextOrLast() if (nextOrLastResult != null) { return when (val offsetResult = offset()) { - is Ok -> { + is Result.Ok -> { val adj = mutableListOf>() adj.add(Adjustment(offsetResult.value.first, offsetResult.value.second, nextOrLastResult)) when (val opResult = parseOp()) { - is Ok -> if (opResult.value != null) { - adj.addAll(opResult.value!!) - Ok(dateBase to adj) + is Result.Ok -> if (opResult.value != null) { + adj.addAll(opResult.value) + Result.Ok(dateBase to adj) } else { - Ok(dateBase to adj) + Result.Ok(dateBase to adj) } - is Err -> opResult + is Result.Err -> opResult } } - is Err -> offsetResult + is Result.Err -> offsetResult } } return if (lexer.empty) { - Ok(dateBase to emptyList()) + Result.Ok(dateBase to emptyList>()) } else { - Err("Error parsing expression: Unexpected characters '${lexer.remainder}' at ${lexer.index}") + Result.Err("Error parsing expression: Unexpected characters '${lexer.remainder}' at ${lexer.index}") } } @@ -123,14 +121,14 @@ class DateExpressionParser(private val lexer: DateExpressionLexer) { if (opResult != null) { while (opResult != null) { when (val durationResult = duration()) { - is Ok -> adj.add(durationResult.value.withOperation(opResult)) - is Err -> return durationResult + is Result.Ok -> adj.add(durationResult.value.withOperation(opResult)) + is Result.Err -> return durationResult } opResult = op() } - return Ok(adj) + return Result.Ok(adj) } - return Ok(null) + return Result.Ok(null) } //base returns [ DateBase t ] : 'now' { $t = DateBase.NOW; } @@ -148,15 +146,15 @@ class DateExpressionParser(private val lexer: DateExpressionLexer) { lexer.skipWhitespace() val intResult = when (val result = lexer.parseInt()) { - is Ok -> result.value - is Err -> return result + is Result.Ok -> result.value + is Result.Err -> return result } val durationTypeResult = durationType() return if (durationTypeResult != null) { - Ok(Adjustment(durationTypeResult, intResult)) + Result.Ok(Adjustment(durationTypeResult, intResult)) } else { - Err("Was expecting a duration type at index ${lexer.index}") + Result.Err("Was expecting a duration type at index ${lexer.index}") } } @@ -228,49 +226,49 @@ class DateExpressionParser(private val lexer: DateExpressionLexer) { fun offset(): Result, String> { lexer.skipWhitespace() return when { - lexer.matchString("day") -> Ok(DateOffsetType.DAY to 1) - lexer.matchString("week") -> Ok(DateOffsetType.WEEK to 1) - lexer.matchString("month") -> Ok(DateOffsetType.MONTH to 1) - lexer.matchString("year") -> Ok(DateOffsetType.YEAR to 1) - lexer.matchString("fortnight") -> Ok(DateOffsetType.WEEK to 2) - lexer.matchString("monday") -> Ok(DateOffsetType.MONDAY to 1) - lexer.matchString("mon") -> Ok(DateOffsetType.MONDAY to 1) - lexer.matchString("tuesday") -> Ok(DateOffsetType.TUESDAY to 1) - lexer.matchString("tues") -> Ok(DateOffsetType.TUESDAY to 1) - lexer.matchString("wednesday") -> Ok(DateOffsetType.WEDNESDAY to 1) - lexer.matchString("wed") -> Ok(DateOffsetType.WEDNESDAY to 1) - lexer.matchString("thursday") -> Ok(DateOffsetType.THURSDAY to 1) - lexer.matchString("thurs") -> Ok(DateOffsetType.THURSDAY to 1) - lexer.matchString("friday") -> Ok(DateOffsetType.FRIDAY to 1) - lexer.matchString("fri") -> Ok(DateOffsetType.FRIDAY to 1) - lexer.matchString("saturday") -> Ok(DateOffsetType.SATURDAY to 1) - lexer.matchString("sat") -> Ok(DateOffsetType.SATURDAY to 1) - lexer.matchString("sunday") -> Ok(DateOffsetType.SUNDAY to 1) - lexer.matchString("sun") -> Ok(DateOffsetType.SUNDAY to 1) - lexer.matchString("january") -> Ok(DateOffsetType.JAN to 1) - lexer.matchString("jan") -> Ok(DateOffsetType.JAN to 1) - lexer.matchString("february") -> Ok(DateOffsetType.FEB to 1) - lexer.matchString("feb") -> Ok(DateOffsetType.FEB to 1) - lexer.matchString("march") -> Ok(DateOffsetType.MAR to 1) - lexer.matchString("mar") -> Ok(DateOffsetType.MAR to 1) - lexer.matchString("april") -> Ok(DateOffsetType.APR to 1) - lexer.matchString("apr") -> Ok(DateOffsetType.APR to 1) - lexer.matchString("may") -> Ok(DateOffsetType.MAY to 1) - lexer.matchString("june") -> Ok(DateOffsetType.JUNE to 1) - lexer.matchString("jun") -> Ok(DateOffsetType.JUNE to 1) - lexer.matchString("july") -> Ok(DateOffsetType.JULY to 1) - lexer.matchString("jul") -> Ok(DateOffsetType.JULY to 1) - lexer.matchString("august") -> Ok(DateOffsetType.AUG to 1) - lexer.matchString("aug") -> Ok(DateOffsetType.AUG to 1) - lexer.matchString("september") -> Ok(DateOffsetType.SEP to 1) - lexer.matchString("sep") -> Ok(DateOffsetType.SEP to 1) - lexer.matchString("october") -> Ok(DateOffsetType.OCT to 1) - lexer.matchString("oct") -> Ok(DateOffsetType.OCT to 1) - lexer.matchString("november") -> Ok(DateOffsetType.NOV to 1) - lexer.matchString("nov") -> Ok(DateOffsetType.NOV to 1) - lexer.matchString("december") -> Ok(DateOffsetType.DEC to 1) - lexer.matchString("dec") -> Ok(DateOffsetType.DEC to 1) - else -> Err("Was expecting an offset type at index ${lexer.index}") + lexer.matchString("day") -> Result.Ok(DateOffsetType.DAY to 1) + lexer.matchString("week") -> Result.Ok(DateOffsetType.WEEK to 1) + lexer.matchString("month") -> Result.Ok(DateOffsetType.MONTH to 1) + lexer.matchString("year") -> Result.Ok(DateOffsetType.YEAR to 1) + lexer.matchString("fortnight") -> Result.Ok(DateOffsetType.WEEK to 2) + lexer.matchString("monday") -> Result.Ok(DateOffsetType.MONDAY to 1) + lexer.matchString("mon") -> Result.Ok(DateOffsetType.MONDAY to 1) + lexer.matchString("tuesday") -> Result.Ok(DateOffsetType.TUESDAY to 1) + lexer.matchString("tues") -> Result.Ok(DateOffsetType.TUESDAY to 1) + lexer.matchString("wednesday") -> Result.Ok(DateOffsetType.WEDNESDAY to 1) + lexer.matchString("wed") -> Result.Ok(DateOffsetType.WEDNESDAY to 1) + lexer.matchString("thursday") -> Result.Ok(DateOffsetType.THURSDAY to 1) + lexer.matchString("thurs") -> Result.Ok(DateOffsetType.THURSDAY to 1) + lexer.matchString("friday") -> Result.Ok(DateOffsetType.FRIDAY to 1) + lexer.matchString("fri") -> Result.Ok(DateOffsetType.FRIDAY to 1) + lexer.matchString("saturday") -> Result.Ok(DateOffsetType.SATURDAY to 1) + lexer.matchString("sat") -> Result.Ok(DateOffsetType.SATURDAY to 1) + lexer.matchString("sunday") -> Result.Ok(DateOffsetType.SUNDAY to 1) + lexer.matchString("sun") -> Result.Ok(DateOffsetType.SUNDAY to 1) + lexer.matchString("january") -> Result.Ok(DateOffsetType.JAN to 1) + lexer.matchString("jan") -> Result.Ok(DateOffsetType.JAN to 1) + lexer.matchString("february") -> Result.Ok(DateOffsetType.FEB to 1) + lexer.matchString("feb") -> Result.Ok(DateOffsetType.FEB to 1) + lexer.matchString("march") -> Result.Ok(DateOffsetType.MAR to 1) + lexer.matchString("mar") -> Result.Ok(DateOffsetType.MAR to 1) + lexer.matchString("april") -> Result.Ok(DateOffsetType.APR to 1) + lexer.matchString("apr") -> Result.Ok(DateOffsetType.APR to 1) + lexer.matchString("may") -> Result.Ok(DateOffsetType.MAY to 1) + lexer.matchString("june") -> Result.Ok(DateOffsetType.JUNE to 1) + lexer.matchString("jun") -> Result.Ok(DateOffsetType.JUNE to 1) + lexer.matchString("july") -> Result.Ok(DateOffsetType.JULY to 1) + lexer.matchString("jul") -> Result.Ok(DateOffsetType.JULY to 1) + lexer.matchString("august") -> Result.Ok(DateOffsetType.AUG to 1) + lexer.matchString("aug") -> Result.Ok(DateOffsetType.AUG to 1) + lexer.matchString("september") -> Result.Ok(DateOffsetType.SEP to 1) + lexer.matchString("sep") -> Result.Ok(DateOffsetType.SEP to 1) + lexer.matchString("october") -> Result.Ok(DateOffsetType.OCT to 1) + lexer.matchString("oct") -> Result.Ok(DateOffsetType.OCT to 1) + lexer.matchString("november") -> Result.Ok(DateOffsetType.NOV to 1) + lexer.matchString("nov") -> Result.Ok(DateOffsetType.NOV to 1) + lexer.matchString("december") -> Result.Ok(DateOffsetType.DEC to 1) + lexer.matchString("dec") -> Result.Ok(DateOffsetType.DEC to 1) + else -> Result.Err("Was expecting an offset type at index ${lexer.index}") } } } diff --git a/core/support/src/main/kotlin/au/com/dius/pact/core/support/generators/expressions/TimeExpression.kt b/core/support/src/main/kotlin/au/com/dius/pact/core/support/generators/expressions/TimeExpression.kt index f4ff42ccd4..a946255ea4 100644 --- a/core/support/src/main/kotlin/au/com/dius/pact/core/support/generators/expressions/TimeExpression.kt +++ b/core/support/src/main/kotlin/au/com/dius/pact/core/support/generators/expressions/TimeExpression.kt @@ -1,9 +1,7 @@ package au.com.dius.pact.core.support.generators.expressions +import au.com.dius.pact.core.support.Result import au.com.dius.pact.core.support.parsers.StringLexer -import com.github.michaelbull.result.Err -import com.github.michaelbull.result.Ok -import com.github.michaelbull.result.Result class TimeExpressionLexer(expression: String): StringLexer(expression) { companion object { @@ -33,50 +31,50 @@ class TimeExpressionParser(private val lexer: TimeExpressionLexer) { val timeBase = TimeBase.Now val baseResult = base() - if (baseResult is Ok && baseResult.value != null) { + if (baseResult is Result.Ok && baseResult.value != null) { return when (val opResult = parseOp()) { - is Ok -> if (opResult.value != null) { - Ok(baseResult.value!! to opResult.value!!) + is Result.Ok -> if (opResult.value != null) { + Result.Ok(baseResult.value to opResult.value) } else { - Ok(baseResult.value!! to emptyList()) + Result.Ok(baseResult.value to emptyList()) } - is Err -> opResult + is Result.Err -> opResult } - } else if (baseResult is Err) { + } else if (baseResult is Result.Err) { return baseResult } when (val opResult = parseOp()) { - is Ok -> if (opResult.value != null) { - return Ok(timeBase to opResult.value!!) + is Result.Ok -> if (opResult.value != null) { + return Result.Ok(timeBase to opResult.value) } - is Err -> return opResult + is Result.Err -> return opResult } val nextOrLastResult = parseNextOrLast() if (nextOrLastResult != null) { return when (val offsetResult = offset()) { - is Ok -> { + is Result.Ok -> { val adj = mutableListOf>() adj.add(Adjustment(offsetResult.value.first, offsetResult.value.second, nextOrLastResult)) when (val opResult = parseOp()) { - is Ok -> if (opResult.value != null) { - adj.addAll(opResult.value!!) - Ok(timeBase to adj) + is Result.Ok -> if (opResult.value != null) { + adj.addAll(opResult.value) + Result.Ok(timeBase to adj) } else { - Ok(timeBase to adj) + Result.Ok(timeBase to adj) } - is Err -> opResult + is Result.Err -> opResult } } - is Err -> offsetResult + is Result.Err -> offsetResult } } return if (lexer.empty) { - Ok(timeBase to emptyList()) + Result.Ok(timeBase to emptyList()) } else { - Err("Unexpected characters '${lexer.remainder}' at index ${lexer.index}") + Result.Err("Unexpected characters '${lexer.remainder}' at index ${lexer.index}") } } @@ -87,14 +85,14 @@ class TimeExpressionParser(private val lexer: TimeExpressionLexer) { if (opResult != null) { while (opResult != null) { when (val durationResult = duration()) { - is Ok -> adj.add(durationResult.value.withOperation(opResult)) - is Err -> return durationResult + is Result.Ok -> adj.add(durationResult.value.withOperation(opResult)) + is Result.Err -> return durationResult } opResult = op() } - return Ok(adj) + return Result.Ok(adj) } - return Ok(null) + return Result.Ok(null) } //base returns [ TimeBase t ] : 'now' { $t = TimeBase.Now.INSTANCE; } @@ -109,15 +107,15 @@ class TimeExpressionParser(private val lexer: TimeExpressionLexer) { return if (result != null) { val intValue = result.toInt() when (val hourResult = oclock()) { - is Ok -> Ok(TimeBase.of(intValue, hourResult.value)) - is Err -> Err(hourResult.error) + is Result.Ok -> Result.Ok(TimeBase.of(intValue, hourResult.value)) + is Result.Err -> Result.Err(hourResult.error) } } else { when { - lexer.matchString("now") -> Ok(TimeBase.Now) - lexer.matchString("midnight") -> Ok(TimeBase.Midnight) - lexer.matchString("noon") -> Ok(TimeBase.Noon) - else -> Ok(null) + lexer.matchString("now") -> Result.Ok(TimeBase.Now) + lexer.matchString("midnight") -> Result.Ok(TimeBase.Midnight) + lexer.matchString("noon") -> Result.Ok(TimeBase.Noon) + else -> Result.Ok(null) } } } @@ -130,12 +128,12 @@ class TimeExpressionParser(private val lexer: TimeExpressionLexer) { return if (lexer.matchString("o'clock")) { lexer.skipWhitespace() when { - lexer.matchString("am") -> Ok(ClockHour.AM) - lexer.matchString("pm") -> Ok(ClockHour.PM) - else -> Ok(ClockHour.NEXT) + lexer.matchString("am") -> Result.Ok(ClockHour.AM) + lexer.matchString("pm") -> Result.Ok(ClockHour.PM) + else -> Result.Ok(ClockHour.NEXT) } } else { - Err("Was expecting a clock hour at index ${lexer.index}") + Result.Err("Was expecting a clock hour at index ${lexer.index}") } } @@ -144,15 +142,15 @@ class TimeExpressionParser(private val lexer: TimeExpressionLexer) { lexer.skipWhitespace() val intResult = when (val result = lexer.parseInt()) { - is Ok -> result.value - is Err -> return result + is Result.Ok -> result.value + is Result.Err -> return result } val durationTypeResult = durationType() return if (durationTypeResult != null) { - Ok(Adjustment(durationTypeResult, intResult)) + Result.Ok(Adjustment(durationTypeResult, intResult)) } else { - Err("Was expecting a duration type at index ${lexer.index}") + Result.Err("Was expecting a duration type at index ${lexer.index}") } } @@ -196,11 +194,11 @@ class TimeExpressionParser(private val lexer: TimeExpressionLexer) { fun offset(): Result, String> { lexer.skipWhitespace() return when { - lexer.matchString("hour") -> Ok(TimeOffsetType.HOUR to 1) - lexer.matchString("minute") -> Ok(TimeOffsetType.MINUTE to 1) - lexer.matchString("second") -> Ok(TimeOffsetType.SECOND to 1) - lexer.matchString("millisecond") -> Ok(TimeOffsetType.MILLISECOND to 1) - else -> Err("Was expecting an offset type at index ${lexer.index}") + lexer.matchString("hour") -> Result.Ok(TimeOffsetType.HOUR to 1) + lexer.matchString("minute") -> Result.Ok(TimeOffsetType.MINUTE to 1) + lexer.matchString("second") -> Result.Ok(TimeOffsetType.SECOND to 1) + lexer.matchString("millisecond") -> Result.Ok(TimeOffsetType.MILLISECOND to 1) + else -> Result.Err("Was expecting an offset type at index ${lexer.index}") } } diff --git a/core/support/src/main/kotlin/au/com/dius/pact/core/support/json/JsonParser.kt b/core/support/src/main/kotlin/au/com/dius/pact/core/support/json/JsonParser.kt index 840a5bbad7..b3739ca879 100644 --- a/core/support/src/main/kotlin/au/com/dius/pact/core/support/json/JsonParser.kt +++ b/core/support/src/main/kotlin/au/com/dius/pact/core/support/json/JsonParser.kt @@ -1,8 +1,6 @@ package au.com.dius.pact.core.support.json -import com.github.michaelbull.result.Err -import com.github.michaelbull.result.Ok -import com.github.michaelbull.result.Result +import au.com.dius.pact.core.support.Result import java.io.InputStream import java.io.Reader import java.util.ArrayDeque @@ -64,29 +62,29 @@ class JsonLexer(json: JsonSource) : BaseJsonLexer(json) { return when { next.isWhitespace() -> { skipWhitespace() - Ok(JsonToken.Whitespace) + Result.Ok(JsonToken.Whitespace) } next == '-' || next.isDigit() -> scanNumber(next) next == 't' -> scanTrue() next == 'f' -> scanFalse() next == 'n' -> scanNull() next == '"' -> scanString() - next == '[' -> Ok(JsonToken.ArrayStart) - next == ']' -> Ok(JsonToken.ArrayEnd) - next == '{' -> Ok(JsonToken.ObjectStart) - next == '}' -> Ok(JsonToken.ObjectEnd) - next == ',' -> Ok(JsonToken.Comma) - next == ':' -> Ok(JsonToken.Colon) + next == '[' -> Result.Ok(JsonToken.ArrayStart) + next == ']' -> Result.Ok(JsonToken.ArrayEnd) + next == '{' -> Result.Ok(JsonToken.ObjectStart) + next == '}' -> Result.Ok(JsonToken.ObjectEnd) + next == ',' -> Result.Ok(JsonToken.Comma) + next == ':' -> Result.Ok(JsonToken.Colon) else -> unexpectedCharacter(next) } } - return Ok(null) + return Result.Ok(null) } private fun unexpectedCharacter(next: Char?) = if (next == null) - Err(JsonException("Invalid JSON (${documentPointer()}), unexpected end of the JSON document")) + Result.Err(JsonException("Invalid JSON (${documentPointer()}), unexpected end of the JSON document")) else - Err(JsonException("Invalid JSON (${documentPointer()}), found unexpected character '$next'")) + Result.Err(JsonException("Invalid JSON (${documentPointer()}), found unexpected character '$next'")) private fun scanNull(): Result { var next = json.nextChar() @@ -95,7 +93,7 @@ class JsonLexer(json: JsonSource) : BaseJsonLexer(json) { if (next == null || next != 'l') return unexpectedCharacter(next) next = json.nextChar() if (next == null || next != 'l') return unexpectedCharacter(next) - return Ok(JsonToken.Null) + return Result.Ok(JsonToken.Null) } private fun scanFalse(): Result { @@ -107,7 +105,7 @@ class JsonLexer(json: JsonSource) : BaseJsonLexer(json) { if (next == null || next != 's') return unexpectedCharacter(next) next = json.nextChar() if (next == null || next != 'e') return unexpectedCharacter(next) - return Ok(JsonToken.False) + return Result.Ok(JsonToken.False) } private fun scanTrue(): Result { @@ -117,7 +115,7 @@ class JsonLexer(json: JsonSource) : BaseJsonLexer(json) { if (next == null || next != 'u') return unexpectedCharacter(next) next = json.nextChar() if (next == null || next != 'e') return unexpectedCharacter(next) - return Ok(JsonToken.True) + return Result.Ok(JsonToken.True) } fun documentPointer() = json.documentPointer() @@ -279,8 +277,8 @@ object JsonParser { do { val next = lexer.nextToken() token = when (next) { - is Err -> throw next.error - is Ok -> next.value + is Result.Err -> throw next.error + is Result.Ok -> next.value } } while (token is JsonToken.Whitespace) return token diff --git a/core/support/src/main/kotlin/au/com/dius/pact/core/support/parsers/StringLexer.kt b/core/support/src/main/kotlin/au/com/dius/pact/core/support/parsers/StringLexer.kt index 87d5e51cc1..206d54138a 100644 --- a/core/support/src/main/kotlin/au/com/dius/pact/core/support/parsers/StringLexer.kt +++ b/core/support/src/main/kotlin/au/com/dius/pact/core/support/parsers/StringLexer.kt @@ -1,8 +1,6 @@ package au.com.dius.pact.core.support.parsers -import com.github.michaelbull.result.Err -import com.github.michaelbull.result.Ok -import com.github.michaelbull.result.Result +import au.com.dius.pact.core.support.Result open class StringLexer(private val buffer: String) { var index = 0 @@ -85,10 +83,10 @@ open class StringLexer(private val buffer: String) { fun parseInt(): Result { return when (val result = matchRegex(INT)) { - null -> Err("Was expecting an integer at index $index") + null -> Result.Err("Was expecting an integer at index $index") else -> { lastMatch = result - Ok(result.toInt()) + Result.Ok(result.toInt()) } } } diff --git a/core/support/src/test/groovy/au/com/dius/pact/core/support/UtilsSpec.groovy b/core/support/src/test/groovy/au/com/dius/pact/core/support/UtilsSpec.groovy index e548eb442a..34896f2be5 100644 --- a/core/support/src/test/groovy/au/com/dius/pact/core/support/UtilsSpec.groovy +++ b/core/support/src/test/groovy/au/com/dius/pact/core/support/UtilsSpec.groovy @@ -3,8 +3,6 @@ package au.com.dius.pact.core.support import kotlin.Pair import spock.lang.Specification import spock.lang.Unroll -import com.github.michaelbull.result.Err -import com.github.michaelbull.result.Ok @SuppressWarnings('UnnecessaryBooleanExpression') class UtilsSpec extends Specification { @@ -93,15 +91,15 @@ class UtilsSpec extends Specification { where: size || result - '' || new Err("'' is not a valid data size") - '100' || new Err("'100' is not a valid data size") - 'aksldjsk' || new Err("'aksldjsk' is not a valid data size") - '-kb' || new Err("'-kb' is not a valid data size") - '-1kb' || new Err("'-1kb' is not a valid data size") - '22b' || new Ok(22) - '2kb' || new Ok(2048) - '2KB' || new Ok(2048) - '2mb' || new Ok(2048 * 1024) + '' || new Result.Err("'' is not a valid data size") + '100' || new Result.Err("'100' is not a valid data size") + 'aksldjsk' || new Result.Err("'aksldjsk' is not a valid data size") + '-kb' || new Result.Err("'-kb' is not a valid data size") + '-1kb' || new Result.Err("'-1kb' is not a valid data size") + '22b' || new Result.Ok(22) + '2kb' || new Result.Ok(2048) + '2KB' || new Result.Ok(2048) + '2mb' || new Result.Ok(2048 * 1024) } @Unroll diff --git a/core/support/src/test/groovy/au/com/dius/pact/core/support/VersionParserSpec.groovy b/core/support/src/test/groovy/au/com/dius/pact/core/support/VersionParserSpec.groovy index 1870e0c181..796580096e 100644 --- a/core/support/src/test/groovy/au/com/dius/pact/core/support/VersionParserSpec.groovy +++ b/core/support/src/test/groovy/au/com/dius/pact/core/support/VersionParserSpec.groovy @@ -7,23 +7,23 @@ class VersionParserSpec extends Specification { def 'parse full version'() { expect: - Version.parse('1.2.3').component1() == new Version(1, 2, 3) + Version.parse('1.2.3').get() == new Version(1, 2, 3) } def 'parse major.minor version'() { expect: - Version.parse('1.2').component1() == new Version(1, 2, null) + Version.parse('1.2').get() == new Version(1, 2, null) } def 'parse invalid version'() { expect: - Version.parse('lkzasdjskjdf').component2() == 'Was expecting an integer at index 0' + Version.parse('lkzasdjskjdf').errorValue() == 'Was expecting an integer at index 0' } @Unroll def 'parse errors'() { expect: - Version.parse(version).component2() == error + Version.parse(version).errorValue() == error where: diff --git a/core/support/src/test/groovy/au/com/dius/pact/core/support/json/JsonLexerSpec.groovy b/core/support/src/test/groovy/au/com/dius/pact/core/support/json/JsonLexerSpec.groovy index d00c21968c..7b87e554af 100644 --- a/core/support/src/test/groovy/au/com/dius/pact/core/support/json/JsonLexerSpec.groovy +++ b/core/support/src/test/groovy/au/com/dius/pact/core/support/json/JsonLexerSpec.groovy @@ -1,6 +1,6 @@ package au.com.dius.pact.core.support.json -import com.github.michaelbull.result.Err +import au.com.dius.pact.core.support.Result import spock.lang.Specification import spock.lang.Unroll @@ -51,7 +51,7 @@ class JsonLexerSpec extends Specification { def token = lexer.nextToken() then: - token instanceof Err + token instanceof Result.Err where: diff --git a/pact-jvm-server/src/main/scala/au/com/dius/pact/server/Publish.scala b/pact-jvm-server/src/main/scala/au/com/dius/pact/server/Publish.scala index 6d2d0f792c..788f60c61b 100644 --- a/pact-jvm-server/src/main/scala/au/com/dius/pact/server/Publish.scala +++ b/pact-jvm-server/src/main/scala/au/com/dius/pact/server/Publish.scala @@ -51,12 +51,12 @@ object Publish extends StrictLogging { val options = getOptions(authToken) val brokerClient: PactBrokerClient = new PactBrokerClient(broker, options.asJava, new PactBrokerClientConfig()) val res = brokerClient.uploadPactFile(pact, consumerVersion, tags.getOrElse(List()).asJava) - if( res.component2() == null) { + if (res.errorValue() == null) { logger.debug("Pact successfully shared. deleting file..") removePact(pact) - new Response(200, ResponseUtils.CrossSiteHeaders.asJava, OptionalBody.body(res.component1().getBytes())) + new Response(200, ResponseUtils.CrossSiteHeaders.asJava, OptionalBody.body(res.get().getBytes())) } else { - new Response(500, ResponseUtils.CrossSiteHeaders.asJava, OptionalBody.body(res.component2().getLocalizedMessage.getBytes())) + new Response(500, ResponseUtils.CrossSiteHeaders.asJava, OptionalBody.body(res.errorValue().getLocalizedMessage.getBytes())) } } catch { diff --git a/pact-publish/src/test/groovy/broker/PactBrokerClientPactSpec.groovy b/pact-publish/src/test/groovy/broker/PactBrokerClientPactSpec.groovy index bd8130b070..4c44fbdb2b 100644 --- a/pact-publish/src/test/groovy/broker/PactBrokerClientPactSpec.groovy +++ b/pact-publish/src/test/groovy/broker/PactBrokerClientPactSpec.groovy @@ -7,8 +7,7 @@ import au.com.dius.pact.core.pactbroker.Latest import au.com.dius.pact.core.pactbroker.PactBrokerClient import au.com.dius.pact.core.pactbroker.PactBrokerClientConfig import au.com.dius.pact.core.pactbroker.TestResult -import com.github.michaelbull.result.Err -import com.github.michaelbull.result.Ok +import au.com.dius.pact.core.support.Result import spock.lang.Specification @SuppressWarnings(['UnnecessaryGetter', 'LineLength', 'NestedBlockDepth', 'AbcMetric', 'MethodSize', 'ClassSize']) @@ -75,7 +74,7 @@ class PactBrokerClientPactSpec extends Specification { when: def result = pactBroker.runTest { server, context -> - assert pactBrokerClient.uploadPactFile(pactFile, '10.0.0/A') instanceof Ok + assert pactBrokerClient.uploadPactFile(pactFile, '10.0.0/A') instanceof Result.Ok } then: @@ -107,7 +106,7 @@ class PactBrokerClientPactSpec extends Specification { when: def result = pactBroker.runTest { server, context -> - assert pactBrokerClient.createVersionTag('Foo Consumer', '10.0.0', 'A') instanceof Ok + assert pactBrokerClient.createVersionTag('Foo Consumer', '10.0.0', 'A') instanceof Result.Ok } then: @@ -139,7 +138,7 @@ class PactBrokerClientPactSpec extends Specification { when: def result = pactBroker.runTest { server, context -> - assert pactBrokerClient.createVersionTag('Foo Consumer', '10.0.0', 'A') instanceof Err + assert pactBrokerClient.createVersionTag('Foo Consumer', '10.0.0', 'A') instanceof Result.Err } then: @@ -173,7 +172,7 @@ class PactBrokerClientPactSpec extends Specification { when: def result = pactBroker.runTest { server, context -> - assert pactBrokerClient.uploadPactFile(pactFile, '10.0.0') instanceof Err + assert pactBrokerClient.uploadPactFile(pactFile, '10.0.0') instanceof Result.Err } then: @@ -210,7 +209,7 @@ class PactBrokerClientPactSpec extends Specification { when: def result = pactBroker.runTest { server, context -> def result = pactBrokerClient.uploadPactFile(pactFile, 'XXXX') - assert result instanceof Err + assert result instanceof Result.Err assert result.error.body == body } @@ -254,7 +253,7 @@ class PactBrokerClientPactSpec extends Specification { when: def result = pactBroker.runTest { server, context -> def result = pactBrokerClient.uploadPactFile(pactFile, '10.0.0') - assert result instanceof Err + assert result instanceof Result.Err assert result.error.body == body } @@ -309,7 +308,7 @@ class PactBrokerClientPactSpec extends Specification { when: def result = pactBroker.runTest { server, context -> - assert pactBrokerClient.uploadPactFile(pactFile, '10.0.0/A') instanceof Ok + assert pactBrokerClient.uploadPactFile(pactFile, '10.0.0/A') instanceof Result.Ok } then: @@ -368,7 +367,7 @@ class PactBrokerClientPactSpec extends Specification { when: def result = pactBroker.runTest { server, context -> - assert pactBrokerClient.uploadPactFile(pactFile, '10.0.0/A', ['A', 'B']) instanceof Ok + assert pactBrokerClient.uploadPactFile(pactFile, '10.0.0/A', ['A', 'B']) instanceof Result.Ok } then: @@ -414,7 +413,7 @@ class PactBrokerClientPactSpec extends Specification { when: def result = pactBroker.runTest { server, context -> - assert pactBrokerClient.uploadPactFile(pactFile, '10.0.0') instanceof Err + assert pactBrokerClient.uploadPactFile(pactFile, '10.0.0') instanceof Result.Err } then: @@ -464,7 +463,7 @@ class PactBrokerClientPactSpec extends Specification { when: def result = pactBroker.runTest { server, context -> def result = pactBrokerClient.uploadPactFile(pactFile, 'XXXX') - assert result instanceof Err + assert result instanceof Result.Err assert result.error.body == body } @@ -525,7 +524,7 @@ class PactBrokerClientPactSpec extends Specification { when: def result = pactBroker.runTest { server, context -> def result = pactBrokerClient.uploadPactFile(pactFile, '10.0.0') - assert result instanceof Err + assert result instanceof Result.Err } then: @@ -561,7 +560,7 @@ class PactBrokerClientPactSpec extends Specification { when: def result = imaginaryBroker.runTest { server, context -> - assert pactBrokerClient.uploadPactFile(pactFile, '10.0.0') instanceof Err + assert pactBrokerClient.uploadPactFile(pactFile, '10.0.0') instanceof Result.Err } then: @@ -918,7 +917,7 @@ class PactBrokerClientPactSpec extends Specification { def consumerPacts = pactBrokerClient.fetchConsumersWithSelectorsV2('Activity Service', [ new ConsumerVersionSelectors.Selector('test', true, null, null ) ], [], '', false, '') - assert consumerPacts instanceof Ok + assert consumerPacts instanceof Result.Ok assert consumerPacts.value.size == 2 assert !consumerPacts.value[0].pending assert !consumerPacts.value[1].pending @@ -1031,7 +1030,7 @@ class PactBrokerClientPactSpec extends Specification { def consumerPacts = pactBrokerClient.fetchConsumersWithSelectorsV2('Activity Service', [ new ConsumerVersionSelectors.Selector('test', true, null, null) ], ['master'], '', true, '') - assert consumerPacts instanceof Ok + assert consumerPacts instanceof Result.Ok assert consumerPacts.value.size == 2 assert !consumerPacts.value[0].pending assert consumerPacts.value[1].pending @@ -1155,7 +1154,7 @@ class PactBrokerClientPactSpec extends Specification { def consumerPacts = pactBrokerClient.fetchConsumersWithSelectorsV2('Activity Service', [ new ConsumerVersionSelectors.Selector('test', true, null, null) ], ['master'], '', true, '2020-06-24') - assert consumerPacts instanceof Ok + assert consumerPacts instanceof Result.Ok assert consumerPacts.value.size == 2 assert !consumerPacts.value[0].wip assert consumerPacts.value[1].wip diff --git a/pact-specification-test/build.gradle b/pact-specification-test/build.gradle index 668b9e1f12..7668dae6c8 100644 --- a/pact-specification-test/build.gradle +++ b/pact-specification-test/build.gradle @@ -12,7 +12,7 @@ dependencies { testImplementation 'org.apache.groovy:groovy' testImplementation 'org.apache.groovy:groovy-json' testImplementation 'org.apache.tika:tika-core' - testImplementation('io.pact.plugin.driver:core:0.1.7') { + testImplementation('io.pact.plugin.driver:core:0.1.8') { exclude group: 'au.com.dius.pact.core' } testImplementation 'org.spockframework:spock-core:2.3-groovy-4.0' diff --git a/provider/build.gradle b/provider/build.gradle index 0330843d92..e92758c32a 100644 --- a/provider/build.gradle +++ b/provider/build.gradle @@ -12,11 +12,10 @@ dependencies { api project(':core:pactbroker') api 'org.apache.httpcomponents.client5:httpclient5' api 'io.github.classgraph:classgraph:4.8.129' - api 'com.michael-bull.kotlin-result:kotlin-result' implementation 'commons-io:commons-io:2.11.0' implementation 'org.slf4j:slf4j-api' - implementation('io.pact.plugin.driver:core:0.1.7') { + implementation('io.pact.plugin.driver:core:0.1.8') { exclude group: 'au.com.dius.pact.core' } implementation 'org.apache.commons:commons-lang3' @@ -25,6 +24,7 @@ dependencies { implementation 'com.vladsch.flexmark:flexmark:0.62.2' implementation 'com.vladsch.flexmark:flexmark-ext-tables:0.62.2' implementation 'org.apache.groovy:groovy' + implementation 'com.michael-bull.kotlin-result:kotlin-result:1.1.14' testImplementation 'org.hamcrest:hamcrest' testImplementation 'org.spockframework:spock-core' diff --git a/provider/gradle/build.gradle b/provider/gradle/build.gradle index dca343ec8d..64482ba687 100644 --- a/provider/gradle/build.gradle +++ b/provider/gradle/build.gradle @@ -16,7 +16,6 @@ dependencies { implementation 'commons-io:commons-io:2.11.0' implementation 'org.apache.commons:commons-lang3' implementation 'io.github.microutils:kotlin-logging' - implementation 'com.michael-bull.kotlin-result:kotlin-result' testImplementation 'junit:junit' testImplementation 'org.mockito:mockito-core:2.28.2' diff --git a/provider/gradle/src/main/groovy/au/com/dius/pact/provider/gradle/PactPublishTask.groovy b/provider/gradle/src/main/groovy/au/com/dius/pact/provider/gradle/PactPublishTask.groovy index 5f652836e9..8bde359cb2 100644 --- a/provider/gradle/src/main/groovy/au/com/dius/pact/provider/gradle/PactPublishTask.groovy +++ b/provider/gradle/src/main/groovy/au/com/dius/pact/provider/gradle/PactPublishTask.groovy @@ -4,7 +4,7 @@ import au.com.dius.pact.core.pactbroker.PactBrokerClient import au.com.dius.pact.core.pactbroker.PactBrokerClientConfig import au.com.dius.pact.core.pactbroker.PublishConfiguration import au.com.dius.pact.core.pactbroker.RequestFailedException -import com.github.michaelbull.result.Ok +import au.com.dius.pact.core.support.Result import groovy.io.FileType import org.apache.commons.io.FilenameUtils import org.apache.commons.lang3.StringUtils @@ -86,7 +86,7 @@ abstract class PactPublishTask extends DefaultTask { println "Publishing '${pactFile.name}' ... " } result = brokerClient.uploadPactFile(pactFile, publishConfig) - if (result instanceof Ok) { + if (result instanceof Result.Ok) { println('OK') } else { println("Failed - ${result.error.message}") diff --git a/provider/gradle/src/test/groovy/au/com/dius/pact/provider/gradle/PactPublishTaskSpec.groovy b/provider/gradle/src/test/groovy/au/com/dius/pact/provider/gradle/PactPublishTaskSpec.groovy index 996ff640ff..8cb93ae13a 100644 --- a/provider/gradle/src/test/groovy/au/com/dius/pact/provider/gradle/PactPublishTaskSpec.groovy +++ b/provider/gradle/src/test/groovy/au/com/dius/pact/provider/gradle/PactPublishTaskSpec.groovy @@ -2,9 +2,8 @@ package au.com.dius.pact.provider.gradle import au.com.dius.pact.core.pactbroker.PactBrokerClient import au.com.dius.pact.core.pactbroker.PublishConfiguration +import au.com.dius.pact.core.support.Result import au.com.dius.pact.core.support.Version -import com.github.michaelbull.result.Err -import com.github.michaelbull.result.Ok import org.apache.commons.io.IOUtils import org.gradle.api.GradleScriptException import org.gradle.api.Project @@ -55,7 +54,7 @@ class PactPublishTaskSpec extends Specification { project.tasks.pactPublish.publishPacts() then: - 1 * brokerClient.uploadPactFile(_, _) >> new Ok(null) + 1 * brokerClient.uploadPactFile(_, _) >> new Result.Ok(null) } def 'failure to publish'() { @@ -71,7 +70,7 @@ class PactPublishTaskSpec extends Specification { project.tasks.pactPublish.publishPacts() then: - 1 * brokerClient.uploadPactFile(_, _) >> new Err(new RuntimeException('Boom')) + 1 * brokerClient.uploadPactFile(_, _) >> new Result.Err(new RuntimeException('Boom')) thrown(GradleScriptException) } @@ -90,7 +89,7 @@ class PactPublishTaskSpec extends Specification { then: 1 * new PactBrokerClient(_, ['authentication': ['basic', 'my user name', null]], _) >> brokerClient - 1 * brokerClient.uploadPactFile(_, _) >> new Ok(null) + 1 * brokerClient.uploadPactFile(_, _) >> new Result.Ok(null) } def 'passes in bearer token to the broker client'() { @@ -108,7 +107,7 @@ class PactPublishTaskSpec extends Specification { then: 1 * new PactBrokerClient(_, ['authentication': ['bearer', 'token1234', 'Authorization']], _) >> brokerClient - 1 * brokerClient.uploadPactFile(_, _) >> new Ok(null) + 1 * brokerClient.uploadPactFile(_, _) >> new Result.Ok(null) } def 'passes in bearer token to the broker client with custom auth header'() { @@ -127,7 +126,7 @@ class PactPublishTaskSpec extends Specification { then: 1 * new PactBrokerClient(_, ['authentication': ['bearer', 'token1234', 'custom-header']], _) >> brokerClient - 1 * brokerClient.uploadPactFile(_, _) >> new Ok(null) + 1 * brokerClient.uploadPactFile(_, _) >> new Result.Ok(null) } def 'passes in any tags to the broker client'() { @@ -145,7 +144,7 @@ class PactPublishTaskSpec extends Specification { project.tasks.pactPublish.publishPacts() then: - 1 * brokerClient.uploadPactFile(_, new PublishConfiguration('1', ['tag1'])) >> new Ok(null) + 1 * brokerClient.uploadPactFile(_, new PublishConfiguration('1', ['tag1'])) >> new Result.Ok(null) } def 'allows pact files to be excluded from publishing'() { @@ -170,7 +169,7 @@ class PactPublishTaskSpec extends Specification { project.tasks.pactPublish.publishPacts() then: - 1 * brokerClient.uploadPactFile(pactFile, _) >> new Ok(null) + 1 * brokerClient.uploadPactFile(pactFile, _) >> new Result.Ok(null) 0 * brokerClient.uploadPactFile(excluded[0], _) 0 * brokerClient.uploadPactFile(excluded[1], _) 0 * brokerClient.uploadPactFile(excluded[2], _) @@ -181,7 +180,7 @@ class PactPublishTaskSpec extends Specification { project.pact { publish { pactBrokerUrl = 'pactBrokerUrl' - consumerVersion = Version.parse('1.2.3').component1() + consumerVersion = Version.parse('1.2.3').get() } } project.evaluate() @@ -190,6 +189,6 @@ class PactPublishTaskSpec extends Specification { project.tasks.pactPublish.publishPacts() then: - 1 * brokerClient.uploadPactFile(_, new PublishConfiguration('1.2.3')) >> new Ok(null) + 1 * brokerClient.uploadPactFile(_, new PublishConfiguration('1.2.3')) >> new Result.Ok(null) } } diff --git a/provider/gradle/src/test/groovy/au/com/dius/pact/provider/gradle/ProviderVerifierStateChangeSpec.groovy b/provider/gradle/src/test/groovy/au/com/dius/pact/provider/gradle/ProviderVerifierStateChangeSpec.groovy index 7f8ec3cbe1..f4b923d73b 100644 --- a/provider/gradle/src/test/groovy/au/com/dius/pact/provider/gradle/ProviderVerifierStateChangeSpec.groovy +++ b/provider/gradle/src/test/groovy/au/com/dius/pact/provider/gradle/ProviderVerifierStateChangeSpec.groovy @@ -5,6 +5,7 @@ import au.com.dius.pact.core.model.ProviderState import au.com.dius.pact.core.model.Request import au.com.dius.pact.core.model.RequestResponseInteraction import au.com.dius.pact.core.model.Response +import au.com.dius.pact.core.support.Result import au.com.dius.pact.provider.ConsumerInfo import au.com.dius.pact.provider.DefaultStateChange import au.com.dius.pact.provider.ProviderClient @@ -12,7 +13,6 @@ import au.com.dius.pact.provider.ProviderInfo import au.com.dius.pact.provider.ProviderVerifier import au.com.dius.pact.provider.StateChange import au.com.dius.pact.provider.StateChangeResult -import com.github.michaelbull.result.Ok import spock.lang.Specification class ProviderVerifierStateChangeSpec extends Specification { @@ -43,7 +43,7 @@ class ProviderVerifierStateChangeSpec extends Specification { providerVerifier.verifyInteraction(providerInfo, consumer, failures, interaction) then: - 1 * statechange.executeStateChange(*_) >> new StateChangeResult(new Ok([:]), 'interactionMessage') + 1 * statechange.executeStateChange(*_) >> new StateChangeResult(new Result.Ok([:]), 'interactionMessage') 1 * statechange.executeStateChangeTeardown(providerVerifier, interaction, providerInfo, consumer, _) } diff --git a/provider/junit/src/main/kotlin/au/com/dius/pact/provider/junit/InteractionRunner.kt b/provider/junit/src/main/kotlin/au/com/dius/pact/provider/junit/InteractionRunner.kt index dfdf111b0d..110d1c067b 100644 --- a/provider/junit/src/main/kotlin/au/com/dius/pact/provider/junit/InteractionRunner.kt +++ b/provider/junit/src/main/kotlin/au/com/dius/pact/provider/junit/InteractionRunner.kt @@ -9,9 +9,9 @@ import au.com.dius.pact.core.model.PactSource import au.com.dius.pact.core.model.ProviderState import au.com.dius.pact.core.support.MetricEvent import au.com.dius.pact.core.support.Metrics +import au.com.dius.pact.core.support.Result import au.com.dius.pact.core.support.expressions.SystemPropertyResolver import au.com.dius.pact.core.support.expressions.ValueResolver -import au.com.dius.pact.core.support.ifNullOrEmpty import au.com.dius.pact.provider.DefaultTestResultAccumulator import au.com.dius.pact.provider.IProviderVerifier import au.com.dius.pact.provider.ProviderUtils @@ -27,7 +27,6 @@ import au.com.dius.pact.provider.junitsupport.State import au.com.dius.pact.provider.junitsupport.TargetRequestFilter import au.com.dius.pact.provider.junitsupport.target.Target import au.com.dius.pact.provider.junitsupport.target.TestTarget -import com.github.michaelbull.result.Err import mu.KLogging import org.junit.After import org.junit.Before @@ -48,11 +47,19 @@ import org.junit.runners.model.FrameworkMethod import org.junit.runners.model.InitializationError import org.junit.runners.model.Statement import org.junit.runners.model.TestClass -import java.lang.RuntimeException import java.util.concurrent.ConcurrentHashMap import java.util.function.Supplier +import kotlin.Annotation +import kotlin.Any +import kotlin.Boolean +import kotlin.Exception +import kotlin.Pair +import kotlin.RuntimeException +import kotlin.String +import kotlin.Throwable import kotlin.reflect.jvm.isAccessible import kotlin.reflect.jvm.kotlinProperty +import kotlin.to import org.apache.commons.lang3.tuple.Pair as TuplePair /** @@ -184,7 +191,7 @@ open class InteractionRunner( } finally { val updateTestResult = testResultAccumulator.updateTestResult(if (pact is FilteredPact) pact.pact else pact, interaction, testResult.toTestResult(), pactSource, propertyResolver) - if (testResult is VerificationResult.Ok && updateTestResult is Err) { + if (testResult is VerificationResult.Ok && updateTestResult is Result.Err) { testResult = VerificationResult.Failed("Failed to publish results to Pact broker", description.displayName, mapOf(interaction.interactionId.orEmpty() to listOf(VerificationFailureType.PublishResultsFailure(updateTestResult.error))), diff --git a/provider/junit/src/test/groovy/au/com/dius/pact/provider/junit/InteractionRunnerSpec.groovy b/provider/junit/src/test/groovy/au/com/dius/pact/provider/junit/InteractionRunnerSpec.groovy index ef43879a49..df2d9b3d12 100644 --- a/provider/junit/src/test/groovy/au/com/dius/pact/provider/junit/InteractionRunnerSpec.groovy +++ b/provider/junit/src/test/groovy/au/com/dius/pact/provider/junit/InteractionRunnerSpec.groovy @@ -13,6 +13,7 @@ import au.com.dius.pact.core.model.RequestResponsePact import au.com.dius.pact.core.model.Response import au.com.dius.pact.core.model.UnknownPactSource import au.com.dius.pact.core.pactbroker.PactBrokerResult +import au.com.dius.pact.core.support.Result import au.com.dius.pact.provider.DefaultTestResultAccumulator import au.com.dius.pact.provider.IProviderVerifier import au.com.dius.pact.provider.TestResultAccumulator @@ -21,8 +22,6 @@ import au.com.dius.pact.provider.VerificationResult import au.com.dius.pact.provider.junit.target.HttpTarget import au.com.dius.pact.provider.junitsupport.target.Target import au.com.dius.pact.provider.junitsupport.target.TestTarget -import com.github.michaelbull.result.Err -import com.github.michaelbull.result.Ok import junit.framework.AssertionFailedError import org.apache.commons.lang3.tuple.Pair import org.jetbrains.annotations.NotNull @@ -299,7 +298,7 @@ class InteractionRunnerSpec extends Specification { 1 * notifier.fireTestStarted({ it.displayName.startsWith('consumer - Upon Interaction 1') }) then: - 1 * testResultAccumulator.updateTestResult(pact, interaction1, _, _, _) >> new Ok(true) + 1 * testResultAccumulator.updateTestResult(pact, interaction1, _, _, _) >> new Result.Ok(true) then: 1 * notifier.fireTestFinished({ it.displayName.startsWith('consumer - Upon Interaction 1') }) @@ -308,7 +307,7 @@ class InteractionRunnerSpec extends Specification { 1 * notifier.fireTestStarted({ it.displayName.startsWith('consumer - Upon Interaction 2') }) then: - 1 * testResultAccumulator.updateTestResult(pact, interaction2, _, _, _) >> new Ok(true) + 1 * testResultAccumulator.updateTestResult(pact, interaction2, _, _, _) >> new Result.Ok(true) then: 1 * notifier.fireTestFinished({ it.displayName.startsWith('consumer - Upon Interaction 2') }) @@ -334,13 +333,13 @@ class InteractionRunnerSpec extends Specification { 1 * notifier.fireTestIgnored({ it.displayName.startsWith(' - Upon Interaction 1 ') }) then: - 1 * testResultAccumulator.updateTestResult(pact, interaction1, _, _, _) >> new Ok(true) + 1 * testResultAccumulator.updateTestResult(pact, interaction1, _, _, _) >> new Result.Ok(true) then: 1 * notifier.fireTestIgnored({ it.displayName.startsWith(' - Upon Interaction 2 ') }) then: - 1 * testResultAccumulator.updateTestResult(pact, interaction2, _, _, _) >> new Ok(true) + 1 * testResultAccumulator.updateTestResult(pact, interaction2, _, _, _) >> new Result.Ok(true) } def 'if the test result is a failure, call the notifier that the test has failed'() { @@ -361,7 +360,7 @@ class InteractionRunnerSpec extends Specification { 1 * notifier.fireTestStarted({ it.displayName.startsWith('consumer - Upon Interaction 1') }) then: - 1 * testResultAccumulator.updateTestResult(pact, interaction1, _, _, _) >> new Ok(true) + 1 * testResultAccumulator.updateTestResult(pact, interaction1, _, _, _) >> new Result.Ok(true) then: 1 * notifier.fireTestFinished({ it.displayName.startsWith('consumer - Upon Interaction 1') }) @@ -370,7 +369,7 @@ class InteractionRunnerSpec extends Specification { 1 * notifier.fireTestStarted({ it.displayName.startsWith('consumer - Upon Interaction 2') }) then: - 1 * testResultAccumulator.updateTestResult(pact, interaction2, _, _, _) >> new Ok(true) + 1 * testResultAccumulator.updateTestResult(pact, interaction2, _, _, _) >> new Result.Ok(true) then: 1 * notifier.fireTestFinished({ it.displayName.startsWith('consumer - Upon Interaction 2') }) @@ -396,13 +395,13 @@ class InteractionRunnerSpec extends Specification { 1 * notifier.fireTestIgnored({ it.displayName.startsWith(' - Upon Interaction 1 ') }) then: - 1 * testResultAccumulator.updateTestResult(pact, interaction1, _, _, _) >> new Ok(true) + 1 * testResultAccumulator.updateTestResult(pact, interaction1, _, _, _) >> new Result.Ok(true) then: 1 * notifier.fireTestIgnored({ it.displayName.startsWith(' - Upon Interaction 2 ') }) then: - 1 * testResultAccumulator.updateTestResult(pact, interaction2, _, _, _) >> new Ok(true) + 1 * testResultAccumulator.updateTestResult(pact, interaction2, _, _, _) >> new Result.Ok(true) } def 'if publishing a verification result fails, set the test result to a failure'() { @@ -423,7 +422,7 @@ class InteractionRunnerSpec extends Specification { 1 * notifier.fireTestStarted({ it.displayName.startsWith('consumer - Upon Interaction 1') }) then: - 1 * testResultAccumulator.updateTestResult(pact, interaction1, _, _, _) >> new Err(['Publish failed']) + 1 * testResultAccumulator.updateTestResult(pact, interaction1, _, _, _) >> new Result.Err(['Publish failed']) then: 1 * notifier.fireTestFailure({ it.description.displayName.startsWith('consumer - Upon Interaction 1') }) @@ -433,7 +432,7 @@ class InteractionRunnerSpec extends Specification { 1 * notifier.fireTestStarted({ it.displayName.startsWith('consumer - Upon Interaction 2') }) then: - 1 * testResultAccumulator.updateTestResult(pact, interaction2, _, _, _) >> new Ok(true) + 1 * testResultAccumulator.updateTestResult(pact, interaction2, _, _, _) >> new Result.Ok(true) then: 1 * notifier.fireTestFinished({ it.displayName.startsWith('consumer - Upon Interaction 2') }) diff --git a/provider/junit5/build.gradle b/provider/junit5/build.gradle index 183f1864d5..2b3d7a3cd1 100644 --- a/provider/junit5/build.gradle +++ b/provider/junit5/build.gradle @@ -13,9 +13,10 @@ dependencies { api 'org.junit.jupiter:junit-jupiter-api:5.9.0' implementation 'org.slf4j:slf4j-api' - implementation('io.pact.plugin.driver:core:0.1.7') { + implementation('io.pact.plugin.driver:core:0.1.8') { exclude group: 'au.com.dius.pact.core' } + implementation 'com.michael-bull.kotlin-result:kotlin-result:1.1.14' testRuntimeOnly 'ch.qos.logback:logback-classic' testImplementation 'ru.lanwen.wiremock:wiremock-junit5:1.3.1' diff --git a/provider/junit5/src/main/kotlin/au/com/dius/pact/provider/junit5/PactJUnit5VerificationProvider.kt b/provider/junit5/src/main/kotlin/au/com/dius/pact/provider/junit5/PactJUnit5VerificationProvider.kt index 15a15cf967..e5e60fcc1a 100644 --- a/provider/junit5/src/main/kotlin/au/com/dius/pact/provider/junit5/PactJUnit5VerificationProvider.kt +++ b/provider/junit5/src/main/kotlin/au/com/dius/pact/provider/junit5/PactJUnit5VerificationProvider.kt @@ -7,6 +7,7 @@ import au.com.dius.pact.core.support.expressions.DataType import au.com.dius.pact.core.support.expressions.ExpressionParser import au.com.dius.pact.core.support.expressions.SystemPropertyResolver import au.com.dius.pact.core.support.expressions.ValueResolver +import au.com.dius.pact.core.support.getOrElse import au.com.dius.pact.core.support.handleWith import au.com.dius.pact.core.support.isNotEmpty import au.com.dius.pact.provider.ProviderUtils @@ -20,7 +21,6 @@ import au.com.dius.pact.provider.junitsupport.Provider import au.com.dius.pact.provider.junitsupport.State import au.com.dius.pact.provider.junitsupport.loader.NoPactsFoundException import au.com.dius.pact.provider.junitsupport.loader.PactLoader -import com.github.michaelbull.result.getOrElse import mu.KLogging import org.junit.jupiter.api.extension.ExtensionContext import org.junit.jupiter.api.extension.TestTemplateInvocationContext diff --git a/provider/junit5/src/main/kotlin/au/com/dius/pact/provider/junit5/PactVerificationContext.kt b/provider/junit5/src/main/kotlin/au/com/dius/pact/provider/junit5/PactVerificationContext.kt index ffe6383def..2bd9fc9f10 100644 --- a/provider/junit5/src/main/kotlin/au/com/dius/pact/provider/junit5/PactVerificationContext.kt +++ b/provider/junit5/src/main/kotlin/au/com/dius/pact/provider/junit5/PactVerificationContext.kt @@ -5,11 +5,12 @@ import au.com.dius.pact.core.model.Interaction import au.com.dius.pact.core.model.Pact import au.com.dius.pact.core.model.PactSource import au.com.dius.pact.core.model.RequestResponseInteraction -import au.com.dius.pact.core.model.V4Interaction import au.com.dius.pact.core.model.UnknownPactSource +import au.com.dius.pact.core.model.V4Interaction import au.com.dius.pact.core.model.generators.GeneratorTestMode import au.com.dius.pact.core.support.MetricEvent import au.com.dius.pact.core.support.Metrics +import au.com.dius.pact.core.support.Result import au.com.dius.pact.core.support.expressions.SystemPropertyResolver import au.com.dius.pact.core.support.expressions.ValueResolver import au.com.dius.pact.provider.IConsumerInfo @@ -20,8 +21,6 @@ import au.com.dius.pact.provider.ProviderVerifier import au.com.dius.pact.provider.VerificationFailureType import au.com.dius.pact.provider.VerificationResult import au.com.dius.pact.provider.junitsupport.TestDescription -import com.github.michaelbull.result.Err -import com.github.michaelbull.result.Ok import org.junit.jupiter.api.extension.ExtensionContext /** @@ -128,8 +127,8 @@ data class PactVerificationContext @JvmOverloads constructor( } PactVerification.PLUGIN -> { val v4pact = when(val p = pact.asV4Pact()) { - is Ok -> p.value - is Err -> return listOf( + is Result.Ok -> p.value + is Result.Err -> return listOf( VerificationResult.Failed( "Plugins can only be used with V4 Pacts", interactionMessage, mapOf( diff --git a/provider/junit5/src/main/kotlin/au/com/dius/pact/provider/junit5/PactVerificationExtension.kt b/provider/junit5/src/main/kotlin/au/com/dius/pact/provider/junit5/PactVerificationExtension.kt index 9c2734014c..8ec58081ed 100644 --- a/provider/junit5/src/main/kotlin/au/com/dius/pact/provider/junit5/PactVerificationExtension.kt +++ b/provider/junit5/src/main/kotlin/au/com/dius/pact/provider/junit5/PactVerificationExtension.kt @@ -5,6 +5,7 @@ import au.com.dius.pact.core.model.BrokerUrlSource import au.com.dius.pact.core.model.FilteredPact import au.com.dius.pact.core.model.Interaction import au.com.dius.pact.core.model.Pact +import au.com.dius.pact.core.support.Result import au.com.dius.pact.core.support.expressions.SystemPropertyResolver import au.com.dius.pact.core.support.expressions.ValueResolver import au.com.dius.pact.core.support.isNotEmpty @@ -16,7 +17,6 @@ import au.com.dius.pact.provider.ProviderVerifier import au.com.dius.pact.provider.TestResultAccumulator import au.com.dius.pact.provider.junitsupport.VerificationReports import au.com.dius.pact.provider.reporters.ReporterManager -import com.github.michaelbull.result.Err import mu.KLogging import org.apache.hc.core5.http.ClassicHttpRequest import org.apache.hc.core5.http.HttpRequest @@ -200,7 +200,7 @@ open class PactVerificationExtension( val pact = if (this.pact is FilteredPact) pact.pact else pact val updateTestResult = testResultAccumulator.updateTestResult(pact, interaction, testContext.testExecutionResult, pactSource, propertyResolver) - if (updateTestResult is Err) { + if (updateTestResult is Result.Err) { throw AssertionError("Failed to update the test results: " + updateTestResult.error.joinToString("\n")) } } diff --git a/provider/junit5/src/main/kotlin/au/com/dius/pact/provider/junit5/PactVerificationStateChangeExtension.kt b/provider/junit5/src/main/kotlin/au/com/dius/pact/provider/junit5/PactVerificationStateChangeExtension.kt index 812ea75ab0..a5fca59748 100644 --- a/provider/junit5/src/main/kotlin/au/com/dius/pact/provider/junit5/PactVerificationStateChangeExtension.kt +++ b/provider/junit5/src/main/kotlin/au/com/dius/pact/provider/junit5/PactVerificationStateChangeExtension.kt @@ -3,6 +3,7 @@ package au.com.dius.pact.provider.junit5 import au.com.dius.pact.core.model.BrokerUrlSource import au.com.dius.pact.core.model.Interaction import au.com.dius.pact.core.model.ProviderState +import au.com.dius.pact.core.support.Result import au.com.dius.pact.core.support.isNotEmpty import au.com.dius.pact.provider.ProviderUtils import au.com.dius.pact.provider.StateChangeResult @@ -12,7 +13,6 @@ import au.com.dius.pact.provider.junitsupport.IgnoreMissingStateChange import au.com.dius.pact.provider.junitsupport.MissingStateChangeMethod import au.com.dius.pact.provider.junitsupport.State import au.com.dius.pact.provider.junitsupport.StateChangeAction -import com.github.michaelbull.result.Err import mu.KLogging import org.junit.jupiter.api.extension.AfterTestExecutionCallback import org.junit.jupiter.api.extension.BeforeTestExecutionCallback @@ -41,7 +41,7 @@ class PactVerificationStateChangeExtension( } catch (e: Exception) { val pending = pactSource is BrokerUrlSource && pactSource.result?.pending == true logger.error(e) { "Provider state change callback failed" } - val error = StateChangeResult(Err(e)) + val error = StateChangeResult(Result.Err(e)) testContext.testExecutionResult.add(VerificationResult.Failed( description = "Provider state change callback failed", failures = mapOf(interaction.interactionId.orEmpty() to @@ -64,7 +64,7 @@ class PactVerificationStateChangeExtension( } catch (e: Exception) { val pending = pactSource is BrokerUrlSource && pactSource.result?.pending == true logger.error(e) { "Provider state change callback failed" } - val error = StateChangeResult(Err(e)) + val error = StateChangeResult(Result.Err(e)) testContext.testExecutionResult.add(VerificationResult.Failed( description = "Provider state change teardown callback failed", failures = mapOf(interaction.interactionId.orEmpty() to listOf( diff --git a/provider/junit5/src/main/kotlin/au/com/dius/pact/provider/junit5/PluginTestTarget.kt b/provider/junit5/src/main/kotlin/au/com/dius/pact/provider/junit5/PluginTestTarget.kt index 49a12f2eca..e8cd4ebd83 100644 --- a/provider/junit5/src/main/kotlin/au/com/dius/pact/provider/junit5/PluginTestTarget.kt +++ b/provider/junit5/src/main/kotlin/au/com/dius/pact/provider/junit5/PluginTestTarget.kt @@ -3,6 +3,7 @@ package au.com.dius.pact.provider.junit5 import au.com.dius.pact.core.model.Interaction import au.com.dius.pact.core.model.Pact import au.com.dius.pact.core.model.PactSource +import au.com.dius.pact.core.support.Result import au.com.dius.pact.provider.IConsumerInfo import au.com.dius.pact.provider.IProviderInfo import au.com.dius.pact.provider.IProviderVerifier @@ -13,7 +14,6 @@ import com.github.michaelbull.result.Ok import io.pact.plugins.jvm.core.CatalogueEntry import io.pact.plugins.jvm.core.CatalogueManager import io.pact.plugins.jvm.core.DefaultPluginManager -import io.pact.plugins.jvm.core.InteractionVerificationData import io.pact.plugins.jvm.core.PactPluginNotFoundException import java.io.File import java.net.URL @@ -86,12 +86,12 @@ class PluginTestTarget(private val config: MutableMap = mutableMap override fun prepareRequest(pact: Pact, interaction: Interaction, context: MutableMap): Pair? { return when (val v4pact = pact.asV4Pact()) { - is Ok -> when (val result = DefaultPluginManager.prepareValidationForInteraction(transportEntry, v4pact.value, + is Result.Ok -> when (val result = DefaultPluginManager.prepareValidationForInteraction(transportEntry, v4pact.value, interaction.asV4Interaction(), config)) { is Ok -> result.value to transportEntry is Err -> throw RuntimeException("Failed to configure the interaction for verification - ${result.error}") } - is Err -> throw RuntimeException("PluginTestTarget can only be used with V4 Pacts") + is Result.Err -> throw RuntimeException("PluginTestTarget can only be used with V4 Pacts") } } @@ -106,7 +106,7 @@ class PluginTestTarget(private val config: MutableMap = mutableMap override fun prepareVerifier(verifier: IProviderVerifier, testInstance: Any, pact: Pact) { if (pact.isV4Pact()) { when (val v4pact = pact.asV4Pact()) { - is Ok -> { + is Result.Ok -> { for (plugin in v4pact.value.pluginData()) { when (DefaultPluginManager.loadPlugin(plugin.name, plugin.version)) { is Ok -> {} @@ -125,7 +125,7 @@ class PluginTestTarget(private val config: MutableMap = mutableMap throw RuntimeException("PluginTestTarget requires the transport to be configured") } } - is Err -> throw RuntimeException("PluginTestTarget can only be used with V4 Pacts") + is Result.Err -> throw RuntimeException("PluginTestTarget can only be used with V4 Pacts") } } else { throw RuntimeException("PluginTestTarget can only be used with V4 Pacts") diff --git a/provider/junit5/src/test/groovy/au/com/dius/pact/provider/junit5/PactVerificationExtensionSpec.groovy b/provider/junit5/src/test/groovy/au/com/dius/pact/provider/junit5/PactVerificationExtensionSpec.groovy index f51ce645a7..5f81940f09 100644 --- a/provider/junit5/src/test/groovy/au/com/dius/pact/provider/junit5/PactVerificationExtensionSpec.groovy +++ b/provider/junit5/src/test/groovy/au/com/dius/pact/provider/junit5/PactVerificationExtensionSpec.groovy @@ -8,13 +8,12 @@ import au.com.dius.pact.core.model.Request import au.com.dius.pact.core.model.RequestResponseInteraction import au.com.dius.pact.core.model.RequestResponsePact import au.com.dius.pact.core.model.Response +import au.com.dius.pact.core.support.Result import au.com.dius.pact.core.support.expressions.ValueResolver import au.com.dius.pact.provider.IConsumerInfo import au.com.dius.pact.provider.IProviderInfo import au.com.dius.pact.provider.IProviderVerifier import au.com.dius.pact.provider.TestResultAccumulator -import com.github.michaelbull.result.Err -import com.github.michaelbull.result.Ok import org.junit.jupiter.api.extension.ExtensionContext import spock.lang.Issue import spock.lang.Specification @@ -54,7 +53,7 @@ class PactVerificationExtensionSpec extends Specification { then: 1 * extension.testResultAccumulator.updateTestResult(pact, interaction1, [], pactSource, mockValueResolver) >> - new Ok(true) + new Result.Ok(true) } def 'updateTestResult uses the pact itself when pact is not filtered '() { @@ -123,7 +122,7 @@ class PactVerificationExtensionSpec extends Specification { then: 1 * extension.testResultAccumulator.updateTestResult(pact, interaction1, [], pactSource, mockValueResolver) >> - new Err(['failed']) + new Result.Err(['failed']) def exception = thrown(AssertionError) exception.message == 'Failed to update the test results: failed' } diff --git a/provider/maven/src/main/kotlin/au/com/dius/pact/provider/maven/PactProviderMojo.kt b/provider/maven/src/main/kotlin/au/com/dius/pact/provider/maven/PactProviderMojo.kt index 9865de043c..d56b2fa601 100644 --- a/provider/maven/src/main/kotlin/au/com/dius/pact/provider/maven/PactProviderMojo.kt +++ b/provider/maven/src/main/kotlin/au/com/dius/pact/provider/maven/PactProviderMojo.kt @@ -1,11 +1,11 @@ package au.com.dius.pact.provider.maven import au.com.dius.pact.core.model.FileSource -import au.com.dius.pact.core.pactbroker.ConsumerVersionSelector import au.com.dius.pact.core.pactbroker.ConsumerVersionSelectors import au.com.dius.pact.core.pactbroker.NotFoundHalResponse import au.com.dius.pact.core.support.expressions.DataType import au.com.dius.pact.core.support.expressions.ExpressionParser +import au.com.dius.pact.core.support.getOrElse import au.com.dius.pact.core.support.handleWith import au.com.dius.pact.core.support.isNotEmpty import au.com.dius.pact.core.support.toUrl @@ -19,7 +19,6 @@ import au.com.dius.pact.provider.ProviderVerifier import au.com.dius.pact.provider.ProviderVersion import au.com.dius.pact.provider.VerificationResult import au.com.dius.pact.provider.reporters.ReporterManager -import com.github.michaelbull.result.getOrElse import org.apache.maven.plugin.MojoFailureException import org.apache.maven.plugins.annotations.Mojo import org.apache.maven.plugins.annotations.Parameter diff --git a/provider/maven/src/main/kotlin/au/com/dius/pact/provider/maven/PactPublishMojo.kt b/provider/maven/src/main/kotlin/au/com/dius/pact/provider/maven/PactPublishMojo.kt index a710db323e..44555c7468 100644 --- a/provider/maven/src/main/kotlin/au/com/dius/pact/provider/maven/PactPublishMojo.kt +++ b/provider/maven/src/main/kotlin/au/com/dius/pact/provider/maven/PactPublishMojo.kt @@ -4,8 +4,7 @@ import au.com.dius.pact.core.pactbroker.PactBrokerClient import au.com.dius.pact.core.pactbroker.PublishConfiguration import au.com.dius.pact.core.pactbroker.RequestFailedException import au.com.dius.pact.core.support.isNotEmpty -import com.github.michaelbull.result.Err -import com.github.michaelbull.result.Ok +import au.com.dius.pact.core.support.Result import org.apache.maven.plugin.MojoExecutionException import org.apache.maven.plugins.annotations.Mojo import org.apache.maven.plugins.annotations.Parameter @@ -81,8 +80,8 @@ open class PactPublishMojo : PactBaseMojo() { println("Publishing '${pactFile.name}' ... ") } when (val result = brokerClient!!.uploadPactFile(pactFile, publishConfiguration)) { - is Ok -> println("OK") - is Err -> { + is Result.Ok -> println("OK") + is Result.Err -> { val error = result.error println("Failed - ${result.error.message}") if (error is RequestFailedException && error.body.isNotEmpty()) { diff --git a/provider/maven/src/test/groovy/au/com/dius/pact/provider/maven/PactPublishMojoSpec.groovy b/provider/maven/src/test/groovy/au/com/dius/pact/provider/maven/PactPublishMojoSpec.groovy index 337379e90e..7013007ee3 100644 --- a/provider/maven/src/test/groovy/au/com/dius/pact/provider/maven/PactPublishMojoSpec.groovy +++ b/provider/maven/src/test/groovy/au/com/dius/pact/provider/maven/PactPublishMojoSpec.groovy @@ -2,8 +2,7 @@ package au.com.dius.pact.provider.maven import au.com.dius.pact.core.pactbroker.PactBrokerClient import au.com.dius.pact.core.pactbroker.PublishConfiguration -import com.github.michaelbull.result.Err -import com.github.michaelbull.result.Ok +import au.com.dius.pact.core.support.Result import org.apache.maven.plugin.MojoExecutionException import spock.lang.Specification import spock.util.environment.RestoreSystemProperties @@ -35,7 +34,7 @@ class PactPublishMojoSpec extends Specification { mojo.execute() then: - 3 * brokerClient.uploadPactFile(_, _) >> new Ok(null) + 3 * brokerClient.uploadPactFile(_, _) >> new Result.Ok(null) cleanup: dir.deleteDir() @@ -55,8 +54,8 @@ class PactPublishMojoSpec extends Specification { mojo.execute() then: - 3 * brokerClient.uploadPactFile(_, _) >> new Ok(null) >> - new Err(new RuntimeException('FAILED! Bang')) >> new Ok(null) + 3 * brokerClient.uploadPactFile(_, _) >> new Result.Ok(null) >> + new Result.Err(new RuntimeException('FAILED! Bang')) >> new Result.Ok(null) thrown(MojoExecutionException) cleanup: @@ -165,7 +164,7 @@ class PactPublishMojoSpec extends Specification { mojo.execute() then: - 1 * brokerClient.uploadPactFile(_, new PublishConfiguration('0.0.0', tags)) >> new Ok(null) + 1 * brokerClient.uploadPactFile(_, new PublishConfiguration('0.0.0', tags)) >> new Result.Ok(null) cleanup: dir.deleteDir() @@ -186,7 +185,7 @@ class PactPublishMojoSpec extends Specification { mojo.execute() then: - 1 * brokerClient.uploadPactFile(_, new PublishConfiguration('0.0.0', ['1', '2', '3'])) >> new Ok(null) + 1 * brokerClient.uploadPactFile(_, new PublishConfiguration('0.0.0', ['1', '2', '3'])) >> new Result.Ok(null) cleanup: dir.deleteDir() @@ -211,7 +210,7 @@ class PactPublishMojoSpec extends Specification { mojo.execute() then: - 1 * brokerClient.uploadPactFile(file1, _) >> new Ok(null) + 1 * brokerClient.uploadPactFile(file1, _) >> new Result.Ok(null) 0 * brokerClient.uploadPactFile(file2, _) 0 * brokerClient.uploadPactFile(file3, _) 0 * brokerClient.uploadPactFile(file4, _) @@ -235,7 +234,7 @@ class PactPublishMojoSpec extends Specification { mojo.execute() then: - 1 * brokerClient.uploadPactFile(_, new PublishConfiguration('0.0.0', [], 'feat/test', 'http:/1234')) >> new Ok(null) + 1 * brokerClient.uploadPactFile(_, new PublishConfiguration('0.0.0', [], 'feat/test', 'http:/1234')) >> new Result.Ok(null) cleanup: dir.deleteDir() diff --git a/provider/src/main/kotlin/au/com/dius/pact/provider/ProviderInfo.kt b/provider/src/main/kotlin/au/com/dius/pact/provider/ProviderInfo.kt index 6b7ff6b873..1c975db695 100644 --- a/provider/src/main/kotlin/au/com/dius/pact/provider/ProviderInfo.kt +++ b/provider/src/main/kotlin/au/com/dius/pact/provider/ProviderInfo.kt @@ -6,10 +6,9 @@ import au.com.dius.pact.core.pactbroker.ConsumerVersionSelector import au.com.dius.pact.core.pactbroker.ConsumerVersionSelectors import au.com.dius.pact.core.pactbroker.PactBrokerClient import au.com.dius.pact.core.pactbroker.PactBrokerClientConfig +import au.com.dius.pact.core.support.Result import au.com.dius.pact.core.support.Utils -import com.github.michaelbull.result.Err -import com.github.michaelbull.result.Ok -import com.github.michaelbull.result.map +import au.com.dius.pact.core.support.mapOk import mu.KLogging import org.apache.commons.lang3.builder.HashCodeBuilder import org.apache.commons.lang3.builder.ToStringBuilder @@ -127,15 +126,15 @@ open class ProviderInfo @JvmOverloads constructor ( val client = pactBrokerClient(pactBrokerUrl, options) val consumersFromBroker = client.fetchConsumersWithSelectorsV2(name, selectors, options.providerTags, options.providerBranch, options.enablePending, options.includeWipPactsSince) - .map { results -> results.map { ConsumerInfo.from(it) } } + .mapOk { results -> results.map { ConsumerInfo.from(it) } } return when (consumersFromBroker) { - is Ok> -> { + is Result.Ok -> { val list = consumersFromBroker.value consumers.addAll(list) list } - is Err -> { + is Result.Err -> { throw RuntimeException("Call to fetch pacts from Pact Broker failed with an exception", consumersFromBroker.error) } diff --git a/provider/src/main/kotlin/au/com/dius/pact/provider/ProviderVerifier.kt b/provider/src/main/kotlin/au/com/dius/pact/provider/ProviderVerifier.kt index a721176ae9..fe9a5e7580 100644 --- a/provider/src/main/kotlin/au/com/dius/pact/provider/ProviderVerifier.kt +++ b/provider/src/main/kotlin/au/com/dius/pact/provider/ProviderVerifier.kt @@ -4,7 +4,6 @@ import au.com.dius.pact.core.matchers.BodyMismatch import au.com.dius.pact.core.matchers.BodyTypeMismatch import au.com.dius.pact.core.matchers.HeaderMismatch import au.com.dius.pact.core.matchers.MetadataMismatch -import au.com.dius.pact.core.matchers.Mismatch import au.com.dius.pact.core.matchers.StatusMismatch import au.com.dius.pact.core.matchers.generators.ArrayContainsJsonGenerator import au.com.dius.pact.core.model.BrokerUrlSource @@ -30,6 +29,7 @@ import au.com.dius.pact.core.pactbroker.IPactBrokerClient import au.com.dius.pact.core.support.Auth import au.com.dius.pact.core.support.MetricEvent import au.com.dius.pact.core.support.Metrics +import au.com.dius.pact.core.support.Result import au.com.dius.pact.core.support.expressions.SystemPropertyResolver import au.com.dius.pact.core.support.hasProperty import au.com.dius.pact.core.support.ifNullOrEmpty @@ -39,7 +39,6 @@ import au.com.dius.pact.provider.reporters.Event import au.com.dius.pact.provider.reporters.VerifierReporter import com.github.michaelbull.result.Err import com.github.michaelbull.result.Ok -import com.github.michaelbull.result.Result import groovy.lang.Closure import io.github.classgraph.ClassGraph import io.pact.plugins.jvm.core.CatalogueEntry @@ -516,19 +515,19 @@ open class ProviderVerifier @JvmOverloads constructor ( interactionId: String, pending: Boolean ): VerificationResult { - return if (comparison is Ok && comparison.value.mismatches.isEmpty()) { + return if (comparison is Result.Ok && comparison.value.mismatches.isEmpty()) { emitEvent(Event.BodyComparisonOk) VerificationResult.Ok(interactionId, emptyList()) } else { emitEvent(Event.BodyComparisonFailed(comparison)) val description = "$comparisonDescription has a matching body" when (comparison) { - is Err -> { + is Result.Err -> { failures[description] = comparison.error.description() VerificationResult.Failed("Body had differences", description, mapOf(interactionId to listOf(VerificationFailureType.MismatchFailure(comparison.error))), pending) } - is Ok -> { + is Result.Ok -> { failures[description] = comparison.value VerificationResult.Failed("Body had differences", description, mapOf(interactionId to comparison.value.mismatches.values.flatten() @@ -679,7 +678,7 @@ open class ProviderVerifier @JvmOverloads constructor ( val stateChangeResult = stateChangeHandler.executeStateChange(this, provider, consumer, interaction, interactionMessage, failures, providerClient) - if (stateChangeResult.stateChangeResult is Ok) { + if (stateChangeResult.stateChangeResult is Result.Ok) { interactionMessage = stateChangeResult.message reportInteractionDescription(interaction) @@ -916,8 +915,8 @@ open class ProviderVerifier @JvmOverloads constructor ( providerTags?.get().orEmpty(), providerBranch?.get().orEmpty()) when (reportResults) { - is Ok -> VerificationResult.Ok() - is Err -> VerificationResult.Failed("Failed to publish results to the Pact broker", "", + is Result.Ok -> VerificationResult.Ok() + is Result.Err -> VerificationResult.Failed("Failed to publish results to the Pact broker", "", mapOf("" to listOf(VerificationFailureType.PublishResultsFailure(reportResults.error)))) } } diff --git a/provider/src/main/kotlin/au/com/dius/pact/provider/ResponseComparison.kt b/provider/src/main/kotlin/au/com/dius/pact/provider/ResponseComparison.kt index 1b45bc4928..f60568400c 100755 --- a/provider/src/main/kotlin/au/com/dius/pact/provider/ResponseComparison.kt +++ b/provider/src/main/kotlin/au/com/dius/pact/provider/ResponseComparison.kt @@ -22,14 +22,12 @@ import au.com.dius.pact.core.model.messaging.MessageInteraction import au.com.dius.pact.core.model.orEmpty import au.com.dius.pact.core.model.orEmptyBody import au.com.dius.pact.core.support.Json +import au.com.dius.pact.core.support.Result import au.com.dius.pact.core.support.Utils.sizeOf import au.com.dius.pact.core.support.expressions.SystemPropertyResolver import au.com.dius.pact.core.support.expressions.ValueResolver import au.com.dius.pact.core.support.isNotEmpty import au.com.dius.pact.core.support.jsonObject -import com.github.michaelbull.result.Err -import com.github.michaelbull.result.Ok -import com.github.michaelbull.result.Result import io.pact.plugins.jvm.core.PluginConfiguration import mu.KLogging import java.lang.Integer.max @@ -47,7 +45,7 @@ data class BodyComparisonResult( data class ComparisonResult( val statusMismatch: StatusMismatch? = null, val headerMismatches: Map> = emptyMap(), - val bodyMismatches: Result = Ok(BodyComparisonResult()), + val bodyMismatches: Result = Result.Ok(BodyComparisonResult()), val metadataMismatches: Map> = emptyMap() ) @@ -82,7 +80,7 @@ class ResponseComparison( ): Result { val bodyTypeMismatch = mismatches.filterIsInstance().firstOrNull() return if (bodyTypeMismatch != null) { - Err(bodyTypeMismatch) + Result.Err(bodyTypeMismatch) } else { val bodyMismatches = mismatches .filterIsInstance() @@ -92,17 +90,17 @@ class ResponseComparison( val expected = expectedBody.valueAsString() val actual = actualBody.orEmpty() val diff = when (val shouldIncludeDiff = shouldGenerateDiff(resolver, max(actual.size, expected.length))) { - is Ok -> if (shouldIncludeDiff.value) { + is Result.Ok -> if (shouldIncludeDiff.value) { generateFullDiff(actual.toString(contentType.asCharset()), contentType, expected, isJsonBody) } else { emptyList() } - is Err -> { + is Result.Err -> { logger.warn { "Invalid value for property 'pact.verifier.generateDiff' - ${shouldIncludeDiff.error}" } emptyList() } } - Ok(BodyComparisonResult(bodyMismatches, diff)) + Result.Ok(BodyComparisonResult(bodyMismatches, diff)) } } @@ -137,16 +135,16 @@ class ResponseComparison( @JvmStatic fun shouldGenerateDiff(resolver: ValueResolver, length: Int): Result { val shouldIncludeDiff = resolver.resolveValue("pact.verifier.generateDiff", "NOT_SET") - return when (val v = shouldIncludeDiff?.toLowerCase()) { - "true", "not_set" -> Ok(true) - "false" -> Ok(false) + return when (val v = shouldIncludeDiff?.lowercase()) { + "true", "not_set" -> Result.Ok(true) + "false" -> Result.Ok(false) else -> if (v.isNotEmpty()) { when (val result = sizeOf(v!!)) { - is Ok -> Ok(length <= result.value) - is Err -> result + is Result.Ok -> Result.Ok(length <= result.value) + is Result.Err -> result } } else { - Ok(false) + Result.Ok(false) } } } diff --git a/provider/src/main/kotlin/au/com/dius/pact/provider/StateChange.kt b/provider/src/main/kotlin/au/com/dius/pact/provider/StateChange.kt index d2f8708f7c..b696c52112 100644 --- a/provider/src/main/kotlin/au/com/dius/pact/provider/StateChange.kt +++ b/provider/src/main/kotlin/au/com/dius/pact/provider/StateChange.kt @@ -3,12 +3,9 @@ package au.com.dius.pact.provider import au.com.dius.pact.core.model.Interaction import au.com.dius.pact.core.model.ProviderState import au.com.dius.pact.core.support.Json +import au.com.dius.pact.core.support.Result import au.com.dius.pact.core.support.json.JsonParser -import com.github.michaelbull.result.Err -import com.github.michaelbull.result.Ok -import com.github.michaelbull.result.Result -import com.github.michaelbull.result.mapEither -import com.github.michaelbull.result.unwrap +import au.com.dius.pact.core.support.mapEither import groovy.lang.Closure import mu.KLogging import org.apache.hc.core5.http.ContentType @@ -67,12 +64,12 @@ object DefaultStateChange : StateChange, KLogging() { providerClient: ProviderClient ): StateChangeResult { var message = interactionMessage - var stateChangeResult: Result, Exception> = Ok(emptyMap()) + var stateChangeResult: Result, Exception> = Result.Ok(emptyMap()) if (interaction.providerStates.isNotEmpty()) { val iterator = interaction.providerStates.iterator() var first = true - while (stateChangeResult is Ok && iterator.hasNext()) { + while (stateChangeResult is Result.Ok && iterator.hasNext()) { val providerState = iterator.next() val result = stateChange(verifier, providerState, provider, consumer, true, providerClient) logger.debug { "State Change: \"$providerState\" -> $result" } @@ -114,11 +111,11 @@ object DefaultStateChange : StateChange, KLogging() { } if (stateChangeHandler == null || (stateChangeHandler is String && stateChangeHandler.isBlank())) { verifier.reporters.forEach { it.warnStateChangeIgnored(state.name.toString(), provider, consumer) } - return Ok(emptyMap()) + return Result.Ok(emptyMap()) } else if (verifier.checkBuildSpecificTask.apply(stateChangeHandler)) { logger.debug { "Invoking build specific task $stateChangeHandler" } verifier.executeBuildSpecificTask.accept(stateChangeHandler, state) - return Ok(emptyMap()) + return Result.Ok(emptyMap()) } else if (stateChangeHandler is Closure<*>) { val result = if (provider.stateChangeTeardown) { stateChangeHandler.call(state, if (isSetup) "setup" else "teardown") @@ -127,7 +124,7 @@ object DefaultStateChange : StateChange, KLogging() { } logger.debug { "Invoked state change closure -> $result" } if (result !is URL) { - return Ok(if (result is Map<*, *>) result as Map else emptyMap()) + return Result.Ok(if (result is Map<*, *>) result as Map else emptyMap()) } stateChangeHandler = result } @@ -135,7 +132,7 @@ object DefaultStateChange : StateChange, KLogging() { providerClient) } catch (e: Exception) { verifier.reportStateChangeFailed(state, e, isSetup) - return Err(e) + return Result.Err(e) } } @@ -174,16 +171,16 @@ object DefaultStateChange : StateChange, KLogging() { "${response.code} ${response.reasonPhrase}" ) } - Err(Exception("State Change Request Failed - ${response.code} ${response.reasonPhrase}")) + Result.Err(Exception("State Change Request Failed - ${response.code} ${response.reasonPhrase}")) } else { parseJsonResponse(response.entity) } - } ?: Ok(emptyMap()) + } ?: Result.Ok(emptyMap()) } catch (ex: URISyntaxException) { verifier.reporters.forEach { it.warnStateChangeIgnoredDueToInvalidUrl(state.name.toString(), provider, isSetup, stateChangeHandler) } - Ok(emptyMap()) + Result.Ok(emptyMap()) } } @@ -191,13 +188,13 @@ object DefaultStateChange : StateChange, KLogging() { return if (entity != null) { val contentType: ContentType? = ContentType.parse(entity.contentType) if (contentType != null && contentType.mimeType == ContentType.APPLICATION_JSON.mimeType) { - val body = EntityUtils.toString(entity) - Ok(Json.toMap(JsonParser.parseString(body))) - } else { - Ok(emptyMap()) - } + val body = EntityUtils.toString(entity) + Result.Ok(Json.toMap(JsonParser.parseString(body))) + } else { + Result.Ok(emptyMap()) + } } else { - Ok(emptyMap()) + Result.Ok(emptyMap()) } } } diff --git a/provider/src/main/kotlin/au/com/dius/pact/provider/TestResultAccumulator.kt b/provider/src/main/kotlin/au/com/dius/pact/provider/TestResultAccumulator.kt index e7cd5f12aa..4200a4bff5 100644 --- a/provider/src/main/kotlin/au/com/dius/pact/provider/TestResultAccumulator.kt +++ b/provider/src/main/kotlin/au/com/dius/pact/provider/TestResultAccumulator.kt @@ -5,12 +5,11 @@ import au.com.dius.pact.core.model.Interaction import au.com.dius.pact.core.model.Pact import au.com.dius.pact.core.model.PactSource import au.com.dius.pact.core.pactbroker.TestResult +import au.com.dius.pact.core.support.Result import au.com.dius.pact.core.support.expressions.SystemPropertyResolver import au.com.dius.pact.core.support.expressions.ValueResolver import au.com.dius.pact.core.support.isNotEmpty import au.com.dius.pact.provider.ProviderVerifier.Companion.PACT_VERIFIER_PUBLISH_RESULTS -import com.github.michaelbull.result.Ok -import com.github.michaelbull.result.Result import mu.KLogging import org.apache.commons.lang3.builder.HashCodeBuilder @@ -82,7 +81,7 @@ object DefaultTestResultAccumulator : TestResultAccumulator, KLogging() { "Skipping publishing of verification results as it has been disabled " + "($PACT_VERIFIER_PUBLISH_RESULTS is not 'true')" } - Ok(false) + Result.Ok(false) } else { val calculatedTestResult = interactionResults.values.reduce { acc: TestResult, result -> acc.merge(result) } verificationReporter.reportResults(pact, calculatedTestResult, lookupProviderVersion(propertyResolver), @@ -95,7 +94,7 @@ object DefaultTestResultAccumulator : TestResultAccumulator, KLogging() { unverifiedInteractions.forEach { logger.warn { " ${it.description}" } } - Ok(true) + Result.Ok(true) } } diff --git a/provider/src/main/kotlin/au/com/dius/pact/provider/VerificationReporter.kt b/provider/src/main/kotlin/au/com/dius/pact/provider/VerificationReporter.kt index 928caa4697..49fca01d4a 100644 --- a/provider/src/main/kotlin/au/com/dius/pact/provider/VerificationReporter.kt +++ b/provider/src/main/kotlin/au/com/dius/pact/provider/VerificationReporter.kt @@ -6,12 +6,10 @@ import au.com.dius.pact.core.pactbroker.IPactBrokerClient import au.com.dius.pact.core.pactbroker.PactBrokerClient import au.com.dius.pact.core.pactbroker.PactBrokerClientConfig import au.com.dius.pact.core.pactbroker.TestResult +import au.com.dius.pact.core.support.Result import au.com.dius.pact.core.support.expressions.SystemPropertyResolver import au.com.dius.pact.core.support.expressions.ValueResolver -import com.github.michaelbull.result.Err -import com.github.michaelbull.result.Ok -import com.github.michaelbull.result.Result -import com.github.michaelbull.result.mapError +import au.com.dius.pact.core.support.mapError import mu.KLogging /** @@ -91,7 +89,7 @@ object DefaultVerificationReporter : VerificationReporter, KLogging() { } else -> { logger.info { "Skipping publishing verification results for source $source" } - Ok(false) + Result.Ok(false) } } } @@ -108,12 +106,12 @@ object DefaultVerificationReporter : VerificationReporter, KLogging() { val branchResult = if (branch?.isNotBlank() == true) { brokerClient.publishProviderBranch(source.attributes, pact.provider.name, branch, version) } else { - Ok(true) + Result.Ok(true) } val tagsResult = if (tags.isNotEmpty()) { brokerClient.publishProviderTags(source.attributes, pact.provider.name, tags, version) } else { - Ok(true) + Result.Ok(true) } val buildUrl = System.getProperty(ProviderVerifier.PACT_VERIFIER_BUILD_URL) val publishResult = if (buildUrl.isNullOrEmpty()) { @@ -121,18 +119,18 @@ object DefaultVerificationReporter : VerificationReporter, KLogging() { } else { brokerClient.publishVerificationResults(source.attributes, result, version, buildUrl) } - if (publishResult is Err) { + if (publishResult is Result.Err) { logger.error { "Failed to publish verification results - ${publishResult.error}" } } else { logger.info { "Published verification result of '$result' for consumer '${pact.consumer}'" } } return when { - tagsResult is Err && branchResult is Ok && publishResult is Ok -> tagsResult - branchResult is Err && tagsResult is Ok && publishResult is Ok -> branchResult.mapError { listOf(it) } - tagsResult is Err && branchResult is Err && publishResult is Ok -> Err( + tagsResult is Result.Err && branchResult is Result.Ok && publishResult is Result.Ok -> tagsResult + branchResult is Result.Err && tagsResult is Result.Ok && publishResult is Result.Ok -> branchResult.mapError { listOf(it) } + tagsResult is Result.Err && branchResult is Result.Err && publishResult is Result.Ok -> Result.Err( tagsResult.error + branchResult.error) - tagsResult is Err && branchResult is Err && publishResult is Err -> Err( + tagsResult is Result.Err && branchResult is Result.Err && publishResult is Result.Err -> Result.Err( tagsResult.error + branchResult.error + publishResult.error) else -> publishResult.mapError { listOf(it) } } diff --git a/provider/src/main/kotlin/au/com/dius/pact/provider/VerificationResult.kt b/provider/src/main/kotlin/au/com/dius/pact/provider/VerificationResult.kt index e54e50f002..17d6e1f289 100644 --- a/provider/src/main/kotlin/au/com/dius/pact/provider/VerificationResult.kt +++ b/provider/src/main/kotlin/au/com/dius/pact/provider/VerificationResult.kt @@ -8,6 +8,7 @@ import au.com.dius.pact.core.matchers.QueryMismatch import au.com.dius.pact.core.model.Interaction import au.com.dius.pact.core.model.Pact import au.com.dius.pact.core.pactbroker.TestResult +import au.com.dius.pact.core.support.Result import au.com.dius.pact.core.support.isNotEmpty import com.github.ajalt.mordant.TermColors import com.github.michaelbull.result.Err @@ -83,12 +84,12 @@ sealed class VerificationFailureType { data class StateChangeFailure(val description: String, val result: StateChangeResult) : VerificationFailureType() { override fun description() = formatForDisplay(TermColors()) override fun formatForDisplay(t: TermColors): String { - val e = result.stateChangeResult.getError() + val e = result.stateChangeResult.errorValue() return "State change callback failed with an exception - " + e?.message.toString() } - override fun hasException() = result.stateChangeResult is Err - override fun getException() = result.stateChangeResult.getError() + override fun hasException() = result.stateChangeResult is Result.Err + override fun getException() = result.stateChangeResult.errorValue() } data class PublishResultsFailure(val cause: List) : VerificationFailureType() { diff --git a/provider/src/main/kotlin/au/com/dius/pact/provider/junitsupport/loader/PactBrokerLoader.kt b/provider/src/main/kotlin/au/com/dius/pact/provider/junitsupport/loader/PactBrokerLoader.kt index e8dc378764..a5c57833cd 100644 --- a/provider/src/main/kotlin/au/com/dius/pact/provider/junitsupport/loader/PactBrokerLoader.kt +++ b/provider/src/main/kotlin/au/com/dius/pact/provider/junitsupport/loader/PactBrokerLoader.kt @@ -12,14 +12,13 @@ import au.com.dius.pact.core.pactbroker.ConsumerVersionSelectors import au.com.dius.pact.core.pactbroker.IPactBrokerClient import au.com.dius.pact.core.pactbroker.PactBrokerClient import au.com.dius.pact.core.pactbroker.PactBrokerClientConfig +import au.com.dius.pact.core.support.Result import au.com.dius.pact.core.support.Utils.permutations import au.com.dius.pact.core.support.expressions.DataType import au.com.dius.pact.core.support.expressions.ExpressionParser import au.com.dius.pact.core.support.expressions.SystemPropertyResolver import au.com.dius.pact.core.support.expressions.ValueResolver import au.com.dius.pact.core.support.isNotEmpty -import com.github.michaelbull.result.Err -import com.github.michaelbull.result.Ok import mu.KLogging import org.apache.hc.core5.net.URIBuilder import java.io.IOException @@ -33,7 +32,6 @@ import kotlin.reflect.full.companionObjectInstance import kotlin.reflect.full.declaredFunctions import kotlin.reflect.full.hasAnnotation import kotlin.reflect.full.isSubtypeOf -import kotlin.reflect.full.memberFunctions import kotlin.reflect.full.starProjectedType import kotlin.reflect.jvm.javaMethod import kotlin.reflect.jvm.kotlinFunction @@ -250,8 +248,8 @@ open class PactBrokerLoader( val result = pactBrokerClient.fetchConsumersWithSelectorsV2(providerName, selectors, providerTags, providerBranch, pending, wipSinceDate) var consumers = when (result) { - is Ok -> result.value - is Err -> throw result.error + is Result.Ok -> result.value + is Result.Err -> throw result.error } if (failIfNoPactsFound && consumers.isEmpty()) { diff --git a/provider/src/main/kotlin/au/com/dius/pact/provider/reporters/Events.kt b/provider/src/main/kotlin/au/com/dius/pact/provider/reporters/Events.kt index 98de7edeed..7eeb21d042 100644 --- a/provider/src/main/kotlin/au/com/dius/pact/provider/reporters/Events.kt +++ b/provider/src/main/kotlin/au/com/dius/pact/provider/reporters/Events.kt @@ -4,7 +4,7 @@ import au.com.dius.pact.core.matchers.BodyTypeMismatch import au.com.dius.pact.core.model.Interaction import au.com.dius.pact.core.support.json.JsonValue import au.com.dius.pact.provider.BodyComparisonResult -import com.github.michaelbull.result.Result +import au.com.dius.pact.core.support.Result sealed class Event { data class ErrorHasNoAnnotatedMethodsFoundForInteraction(val interaction: Interaction) : Event() diff --git a/provider/src/test/groovy/au/com/dius/pact/provider/DefaultVerificationReporterSpec.groovy b/provider/src/test/groovy/au/com/dius/pact/provider/DefaultVerificationReporterSpec.groovy index f072efd6a1..c4dbd7c1ab 100644 --- a/provider/src/test/groovy/au/com/dius/pact/provider/DefaultVerificationReporterSpec.groovy +++ b/provider/src/test/groovy/au/com/dius/pact/provider/DefaultVerificationReporterSpec.groovy @@ -9,8 +9,7 @@ import au.com.dius.pact.core.model.UnknownPactSource import au.com.dius.pact.core.pactbroker.IPactBrokerClient import au.com.dius.pact.core.pactbroker.PactBrokerClient import au.com.dius.pact.core.pactbroker.TestResult -import com.github.michaelbull.result.Err -import com.github.michaelbull.result.Ok +import au.com.dius.pact.core.support.Result import spock.lang.Specification import spock.util.environment.RestoreSystemProperties @@ -31,8 +30,8 @@ class DefaultVerificationReporterSpec extends Specification { def result = DefaultVerificationReporter.INSTANCE.reportResults(pact, testResult, '0', brokerClient, [], null) then: - 1 * brokerClient.publishVerificationResults(links, testResult, '0') >> new Ok(true) - result == new Ok(true) + 1 * brokerClient.publishVerificationResults(links, testResult, '0') >> new Result.Ok(true) + result == new Result.Ok(true) } @RestoreSystemProperties @@ -52,8 +51,8 @@ class DefaultVerificationReporterSpec extends Specification { then: 1 * brokerClient.publishVerificationResults(links, testResult, '0', 'https://buildsystem.com/job/1234') >> - new Ok(true) - result == new Ok(true) + new Result.Ok(true) + result == new Result.Ok(true) } @RestoreSystemProperties @@ -74,8 +73,8 @@ class DefaultVerificationReporterSpec extends Specification { def result = DefaultVerificationReporter.INSTANCE.reportResults(pact, testResult, '0', brokerClient, [], null) then: - 1 * brokerClient.publishVerificationResults(links, testResult, '0', buildUrl) >> new Ok(true) - result == new Ok(true) + 1 * brokerClient.publishVerificationResults(links, testResult, '0', buildUrl) >> new Result.Ok(true) + result == new Result.Ok(true) } def 'for non-Pact broker sources, do not publish anything and return Ok'() { @@ -92,7 +91,7 @@ class DefaultVerificationReporterSpec extends Specification { then: 0 * brokerClient.publishVerificationResults(_, new TestResult.Ok(), '0') - result == new Ok(false) + result == new Result.Ok(false) } def 'return an error if publishing the test results fails'() { @@ -108,8 +107,8 @@ class DefaultVerificationReporterSpec extends Specification { def result = DefaultVerificationReporter.INSTANCE.reportResults(pact, testResult, '', brokerClient, [], null) then: - 1 * brokerClient.publishVerificationResults(_, testResult, _) >> new Err('failed') - result == new Err(['failed']) + 1 * brokerClient.publishVerificationResults(_, testResult, _) >> new Result.Err('failed') + result == new Result.Err(['failed']) } def 'return an error if publishing the provider tag fails'() { @@ -127,9 +126,9 @@ class DefaultVerificationReporterSpec extends Specification { then: 0 * brokerClient.publishProviderBranch(_, 'provider', _, '') - 1 * brokerClient.publishProviderTags(_, 'provider', tags, '') >> new Err(['failed']) - 1 * brokerClient.publishVerificationResults(_, testResult, _) >> new Ok(true) - result == new Err(['failed']) + 1 * brokerClient.publishProviderTags(_, 'provider', tags, '') >> new Result.Err(['failed']) + 1 * brokerClient.publishVerificationResults(_, testResult, _) >> new Result.Ok(true) + result == new Result.Err(['failed']) } def 'return an error if publishing the provider branch fails'() { @@ -147,9 +146,9 @@ class DefaultVerificationReporterSpec extends Specification { then: 0 * brokerClient.publishProviderTags(_, 'provider', _, '') - 1 * brokerClient.publishProviderBranch(_, 'provider', branch, '') >> new Err('failed') - 1 * brokerClient.publishVerificationResults(_, testResult, _) >> new Ok(true) - result == new Err(['failed']) + 1 * brokerClient.publishProviderBranch(_, 'provider', branch, '') >> new Result.Err('failed') + 1 * brokerClient.publishVerificationResults(_, testResult, _) >> new Result.Ok(true) + result == new Result.Err(['failed']) } def 'return list of errors if publishing the provider tags and branch fails'() { @@ -167,9 +166,9 @@ class DefaultVerificationReporterSpec extends Specification { def result = DefaultVerificationReporter.INSTANCE.reportResults(pact, testResult, '', brokerClient, tags, branch) then: - 1 * brokerClient.publishProviderTags(_, 'provider', tags, '') >> new Err(['tags failed']) - 1 * brokerClient.publishProviderBranch(_, 'provider', branch, '') >> new Err('branch failed') - 1 * brokerClient.publishVerificationResults(_, testResult, _) >> new Ok(true) - result == new Err(['tags failed', 'branch failed']) + 1 * brokerClient.publishProviderTags(_, 'provider', tags, '') >> new Result.Err(['tags failed']) + 1 * brokerClient.publishProviderBranch(_, 'provider', branch, '') >> new Result.Err('branch failed') + 1 * brokerClient.publishVerificationResults(_, testResult, _) >> new Result.Ok(true) + result == new Result.Err(['tags failed', 'branch failed']) } } diff --git a/provider/src/test/groovy/au/com/dius/pact/provider/MessageComparisonSpec.groovy b/provider/src/test/groovy/au/com/dius/pact/provider/MessageComparisonSpec.groovy index 535d3a4db0..73419d00bd 100644 --- a/provider/src/test/groovy/au/com/dius/pact/provider/MessageComparisonSpec.groovy +++ b/provider/src/test/groovy/au/com/dius/pact/provider/MessageComparisonSpec.groovy @@ -4,7 +4,7 @@ import au.com.dius.pact.core.model.OptionalBody import au.com.dius.pact.core.model.generators.Generators import au.com.dius.pact.core.model.matchingrules.MatchingRulesImpl import au.com.dius.pact.core.model.messaging.Message -import com.github.michaelbull.result.Ok +import au.com.dius.pact.core.support.Result import spock.lang.Specification @SuppressWarnings('LineLength') @@ -19,7 +19,7 @@ class MessageComparisonSpec extends Specification { def result = ResponseComparison.compareMessage(message, actual).bodyMismatches then: - result instanceof Ok + result instanceof Result.Ok result.value.mismatches.collectEntries { [ it.key, it.value*.description() ] } == [ '$.b': ['Expected \'2\' (String) but received \'3\' (String)'] ] @@ -35,7 +35,7 @@ class MessageComparisonSpec extends Specification { def result = ResponseComparison.compareMessage(message, actual).bodyMismatches then: - result instanceof Ok + result instanceof Result.Ok result.value.mismatches.collectEntries { [ it.key, it.value*.description() ] } == [ '/': [ 'Expected body \'{"a":1,"b":"2"}\' to match \'{"a":1,"b":"3"}\' using equality but did not match' diff --git a/provider/src/test/groovy/au/com/dius/pact/provider/ProviderInfoSpec.groovy b/provider/src/test/groovy/au/com/dius/pact/provider/ProviderInfoSpec.groovy index 4389a50a45..72408821c5 100644 --- a/provider/src/test/groovy/au/com/dius/pact/provider/ProviderInfoSpec.groovy +++ b/provider/src/test/groovy/au/com/dius/pact/provider/ProviderInfoSpec.groovy @@ -4,7 +4,7 @@ import au.com.dius.pact.core.pactbroker.ConsumerVersionSelectors import au.com.dius.pact.core.pactbroker.PactBrokerClient import au.com.dius.pact.core.pactbroker.PactBrokerResult import au.com.dius.pact.core.support.Auth -import com.github.michaelbull.result.Ok +import au.com.dius.pact.core.support.Result import spock.lang.Issue import spock.lang.Specification @@ -76,7 +76,7 @@ class ProviderInfoSpec extends Specification { def result = providerInfo.hasPactsFromPactBrokerWithSelectorsV2(options, url, selectors) then: - pactBrokerClient.fetchConsumersWithSelectorsV2('TestProvider', selectors, [], '', false, '') >> new Ok([ + pactBrokerClient.fetchConsumersWithSelectorsV2('TestProvider', selectors, [], '', false, '') >> new Result.Ok([ new PactBrokerResult('consumer', '', url, [], [], false, null, false, false, null) ]) result.size() == 1 @@ -99,7 +99,7 @@ class ProviderInfoSpec extends Specification { def result = providerInfo.hasPactsFromPactBrokerWithSelectorsV2(options, url, selectors) then: - pactBrokerClient.fetchConsumersWithSelectorsV2('TestProvider', selectors, ['master'], '', true, '') >> new Ok([ + pactBrokerClient.fetchConsumersWithSelectorsV2('TestProvider', selectors, ['master'], '', true, '') >> new Result.Ok([ new PactBrokerResult('consumer', '', url, [], [], true, null, false, false, null) ]) result.size() == 1 @@ -122,7 +122,7 @@ class ProviderInfoSpec extends Specification { def result = providerInfo.hasPactsFromPactBrokerWithSelectorsV2(options, url, selectors) then: - pactBrokerClient.fetchConsumersWithSelectorsV2('TestProvider', selectors, [], 'master', true, '') >> new Ok([ + pactBrokerClient.fetchConsumersWithSelectorsV2('TestProvider', selectors, [], 'master', true, '') >> new Result.Ok([ new PactBrokerResult('consumer', '', url, [], [], true, null, false, false, null) ]) result.size() == 1 @@ -164,7 +164,7 @@ class ProviderInfoSpec extends Specification { def result = providerInfo.hasPactsFromPactBrokerWithSelectorsV2(options, url, selectors) then: - pactBrokerClient.fetchConsumersWithSelectorsV2('TestProvider', selectors, ['master'], '', true, '') >> new Ok([ + pactBrokerClient.fetchConsumersWithSelectorsV2('TestProvider', selectors, ['master'], '', true, '') >> new Result.Ok([ new PactBrokerResult('consumer', '', url, [], [], false, null, false, false, null) ]) result.size() == 1 @@ -188,7 +188,7 @@ class ProviderInfoSpec extends Specification { def result = providerInfo.hasPactsFromPactBrokerWithSelectorsV2(options, url, selectors) then: - pactBrokerClient.fetchConsumersWithSelectorsV2('TestProvider', selectors, ['master'], '', true, '2020-05-23') >> new Ok([ + pactBrokerClient.fetchConsumersWithSelectorsV2('TestProvider', selectors, ['master'], '', true, '2020-05-23') >> new Result.Ok([ new PactBrokerResult('consumer', '', url, [], [], true, null, true, false, null) ]) result.size() == 1 @@ -210,7 +210,7 @@ class ProviderInfoSpec extends Specification { then: providerInfo.pactBrokerClient(_, { it.auth == new Auth.BearerAuthentication('Authorization', '123ABC') }) >> pactBrokerClient - pactBrokerClient.fetchConsumersWithSelectorsV2('TestProvider', selectors, [], '', false, '') >> new Ok([ + pactBrokerClient.fetchConsumersWithSelectorsV2('TestProvider', selectors, [], '', false, '') >> new Result.Ok([ new PactBrokerResult('consumer', '', url, [], [], true, null, true, false, null) ]) result.size() == 1 diff --git a/provider/src/test/groovy/au/com/dius/pact/provider/ProviderVerifierSpec.groovy b/provider/src/test/groovy/au/com/dius/pact/provider/ProviderVerifierSpec.groovy index 31e9dfd48b..94602763e6 100644 --- a/provider/src/test/groovy/au/com/dius/pact/provider/ProviderVerifierSpec.groovy +++ b/provider/src/test/groovy/au/com/dius/pact/provider/ProviderVerifierSpec.groovy @@ -29,11 +29,10 @@ import au.com.dius.pact.core.model.v4.MessageContents import au.com.dius.pact.core.pactbroker.IPactBrokerClient import au.com.dius.pact.core.pactbroker.PactBrokerClient import au.com.dius.pact.core.pactbroker.TestResult +import au.com.dius.pact.core.support.Result import au.com.dius.pact.core.support.expressions.SystemPropertyResolver import au.com.dius.pact.provider.reporters.Event import au.com.dius.pact.provider.reporters.VerifierReporter -import com.github.michaelbull.result.Err -import com.github.michaelbull.result.Ok import groovy.json.JsonOutput import spock.lang.Specification import spock.lang.Unroll @@ -421,7 +420,7 @@ class ProviderVerifierSpec extends Specification { verifier.verificationReporter = Mock(VerificationReporter) verifier.pactReader = Stub(PactReader) def statechange = Stub(StateChange) { - executeStateChange(*_) >> new StateChangeResult(new Ok([:])) + executeStateChange(*_) >> new StateChangeResult(new Result.Ok([:])) } def interaction1 = Stub(RequestResponseInteraction) def interaction2 = Stub(RequestResponseInteraction) @@ -445,7 +444,8 @@ class ProviderVerifierSpec extends Specification { verifier.runVerificationForConsumer([:], provider, consumer, pactBrokerClient) then: - 1 * verifier.verificationReporter.reportResults(_, finalResult, '0.0.0', pactBrokerClient, tags, _) >> new Ok(true) + 1 * verifier.verificationReporter.reportResults(_, finalResult, '0.0.0', pactBrokerClient, tags, _) >> + new Result.Ok(true) 1 * verifier.verifyResponseFromProvider(provider, interaction1, _, _, _, _, false) >> result1 1 * verifier.verifyResponseFromProvider(provider, interaction2, _, _, _, _, false) >> result2 @@ -469,7 +469,7 @@ class ProviderVerifierSpec extends Specification { verifier.verificationReporter = Mock(VerificationReporter) verifier.pactReader = Stub(PactReader) def statechange = Stub(StateChange) { - executeStateChange(*_) >> new StateChangeResult(new Ok([:])) + executeStateChange(*_) >> new StateChangeResult(new Result.Ok([:])) } def interaction1 = Stub(RequestResponseInteraction) def interaction2 = Stub(RequestResponseInteraction) @@ -493,7 +493,7 @@ class ProviderVerifierSpec extends Specification { verifier.runVerificationForConsumer([:], provider, consumer, pactBrokerClient) then: - 1 * verifier.verificationReporter.reportResults(_, finalResult, '0.0.0', pactBrokerClient, [], branch) >> new Ok(true) + 1 * verifier.verificationReporter.reportResults(_, finalResult, '0.0.0', pactBrokerClient, [], branch) >> new Result.Ok(true) 1 * verifier.verifyResponseFromProvider(provider, interaction1, _, _, _, _, false) >> result1 1 * verifier.verifyResponseFromProvider(provider, interaction2, _, _, _, _, false) >> result2 @@ -514,7 +514,7 @@ class ProviderVerifierSpec extends Specification { verifier.verificationReporter = Mock(VerificationReporter) verifier.pactReader = Stub(PactReader) def statechange = Stub(StateChange) { - executeStateChange(*_) >> new StateChangeResult(new Ok([:])) + executeStateChange(*_) >> new StateChangeResult(new Result.Ok([:])) } def interaction1 = Stub(RequestResponseInteraction) def interaction2 = Stub(RequestResponseInteraction) @@ -535,7 +535,8 @@ class ProviderVerifierSpec extends Specification { def result = verifier.runVerificationForConsumer([:], provider, consumer, pactBrokerClient) then: - 1 * verifier.verificationReporter.reportResults(_, _, '0.0.0', pactBrokerClient, [], _) >> new Err(['failed']) + 1 * verifier.verificationReporter.reportResults(_, _, '0.0.0', pactBrokerClient, [], _) >> + new Result.Err(['failed']) 1 * verifier.verifyResponseFromProvider(provider, interaction1, _, _, _, _, false) >> new VerificationResult.Ok() 1 * verifier.verifyResponseFromProvider(provider, interaction2, _, _, _, _, false) >> new VerificationResult.Ok() result instanceof VerificationResult.Failed @@ -550,7 +551,7 @@ class ProviderVerifierSpec extends Specification { ConsumerInfo consumer = new ConsumerInfo(name: 'Test Consumer', pactSource: UnknownPactSource.INSTANCE) verifier.pactReader = Mock(PactReader) def statechange = Mock(StateChange) { - executeStateChange(*_) >> new StateChangeResult(new Ok([:])) + executeStateChange(*_) >> new StateChangeResult(new Result.Ok([:])) } def interaction1 = Mock(RequestResponseInteraction) { getDescription() >> 'Interaction 1' @@ -614,7 +615,7 @@ class ProviderVerifierSpec extends Specification { then: 1 * verifier.pactReader.loadPact(_) >> pact - 1 * statechange.executeStateChange(_, _, _, _, _, _, _) >> new StateChangeResult(new Ok([:]), '') + 1 * statechange.executeStateChange(_, _, _, _, _, _, _) >> new StateChangeResult(new Result.Ok([:]), '') 1 * verifier.verifyResponseByInvokingProviderMethods(providerInfo, consumerInfo, interaction, _, _, false) >> new VerificationResult.Ok() 0 * client.publishVerificationResults(_, new TestResult.Ok(), _, _) } @@ -675,7 +676,7 @@ class ProviderVerifierSpec extends Specification { result.description == 'State change request failed' result.failures.size() == 1 result.failures['1234'][0].description == 'Provider state change callback failed' - result.failures['1234'][0].result.stateChangeResult instanceof Err + result.failures['1234'][0].result.stateChangeResult instanceof Result.Err } def 'verifyInteraction returns an error result if any matcher paths are invalid'() { diff --git a/provider/src/test/groovy/au/com/dius/pact/provider/ResponseComparisonSpec.groovy b/provider/src/test/groovy/au/com/dius/pact/provider/ResponseComparisonSpec.groovy index e72ed32f37..dfc33c9495 100644 --- a/provider/src/test/groovy/au/com/dius/pact/provider/ResponseComparisonSpec.groovy +++ b/provider/src/test/groovy/au/com/dius/pact/provider/ResponseComparisonSpec.groovy @@ -10,8 +10,7 @@ import au.com.dius.pact.core.model.matchingrules.MatchingRulesImpl import au.com.dius.pact.core.model.messaging.Message import au.com.dius.pact.core.model.messaging.MessageInteraction import au.com.dius.pact.core.support.expressions.SystemPropertyResolver -import com.github.michaelbull.result.Err -import com.github.michaelbull.result.Ok +import au.com.dius.pact.core.support.Result import spock.lang.Issue import spock.lang.Specification import spock.lang.Unroll @@ -83,7 +82,7 @@ class ResponseComparisonSpec extends Specification { def result = subject().bodyMismatches then: - result instanceof Err + result instanceof Result.Err result.error.description() == 'Expected a response type of \'application/json\' but the actual type was \'text/plain\'' } @@ -93,7 +92,7 @@ class ResponseComparisonSpec extends Specification { def result = subject().bodyMismatches expect: - result instanceof Ok + result instanceof Result.Ok result.value.mismatches.isEmpty() } @@ -105,7 +104,7 @@ class ResponseComparisonSpec extends Specification { def result = subject().bodyMismatches expect: - result instanceof Ok + result instanceof Result.Ok result.value.mismatches.isEmpty() } @@ -115,7 +114,7 @@ class ResponseComparisonSpec extends Specification { def result = subject().bodyMismatches expect: - result instanceof Ok + result instanceof Result.Ok result.value.mismatches.collectEntries { [ it.key, it.value*.description() ] } == [ '$.stuff': ["Expected 'is good' (String) but received 'should make the test fail' (String)"] ] @@ -164,14 +163,14 @@ class ResponseComparisonSpec extends Specification { where: desc | value || result - 'if property is not set' | null || new Ok(true) - 'if property is empty' | '' || new Ok(false) - 'if property is true' | 'true' || new Ok(true) - 'if property is false' | 'FALSE' || new Ok(false) - 'if property > data size' | '2kb' || new Ok(false) - 'if property == data size' | '4kb' || new Ok(true) - 'if property < data size' | '8kb' || new Ok(true) - 'if property is invalid' | 'jhjhj' || new Err("'jhjhj' is not a valid data size") + 'if property is not set' | null || new Result.Ok(true) + 'if property is empty' | '' || new Result.Ok(false) + 'if property is true' | 'true' || new Result.Ok(true) + 'if property is false' | 'FALSE' || new Result.Ok(false) + 'if property > data size' | '2kb' || new Result.Ok(false) + 'if property == data size' | '4kb' || new Result.Ok(true) + 'if property < data size' | '8kb' || new Result.Ok(true) + 'if property is invalid' | 'jhjhj' || new Result.Err("'jhjhj' is not a valid data size") } @Issue('#1375') @@ -183,7 +182,7 @@ class ResponseComparisonSpec extends Specification { def result = subject().bodyMismatches expect: - result instanceof Ok + result instanceof Result.Ok result.value.mismatches.collectEntries { [ it.key, it.value*.description() ] } == [ '$.stuff': ["Expected 'is good' (String) but received 'should make the test fail' (String)"] ] diff --git a/provider/src/test/groovy/au/com/dius/pact/provider/StateChangeSpec.groovy b/provider/src/test/groovy/au/com/dius/pact/provider/StateChangeSpec.groovy index 78e18e4c5f..a6ee933c0a 100644 --- a/provider/src/test/groovy/au/com/dius/pact/provider/StateChangeSpec.groovy +++ b/provider/src/test/groovy/au/com/dius/pact/provider/StateChangeSpec.groovy @@ -4,7 +4,7 @@ import au.com.dius.pact.core.model.ContentType import au.com.dius.pact.core.model.Interaction import au.com.dius.pact.core.model.OptionalBody import au.com.dius.pact.core.model.ProviderState -import com.github.michaelbull.result.Ok +import au.com.dius.pact.core.support.Result import org.apache.hc.core5.http.ClassicHttpResponse import org.apache.hc.core5.http.HttpEntity import spock.lang.Specification @@ -45,7 +45,7 @@ class StateChangeSpec extends Specification { mockProviderClient) then: - result instanceof Ok + result instanceof Result.Ok makeStateChangeRequestArgs == [] } @@ -58,7 +58,7 @@ class StateChangeSpec extends Specification { mockProviderClient) then: - result instanceof Ok + result instanceof Result.Ok makeStateChangeRequestArgs == [] } @@ -71,7 +71,7 @@ class StateChangeSpec extends Specification { mockProviderClient) then: - result instanceof Ok + result instanceof Result.Ok makeStateChangeRequestArgs == [] } @@ -84,7 +84,7 @@ class StateChangeSpec extends Specification { mockProviderClient) then: - result instanceof Ok + result instanceof Result.Ok makeStateChangeRequestArgs == [ [new URI('http://localhost:2000/hello'), state, true, true, false] ] @@ -105,7 +105,7 @@ class StateChangeSpec extends Specification { mockProviderClient) then: - result instanceof Ok + result instanceof Result.Ok } def 'if the state change is a closure, executes it with the state change as a parameter'() { @@ -118,7 +118,7 @@ class StateChangeSpec extends Specification { mockProviderClient) then: - result instanceof Ok + result instanceof Result.Ok makeStateChangeRequestArgs == [] closureArgs == [state] } @@ -132,7 +132,7 @@ class StateChangeSpec extends Specification { mockProviderClient) then: - result instanceof Ok + result instanceof Result.Ok makeStateChangeRequestArgs == [] } @@ -150,7 +150,7 @@ class StateChangeSpec extends Specification { '', [:], mockProviderClient) then: - result.stateChangeResult instanceof Ok + result.stateChangeResult instanceof Result.Ok result.message == ' Given one And two' makeStateChangeRequestArgs == [ [new URI('http://localhost:2000/hello'), stateOne, true, true, false], diff --git a/provider/src/test/groovy/au/com/dius/pact/provider/TestResultAccumulatorSpec.groovy b/provider/src/test/groovy/au/com/dius/pact/provider/TestResultAccumulatorSpec.groovy index b2c762c0e2..262d5adf90 100644 --- a/provider/src/test/groovy/au/com/dius/pact/provider/TestResultAccumulatorSpec.groovy +++ b/provider/src/test/groovy/au/com/dius/pact/provider/TestResultAccumulatorSpec.groovy @@ -18,8 +18,7 @@ import au.com.dius.pact.core.model.messaging.MessagePact import au.com.dius.pact.core.pactbroker.TestResult import au.com.dius.pact.core.support.expressions.SystemPropertyResolver import au.com.dius.pact.core.support.expressions.ValueResolver -import com.github.michaelbull.result.Err -import com.github.michaelbull.result.Ok +import au.com.dius.pact.core.support.Result import org.apache.commons.lang3.builder.HashCodeBuilder import spock.lang.Issue import spock.lang.Specification @@ -121,8 +120,8 @@ class TestResultAccumulatorSpec extends Specification { UnknownPactSource.INSTANCE, mockValueResolver) then: - 0 * testResultAccumulator.verificationReporter.reportResults(_, _, _, _, _) >> new Ok(false) - result == new Ok(false) + 0 * testResultAccumulator.verificationReporter.reportResults(_, _, _, _, _) >> new Result.Ok(false) + result == new Result.Ok(false) cleanup: testResultAccumulator.verificationReporter = reporter @@ -144,8 +143,8 @@ class TestResultAccumulatorSpec extends Specification { mockValueResolver) then: - 1 * testResultAccumulator.verificationReporter.reportResults(_, result, _, _, _, _) >> new Ok(true) - updateTestResult == new Ok(true) + 1 * testResultAccumulator.verificationReporter.reportResults(_, result, _, _, _, _) >> new Result.Ok(true) + updateTestResult == new Result.Ok(true) cleanup: testResultAccumulator.verificationReporter = reporter @@ -448,10 +447,10 @@ class TestResultAccumulatorSpec extends Specification { then: 1 * testResultAccumulator.verificationReporter.reportResults(_, new TestResult.Ok(), _, _, _, _) >> - new Err('failed') + new Result.Err('failed') testResultAccumulator.testResults.isEmpty() - result1 instanceof Ok - result2 instanceof Err + result1 instanceof Result.Ok + result2 instanceof Result.Err cleanup: testResultAccumulator.verificationReporter = reporter diff --git a/provider/src/test/groovy/au/com/dius/pact/provider/VerificationResultSpec.groovy b/provider/src/test/groovy/au/com/dius/pact/provider/VerificationResultSpec.groovy index 4881b848ac..f4cdcc99d0 100644 --- a/provider/src/test/groovy/au/com/dius/pact/provider/VerificationResultSpec.groovy +++ b/provider/src/test/groovy/au/com/dius/pact/provider/VerificationResultSpec.groovy @@ -4,7 +4,7 @@ import au.com.dius.pact.core.matchers.BodyMismatch import au.com.dius.pact.core.matchers.HeaderMismatch import au.com.dius.pact.core.matchers.StatusMismatch import au.com.dius.pact.core.pactbroker.TestResult -import com.github.michaelbull.result.Err +import au.com.dius.pact.core.support.Result import spock.lang.Specification import spock.lang.Unroll @@ -62,7 +62,7 @@ class VerificationResultSpec extends Specification { given: def description = 'Provider state change callback failed' def failures = [ - '1234ABCD': [new VerificationFailureType.StateChangeFailure(description, new StateChangeResult(new Err(new RuntimeException('Boom'))))] + '1234ABCD': [new VerificationFailureType.StateChangeFailure(description, new StateChangeResult(new Result.Err(new RuntimeException('Boom'))))] ] def verification = new VerificationResult.Failed(description, '', failures, false) diff --git a/provider/src/test/groovy/au/com/dius/pact/provider/junitsupport/loader/PactBrokerLoaderSpec.groovy b/provider/src/test/groovy/au/com/dius/pact/provider/junitsupport/loader/PactBrokerLoaderSpec.groovy index 65a6ed5d69..11c436dcdc 100644 --- a/provider/src/test/groovy/au/com/dius/pact/provider/junitsupport/loader/PactBrokerLoaderSpec.groovy +++ b/provider/src/test/groovy/au/com/dius/pact/provider/junitsupport/loader/PactBrokerLoaderSpec.groovy @@ -12,8 +12,7 @@ import au.com.dius.pact.core.support.expressions.DataType import au.com.dius.pact.core.support.expressions.ExpressionParser import au.com.dius.pact.core.support.expressions.SystemPropertyResolver import au.com.dius.pact.core.support.expressions.ValueResolver -import com.github.michaelbull.result.Err -import com.github.michaelbull.result.Ok +import au.com.dius.pact.core.support.Result import spock.lang.Issue import spock.lang.Specification import spock.lang.Unroll @@ -89,7 +88,7 @@ class PactBrokerLoaderSpec extends Specification { def list = pactBrokerLoader().load('test') then: - 1 * brokerClient.fetchConsumersWithSelectorsV2('test', _, _, _, _, _) >> new Ok([]) + 1 * brokerClient.fetchConsumersWithSelectorsV2('test', _, _, _, _, _) >> new Result.Ok([]) notThrown(NoPactsFoundException) list.empty } @@ -99,13 +98,13 @@ class PactBrokerLoaderSpec extends Specification { def result = pactBrokerLoader(false).load('test') then: - 1 * brokerClient.fetchConsumersWithSelectorsV2('test', _, _, _, _, _) >> new Ok([]) + 1 * brokerClient.fetchConsumersWithSelectorsV2('test', _, _, _, _, _) >> new Result.Ok([]) result == [] } def 'Throws any Exception On Execution Exception'() { given: - 1 * brokerClient.fetchConsumersWithSelectorsV2('test', _, _, _, _, _) >> new Err(new InvalidHalResponse('message')) + 1 * brokerClient.fetchConsumersWithSelectorsV2('test', _, _, _, _, _) >> new Result.Err(new InvalidHalResponse('message')) when: pactBrokerLoader().load('test') @@ -154,7 +153,7 @@ class PactBrokerLoaderSpec extends Specification { then: result == [] - 1 * brokerClient.fetchConsumersWithSelectorsV2('test', _, _, _, _, _) >> new Ok([]) + 1 * brokerClient.fetchConsumersWithSelectorsV2('test', _, _, _, _, _) >> new Result.Ok([]) } @RestoreSystemProperties @@ -178,7 +177,7 @@ class PactBrokerLoaderSpec extends Specification { then: result == [] - 1 * brokerClient.fetchConsumersWithSelectorsV2('test', _, _, _, _, _) >> new Ok([]) + 1 * brokerClient.fetchConsumersWithSelectorsV2('test', _, _, _, _, _) >> new Result.Ok([]) } @RestoreSystemProperties @@ -202,7 +201,7 @@ class PactBrokerLoaderSpec extends Specification { then: result == [] - 1 * brokerClient.fetchConsumersWithSelectorsV2('test', _, _, _, _, _) >> new Ok([]) + 1 * brokerClient.fetchConsumersWithSelectorsV2('test', _, _, _, _, _) >> new Result.Ok([]) } @RestoreSystemProperties @@ -274,7 +273,7 @@ class PactBrokerLoaderSpec extends Specification { then: noExceptionThrown() - 1 * brokerClient.fetchConsumersWithSelectorsV2('test', _, _, _, _, _) >> new Ok([]) + 1 * brokerClient.fetchConsumersWithSelectorsV2('test', _, _, _, _, _) >> new Result.Ok([]) } def 'Loads pacts for each provided tag'() { @@ -296,7 +295,7 @@ class PactBrokerLoaderSpec extends Specification { then: brokerClient.getOptions() >> [:] - 1 * brokerClient.fetchConsumersWithSelectorsV2('test', selectors, [], '', false, '') >> new Ok(expected) + 1 * brokerClient.fetchConsumersWithSelectorsV2('test', selectors, [], '', false, '') >> new Result.Ok(expected) 0 * brokerClient._ result.size() == 3 } @@ -324,7 +323,7 @@ class PactBrokerLoaderSpec extends Specification { then: brokerClient.getOptions() >> [:] - 1 * brokerClient.fetchConsumersWithSelectorsV2('test', selectors, [], '', false, '') >> new Ok(expected) + 1 * brokerClient.fetchConsumersWithSelectorsV2('test', selectors, [], '', false, '') >> new Result.Ok(expected) 0 * brokerClient._ result.size() == 3 } @@ -348,7 +347,7 @@ class PactBrokerLoaderSpec extends Specification { def result = pactBrokerLoader().load('test') then: - 1 * brokerClient.fetchConsumersWithSelectorsV2('test', selectors, [], '', false, '') >> new Ok(expected) + 1 * brokerClient.fetchConsumersWithSelectorsV2('test', selectors, [], '', false, '') >> new Result.Ok(expected) result.size() == 2 } @@ -372,7 +371,7 @@ class PactBrokerLoaderSpec extends Specification { def result = pactBrokerLoader().load('test') then: - 1 * brokerClient.fetchConsumersWithSelectorsV2('test', selectors, [], '', false, '') >> new Ok(expected) + 1 * brokerClient.fetchConsumersWithSelectorsV2('test', selectors, [], '', false, '') >> new Result.Ok(expected) result.size() == 2 } @@ -386,7 +385,7 @@ class PactBrokerLoaderSpec extends Specification { then: result.size() == 1 - 1 * brokerClient.fetchConsumersWithSelectorsV2('test', [], [], '', false, '') >> new Ok(expected) + 1 * brokerClient.fetchConsumersWithSelectorsV2('test', [], [], '', false, '') >> new Result.Ok(expected) } @SuppressWarnings('GStringExpressionWithinString') @@ -407,7 +406,7 @@ class PactBrokerLoaderSpec extends Specification { then: 1 * brokerClient.getOptions() >> [:] - 1 * brokerClient.fetchConsumersWithSelectorsV2('test', selectors, [], '', false, '') >> new Ok(expected) + 1 * brokerClient.fetchConsumersWithSelectorsV2('test', selectors, [], '', false, '') >> new Result.Ok(expected) 0 * brokerClient._ result.size() == 1 } @@ -435,7 +434,7 @@ class PactBrokerLoaderSpec extends Specification { then: 1 * brokerClient.getOptions() >> [:] - 1 * brokerClient.fetchConsumersWithSelectorsV2('test', selectors, [], '', false, '') >> new Ok(expected) + 1 * brokerClient.fetchConsumersWithSelectorsV2('test', selectors, [], '', false, '') >> new Result.Ok(expected) 0 * brokerClient._ result.size() == 1 } @@ -460,7 +459,7 @@ class PactBrokerLoaderSpec extends Specification { def result = pactBrokerLoader().load('test') then: - 1 * brokerClient.fetchConsumersWithSelectorsV2('test', selectors, [], '', false, '') >> new Ok(expected) + 1 * brokerClient.fetchConsumersWithSelectorsV2('test', selectors, [], '', false, '') >> new Result.Ok(expected) result.size() == 2 } @@ -499,7 +498,7 @@ class PactBrokerLoaderSpec extends Specification { then: brokerClient.getOptions() >> [:] - 1 * brokerClient.fetchConsumersWithSelectorsV2('test', selectors, [], '', false, '') >> new Ok(expected) + 1 * brokerClient.fetchConsumersWithSelectorsV2('test', selectors, [], '', false, '') >> new Result.Ok(expected) 0 * brokerClient._ result.size() == 3 } @@ -528,7 +527,7 @@ class PactBrokerLoaderSpec extends Specification { then: brokerClient.getOptions() >> [:] - 1 * brokerClient.fetchConsumersWithSelectorsV2('test', selectors, [], '', false, '') >> new Ok(expected) + 1 * brokerClient.fetchConsumersWithSelectorsV2('test', selectors, [], '', false, '') >> new Result.Ok(expected) 0 * brokerClient._ result.size() == 4 } @@ -556,7 +555,7 @@ class PactBrokerLoaderSpec extends Specification { then: brokerClient.getOptions() >> [:] - 1 * brokerClient.fetchConsumersWithSelectorsV2('test', selectors, [], '', false, '') >> new Ok(expected) + 1 * brokerClient.fetchConsumersWithSelectorsV2('test', selectors, [], '', false, '') >> new Result.Ok(expected) 0 * brokerClient._ result.size() == 3 } @@ -576,7 +575,7 @@ class PactBrokerLoaderSpec extends Specification { then: brokerClient.getOptions() >> [:] - 1 * brokerClient.fetchConsumersWithSelectorsV2('test', [], [], '', false, '') >> new Ok(expected) + 1 * brokerClient.fetchConsumersWithSelectorsV2('test', [], [], '', false, '') >> new Result.Ok(expected) 0 * brokerClient._ result.size() == 4 } @@ -598,7 +597,7 @@ class PactBrokerLoaderSpec extends Specification { then: brokerClient.getOptions() >> [:] - 1 * brokerClient.fetchConsumersWithSelectorsV2('test', [], [], '', false, '') >> new Ok(expected) + 1 * brokerClient.fetchConsumersWithSelectorsV2('test', [], [], '', false, '') >> new Result.Ok(expected) 0 * brokerClient._ result.size() == 4 } @@ -624,7 +623,7 @@ class PactBrokerLoaderSpec extends Specification { then: brokerClient.getOptions() >> [:] - 1 * brokerClient.fetchConsumersWithSelectorsV2('test', selectors, [], '', false, '') >> new Ok(expected) + 1 * brokerClient.fetchConsumersWithSelectorsV2('test', selectors, [], '', false, '') >> new Result.Ok(expected) 0 * brokerClient._ result.size() == 3 } @@ -646,7 +645,7 @@ class PactBrokerLoaderSpec extends Specification { then: brokerClient.getOptions() >> [:] - 1 * brokerClient.fetchConsumersWithSelectorsV2('test', selectors, [], '', false, '') >> new Ok(expected) + 1 * brokerClient.fetchConsumersWithSelectorsV2('test', selectors, [], '', false, '') >> new Result.Ok(expected) 0 * brokerClient._ result.size() == 3 } @@ -672,7 +671,7 @@ class PactBrokerLoaderSpec extends Specification { then: result == [] - 1 * brokerClient.fetchConsumersWithSelectorsV2('test', selectors, [], '', false, '') >> new Ok([]) + 1 * brokerClient.fetchConsumersWithSelectorsV2('test', selectors, [], '', false, '') >> new Result.Ok([]) } @Issue('#1208') @@ -699,7 +698,7 @@ class PactBrokerLoaderSpec extends Specification { then: valueResolver.propertyDefined('pactbroker.consumerversionselectors.tags') >> true valueResolver.resolveValue('pactbroker.consumerversionselectors.tags') >> 'one,two,three' - 1 * brokerClient.fetchConsumersWithSelectorsV2('test', selectors, [], '', false, '') >> new Ok(expected) + 1 * brokerClient.fetchConsumersWithSelectorsV2('test', selectors, [], '', false, '') >> new Result.Ok(expected) } def 'Loads pacts with consumer version selectors when consumer version selectors and tags are both present'() { @@ -719,7 +718,7 @@ class PactBrokerLoaderSpec extends Specification { then: brokerClient.getOptions() >> [:] - 1 * brokerClient.fetchConsumersWithSelectorsV2('test', selectors, [], '', false, '') >> new Ok(expected) + 1 * brokerClient.fetchConsumersWithSelectorsV2('test', selectors, [], '', false, '') >> new Result.Ok(expected) 0 * brokerClient._ result.size() == 4 } @@ -742,7 +741,7 @@ class PactBrokerLoaderSpec extends Specification { then: result == [] - 1 * brokerClient.fetchConsumersWithSelectorsV2('test', [], [], '', false, '') >> new Ok([]) + 1 * brokerClient.fetchConsumersWithSelectorsV2('test', [], [], '', false, '') >> new Result.Ok([]) } def 'Does not loads wip pacts when pending is false'() { @@ -767,7 +766,7 @@ class PactBrokerLoaderSpec extends Specification { then: brokerClient.getOptions() >> [:] - 1 * brokerClient.fetchConsumersWithSelectorsV2('test', selectors, [], '', false, '') >> new Ok(expected) + 1 * brokerClient.fetchConsumersWithSelectorsV2('test', selectors, [], '', false, '') >> new Result.Ok(expected) 0 * brokerClient._ result.size() == 3 } @@ -796,7 +795,7 @@ class PactBrokerLoaderSpec extends Specification { then: brokerClient.getOptions() >> [:] - 1 * brokerClient.fetchConsumersWithSelectorsV2('test', selectors, ['dev'], '', true, '2020-06-25') >> new Ok(expected) + 1 * brokerClient.fetchConsumersWithSelectorsV2('test', selectors, ['dev'], '', true, '2020-06-25') >> new Result.Ok(expected) 0 * brokerClient._ result.size() == 3 } @@ -823,7 +822,7 @@ class PactBrokerLoaderSpec extends Specification { pactBrokerLoader().load('test') then: - 1 * brokerClient.fetchConsumersWithSelectorsV2('test', [], [], '', false, '') >> new Ok([]) + 1 * brokerClient.fetchConsumersWithSelectorsV2('test', [], [], '', false, '') >> new Result.Ok([]) noExceptionThrown() } @@ -847,7 +846,7 @@ class PactBrokerLoaderSpec extends Specification { then: result == [] - 1 * brokerClient.fetchConsumersWithSelectorsV2('test', [], [], '', false, '') >> new Ok([]) + 1 * brokerClient.fetchConsumersWithSelectorsV2('test', [], [], '', false, '') >> new Result.Ok([]) } def 'configured from annotation with https and no port'() { @@ -872,7 +871,7 @@ class PactBrokerLoaderSpec extends Specification { then: result == [] - 1 * brokerClient.fetchConsumersWithSelectorsV2('test', [], [], '', false, '') >> new Ok([]) + 1 * brokerClient.fetchConsumersWithSelectorsV2('test', [], [], '', false, '') >> new Result.Ok([]) } def 'Auth: Uses no auth if no auth is provided'() { @@ -1307,7 +1306,7 @@ class PactBrokerLoaderSpec extends Specification { then: result == [] - 1 * brokerClient.fetchConsumersWithSelectorsV2(_, selectors, _, _, _, _) >> new Ok([]) + 1 * brokerClient.fetchConsumersWithSelectorsV2(_, selectors, _, _, _, _) >> new Result.Ok([]) } @Unroll @@ -1386,7 +1385,7 @@ class PactBrokerLoaderSpec extends Specification { then: result == [] - 1 * brokerClient.fetchConsumersWithSelectorsV2('test', _, _, _, _, _) >> new Ok([]) + 1 * brokerClient.fetchConsumersWithSelectorsV2('test', _, _, _, _, _) >> new Result.Ok([]) } void 'Enables insecure TLS from explicit PactBroker annotation setting'() { @@ -1406,7 +1405,7 @@ class PactBrokerLoaderSpec extends Specification { then: result == [] - 1 * brokerClient.fetchConsumersWithSelectorsV2('test', _, _, _, _, _) >> new Ok([]) + 1 * brokerClient.fetchConsumersWithSelectorsV2('test', _, _, _, _, _) >> new Result.Ok([]) } @RestoreSystemProperties @@ -1430,7 +1429,7 @@ class PactBrokerLoaderSpec extends Specification { then: result == [] - 1 * brokerClient.fetchConsumersWithSelectorsV2('test', _, _, _, _, _) >> new Ok([]) + 1 * brokerClient.fetchConsumersWithSelectorsV2('test', _, _, _, _, _) >> new Result.Ok([]) } def 'Uses the insecure TlS setting when creating the PactBrokerClient'() {