https://pact.io logo
Join Slack
Powered by
# pact-jvm
  • v

    Vishal Kukreja

    08/01/2022, 3:07 PM
    Copy code
    @HiltAndroidTest
    @Config(sdk = [Build.VERSION_CODES.Q])
    @PactTestFor(
        providerName = "our_provider"
    )
    @PactDirectory("presentation/target/pacts")
    @ExtendWith(
        PactConsumerTestExt::class
    )
    class VerificationEstimationPactTest {
        private var HEADERS: MutableMap<String, String> = HashMap()
        private var JSON: String? = null
    
    
        @get:Rule
        var rule: TestRule = InstantTaskExecutorRule()
    
        @get:Rule
        var hiltRule = HiltAndroidRule(this)
    
      
        lateinit var viewModel: InvestorsProfileViewModel
    
        init {
            HEADERS["Content-Type"] = "application/json"
    
            JSON="{\n" +
                    " \"score\":45,\n"
                    "  \"profile\": \"RISK_AVERSE\"\n" +
                            "}"
    
        }
    
        @Before
        fun setUp() {
            hiltRule.inject()
        }
    
        @Throws(
            UnsupportedEncodingException::class
        )
        @Pact(provider = "our_provider", consumer = "our_consumer")
        fun createFragment(builder: PactDslWithProvider): RequestResponsePact {
       
            return builder
                .given("data count is > 0")
                .uponReceiving("a request for json data")
                .path("/provider.json")
                .method("GET")
                .willRespondWith()
                .status(200)
                .headers(HEADERS)
                .body(JSON)
                .toPact()
        }
    
        @Test
        @PactTestFor(pactMethod = "createFragment")
        fun should_process_the_json_payload_from_provider() {
            val observer: TestObserver<InvestorProfile> = viewModel.getInvestorProfileUseCase.buildUseCaseObservable(
                GetInvestorProfileUseCase.Params.GetInvestorProfileUseCase()).test()
            observer.assertNoErrors()
            observer.assertValue(
                InvestorProfile(
                    45,"RISK_AVERSE"
                )
            )
        }
    }
    m
    b
    • 3
    • 5
  • g

    GitHub

    08/02/2022, 7:45 AM
    Release - 4.1.39 New release published by rholshausen Back-ported fixes and consumer version selectors from v4.3.x • d7fccb6 - fix(Gradle): fixes gradle provider verification from pact file #1587 • 77b79a2 - fix(Gradle): Update methods on GradleProviderInfo to support calling hasPactsFromPactBroker without options #1586 • 14a5143 - fix: for NoSuchMethodError: void kotlin.jvm.internal.FunctionReferenceImpl • 05dce3c - feat: Update Maven plugin readme with latest consumer version selectors • 34d19e3 - feat: Update Maven plugin with latest consumer version selectors • 7177bdc - chore: remove deprecation annotation from selector tag methods • 1a51957 - fix: annotation check was failing on JDK8 • d23fcbe - refactor: rename ConsumerVersionSelectors annotation so it does not clash with the model class • 17e51e3 - refactor: Consumer Version Selectors method does not need a parameter • 743ac4b - Feat: Support consumer version selectors DSL for JUnit 5 • f54ee01 - feat(JUnit): allow pact loader to setup from the test class instead of just annotations • afeca40 - chore: correct the GitHub URL in Gradle plugin • 957f3a3 - chore: upgrade Gradle project to use 1.0 of the plugin-publish plugin • f021ef1 - feat: add Gradle DSL functions for deprecated tag forms of selectors • fe643c9 - fix: call the updated selector method from the Gradle plugin • 0afc954 - Feat: Implement new Gradle DSL for consumer version selectors • 01e45dc - feat: allow consumer version selector JSON to be provided with an environment variable • 57533e3 - Update gradle.properties to fix Vulnerability • 33d659e - Added secondary constructor to FormPostBuilder to facilitate passing a ContentType. • 8a6095c - chore: correct offset expressions in date-time expressions • a36ce77 - chore: correct message on warning log entry • e0b15ab - Update PactCanIDeployTask.groovy • 1a80e41 - Adding support for Kafka Schema Registry JSON messages. Do not store magic bytes in broker: - use the content-type to add them to messages for Consumer Tests - remove first 5 bytes from provider tests before parsing as JSON • b48e37d - feat: Add support for PactLoader path value expressions • 270808a - Adding support for Kafka Schema Registry JSON messages. Utilise the Content-Type to indicate KSR messages. Deal with the 5 "magic" bytes at the start of the JSON. • 8dc11bd - fix: make the use of content type overrides consistent #1569 • 1f2cf91 - docs: link to 'Using provider states effectively' • 3e09e6c - feat: allow consumer version selector JSON to be provided with an environment variable • bec44aa - fix: make the use of content type overrides consistent #1569 pact-foundation/pact-jvm
    m
    t
    +2
    • 5
    • 12
  • y

    Yousaf Nabi (pactflow.io)

    03/04/2022, 9:57 AM
    Our very own members of the pact community @Andy Muir has been kind enough to help with some Kafka pact recipes for our docs website here and also has a new supporting blog post out. Feel free to take a read https://muirandy.wordpress.com/2022/03/03/contract-testing-with-pact-kafka-and-schema-registry-part-2/ Thanks Andy!
    🙌 1
    a
    m
    a
    • 4
    • 27
  • a

    Alan Still

    07/29/2022, 1:15 PM
    Hi Team 👋 , I’ve been seeing some ‘strangeness’ in our logs when our Provider Verification step runs in our build. We are using the junit5 Provider annotations, however 1 of our @PactVerifyProvider annotated methods is not publishing any verification - whereas the other 4 provider tests we have in the same class all do. In our build in pass in the following args to the task • pact.provider.version -> git SHA • pact.provider.tag -> branch-name • pact.provider.branch -> branch-name • pact.provider.environment -> env (we have set up DEV/PROD) • pact.verifier.publishResults -> always true • pactbroker.auth.token -> auth token Is there something in the combination of the tags we are sending that could cause this to happen for a single provider? TIA
    u
    m
    • 3
    • 11
  • a

    Ali Ustek

    08/02/2022, 12:19 PM
    Hi everyone, is anyone using Avro with pact?
    m
    • 2
    • 1
  • a

    Alexandru Mihai

    08/04/2022, 10:31 AM
    Hello everyone! Lets consider the following snippet:
    Copy code
    void setup {
    mockClient instantiation 
    } 
    
    public void pactTest(){
    pact for a POST to the client 
    }
    This worked fine untill we implemented service descovery, and due to that, in setup is now an extra GET call to the mock server which generates Unexpected Request error. Debugging this, I discovered that the pactTest runs just fine, the post request is made after the get one and even if asserts are run and everything is ok, in the end it fails due to that unexpected request error. My question would be, is there any method to ignore the unexpected request, or to tell mock server how to respond to it, without adding it into the pact file ? Thanks in advance
    m
    t
    • 3
    • 23
  • s

    Shan

    08/04/2022, 7:40 PM
    I am trying to use
    @consumerVersionSelectors
    in my provider's tests from this doc but it seems
    consumerVersionSelectors
    method is deprecated.
    Copy code
    /** @deprecated */
      @Deprecated
      VersionSelector[] consumerVersionSelectors() default {@VersionSelector(
      tag = "${pactbroker.consumerversionselectors.tags:}",
      latest = "${pactbroker.consumerversionselectors.latest:}",
      consumer = "${pactbroker.consumers:}"
    )};
    For
    maven provider version 4.3.12.
    What is the alternative for this annotation?
    u
    • 2
    • 2
  • g

    Gaurav

    08/04/2022, 8:46 PM
    Hi Guys, need some help, I am writing pact test for some services, say there are three service, service A, B and C A and B both are consumer to different APIs exposed by C A has a pact consumer test, consumer=A, Provider=C B has a pact consumer test, consumer=B, Provider=C C has two different pact verification tests to verify both pacts when I just run consumer test for A and run verification test in C to verify that pact, it works fine, as soon as I run both consumer test for A and B and then run verification test for C, i get this error java.lang.AssertionError at PactVerificationStateChangeExtension.kt:52 Caused by: au.com.dius.pact.provider.junitsupport.MissingStateChangeMethod at PactVerificationStateChangeExtension.kt:125 Is it not allowed to put the same provider name in more than one consumer tests? or I am missing something in my configuration cc @Matt (pactflow.io / pact-js / pact-go) @Beth (pactflow.io/Pact Broker/pact-ruby)
    b
    u
    • 3
    • 6
  • g

    Gaurav

    08/08/2022, 3:23 PM
    Hi Guys, trying to build a pact test for an API that returns a String (not a json), the consumer side pact method looks like this
    Copy code
    builder
        .given('the instruction is accepted')
        .uponReceiving('a request to create instruction')
        .path("$BASE_URL/instruction")
        .method('POST')
        .headers('Content-Type', 'application/json',
            'Accept', 'application/json')
        .body(buildPactDslJsonBody())
        .willRespondWith()
        .status(201)
        .body("1234")
        .headers(Map.of('Content-Type', 'application/json'))
        .toPact()
    
    but when the pact is produced, it looks like this 
    
    {
      "status": 201,
      "headers": {
        "Content-Type": "application/json"
      },
      "body": 1234
    }
    
    instead of string its converting the response body to a number, is the string response not supported by pact libs?
    u
    • 2
    • 2
  • m

    Manu Mahendran

    08/08/2022, 4:16 PM
    You have .body twice "body(buildPactDslJsonBody())" @Gaurav
    g
    • 2
    • 8
  • m

    Manu Mahendran

    08/08/2022, 4:21 PM
    #C5F4KFKR8 Does anyone have any documentation regarding how the internal libraries of pact such as pactdslprovider work?
    u
    • 2
    • 4
  • c

    Cristian Deac

    08/09/2022, 9:16 AM
    hello guys, i am using
    valueFromProviderState
    syntax in a test and i was wondering if there is any trick to apply a function on the value return by the state provider i.e the state populates the map with
    userId
    in the test to use something like
    Copy code
    newJsonBody((payload) ->
                    payload.valueFromProviderState("id", () -> Base64.encode("${userId}"), "MTIzCg=="))
                    .build()
    u
    • 2
    • 7
  • d

    Daniel Tischner

    08/11/2022, 8:39 AM
    Hello 👋 This might probably be a quick one, but it was not directly clear from the doc for me. I am using the newest Kotlin API. Are the methods
    headers(...)
    and
    matchHeader(...)
    , if not using REGEX in the first place, identical? I.e. do the following behave the same?
    Copy code
    builder
      .given(...)
      .uponReceiving(...)
      ...
      .headers("foo", "bar")
      // vs
      .matchHeader("foo", "bar")
    (same goes for other similar methods that have a
    matchXXX
    equivalent)
    ✅ 1
    u
    • 2
    • 4
  • d

    Daniel Tischner

    08/11/2022, 8:50 AM
    For Kotlin, any opinions on a Lambda DSL for the actual
    uponReceiving ... willRespondWith ...
    part? I noticed that some examples in the docs indent the parts to visually separate the request and the response:
    Copy code
    builder
      .given("foo")
      .uponReceiving("something")
        .path("ping/pong")
        .method("POST")
        .body("Hello")
      .willRespondWith()
        .successStatus()
        .body("World")
      .build()
    But with most auto-formatting tools (IDE, Spotless, ...) this might not always be possible to achieve and it will just collapse back to:
    Copy code
    builder
      .given("foo")
      .uponReceiving("something")
      .path("ping/pong")
      .method("POST")
      .body("Hello")
      .willRespondWith()
      .successStatus()
      .body("World")
      .build()
    Now, it is fairly simple to add a Lambda DSL to achieve this indents:
    Copy code
    builder
      .given("foo")
      .uponReceiving("something")
      .path("ping/pong") {
        method("POST")
        body("Hello")
      }.willRespondWith()
        successStatus()
        body("World")
      }.build()
    Should I invest time into creating a PR, or am I overlooking something here? (I noticed one issue between
    uponReceiving
    and
    path
    though, since they are changing types from
    ...WithoutPath
    to
    ...WithPath
    , so I only managed to make the DSL cut at the
    path
    method)
    🙌 4
    u
    y
    b
    • 4
    • 18
  • d

    Daniel Tischner

    08/12/2022, 1:15 PM
    Sorry if this is simple stuff, but I feel like I am doing something fundamentally wrong when writing my (first more complex) body matcher (with Kotlin Lambda DSL). I guess I am misunderstanding one of the methods and its syntax. Unfortunately, the doc only showed very simple examples when it comes to the Lambda DSL.
    Copy code
    body(newJsonObject {
        newArray("value_added_taxes") {
            eachLike {
                integerType("id")
                newArray("values") {
                    decimalType("rate")
                    datetime("valid_since") // "2020-04-15T17:30:00Z"
                    datetime("valid_until") // "2020-06-15T17:30:00Z"
                }
            }
        }
    })

    https://i.imgur.com/mLhIT5Y.png▾

    the generator creates this response (from the debug logger):

    https://i.imgur.com/yNrfnCS.png▾

    which is definitely not what I intended to get. i was more thinking of:
    Copy code
    {
      "value_added_taxes": [
        {
          "id": 0,
          "values": [
             "rate": 0.12,
             "valid_since": "2020-04-15T17:30:00Z",
             "valid_until": "2020-06-15T17:30:00Z"
          ]
        }
      ]
    }
    ✅ 1
    b
    • 2
    • 4
  • d

    Daniel Tischner

    08/22/2022, 10:03 AM
    I know this may sound a bit weird, but I have an use case where a response must only return a decimal that is like
    0.12
    ,
    0.35
    or
    0.5
    etc. Essentially, it is "percentage" with maximal 2 digits after the separator. How would I add this to my contract?
    decimalType
    allows all kinds of decimals, such as
    -1234.23456
    stringMatcher
    will make it a string type instead of decimal Is there maybe some more general
    matches(...)
    which I could then tell the type + a custom regex matching? If not, how could I implement what I need as extension? Any hints? While at it, what about other similar stuff, such as "any positive number"?
    u
    r
    t
    • 4
    • 8
  • t

    Thai Le

    08/22/2022, 9:04 PM
    hello, i have an aggregation pom named all-modules-pom.xml and it has a build section with pact broker info but when i run mvn pact:publish -f all-modules-pom.xml i got error. Can you advise a solution?
    r
    • 2
    • 2
  • t

    Thai Le

    08/23/2022, 4:10 PM
    Hello, is there recommendation for using pact in a monorepo in which there are many projects interacting with each other through REST API ? Can a single can-i-deploy at a specific commit of the monorepo tell if all consumers and providers are compatible?
    m
    b
    t
    • 4
    • 17
  • a

    Abdurahman Hijazi

    08/25/2022, 10:59 AM
    Is there any way to test that an error has been thrown during the pact test
    Copy code
    @Provider("provider")
    @PactFolder("pacts")
    @ExtendWith(VertxExtension.class)
    public class PactContractTest {
    
        final static AuthSessionRepository authSessionRepositoryMock = mock(AuthSessionRepository.class);
        final static AuthCodeRepository authCodeRepositoryMock = mock(AuthCodeRepository.class);
        final static DateUtils dateUtilsMock = mock(DateUtils.class);
        final static WebClient webClientMock = mock(WebClient.class, RETURNS_DEEP_STUBS);
    
        static WebClient webTestClient;
    
        @BeforeAll
        static void init(Vertx vertx, VertxTestContext testContext) {
            var options = new WebClientOptions().setDefaultPort(8888);
            webTestClient = WebClient.create(vertx, options);
            TestSetupHelper.setupAndDeployVerticleForTests(vertx, testContext, authSessionRepositoryMock, authCodeRepositoryMock, dateUtilsMock, webClientMock);
        }
    
        @BeforeEach
        void set_context(PactVerificationContext context) {
            context.setTarget(new HttpTestTarget("localhost", 8888, "/"));
        }
    
        @TestTemplate
        @ExtendWith(PactVerificationInvocationContextProvider.class)
        void pactVerificationTestTemplate(VertxTestContext testContext, PactVerificationContext context) throws MalformedURLException {
            context.verifyInteraction();
            testContext.completeNow();
        }
    
        @State("returns id token as jwt")
        void create_id_token_as_jwt(){
    
        }
    
        @State("token error")
        void assert_correct_error_is_thrown_for_bad_token_request(PactVerificationContext context) {
          // Assert that a certain exception is thrown
        }
    
    
    
    }
    in one of my tests I am expecting a custom error to be thrown, can I catch it in my pact test or is that out of the scope of pact?
    t
    u
    • 3
    • 6
  • t

    Thai Le

    08/25/2022, 8:08 PM
    Hello, when running verify (and publish result) on the provider side, I have to specify the version of the provider -Dpact.provider.version="1.2.3-$(git rev-parse --short HEAD)". However, the base version of the provider is usually defined in the pom of the provider (project.version). Is there some config in the pom that I can set so that I do not have to pass this directive to maven? I see for the consumer, i can do:
  • h

    Hari Ravi

    08/29/2022, 4:18 PM
    Hi Team, Need your input. I would like to know if there are any maven properties to enable/disable pact test when we run mvn clean install on the provider side.
    t
    • 2
    • 1
  • s

    Sravan

    08/30/2022, 4:29 PM
    Hi, I'm facing the below issue while publishing the pact json :
    Copy code
    Publishing 'ppe-service-bus-issue-compilation-ppe-service-ent-issue-compilation.json' ... FAILED! 409 Conflict - {"error":"Cannot change the content of the pact for ppe-service-bus-issue-compilation version 1.0.0 and provider ppe-service-ent-issue-compilation, as race conditions will cause unreliable results for can-i-deploy. Each pact must be published with a unique consumer version number. For more information see <https://docs.pact.io/go/versioning>"}
    I'm not sure why it is failing and the same json file is getting verified when the run the provider from my local machine pointing to the json file. Any idea?
  • s

    Sravan

    08/30/2022, 5:04 PM
    I have tried to invoke the endpoint that publishes the contract with a similar body mentioned below and got a response:
    Copy code
    {
      "pacticipantName": "Foo",
      "pacticipantVersionNumber": "dc5eb529230038a4673b8c971395bd2922d8b240",
      "branch": "main",
      "tags": [
        "main"
      ],
      "buildUrl": "<https://ci/builds/1234>",
      "contracts": [
        {
          "consumerName": "Foo",
          "providerName": "Bar",
          "specification": "pact",
          "contentType": "application/json",
          "content": "<base64 encoded JSON pact>"
        }
      ]
    }
    Response:
    Copy code
    {
      "notices": [
        {
          "type": "error",
          "text": "Cannot change the content of the pact for ppe-service-ent-issue-compilation version 1.0.0 and provider ppe-service-ent-issue-compilation, as race conditions will cause unreliable results for can-i-deploy. Each pact must be published with a unique consumer version number. For more information see <https://docs.pact.io/go/versioning>"
        },
        {
          "type": "info",
          "text": ""
        }
      ],
      "errors": {
        "contracts": [
          "Cannot change the content of the pact for ppe-service-ent-issue-compilation version 1.0.0 and provider ppe-service-ent-issue-compilation, as race conditions will cause unreliable results for can-i-deploy. Each pact must be published with a unique consumer version number. For more information see <https://docs.pact.io/go/versioning>"
        ]
      }
    }
    I dont see any difference in the content that is causing this issue
    m
    • 2
    • 15
  • é

    Édouard Lopez

    09/02/2022, 10:04 AM
    Hello, some of our provider cannot verify its contracts any more and return an emty list of pacts from http://broker.org/pacts/provider/ms.advice-conversation/for-verification
    Copy code
    {
      "_embedded": {
        "pacts": []
      },
      "_links": {
        "self": {
          "href": "<http://broker.org/pacts/provider/ms.advice-conversation/for-verification>",
          "title": "Pacts to be verified"
        }
      }
    }
    Yet I do have contracts in
    /pacts/provider/ms.advice-conversation/
    . What am I missing here?
    m
    f
    b
    • 4
    • 35
  • é

    Édouard Lopez

    09/05/2022, 3:14 PM
    Related to my previous messages (above), I do have a contract between my consumer and provider as seen in the first image but none when I select the
    latest version
    on the consumer. That could explains
    NoPactsFoundException
    , but I don't understand how this happens? It was working before and my upgrade to
    2.102.1
    was a more than a month ago.
    Copy code
    au.com.dius.pact.provider.junitsupport.loader.NoPactsFoundException: No Pact files were found to verify
    b
    • 2
    • 7
  • p

    Pablo Cabo

    09/06/2022, 12:38 PM
    Hi, one question, I have an openAPI 3.0.3 spec with "oneOf" for body responses, when I match the pact agains swagger-mock-validator, I get the error "response.body.incompatible: 1". exists any matcher that allows to match with one of the responses?
    t
    • 2
    • 17
  • é

    Édouard Lopez

    09/06/2022, 3:52 PM
    What the alternative to of
    consumerVersionSelectors
    in
    @PactBroker
    annotation? I get this IDE message? JavaDoc says to use the same method (apologies I'm not familiar with Java)
    Use consumerVersionSelectors method or pactbroker.consumerversionselectors property instead
    u
    • 2
    • 2
  • p

    pocomon

    09/06/2022, 8:18 PM
    👋 Hello, team!
    👋 1
  • p

    pocomon

    09/06/2022, 8:40 PM
    I am new to PACT and trying to use pact-java for contract testing for a java microservice. I understand the concept of consumer test which generates a pact contract file and uploaded it to the broker. Now I have a question about provider side testing. I read that the provider tests are run against the actual service. So I start the provider service in a container environment in my pipeline before tests are run. My provider service interacts with a database and based on the value obtained from the DB do some logic processing and replay with the response. These are the api's I need to do the provider side testing 1. POST api to create a new transaction. This API will respond with a unique transaction id and owner id. 2. POST api to get the base encoded value of transaction .The request accepts the transaction id and own id in the request body and validate against with db and if the details provided in the request is correct respond with base64 encoded value if the entry is not present in the db respond with a 404 status code. I have create a provider test for the api 1 but for the API 2 to test I need the transaction id and owner id obtained as response of API test 1. Qn1 : Do need to run the provider api against the actual server in a test docker container in pipeline. Qn2 : Do we need to mock the service layer in the provider service as we interested only in the contract Qn3 : How to get the provider testing 1 response and it can be used as input for provider side test 2
    u
    • 2
    • 4
  • j

    James Weng

    09/07/2022, 3:22 AM
    Hi do we have an example to use consumer version selector in kotlin? Thanks. Where in the code should i put this in ?
    Copy code
    @PactBrokerConsumerVersionSelectors
    fun consumerVersionSelectors(): SelectorBuilder = SelectorBuilder()
            .branch("main")
            .environment("prod")
            .environment("qa")
            .environment("int")
    u
    b
    • 3
    • 50
1...678...14Latest