All Downloads are FREE. Search and download functionalities are using the official Maven repository.

au.com.dius.pact.provider.ProviderInfo.kt Maven / Gradle / Ivy

Go to download

Pact provider ============= sub project of https://github.com/DiUS/pact-jvm The pact provider is responsible for verifying that an API provider adheres to a number of pacts authored by its clients This library provides the basic tools required to automate the process, and should be usable on its own in many instances. Framework and build tool specific bindings will be provided in separate libraries that build on top of this core functionality. ### Provider State Before each interaction is executed, the provider under test will have the opportunity to enter a state. Generally the state maps to a set of fixture data for mocking out services that the provider is a consumer of (they will have their own pacts) The pact framework will instruct the test server to enter that state by sending: POST "${config.stateChangeUrl.url}/setup" { "state" : "${interaction.stateName}" } ### An example of running provider verification with junit This example uses Groovy, JUnit 4 and Hamcrest matchers to run the provider verification. As the provider service is a DropWizard application, it uses the DropwizardAppRule to startup the service before running any test. **Warning:** It only grabs the first interaction from the pact file with the consumer, where there could be many. (This could possibly be solved with a parameterized test) ```groovy class ReadmeExamplePactJVMProviderJUnitTest { @ClassRule public static final TestRule startServiceRule = new DropwizardAppRule<DropwizardConfiguration>( TestDropwizardApplication, ResourceHelpers.resourceFilePath('dropwizard/test-config.yaml')) private static ProviderInfo serviceProvider private static Pact<RequestResponseInteraction> testConsumerPact private static ConsumerInfo consumer @BeforeClass static void setupProvider() { serviceProvider = new ProviderInfo('Dropwizard App') serviceProvider.setProtocol('http') serviceProvider.setHost('localhost') serviceProvider.setPort(8080) serviceProvider.setPath('/') consumer = new ConsumerInfo() consumer.setName('test_consumer') consumer.setPactSource(new UrlSource( ReadmeExamplePactJVMProviderJUnitTest.getResource('/pacts/zoo_app-animal_service.json').toString())) testConsumerPact = DefaultPactReader.INSTANCE.loadPact(consumer.getPactSource()) as Pact<RequestResponseInteraction> } @Test void runConsumerPacts() { // grab the first interaction from the pact with consumer Interaction interaction = testConsumerPact.interactions.get(0) // setup the verifier ProviderVerifier verifier = setupVerifier(interaction, serviceProvider, consumer) // setup any provider state // setup the client and interaction to fire against the provider ProviderClient client = new ProviderClient(serviceProvider, new HttpClientFactory()) Map<String, Object> failures = new HashMap<>() verifier.verifyResponseFromProvider(serviceProvider, interaction, interaction.getDescription(), failures, client) // normally assert all good, but in this example it will fail assertThat(failures, is(not(empty()))) verifier.displayFailures(failures) } private ProviderVerifier setupVerifier(Interaction interaction, ProviderInfo provider, ConsumerInfo consumer) { ProviderVerifier verifier = new ProviderVerifier() verifier.initialiseReporters(provider) verifier.reportVerificationForConsumer(consumer, provider, new UrlSource('http://example.example')) if (!interaction.getProviderStates().isEmpty()) { for (ProviderState providerState: interaction.getProviderStates()) { verifier.reportStateForInteraction(providerState.getName(), provider, consumer, true) } } verifier.reportInteractionDescription(interaction) return verifier } } ``` ### An example of running provider verification with spock This example uses groovy and spock to run the provider verification. Again the provider service is a DropWizard application, and is using the DropwizardAppRule to startup the service. This example runs all interactions using spocks Unroll feature ```groovy class ReadmeExamplePactJVMProviderSpockSpec extends Specification { @ClassRule @Shared TestRule startServiceRule = new DropwizardAppRule<DropwizardConfiguration>(TestDropwizardApplication, ResourceHelpers.resourceFilePath('dropwizard/test-config.yaml')) @Shared ProviderInfo serviceProvider ProviderVerifier verifier def setupSpec() { serviceProvider = new ProviderInfo('Dropwizard App') serviceProvider.protocol = 'http' serviceProvider.host = 'localhost' serviceProvider.port = 8080 serviceProvider.path = '/' serviceProvider.hasPactWith('zoo_app') { consumer -> consumer.pactSource = new FileSource(new File(ResourceHelpers.resourceFilePath('pacts/zoo_app-animal_service.json'))) } } def setup() { verifier = new ProviderVerifier() } def cleanup() { // cleanup provider state // ie. db.truncateAllTables() } def cleanupSpec() { // cleanup provider } @Unroll def "Provider Pact - With Consumer #consumer"() { expect: !verifyConsumerPact(consumer).empty where: consumer << serviceProvider.consumers } private Map verifyConsumerPact(ConsumerInfo consumer) { Map failures = [:] verifier.initialiseReporters(serviceProvider) verifier.runVerificationForConsumer(failures, serviceProvider, consumer) if (!failures.empty) { verifier.displayFailures(failures) } failures } } ```

The newest version!
package au.com.dius.pact.provider

