pact-foundation / pact-jvm

JVM version of Pact. Enables consumer driven contract testing, providing a mock service and DSL for the consumer project, and interaction playback and verification for the service provider project.
https://docs.pact.io
Apache License 2.0
1.09k stars 480 forks source link

Turn Pact Requests Into Printable Curl #1507

Open francislainy opened 2 years ago

francislainy commented 2 years ago

When Pact fails, it's a bit hard to know what the issue is considering the requests are not being printed back to the terminal. At the moment, I'm using this custom method to do this but I think it would be nice to have something like this out of the box.

public static void logCurlFromPact(PactVerificationContext context, HttpRequest request) {

        String bodyParam = ((RequestResponseInteraction) context.getInteraction()).getRequest().getBody().valueAsString();

        String bodyResponse = ((RequestResponseInteraction) context.getInteraction()).getResponse().getBody().valueAsString();

        String method = ((RequestResponseInteraction) context.getInteraction()).getRequest().getMethod();

        String url = BASE_URI + request.getPath();

        Header[] headers = request.getHeaders();

        String headersString = "";
        for (Header s : headers) {
            headersString = headersString + "--header " + "'" + s.getName() + ": " + s.getValue() + "'" + "\\" + "\n";
        }

        String curl = "" +
                "curl " +
                "--request " + method + " " +
                "'" + url + "' \\" + "\n" +
                headersString +
                "--data-binary " + "'" + bodyParam + "' \\" + "\n" +
                "--compressed \\" + "\n" +
                "--insecure \\" + "\n" +
                "--verbose" +
                "";

        log.debug(curl + "\n\n " + bodyResponse + "\n ---- \n\n");
        System.out.println(curl + "\n\n " + bodyResponse + "\n ---- \n\n");
    }

I then call it like this:


   @TestTemplate
    @ExtendWith(PactVerificationInvocationContextProvider.class)
    void pactTestTemplate(PactVerificationContext context, HttpRequest request) {

        logCurlFromPact(context, request);

        context.verifyInteraction();
    }

And that gives me the curl printed to the terminal.

image

And It also prints the response (the part under the {} )

I'd love if sth like this (or better) could be added to the library, but I'm not sure I'm the right person to take this task, so just sharing my gist as something to start with maybe?

Thanks very much.

uglyog commented 2 years ago

This is an awesome feature!

PostIt59 commented 2 years ago

Amazing feature ! Indeed, it will help us a lot 👍

YOU54F commented 5 months ago

Hey @francislainy,

Going through some old issues and this is very cool!

If you are still around in the Pact world, would you want to consider turning this into a pull request so it could become a Pact feature?