使用Python模块中unittest工具来测试代码
测试函数
city_functions.py
def strcat_city_country(cityname,countryname):
namecat = cityname + ', '+countryname
return namecat
import unittest
from city_functions import strcat_city_country
class NameTestCase(unittest.TestCase):#继承了unittest.TestCase类
'测试city_functions.py'
def test_two_name(self):
formatted_name = strcat_city_country('Santiago','Chile')
self.assertEqual(formatted_name,'Santiago, Chile')
if __name__== '__main__':
#上面这行书中没有,导致报错AttributeError: module '__main__' has no attribute 'test_name_function'
unittest.main()
注:必须加上if name== ‘main’:
运行结果如下:
成功
============================= test session starts =============================
platform win32 -- Python 3.6.3, pytest-3.2.1, py-1.4.34, pluggy-0.4.0
rootdir: \资源, inifile:
collected 1 item
ex11.py .
========================== 1 passed in 0.01 seconds ===========================
Process finished with exit code 0
错误 把self.assertEqual(formatted_name,‘Santiago, Chile’)内字符串进行更改
============================= test session starts =============================
platform win32 -- Python 3.6.3, pytest-3.2.1, py-1.4.34, pluggy-0.4.0
rootdir: D:\code\python code\PythonCrashCourse\资源, inifile:
collected 1 item
ex11.py F
ex11.py:6 (NameTestCase.test_two_name)
Santidago, Chaile,e != Santiago, Chile
Expected :Santiago, Chile
Actual :Santidago, Chaile,e
<Click to see difference>
self = <ex11.NameTestCase testMethod=test_two_name>, first = 'Santiago, Chile'
second = 'Santidago, Chaile,e', msg = None
def _patched_equals(self, first, second, msg=None):
try:
> old(self, first, second, msg)
D:\Program Files\JetBrains\PyCharm 2017.3.1\helpers\pycharm\teamcity\diff_tools.py:31:
================================== FAILURES ===================================
_________________________ NameTestCase.test_two_name __________________________
更新11-1 11-2 编写函数 接受3个形参:城市名、国家名、人口(可选)
city_functions.py
def strcat_city_country(cityname,countryname,population=''):
namecat = cityname.title() + ', '+countryname.title() +' - population '+str(population)
return namecat
import unittest
from city_functions import strcat_city_country
class NameTestCase(unittest.TestCase):
'测试city_functions.py'
def test_two_name(self):
formatted_name = strcat_city_country('santiago','chile')
self.assertEqual(formatted_name,'Santiago, Chile - population ')
def test_city_country_population(self):
formatted_name = strcat_city_country('santiago', 'chile',population=5000000)
self.assertEqual(formatted_name, 'Santiago, Chile - population 5000000')
if __name__== '__main__':
unittest.main()
均通过
============================= test session starts =============================
platform win32 -- Python 3.6.3, pytest-3.2.1, py-1.4.34, pluggy-0.4.0
rootdir: D:\code\python code\PythonCrashCourse\资源, inifile:
collected 2 items
ex11.py ..
========================== 2 passed in 0.00 seconds ===========================
Process finished with exit code 0
测试类
大同小异,下面是一个类
class AnonymousSurvey():
"""Collect anonymous answers to a survey question."""
def __init__(self, question):
"""Store a question, and prepare to store responses."""
self.question = question
self.responses = []
def show_question(self):
"""Show the survey question."""
print(self.question)
def store_response(self, new_response):
"""Store a single response to the survey."""
self.responses.append(new_response)
def show_results(self):
"""Show all the responses that have been given."""
print("Survey results:")
for response in self.responses:
print('- ' + response)
该类首先存储了一个你指定的调查问题,并创建了一个空表用于存储答案,包含几个方法:打印调查问题的方法、答案列表中添加新答案的方法、将存储在列表中答案都打印出来的方法。
利用setUp()方法(unittest.TestCase类中)创建类的实例(对象),后面可以在每个测试方法中使用,这样每个测试方法中都可使用在方法setUp()中创建的对象了。
栗子:
import unittest
from survey import AnonymousSurvey
class TestAnonymousSurvey(unittest.TestCase):
"""Tests for the class AnonymousSurvey."""
def setUp(self):
"""
Create a survey and a set of responses for use in all test methods.
"""
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):
"""Test that a single response is stored properly."""
self.my_survey.store_response(self.responses[0])
self.assertIn(self.responses[0], self.my_survey.responses)
def test_store_three_responses(self):
"""Test that three individual responses are stored properly."""
for response in self.responses:
self.my_survey.store_response(response)
for response in self.responses:
self.assertIn(response, self.my_survey.responses)
if __name__== '__main__':
unittest.main()
============================= test session starts =============================
platform win32 -- Python 3.6.3, pytest-3.2.1, py-1.4.34, pluggy-0.4.0
rootdir: D:\code\python code\PythonCrashCourse\资源\chapter_11, inifile:
collected 2 items
test_survey.py ..
========================== 2 passed in 0.01 seconds ==========================
.表示测试通过 E表示测试引发错误 F表示测试导致断言失败