【问题标题】:Python unittest code organization - Trello API testingPython unittest 代码组织 - Trello API 测试
【发布时间】:2017-11-11 22:36:03
【问题描述】:

我正在 Python 中测试 Trello API,我有两个文件,第一个文件包含用于创建随机名称的代码和 3 个用于 POST、GET 和 PUT 方法的函数。

我的单元测试在不同的文件中:

import unittest
from board_details import *

class BoardDetails(unittest.TestCase):

    # create new board, get its details and then change board's name
    def test_post_board(self):
        name = nonce(10)
        result_post = post_board_name(name)
        self.assertEqual(result_post.json()['name'], name)
        self.assertEqual(result_post.status_code, 200)
        self.assertEquals(len(name), 10)

    def test_get_details(self):
        name = nonce(10)
        result_post = post_board_name(name)
        board_id = result_post.json()['id']
        result_get = get_board_detals(board_id)
        self.assertEqual(result_get.status_code, 200)
        self.assertEquals(len(name), 10)
        self.assertTrue('name', name)
        self.assertTrue(result_get.headers,'application/json')

    def test_put_new_name(self):
        name = nonce(10)
        result_put = put_new_board_name(name)
        self.assertEqual(result_put.json()['name'], name)
        self.assertEqual(result_put.status_code, 200)


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

它工作正常,所有测试都通过了。但我认为有些事情仍然存在。如果我以正确的方式编写它,有人可以告诉我吗? 我重复“name = nonce(10)”三遍。我该怎么做?

【问题讨论】:

    标签: python python-unittest trello


    【解决方案1】:

    您可以创建一个setUp 函数,该函数将在每次测试之前运行。比如:

    def setUp(self):
        self.name = nonce(10)
    

    然后更新您的测试以查看 self.name 而不是 name。

    它不适用于这种情况,但有一个等效的 tearDown 函数将在每次测试后运行,您可以使用它来清理任何文件、连接或您的测试可能创建的任何内容。

    此外,您可能需要考虑将测试分解为单独的函数,而不是在一个测试中使用多个断言。您会为了可读性而牺牲速度,但是随着您的测试变得更加复杂,可以使故障排除变得更加容易。它会按原样工作,只是一个建议。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2023-03-07
      • 2017-10-05
      • 2010-09-23
      • 2016-12-21
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多