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

au.com.dius.pact.provider.junit.JUnitProviderTestSupport.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.junit

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.isNotEmpty
import au.com.dius.pact.provider.ProviderVerifier
import au.com.dius.pact.provider.junit.filter.InteractionFilter
import au.com.dius.pact.provider.junit.loader.OverrideablePactLoader
import au.com.dius.pact.provider.junit.loader.PactFilter
import au.com.dius.pact.provider.junit.loader.PactLoader
import mu.KLogging
import org.apache.commons.lang3.StringUtils
import org.apache.commons.lang3.exception.ExceptionUtils
import kotlin.reflect.full.createInstance

object JUnitProviderTestSupport : KLogging() {
  fun  filterPactsByAnnotations(pacts: List>, testClass: Class<*>): List> where I : Interaction {
    val pactFilter = testClass.getAnnotation(PactFilter::class.java) ?: return pacts
    if (pactFilter.value == null || pactFilter.value.all { it.isEmpty() }) return pacts

    val interactionFilter = pactFilter.filter.createInstance() as InteractionFilter
    return pacts.map { pact ->
      FilteredPact(pact, interactionFilter.buildPredicate(pactFilter.value))
    }.filter { pact -> pact.interactions.isNotEmpty() }
  }

  @JvmStatic
  fun generateErrorStringFromMismatches(mismatches: Map): String {
    return System.lineSeparator() + mismatches.values
      .mapIndexed { i, value ->
        val errPrefix = "$i - "
        when (value) {
          is Throwable -> errPrefix + exceptionMessage(value, errPrefix.length)
          is Map<*, *> -> errPrefix + convertMapToErrorString(value as Map)
          else -> errPrefix + value.toString()
        }
      }.joinToString(System.lineSeparator())
  }

  @JvmStatic
  fun exceptionMessage(err: Throwable, prefixLength: Int): String {
    val message = err.message

    val cause = err.cause
    var details = ""
    if (cause != null) {
      details = ExceptionUtils.getStackTrace(cause)
    }

    val lineSeparator = System.lineSeparator()
    return if (message != null && message.contains("\n")) {
      val padString = StringUtils.leftPad("", prefixLength)
      val lines = message.split("\n")
      lines.reduceIndexed { index, acc, line ->
        if (index > 0) {
          acc + lineSeparator + padString + line
        } else {
          line + lineSeparator
        }
      }
    } else {
      "$message\n$details"
    }
  }

  private fun convertMapToErrorString(mismatches: Map): String {
    return if (mismatches.containsKey("comparison")) {
      val comparison = mismatches["comparison"]
      if (mismatches.containsKey("diff")) {
        mapToString(comparison as Map)
      } else {
        if (comparison is Map<*, *>) {
          mapToString(comparison as Map)
        } else {
          comparison.toString()
        }
      }
    } else {
      mapToString(mismatches)
    }
  }

  private fun mapToString(comparison: Map): String {
    return comparison.entries.joinToString(System.lineSeparator()) { (key, value) -> "$key -> $value" }
  }

  @JvmStatic
  fun checkForOverriddenPactUrl(
    loader: PactLoader?,
    overridePactUrl: AllowOverridePactUrl?,
    consumer: Consumer?
  ) {
    var pactUrl = System.getProperty(ProviderVerifier.PACT_FILTER_PACTURL)
    if (pactUrl.isNullOrEmpty()) {
      pactUrl = System.getenv(ProviderVerifier.PACT_FILTER_PACTURL)
    }

    if (loader is OverrideablePactLoader && overridePactUrl != null && pactUrl.isNotEmpty()) {
      var consumerProperty = System.getProperty(ProviderVerifier.PACT_FILTER_CONSUMERS)
      if (consumerProperty.isNullOrEmpty()) {
        consumerProperty = System.getenv(ProviderVerifier.PACT_FILTER_CONSUMERS)
      }
      when {
        consumerProperty.isNotEmpty() -> loader.overridePactUrl(pactUrl, consumerProperty)
        consumer != null -> loader.overridePactUrl(pactUrl, consumer.value)
        else -> {
          logger.warn {
            "The property ${ProviderVerifier.PACT_FILTER_PACTURL} has been set, but no consumer filter" +
              " or @Consumer annotation has been provided, Ignoring"
          }
        }
      }
    }
  }
}