Skip to content

Instantly share code, notes, and snippets.

@YOU54F
Last active October 4, 2023 13:54
Show Gist options
  • Save YOU54F/911fa1bde07c0e58b07b08c728d4e4e4 to your computer and use it in GitHub Desktop.
Save YOU54F/911fa1bde07c0e58b07b08c728d4e4e4 to your computer and use it in GitHub Desktop.
Various Pact getting starting snippets, (language tabs for docusaurus)

Consumer

Pact JS (Node JS)

const { Publisher } = require("@pact-foundation/pact")
const opts = {
pactBroker: 'https://<YOUR_BROKER>.pactflow.io',
pactBrokerToken: '<TOKEN>',
consumerVersion: process.env.GIT_COMMIT
pactFilesOrDirs: ['./pacts'],
};

new Publisher(opts).publishPacts()

Java / JUnit 5

pact {
  publish {
    providerVersion = {  '<GIT_COMMIT>' } //yes, this field name is correct :(
    pactBrokerUrl = 'https://<YOUR_BROKER>.pactflow.io/'
    pactBrokerToken = '<TOKEN>'
  }
}

Java / JUnit 4

pact {
  publish {
    providerVersion = {  '<GIT_COMMIT>' } //yes, this field name is correct :(
    pactBrokerUrl = 'https://<YOUR_BROKER>.pactflow.io/'
    pactBrokerToken = '<TOKEN>'
  }
}

Java / Gradle

pact {
  publish {
    providerVersion = {  '<GIT_COMMIT>' } //yes, this field name is correct :(
    pactBrokerUrl = 'https://<YOUR_BROKER>.pactflow.io/'
    pactBrokerToken = '<TOKEN>'
  }
}

Golang

p := dsl.Publisher{}
err := p.Publish(types.PublishRequest{
  PactURLs:        []string{"/path/to/pact/file"},
  PactBroker:      "https://<YOUR_BROKER>.pactflow.io",
  ConsumerVersion: "<GIT_COMMIT>",
  BrokerToken:     "<TOKEN>",
})

Ruby

require 'pact_broker/client/tasks'

PactBroker::Client::PublicationTask.new do | task |
task.consumer_version = ENV['GIT_COMMIT']
task.pact_broker_base_url = "https://<YOUR_BROKER>.pactflow.io"
task.pact_broker_token = "<TOKEN>"
end

.NET

# Ensure TLS1.2 is set, otherwise it will default to TLS1.0 and you won't be able to connect
[Net.ServicePointManager]::SecurityProtocol = [Net.SecurityProtocolType]::Tls12
\$res = Invoke-WebRequest -Uri "https://<YOUR_BROKER>.pactflow.io/pacts/provider/AProvider/consumer/AConsumer/version/SomeVersion" -Method Put -InFile .\a_consumer-a_provider.json -ContentType "application/json" -Headers @{'Authorization' = 'Bearer <your token here>'}
var pactPublisher = new PactPublisher("http://<YOUR_BROKER>.pactflow.io"),
  new PactUriOptions("<TOKEN>"));
pactPublisher.PublishToBroker("/pact/to/pacts/dir",
  Environment.GetEnvironmentVariable("GIT_COMMIT"));

Docker

docker run --rm \
-v ${PWD}:${PWD} \
-e PACT_BROKER_BASE_URL="https://<YOUR_BROKER>.pactflow.io" \
-e PACT_BROKER_TOKEN="<TOKEN>" \
pactfoundation/pact-cli:latest \
publish \
${PWD}/pacts \
--consumer-app-version ${GIT_COMMIT}

Provider

Pact JS (Node JS)

const { Verifier } = require("@pact-foundation/pact");

return new Verifier().verifyProvider({
  provider: "<Your provider name here>",
  providerBaseUrl: "http://localhost:8081",

  // Fetch pacts from broker
  pactBrokerUrl: "https://<YOUR_BROKER>.pactflow.io/",
  pactBrokerToken: "<TOKEN>",

  publishVerificationResult: process.env.CI === "true",
  providerVersion: process.env.GIT_COMMIT,
});

Java / JUnit 5

@Provider("<Your provider name here>")
@PactBroker(host = "<YOUR_BROKER>.pactflow.io", scheme = "https",
  authentication = @PactBrokerAuth(scheme = "bearer", username = "<TOKEN>", password = ""))
public class PactJUnitBrokerTest {

    @TestTemplate
    @ExtendWith(PactVerificationInvocationContextProvider.class)
    void testTemplate(Pact pact, Interaction interaction, HttpRequest request, PactVerificationContext context) {
      context.verifyInteraction();
    }
}

Java / JUnit 4

@RunWith(PactRunner.class)
@Provider("<Your provider name here>")
@PactBroker(host = "<YOUR_BROKER>.pactflow.io", scheme = "https",
  authentication = @PactBrokerAuth(scheme = "bearer", username = "<TOKEN>", password = ""))
public class PactJUnitBrokerTest {
  @TestTarget
  public final Target target = new HttpTarget(8080);
}

Java / Gradle

// To turn on the verification publishing,
// set the project property `pact.verifier.publishResults` to `true`

pact {
  serviceProviders {
    '<Your provider name here>' {

      providerVersion = { '<GIT_COMMIT>' }
      hasPactsFromPactBroker('https://<YOUR_BROKER>.pactflow.io/',
        authentication: ['Bearer', '<TOKEN>'])

    }
  }
}

Golang

_, err := pact.VerifyProvider(t, types.VerifyRequest{
  ProviderBaseURL:            fmt.Sprintf("http://127.0.0.1:%d", port),
  BrokerURL:                  "https://<YOUR_BROKER>.pactflow.io",
  BrokerToken:                "<TOKEN>",
  PublishVerificationResults: true,
  ProviderVersion:            "<GIT_COMMIT>"
})

Ruby

Pact.service_provider "<Your provider name here>" do
  app_version ENV['GIT_COMMIT']
  publish_verification_results ENV['CI'] == 'true'

  honours_pacts_from_pact_broker do
    pact_broker_base_url "https://<YOUR_BROKER>.pactflow.io", { token: "<TOKEN>" }
  end
end

.NET

var config = new PactVerifierConfig
{
    ProviderVersion = Environment.GetEnvironmentVariable("GIT_COMMIT")
    PublishVerificationResults = "true".Equals(Environment.GetEnvironmentVariable("CI"))
};

IPactVerifier pactVerifier = new PactVerifier(config);
pactVerifier
    .ServiceProvider("<Your provider name here>", "http://your-test-provider-url")
   .PactBroker("https://<YOUR_BROKER>.pactflow.io", uriOptions: new PactUriOptions("<TOKEN>"))
   .Verify();

Docker

version: "3"

services:
  api:
    image: "your image"
    expose:
      - "9292"

  pact_verifier:
    image: pactfoundation/pact-cli:latest
    depends_on:
      - api
    environment:
      - PACT_BROKER_BASE_URL="https://<YOUR_BROKER>.pactflow.io"
      - PACT_BROKER_TOKEN="<TOKEN>"
    command: >
      verify
      --provider-base-url http://api:9292
      --provider "<Your provider name here>"

To run

docker-compose -f docker-compose-verify.yml up \
    --build --abort-on-container-exit --exit-code-from pact_verifier
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment