Python unittest PUT方法 - 获取状态代码

时间:2017-06-11 15:29:25

标签: python rest api unit-testing python-unittest

这是我测试Trello API的代码:

import string
import random
import requests
from settings import *

nonce = lambda x: ''.join(random.choice(string.ascii_uppercase + string.digits) for _ in range(10 if not x else x))

def get_board_detals(board_id):
    url = "https://trello.com/1/boards/" + board_id
    params = {"key":key,
          "token":token}
    return requests.get(url=url, params=params)

def post_board_name(board_name):
    url = "https://api.trello.com/1/boards"
    params = {"key": key,
          "token": token,
          "name": board_name}
    return requests.post(url=url, params=params)

def put_new_board_name(board_id):
    url = "https://api.trello.com/1/boards" + board_id
    params = {"key": key,
              "token": token}
    return requests.put(url=url, params=params)

和unittest的代码:

import unittest
from board_details import *

class BoardDetails(unittest.TestCase):
    def setUp(self):
        self.name = nonce(10)

  def test_put_new_name(self):
        result_post = post_board_name(self.name)
        board_id = result_post.json()['id']

        result_put = put_new_board_name(board_id)
        self.assertEqual(result_put.status_code, 200)
        self.assertIn(result_put.json()['name'], self.name)


if __name__ == '__main__':
    unittest.main()

运行代码时,收到错误:AssertionError: 404 != 200。 我不知道为什么会这样,有人能指出我的错误原因是什么?

1 个答案:

答案 0 :(得分:0)

我是这样做的,似乎工作正常:

功能:

def put_new_board_name(board_id, board_name):
    url = "https://api.trello.com/1/boards/" + board_id +"/name"
    params = {"key": key,
              "token": token,
              "value" : board_name}
    return requests.put(url=url, params=params)

和方法:

def test_put_new_name(self):
    result_post = post_board_name(self.name)
    board_id = result_post.json()['id']

    result_put = put_new_board_name(board_id, board_name=self.name)
    self.assertEqual(result_put.status_code, 200)
    self.assertIn(result_put.json()['name'], self.name)