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

au.com.dius.pact.provider.StateChange.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 } } ```

There is a newer version: 4.0.10
Show newest version
package au.com.dius.pact.provider

import au.com.dius.pact.com.github.michaelbull.result.Err
import au.com.dius.pact.com.github.michaelbull.result.Ok
import au.com.dius.pact.com.github.michaelbull.result.Result
import au.com.dius.pact.com.github.michaelbull.result.mapEither
import au.com.dius.pact.com.github.michaelbull.result.unwrap
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 com.google.gson.JsonParser
import groovy.lang.Closure
import mu.KLogging
import org.apache.http.HttpEntity
import org.apache.http.entity.ContentType
import org.apache.http.util.EntityUtils
import java.net.URI
import java.net.URISyntaxException
import java.net.URL

data class StateChangeResult @JvmOverloads constructor (
  val stateChangeResult: Result, Exception>,
  val message: String = ""
)

interface StateChange {
  fun executeStateChange(
    verifier: IProviderVerifier,
    provider: IProviderInfo,
    consumer: IConsumerInfo,
    interaction: Interaction,
    interactionMessage: String,
    failures: MutableMap,
    providerClient: ProviderClient
  ): StateChangeResult

  fun stateChange(
    verifier: IProviderVerifier,
    state: ProviderState,
    provider: IProviderInfo,
    consumer: IConsumerInfo,
    isSetup: Boolean,
    providerClient: ProviderClient
  ): Result, Exception>

  fun executeStateChangeTeardown(
    verifier: IProviderVerifier,
    interaction: Interaction,
    provider: IProviderInfo,
    consumer: IConsumerInfo,
    providerClient: ProviderClient
  )
}

/**
 * Class containing all the state change logic
 */
object DefaultStateChange : StateChange, KLogging() {

  override fun executeStateChange(
    verifier: IProviderVerifier,
    provider: IProviderInfo,
    consumer: IConsumerInfo,
    interaction: Interaction,
    interactionMessage: String,
    failures: MutableMap,
    providerClient: ProviderClient
  ): StateChangeResult {
    var message = interactionMessage
    var stateChangeResult: Result, Exception> = Ok(emptyMap())

    if (interaction.providerStates.isNotEmpty()) {
      val iterator = interaction.providerStates.iterator()
      var first = true
      while (stateChangeResult is Ok && iterator.hasNext()) {
        val providerState = iterator.next()
        val result = stateChange(verifier, providerState, provider, consumer, true, providerClient)
        logger.debug { "State Change: \"$providerState\" -> $result" }

        stateChangeResult = result.mapEither({
          if (first) {
            message += " Given ${providerState.name}"
            first = false
          } else {
            message += " And ${providerState.name}"
          }
          stateChangeResult.unwrap().plus(it)
        }, {
          failures[message] = it.message.toString()
          it
        })
      }
    }

    return StateChangeResult(stateChangeResult, message)
  }

  override fun stateChange(
    verifier: IProviderVerifier,
    state: ProviderState,
    provider: IProviderInfo,
    consumer: IConsumerInfo,
    isSetup: Boolean,
    providerClient: ProviderClient
  ): Result, Exception> {
    verifier.reportStateForInteraction(state.name, provider, consumer, isSetup)
    try {
      var stateChangeHandler = consumer.stateChange
      var stateChangeUsesBody = consumer.stateChangeUsesBody
      if (stateChangeHandler == null) {
        stateChangeHandler = provider.stateChangeUrl
        stateChangeUsesBody = provider.stateChangeUsesBody
      }
      if (stateChangeHandler == null || (stateChangeHandler is String && stateChangeHandler.isBlank())) {
        verifier.reporters.forEach { it.warnStateChangeIgnored(state.name, provider, consumer) }
        return Ok(emptyMap())
      } else if (verifier.checkBuildSpecificTask.apply(stateChangeHandler)) {
        logger.debug { "Invoking build specific task $stateChangeHandler" }
        verifier.executeBuildSpecificTask.accept(stateChangeHandler, state)
        return Ok(emptyMap())
      } else if (stateChangeHandler is Closure<*>) {
        val result = if (provider.stateChangeTeardown) {
          stateChangeHandler.call(state, if (isSetup) "setup" else "teardown")
        } else {
          stateChangeHandler.call(state)
        }
        logger.debug { "Invoked state change closure -> $result" }
        if (result !is URL) {
          return Ok(if (result is Map<*, *>) result as Map else emptyMap())
        }
        stateChangeHandler = result
      }
      return executeHttpStateChangeRequest(verifier, stateChangeHandler, stateChangeUsesBody, state, provider, isSetup,
        providerClient)
    } catch (e: Exception) {
      verifier.reporters.forEach {
        it.stateChangeRequestFailedWithException(state.name, provider, consumer, isSetup, e,
          verifier.projectHasProperty.apply(ProviderVerifier.PACT_SHOW_STACKTRACE))
      }
      return Err(e)
    }
  }

  override fun executeStateChangeTeardown(
    verifier: IProviderVerifier,
    interaction: Interaction,
    provider: IProviderInfo,
    consumer: IConsumerInfo,
    providerClient: ProviderClient
  ) {
    interaction.providerStates.forEach {
      stateChange(verifier, it, provider, consumer, false, providerClient)
    }
  }

  private fun executeHttpStateChangeRequest(
    verifier: IProviderVerifier,
    stateChangeHandler: Any,
    useBody: Boolean,
    state: ProviderState,
    provider: IProviderInfo,
    isSetup: Boolean,
    providerClient: ProviderClient
  ): Result, Exception> {
    return try {
      val url = stateChangeHandler as? URI ?: URI(stateChangeHandler.toString())
      val response = providerClient.makeStateChangeRequest(url, state, useBody, isSetup, provider.stateChangeTeardown)
      logger.debug { "Invoked state change $url -> ${response?.statusLine}" }
      response?.use {
        if (response.statusLine.statusCode >= 400) {
          verifier.reporters.forEach {
            it.stateChangeRequestFailed(state.name, provider, isSetup, response.statusLine.toString())
          }
          Err(Exception("State Change Request Failed - ${response.statusLine}"))
        } else {
          parseJsonResponse(response.entity)
        }
      } ?: Ok(emptyMap())
    } catch (ex: URISyntaxException) {
      verifier.reporters.forEach {
        it.warnStateChangeIgnoredDueToInvalidUrl(state.name, provider, isSetup, stateChangeHandler)
      }
      Ok(emptyMap())
    }
  }

  private fun parseJsonResponse(entity: HttpEntity?): Result, Exception> {
    return if (entity != null && ContentType.get(entity).mimeType == ContentType.APPLICATION_JSON.mimeType) {
      val body = EntityUtils.toString(entity)
      Ok(Json.toMap(JsonParser().parse(body)))
    } else {
      Ok(emptyMap())
    }
  }
}




© 2015 - 2024 Weber Informatics LLC | Privacy Policy