11
14

More than 5 years have passed since last update.

yaml でテストが書ける Tavernというテストツールがすごい

Last updated at Posted at 2018-09-27

Tavern

TavernはRESTfulなAPIのテストコードを yaml で書けるテストツールです。これを使えば毎回似たようなテストコードを書く必要が無くなりますし、気軽にテストコードの修正が可能になります。既に沢山のAPIを持っていてテストコード書くのツライって言う人はぜひ使ってみてください。

できること例

下記のようなテストを全て yaml で書けます

  • hoge.com/api/ に POST でリクエストしステータスコードやBodyのチェック
    • もちろんエラーパターンも書けます
  • login API などにアクセスし token 取得、以降はその tokenを用いてリクエストを投げる
  • JWT認証にも対応

インストール

$ pip install tavern[pytest]

test コードをyamlで定義

命名規則は test_*.tavern.yaml です。

test_minimal.tavern.yaml
test_name: Get some fake data from the JSON placeholder API

stages:
  - name: Make sure we have the right ID
    request:
      url: https://jsonplaceholder.typicode.com/posts/1
      method: GET

    response:
      status_code: 200
      body:
        id: 1

このyamlをカスタマイズすれば色んなパターンのテストを作成できます :smiley:

実行と結果

py.test test_minimal.tavern.yaml -v で実行

platform darwin -- Python 2.7.14, pytest-3.8.0, py-1.6.0, pluggy-0.7.1 -- /Users/kyohei/.pyenv/versions/2.7.14/envs/hogehoge/bin/python2.7
cachedir: .pytest_cache
rootdir: /User/tmp/hello_world, inifile:
plugins: tavern-0.18.1
collected 1 item

test_minimal.tavern.yaml::Get some fake data from the JSON placeholder API PASSED                                                                                   [100%]

うまくテストすることが出来ました!なかなか良い。

pytestベースで実行しましたが Tavern のcliでもテストできます。

tavern-ci --stdout test_minimal.tavern.yaml

ログイン認証有りのAPIの叩く

  1. ログイン -> token取得
  2. tokenを利用しuser情報を取得
test.yaml
test_name: login testing

stages:
  - name: login
    request:
      url: https://hogehoge.com/login
      json:
        id: hogehoge
        password: password
      method: POST
      headers:
        content-type: application/json
    response:
      headers:
        content-type: application/json
      status_code: 200
      body:
        status: 200
        expireStr: !anything
        userId: !anything
        token: !anything
        expire: !anything
        message: success
      save:
        body:
          test_user_id: userId
          test_login_token: token

  - name: Get a user info
    request:
      url: https://hogehoge.com/user/{test_user_id}
      method: GET
      headers:
        content-type: application/json
        Authorization: "Bearer {test_login_token}"
    response:
      status_code: 200
      headers:
        content-type: application/json
      body:
        result:
          userId: "{test_user_id}"

備考

11
14
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
11
14