Python单元测试 – 单元测试示例

今天我们将学习Python的单元测试并浏览Python单元测试示例程序。在上一篇教程中,我们学习了Python的zip函数。

Python单元测试

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.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单元测试模块

Python unittest, python unit test example

Python单元测试结果和基本函数

这个单元测试有三种可能的结果。它们如下所示:

    通过:如果所有的测试用例都通过,输出显示通过。
    失败:如果任何一个测试用例失败并引发了AssertionError异常。
    错误:如果引发了除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

# This is the class we want to test. So, we need to import it
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

    # test case function to check the Person.set_name function
    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):
            # initialize a name
            name = 'name' + str(i)
            # store the name into the list variable
            self.user_name.append(name)
            # get the user id obtained from the function
            user_id = self.person.set_name(name)
            # check if the obtained user id is null or not
            self.assertIsNotNone(user_id)  # null user id will fail the test
            # store the user id to the list
            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")

    # test case function to check the Person.get_name function
    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 not exceed total length then verify the returned name
            if i < length:
                # if the two name not matches it will fail the test case
                self.assertEqual(self.user_name[i], self.person.get_name(self.user_id[i]))
            else:
                print("Testing for get_name no user test")
                # if length exceeds then check the 'no such user' type message
                self.assertEqual('There is no such user', self.person.get_name(i))
        print("\nFinish get_name test\n")


if __name__ == '__main__':
    # begin the unittest.main()
    unittest.main()

请注意,unittest模块按照函数名称的顺序执行测试函数,而不是按照定义的顺序执行。由于我们希望set_name测试首先执行,所以我们将测试用例函数命名为test_0_set_name和test_1_get_name。

Python单元测试示例的输出

python unittest tutorial
$ 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单元测试教程的全部内容,如果想要了解更多,请阅读官方文档。若有任何进一步的疑问,请在评论框中提问。 🙂

发表回复 0

Your email address will not be published. Required fields are marked *


广告
将在 10 秒后关闭
bannerAds