问题描述
我正在使用 Pact gem(并且喜欢它!)合约测试套件.我正在测试的 API 服务需要所有请求的授权令牌.
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.
我知道如何为我的用户生成 API 令牌,但我不知道将令牌放置在 Pact 工作流程中的什么位置.我在 Pact 文档和 repo 中搜索了示例,但没有任何运气.
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.
我尝试在消费者规范中发送 POST 以生成令牌,但 Pact 模拟服务器不知道如何处理请求和错误(正如我所期望的那样).
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).
我发现了这个例子,看起来很有希望,特别是使用 requestFilter
和 addHeader
方法为所有请求分配预定义标头的能力.
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.
如何在 Pact gem 中使用这样的请求过滤器?
How can I use such a request filter with the Pact gem?
如果这不是当前功能,我还有哪些替代方案?
If that's not a current feature, what alternatives do I have?
更新:
J_A_X 的答案 非常适合与模拟服务器创建协议,但它不能满足 API 服务提供商的期望有效的身份验证令牌.更具体地说,我需要在运行 pact:verify 时将有效的身份验证令牌动态插入到协议中.所以,更近了一步,但仍然需要弄清楚后半部分.
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.
马修的回答 包含对后半部分似乎有两种可能的解决方案的提示 (pact:verify).我犹豫要引入另一个依赖项,所以我很想让 ProxyApp 类示例工作.我不明白我到底要传递给 ProxyApp.new() 什么.建议?
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?
推荐答案
Pact 的 Ruby 实现并不像 JVM 实现那样直接支持这一点.
The Ruby implementation of Pact doesn't support this directly as per the JVM implementation.
如果您使用的是 Pact Provider Proxy gem,则可以查看 https://github.com/realestate-com-au/pact/issues/49#issuecomment-65346357 和 https://groups.google.com/forum/#!topic/pact-support/tSyKZMxsECk.
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.
示例可能类似于:
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
这篇关于如何针对需要身份验证令牌的 API 验证协议?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!