今天我们将学习关于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.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集成开发环境,您可以简单地按下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单元测试结果与基本函数
此unittest有3种可能的结果。它们如下所示:
- OK:如果所有测试用例都通过,输出显示OK。
- 失败:如果任何测试用例失败并引发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
#这是我们想要测试的类。因此,我们需要导入它
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):
#如果i未超过总长度,则验证返回的名称
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_name
和test_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