import arrow.core.Either
import au.com.dius.pact.core.model.DefaultPactReader
import au.com.dius.pact.core.model.FileSource
import au.com.dius.pact.core.model.Interaction
import au.com.dius.pact.core.pactbroker.ConsumerVersionSelector
import au.com.dius.pact.core.pactbroker.PactBrokerClient
import org.apache.commons.lang3.builder.HashCodeBuilder
import org.apache.commons.lang3.builder.ToStringBuilder
import java.io.File
import java.net.URL

/**
 * Provider Info Config
 */
open class ProviderInfo @JvmOverloads constructor (
  override var name: String = "provider",
  override var protocol: String = "http",
  override var host: Any? = "localhost",
  override var port: Any? = 8080,
  override var path: String = "/",
  open var startProviderTask: Any? = null,
  open var terminateProviderTask: Any? = null,
  override var requestFilter: Any? = null,
  override var stateChangeRequestFilter: Any? = null,
  override var createClient: Any? = null,
  override var insecure: Boolean = false,
  override var trustStore: File? = null,
  override var trustStorePassword: String? = "changeit",
  override var stateChangeUrl: URL? = null,
  override var stateChangeUsesBody: Boolean = true,
  override var stateChangeTeardown: Boolean = false,
  open var isDependencyForPactVerify: Boolean = true,
  override var verificationType: PactVerification? = PactVerification.REQUEST_RESPONSE,
  override var packagesToScan: List = emptyList(),
  open var consumers: MutableList = mutableListOf()
) : IProviderInfo {

  override fun hashCode() = HashCodeBuilder()
    .append(name).append(protocol).append(host).append(port).append(path).toHashCode()

  override fun toString() = ToStringBuilder.reflectionToString(this)

  open fun hasPactWith(consumer: String, closure: ConsumerInfo.() -> Unit): ConsumerInfo {
    val consumerInfo = ConsumerInfo(consumer)
    consumers.add(consumerInfo)
    consumerInfo.closure()
    return consumerInfo
  }

  open fun hasPactsWith(consumersGroupName: String, closure: ConsumersGroup.() -> Unit): List {
    val consumersGroup = ConsumersGroup(consumersGroupName)
    consumersGroup.closure()

    return setupConsumerListFromPactFiles(consumersGroup)
  }

  @JvmOverloads
  open fun hasPactsFromPactBroker(options: Map = mapOf(), pactBrokerUrl: String) =
    hasPactsFromPactBrokerWithSelectors(options, pactBrokerUrl, emptyList())

  @JvmOverloads
  @Deprecated(message = "Use version that takes selectors",
    replaceWith = ReplaceWith("hasPactsFromPactBrokerWithSelectors"))
  open fun hasPactsFromPactBrokerWithTag(
    options: Map = mapOf(),
    pactBrokerUrl: String,
    tag: String
  ): List {
    val client = PactBrokerClient(pactBrokerUrl, options)
    val consumersFromBroker = client.fetchConsumersWithTag(name, tag).map { ConsumerInfo.from(it) }
    consumers.addAll(consumersFromBroker)
    return consumersFromBroker
  }

  @JvmOverloads
  open fun hasPactsFromPactBrokerWithSelectors(
    options: Map = mapOf(),
    pactBrokerUrl: String,
    selectors: List
  ): List {
    val client = PactBrokerClient(pactBrokerUrl, options)
    val consumersFromBroker = client.fetchConsumersWithSelectors(name, selectors).map { results ->
      results.map { ConsumerInfo.from(it) }
    }
    return when (consumersFromBroker) {
      is Either.Right<*> -> {
        val list = (consumersFromBroker as Either.Right>).b
        consumers.addAll(list)
        list
      }
      is Either.Left<*> -> {
        throw RuntimeException("Call to fetch pacts from Pact Broker failed with an exception",
          consumersFromBroker.a as Exception)
      }
    }
  }

  open fun setupConsumerListFromPactFiles(consumersGroup: ConsumersGroup): MutableList {
    val pactFileDirectory = consumersGroup.pactFileLocation ?: return mutableListOf()
    if (!pactFileDirectory.exists() || !pactFileDirectory.canRead()) {
      throw RuntimeException("pactFileDirectory ${pactFileDirectory.absolutePath} does not exist or is not readable")
    }

    pactFileDirectory.walkBottomUp().forEach { file ->
      if (file.isFile && consumersGroup.include.matches(file.name)) {
        val name = DefaultPactReader.loadPact(file).consumer.name
        consumers.add(ConsumerInfo(name,
          consumersGroup.stateChange,
          consumersGroup.stateChangeUsesBody,
          emptyList(),
          null,
          FileSource(file)
        ))
      }
    }

    return consumers
  }

  override fun equals(other: Any?): Boolean {
    if (this === other) return true
    if (javaClass != other?.javaClass) return false

    other as ProviderInfo

    if (name != other.name) return false
    if (protocol != other.protocol) return false
    if (host != other.host) return false
    if (port != other.port) return false
    if (path != other.path) return false

    return true
  }
}




© 2015 - 2024 Weber Informatics LLC | Privacy Policy