简体   繁体   English

如何测试JSON REST API

[英]How to test a JSON REST API

I'm brand new to ruby (first day working with ruby) so please forgive any novice questions and lack of understanding. 我是红宝石的新手(第一天使用红宝石)所以请原谅任何新手问题和缺乏理解。

I'm trying to validate the responses to http callouts. 我正在尝试验证对http标注的响应。

For example, let's say the endpoint is the following: 例如,假设端点如下:

https://applicationname-api-sbox02.herokuapp.com 

And, I'm trying to authenticate a user by sending a get request like this: 并且,我正在尝试通过发送这样的get请求来验证用户:

get_response = RestClient.get( "https://applicationname-api-sbox02.herokuapp.com/api/v1/users", 
                    {
                        "Content-Type" => "application/json",
                        "Authorization" => "token 4d012314b7e46008f215cdb7d120cdd7",
                        "Manufacturer-Token" => "8d0693ccfe65104600e2555d5af34213"
                    }
                ) 

Now, I want to validate the response and do the following: - parse the response to ensure that it is valid JSON - do some validation and verify the JSON has the correct data (verify that id == 4 for example) - if an error is encountered, raise an exception using the 'raise' method. 现在,我想验证响应并执行以下操作: - 解析响应以确保它是有效的JSON - 执行一些验证并验证JSON是否具有正确的数据(例如,验证id == 4) - 如果出现错误遇到,使用'raise'方法引发异常。

In my first feeble attempt I tried the following: 在我第一次虚弱的尝试中,我尝试了以下方法:

puts get_response.body
if get_response.code == 200
puts "********* Get current user successful"
else
puts "Get current user failed!!"
end 

Now, this returned that getting the current user was successful, but how do I actually parse the json, verify the correct id, and raise an exception if an error occurred? 现在,这返回了获取当前用户的成功,但是如何实际解析json,验证正确的id,并在发生错误时引发异常?

Instead of raising an exception, write a test. 写一个测试,而不是提出异常。

A straightforward approach, using the json parser and unit test framework from the std lib: 一个简单的方法,使用std lib中的json解析器和单元测试框架:

require 'minitest/autorun'
require 'rest_client'
require 'json'

class APITest < MiniTest::Unit::TestCase
  def setup
    response = RestClient.get("https://applicationname-api-sbox02.herokuapp.com/api/v1/users", 
      {
         "Content-Type" => "application/json",
         "Authorization" => "token 4d012314b7e46008f215cdb7d120cdd7",
         "Manufacturer-Token" => "8d0693ccfe65104600e2555d5af34213"
      }
    ) 
    @data = JSON.parse response.body
  end

  def test_id_correct
    assert_equal 4, @data['id']
  end
end

Execute with ruby $filename ruby $filename执行

JSON.parse parses a JSON string into a ruby hash JSON.parse将JSON字符串解析为ruby 哈希

Getting started with minitest 开始使用minitest

If you are using ruby 1.8, you'll need to install the json gem and either install the minitest gem , or switch to the older testunit API. 如果您使用的是ruby 1.8,则需要安装json gem并安装minitest gem ,或者切换到较旧的testunit API。 If you choose the latter, then you'll need to change require 'minitest/autorun' -> require 'test/unit' and MiniTest::Unit::TestCase -> Test::Unit::TestCase 如果选择后者,则需要更改require 'minitest/autorun' - > require 'minitest/autorun' require 'test/unit'MiniTest::Unit::TestCase - > Test::Unit::TestCase

I'm a little late to the party, but I recently co-created an rspec driven framework called Airborne for just this purpose. 我参加聚会的时间有点晚了,但我最近为此目的共同创建了一个名为Airborne的rspec驱动框架。 Check it out: https://github.com/brooklynDev/airborne 看看: https//github.com/brooklynDev/airborne

here is an example from our specs so you can see how we test json api: 这是我们的规范中的一个例子,所以你可以看到我们如何测试json api:

it 'returns charge' do
  get "/charges/#{charge.id}", '', headers

  expect(response.status).to eq(200)
  expect(response).to match_response_schema(:charge)
  expect(response).to match_json(<<-JSON)
  {
    "id":"{id}",
    "email": "{email}",
    "ip": "127.0.0.1",
    "amount": 10500,
    "state": "captured",
    "captured_amount": 10500,
  }
  JSON
end

Lets look at it closely 让我们仔细看看

  1. match_response_schema(:charge)

This matcher checks that json we get in response is in general valid. 这个匹配器检查我们得到的json是否一般有效。 We use json-schema (json schema validator) for it. 我们使用json-schema (json模式验证器)。 Guys from Thoughtbot have a detailed guide how to use json schema validator and create own matcher in this blog post. 来自Thoughtbot的家伙有详细的指南如何使用json架构验证器并在此博客文章中创建自己的匹配器。

Understanding JSON Schema is where I got a lot of useful information on how to create schemas for JSON documents. 了解JSON Schema是我获得有关如何为JSON文档创建模式的大量有用信息的地方。

  1. match_json

This is our own matcher and we have released match_json gem recently. 这是我们自己的匹配器,我们最近发布了match_json gem。 Using it you can test structure and values of your json. 使用它,您可以测试json的结构和值。 Here are two great features of this matcher: 以下是此匹配器的两个重要功能:

  • if you don't know exact values, you can use patterns like {id}, {uuid} {date_time}, etc. we have predefined patterns but you can add your own too. 如果您不知道确切的值,可以使用{id},{uuid} {date_time}等模式。我们有预定义的模式,但您也可以添加自己的模式。
  • you get clear failure message what is wrong with your json eg "5" was not found in " > array":[1,2,3] 你得到明确的失败消息你的json有什么问题,例如在“>数组”中找不到“5”:[1,2,3]

Parsing json can be done with the json gem: http://flori.github.com/json/ 解析json可以使用json gem完成: http//flori.github.com/json/

Parsed json is accessed through key/value just like in javascript. 解析的json是通过键/值访问的,就像在javascript中一样。 You can easily verify the values and conditionally raise errors. 您可以轻松验证值并有条件地引发错误。

Raising errors is done like so: 引发错误的方式如下:

raise "the ID was #{id} instead of 4"

And writing unit tests can be done with Test::Unit - http://www.ruby-doc.org/stdlib-1.9.3/libdoc/test/unit/rdoc/Test/Unit.html 编写单元测试可以使用Test :: Unit - http://www.ruby-doc.org/stdlib-1.9.3/libdoc/test/unit/rdoc/Test/Unit.html完成

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM