python单元测试模块

Posted chqworkhome

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了python单元测试模块相关的知识,希望对你有一定的参考价值。

1、函数测试
import unittest
from name_function import get_formatted_name
class NamesTestCase(unittest.TestCase):
"""测试name_function.py"""
def test_first_last_name(self):
"""能够正确地处理像Janis Joplin这样的姓名吗? """
formatted_name = get_formatted_name(‘janis‘, ‘joplin‘)
self.assertEqual(formatted_name, ‘Janis Joplin‘)
 
unittest.main()
 
2、断言
assertEqual(a, b) 核实a == b
assertNotEqual(a, b) 核实a != b
assertTrue(x) 核实x 为True
assertFalse(x) 核实x 为False
assertIn(item , list ) 核实 item 在 list 中
assertNotIn(item , list ) 核实 item 不在 list 中
 
 
3、类测试
import unittest
from survey import AnonymousSurvey
class TestAnonymousSurvey(unittest.TestCase):
"""针对AnonymousSurvey类的测试"""
def test_store_single_response(self):
"""测试单个答案会被妥善地存储"""
--snip--
def test_store_three_responses(self):
"""测试三个答案会被妥善地存储"""
question = "What language did you first learn to speak?"
my_survey = AnonymousSurvey(question)
responses = [‘English‘, ‘Spanish‘, ‘Mandarin‘]
for response in responses:
my_survey.store_response(response)
for response in responses:
self.assertIn(response, my_survey.responses)
 
unittest.main()
 
4、setup创建实例
import unittest
from survey import AnonymousSurvey
class TestAnonymousSurvey(unittest.TestCase):
"""针对AnonymousSurvey类的测试"""
def setUp(self):
"""
创建一个调查对象和一组答案, 供使用的测试方法使用
"""
question = "What language did you first learn to speak?"
self.my_survey = AnonymousSurvey(question)
self.responses = [‘English‘, ‘Spanish‘, ‘Mandarin‘]
def test_store_single_response(self):
"""测试单个答案会被妥善地存储"""
self.my_survey.store_response(self.responses[0])
self.assertIn(self.responses[0], self.my_survey.responses)
def test_store_three_responses(self):
"""测试三个答案会被妥善地存储"""
for response in self.responses:
self.my_survey.store_response(response)
for response in self.responses:
self.assertIn(response, self.my_survey.responses)
unittest.main()

以上是关于python单元测试模块的主要内容,如果未能解决你的问题,请参考以下文章

Python单元测试找不到模块[重复]

Python单元测试--unittest

python单元测试之unittest

多个模块的 Python 单元测试覆盖率

python中的单元测试模块unittest

python单元测试框架unittest