Python unittest – 單元測試示例

今天我們將學習有關 Python unittest 並查看 Python 單元測試範例程序。在先前的教程中,我們學習了python zip函數

Python unittest

Python unittest模組用於測試源代碼的單元。假設您需要測試您的項目。您知道函數將返回什麼類型的數據。在編寫了大量代碼之後,您需要檢查它的輸出是否正確。通常,我們所做的是打印輸出並將其與參考輸出文件匹配,或手動檢查輸出。為了減輕這種痛苦,Python引入了unittest模組。使用此模組,您可以通過一些簡單的代碼檢查函數的輸出。在本教程中,我們將討論Python unittest模組的基本用法並編寫一些python單元測試案例以測試類函數。

Python單元測試案例源代碼

首先,我們需要編寫一些代碼來進行單元測試。我們將擁有一個Python類別,該類別的主要目的是存儲和檢索個人姓名。因此,我們編寫set_name()函數來存儲數據,並編寫get_name()函數來從類別中檢索名稱。

class Person:
    name = []

    def set_name(self, user_name):
        self.name.append(user_name)
        return len(self.name) - 1

    def get_name(self, user_id):
        if user_id >= len(self.name):
            return 'There is no such user'
        else:
            return self.name[user_id]


if __name__ == '__main__':
    person = Person()
    print('User Abbas has been added with id ', person.set_name('Abbas'))
    print('User associated with id 0 is ', person.get_name(0))

我們將類別文件命名為Person.py。以上代碼的輸出將如下所示。

$ python3.6 Person.py 
User Abbas has been added with id  0
User associated with id 0 is  Abbas
$

Python unittest結構

現在,讓我們學習如何為單元測試編寫代碼。通過繼承unittest.TestCase來創建單個測試用例。通過覆蓋或添加適當的函數,我們可以添加測試邏輯。如果a等於b,則以下代碼將成功運行。

import unittest


class Testing(unittest.TestCase):
    def test_string(self):
        a = 'some'
        b = 'some'
        self.assertEqual(a, b)

    def test_boolean(self):
        a = True
        b = True
        self.assertEqual(a, b)

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

如何運行python unittest模塊

如果您正在使用PyCharm IDE,您可以简单地按ctrl+shift+F10来运行unittest模块。否则,您可以使用命令提示符来运行此模块。例如,我们将用于单元测试的文件命名为Basic_Test.py。因此,运行Python unittest的命令将是:$python3.6 -m unittest Basic_Test.Testing如果您想要查看详细信息,则命令将是:$python3.6 -m unittest -v Basic_Test.Testing通过使用PyCharm,我们可以获得以下输出。

Python單元測試結果與基本功能

此單元測試有3種可能的結果。它們如下所示:

  1. OK:如果所有測試用例都通過,則輸出顯示OK。
  2. Failure:如果任何測試用例失敗並引發AssertionError異常
  3. Error:如果引發了除AssertionError異常之外的任何異常。

unittest模塊下有幾個功能。它們如下列出。

Method Checks that
assertEqual(a,b) a==b
assertNotEqual(a,b) a != b
assertTrue(x) bool(x) is True
assertFalse(x) bool(x) is False
assertIs(a,b) a is b
assertIs(a,b) a is b
assertIsNot(a, b) a is not b
assertIsNone(x) x is None
assertIsNotNone(x) x is not None
assertIn(a, b) a in b
assertNotIn(a, b) a not in b
assertIsInstance(a, b) isinstance(a, b)
assertNotIsInstance(a, b) not isinstance(a, b)

Python單元測試示例

現在是時候為我們的源代碼類 Person 編寫單元測試了。在這個類中,我們實現了兩個函數 – get_name()set_name()。現在,我們將使用 unittest 測試這些函數。因此,我們為這兩個函數設計了兩個測試案例。請查看以下代碼,您將很容易理解。

import unittest

# 這是我們想要測試的類。因此,我們需要導入它
import Person as PersonClass


class Test(unittest.TestCase):
    """
    The basic class that inherits unittest.TestCase
    """
    person = PersonClass.Person()  # instantiate the Person Class
    user_id = []  # variable that stores obtained user_id
    user_name = []  # variable that stores person name

    # 測試案例函數以檢查 Person.set_name 函數
    def test_0_set_name(self):
        print("Start set_name test\n")
        """
        Any method which starts with ``test_`` will considered as a test case.
        """
        for i in range(4):
            # 初始化一個名字
            name = 'name' + str(i)
            # 將名字存儲到列表變量中
            self.user_name.append(name)
            # 從函數獲取用戶 id
            user_id = self.person.set_name(name)
            # 檢查獲取的用戶 id 是否為空
            self.assertIsNotNone(user_id)  # null user id will fail the test
            # 將用戶 id 存儲到列表中
            self.user_id.append(user_id)
        print("user_id length = ", len(self.user_id))
        print(self.user_id)
        print("user_name length = ", len(self.user_name))
        print(self.user_name)
        print("\nFinish set_name test\n")

    # 測試案例函數以檢查 Person.get_name 函數
    def test_1_get_name(self):
        print("\nStart get_name test\n")
        """
        Any method that starts with ``test_`` will be considered as a test case.
        """
        length = len(self.user_id)  # total number of stored user information
        print("user_id length = ", length)
        print("user_name length = ", len(self.user_name))
        for i in range(6):
            # 如果不超過總長度,則驗證返回的名字
            if i < length:
                # 如果兩個名字不匹配,則測試案例將失敗
                self.assertEqual(self.user_name[i], self.person.get_name(self.user_id[i]))
            else:
                print("Testing for get_name no user test")
                # 如果長度超過,則檢查“沒有此用戶”類型的消息
                self.assertEqual('There is no such user', self.person.get_name(i))
        print("\nFinish get_name test\n")


if __name__ == '__main__':
    # 開始 unittest.main()
    unittest.main()

請注意,unittest 模塊按照函數名稱的順序執行測試函數,而不是它們定義的順序。由於我們希望我們的 set_name 測試先執行,我們將我們的測試案例函數命名為 test_0_set_nametest_1_get_name

Python 單元測試範例輸出

以下圖像顯示我們的單元測試程式所產生的輸出 – 包括普通模式和詳細模式。

$ python3.6 -m unittest -v PersonTest.Test
test_0_set_name (PersonTest.Test) ... Start set_name test

user_id length =  4
[0, 1, 2, 3]
user_name length =  4
['name0', 'name1', 'name2', 'name3']

Finish set_name test

ok
test_1_get_name (PersonTest.Test) ... 
Start get_name test

user_id length =  4
user_name length =  4
Testing for get_name no user test
Testing for get_name no user test

Finish get_name test

ok

----------------------------------------------------------------------
Ran 2 tests in 0.000s

OK
$

這就是關於 Python 單元測試教程的全部內容。要瞭解更多,請閱讀 官方文檔。如有任何進一步的查詢,請使用評論框。 🙂

Source:
https://www.digitalocean.com/community/tutorials/python-unittest-unit-test-example