我正在使用 Webmock 测试由 ruby aws-sdk(在本例中为 aws-sdk-batch)发出的 http 请求。
当请求失败时, Webmock 使用更方便的哈希差异和部分匹配来处理 json 请求,但只有当Content-Type
存根请求的application/json
.
然而,aws-sdk-batch
gem 创建了一个空请求Content-type
(尽管已将内容类型记录为 application/json),并且似乎依赖端点的默认行为将其解释为application/json
.
我想手动添加 header Content-type: application/json
,以便我可以从 Webmock 更好地处理 json 请求正文中受益。这可能吗?
未指定的示例 Webmock 响应Content-Type:application/json
:
WebMock::NetConnectNotAllowedError:
Real HTTP connections are disabled. Unregistered request: POST https://batch.us-east-1.amazonaws.com/v1/submitjob with body '{"jobName":"Fakie","jobQueue":"queue","jobDefinition":"def","parameters":{"task":"{\"fake\":\"town\"}"}}' with headers {'Accept'=>'*/*', 'Accept-Encoding'=>'', 'Authorization'=>'AWS4-HMAC-SHA256 Credential=ACCESS_KEY_ID/20190701/us-east-1/batch/aws4_request, SignedHeaders=host;x-amz-content-sha256;x-amz-date, Signature=5f4bf85ba48333e6cda6ff613b4ea2faacd0417b4136621c58b87a488c3019ee', 'Content-Length'=>'106', 'Content-Type'=>'', 'Host'=>'batch.us-east-1.amazonaws.com', 'User-Agent'=>'aws-sdk-ruby3/3.54.2 ruby/2.5.5 x86_64-darwin18 aws-sdk-batch/1.20.0', 'X-Amz-Content-Sha256'=>'cf52595364d1a588b4ca4fdeaddb8170e4ad944fa28ac6df647484bb596de9c4', 'X-Amz-Date'=>'20190701T215756Z'}
You can stub this request with the following snippet:
stub_request(:post, "https://batch.us-east-1.amazonaws.com/v1/submitjob").
with(
body: "{\"jobName\":\"Fakie\",\"jobQueue\":\"quue\",\"jobDefinition\":\"def\",\"parameters\":{\"task\":\"{\\\"fake\\\":\\\"town\\\"}\"}}",
headers: {
'Accept'=>'*/*',
'Accept-Encoding'=>'',
'Authorization'=>'AWS4-HMAC-SHA256 Credential=ACCESS_KEY_ID/20190701/us-east-1/batch/aws4_request, SignedHeaders=host;x-amz-content-sha256;x-amz-date, Signature=5f4bf85ba48333e6cda6ff613b4ea2faacd0417b4136621c58b87a488c3019ee',
'Content-Length'=>'106',
'Content-Type'=>'',
'Host'=>'batch.us-east-1.amazonaws.com',
'User-Agent'=>'aws-sdk-ruby3/3.54.2 ruby/2.5.5 x86_64-darwin18 aws-sdk-batch/1.20.0',
'X-Amz-Content-Sha256'=>'cf52595364d1a588b4ca4fdeaddb8170e4ad944fa28ac6df647484bb596de9c4',
'X-Amz-Date'=>'20190701T215756Z'
}).
to_return(status: 200, body: "", headers: {})
registered request stubs:
stub_request(:post, "https://batch.us-east-1.amazonaws.com/v1/submitjob").
with(
body: {"jobDefinition"=>"def", "jobName"=>"Wrong", "jobQueue"=>"queue", "parameters"=>{"task"=>"{\"fake\":\"town\"}"}})
正如您所看到的,当这些字符串测试失败时,您将面临逐个字符挑选正文的痛苦任务,这是一种非常可怕的开发人员体验。Hashdiff 的体验要好得多。