2

I'm using the Pact gem (and loving it!) for my contract test suite. The API service I'm testing requires an authorization token for all requests.

I know how to generate an API token for my user, but I don't know where to place the token in the Pact workflow. I searched the Pact documentation and repo for examples but didn't have any luck.

I tried sending a POST in the consumer specs to generate a token, but the Pact mock server doesn't know what to do with the request and errors out (as I would expect).

I found this example and it seems promising, particularly the ability to assign predefined headers to all requests with a requestFilter and the addHeader method.

How can I use such a request filter with the Pact gem?

If that's not a current feature, what alternatives do I have?

UPDATE:

J_A_X's answer works great for creating the pacts with the mock server but it doesn't satisfy the API service provider's expectation of a valid auth token. More specifically, I need to dynamically insert valid auth tokens into the pacts upon running pact:verify. So, one step closer but still need to figure out the latter part.

Matthew's answer contains hints for what appear to be two possible solutions for the latter part (pact:verify). I hesitate to introduce another dependency so I'd love to get the ProxyApp class example working. I don't understand what exactly I'd pass into ProxyApp.new() though. Suggestions?

2 Answers 2

1

You actually don't have to use a real token for each pact interaction unless you really want/need to.

Normally for that kind of stuff, I just create a regex to be used on the header to validate certain rules while keeping it 'open'. In my node project (which uses the Ruby binary in the back), I created these 2 utilities functions to create objects with a pattern and another for a object minimum equal:

function term(matcher, generate) {
    if ((typeof matcher === 'undefined') || (typeof generate === 'undefined')) {
      throw 'Matcher and Generate arguments must be specified to use Term';
    }
    return {
      "json_class": "Pact::Term",
      "data": {
        "generate": generate,
        "matcher": {
          "json_class": "Regexp",
          "o": 0,
          "s": matcher
        }
      }
    };
  }

  function somethingLike(value) {
    return {
      "json_class": "Pact::SomethingLike",
      "contents": value
    };
  }

You can then use it in your DSL definition like so:

mockService
      .given('a form')
      .uponReceiving('a GET request with a valid auth')
      .withRequest('get', '/', term('^Bearer (?!null$).+$', 'Bearer eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJzdWIiOiIxMjM0NTY3ODkwIiwibmFtZSI6IkpvaG4gRG9lIiwiYWRtaW4iOnRydWV9.TJVA95OrM7E2cBab30RMHrHDcEfxjoYZgeFONFh7HgQ'))
      .willRespondWith({
        status: 200,
        headers: {'Content-Type': 'application/json;charset=utf-8'},
        body: {worked:true}
      });

The 'term' utility has a regex as the first parameter and then an example (that should match the first) of what to use during the test.

I know that this needs to be expanded better within Pact itself to make it simpler to use. I hope this helps.

6
  • Thank you for your thorough answer! Your example certainly works though it feels more like a workaround to me. I'm hoping for a built-in approach that lets me verify pacts with real auth tokens.
    – mycargus
    Nov 24, 2016 at 5:20
  • 1
    well, you can use them, but the problem here is that you now have to know what that token will be before creating the interactions, and then testing them. I don't know how to create that flow easily without cheating in some kind of way, which is essentially the same as doing this. In the end, ask yourself if this particular interaction check is really that important in the overall testing of your provider. In my mind, it isn't, hence my regex; what's important to me is the business API that returns data in the correct format/type.
    – J_A_X
    Nov 24, 2016 at 5:25
  • Your approach works great for creating the pacts with the mock server but it doesn't satisfy the API service provider's expectation of a valid auth token. More specifically, I need to dynamically insert valid auth tokens into the pacts upon running pact:verify. Does that make sense?
    – mycargus
    Dec 8, 2016 at 20:52
  • @mycargus If you're using the Term matcher, you can add a valid token as the 'generator' and it should validate on that within your contract, but the issue with having a 'valid' auth token will normally have an expiry on them, hence using one will normally fail the real code after the expiry passes, unless you want to keep updating that token in your code. I believe that this is an edge case for Pact's usage and that Token validation is something meant for unit testing, while the contract can still validate the needed header and format like 'Authorization: Bearer .*'
    – J_A_X
    Dec 9, 2016 at 0:22
  • Perhaps I'm misunderstanding what Pact does upon pact:verify. Does it not replay the requests as defined in the Pact file? If so, it will use the same auth token(s) defined therein... and if those tokens aren't valid, then the API service will respond with 401. That's what I'm currently facing. With your solution I can generate the Pact file and I can assert that the actual request has a header that fits the provided regex... but how do I insert the valid auth token into the request? That's my question. I can't rely on generating a valid token when generating the pact file as that may expire.
    – mycargus
    Dec 9, 2016 at 22:22
1

The Ruby implementation of Pact doesn't support this directly as per the JVM implementation.

If you're using the Pact Provider Proxy gem, you could take a look at some of the options discussed at https://github.com/realestate-com-au/pact/issues/49#issuecomment-65346357 and https://groups.google.com/forum/#!topic/pact-support/tSyKZMxsECk.

An example might look something like:

class ProxyApp

  def initialize real_app
    @real_app = real_app
  end

  def call env
    @real_app.call(env.merge('HTTP_AUTHORIZATION' => '12345'))
  end
end

Pact.service_provider "Some Provider" do
  app do
    ProxyApp.new(RealApp)
  end

  honours_pact_with "Some Consumer" do
    #...
  end
end
5
  • I'll consider using the provider proxy. Thank you!
    – mycargus
    Nov 25, 2016 at 0:26
  • I see now that you're recommending two distinct possible solutions: (1) use a Pact Provider Proxy to verify pacts against a separate running provider, or (2) use a class inside the provider's pact_helper.rb to merge the dynamic auth header to the pact verification. I'm attempting the second approach now.
    – mycargus
    Dec 8, 2016 at 21:14
  • Thanks @mycargus, I'd love to hear how you go. This might be a good example to get into our docs, as it does come up every now and then. Dec 9, 2016 at 22:13
  • Cool, I will definitely share. I'd love to get the ProxyApp class example working. I don't understand what exactly I'd pass into ProxyApp.new() though. I'm guessing the Rails app but I'm not sure how to do that. Suggestions?
    – mycargus
    Dec 9, 2016 at 22:26
  • I'll ask somebody in the Ruby know, and see if they can shed any light. In the meanwhile, I've added a start to docs.pact.io/faq Dec 11, 2016 at 11:46

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.