Search code examples
pythonpython-unittesttrello

Python unittest code organization - Trello API testing


I'm testing a Trello API in Python, I have two files, first one with the code for creating a random name and 3 functions for POST, GET and PUT methods.

My unittest is in a different file:

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()

It works fine, all tests passed. But I think something is still off. Can someone please advise me if I'm writing it in a right way? I'm repeating "name = nonce(10)" three times. How can I do it differently?


Solution

  • You can create a setUp function which will run before each test. Something like:

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

    Then update your tests to look at self.name instead of name.

    It doesn't apply in this case, but there's an equivalent tearDown function which will run after each test that you can use to clean up any files, connections or anything your test might have created.

    Also, you might want to consider breaking up your tests into separate functions rather than having multiple asserts in one test. You'd be sacrificing speed for readability, but as your tests get more complex that can make troubleshooting easier. It'll work as-is, just a suggestion.