今天我们将学习Python单元测试并浏览Python单元测试示例程序。在之前的教程中我们了解了python zip 函数.
Python unittest 模块用于测试源代码单元。假设,您需要测试您的项目。您知道该函数将返回什么样的数据。写完大段代码后,需要检查输出是否正确。通常,我们所做的是打印输出并将其与参考输出文件进行匹配或手动检查输出。为了减轻这种痛苦,Python 引入了unittest 模块。使用此模块,您可以通过一些简单的代码检查函数的输出。在本教程中,我们将讨论 Python unittest 模块的基本用法,并编写一些 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
$
现在,让我们学习如何编写单元测试代码。单独的测试用例是通过子类化创建的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()
If you’re using PyCharm IDE, you can simply press ctrl+shift+F10 to run unittest module. Otherwise you can use command prompt to run this module. For example, we named the file for unit-testing as Basic_Test.py
. So the command to run python unittest will be: $python3.6 -m unittest Basic_Test.Testing
If you want to see the verbose, then the command will be; $python3.6 -m unittest -v Basic_Test.Testing
By using the PyCharm, we get the below output.
该单元测试有 3 种可能的结果。下面提到了它们:
-
OK:如果所有测试用例均通过,则输出显示 OK。
-
Failure:如果任何测试用例失败并引发 AssertionError 异常
-
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) |
现在是时候为我们的源类编写单元测试了Person
。在这个类中我们实现了两个函数 -get_name()
and 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
and test_1_get_name
.
Below images show the output produced by our unit test program - both in normal mode and in verbose mode.
$ 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 单元测试教程的全部内容。要了解更多信息,请阅读官方文档。如有任何进一步疑问,请使用评论框。 :)