一、测试一个函数
被测试函数:
D:\workon\yize365\python_work\unit11\test11_1\city_functions.py
#易择365
def city_country(city,country,population=""):
if population:
res=city+","+country+" - population "+str(population)
else:
res=city+","+country
return res
测试模块:
D:\workon\yize365\python_work\unit11\test11_1\test_cities.py
#易择365
from city_functions import city_country
def test_city_country():
res=city_country(city="santiago",country="chile")
assert res=="santiago,chile"
def test_city_country_population():
res=city_country(city="santiago",country="chile",population=2000)
assert res=="santiago,chile - population 2000"
二、测试一个类
D:\workon\yize365\python_work\unit11\test11_3_2\survey.py
#易择365
class AnonymousSurvey:
"""收集匿名调查问卷的答案"""
def __init__(self, question):
"""存储一个问题,并为存储答案做准备"""
self.question = question
self.responses = []
def show_question(self):
"""显示调查问卷"""
print(self.question)
def store_response(self, new_response):
"""存储单份调查答卷"""
self.responses.append(new_response)
def show_results(self):
"""显示收集到的所有答卷"""
print("Survey results:")
for response in self.responses:
print(f"- {response}")
D:\workon\yize365\python_work\unit11\test11_3_2\test_survey.py
#易择365
import pytest
from survey import AnonymousSurvey
def test_store_single_response():
"""测试单个答案会被妥善地存储"""
question = "What language did you first learn to speak?"
language_survey=AnonymousSurvey(question)
language_survey.store_response('English')
assert 'English' in language_survey.responses
def test_store_three_responses():
"""测试三个答案会被妥善地存储"""
question = "What language did you first learn to speak?"
language_survey = AnonymousSurvey(question)
responses = ['English', 'Spanish', 'Mandarin']
for response in responses:
language_survey.store_response(response)
for response in responses:
assert response in language_survey.responses
三、修改test_survey.py模块,
使用夹具(fixture):
D:\workon\yize365\python_work\unit11\test11_3_2\test_survey.py
#易择365
import pytest
from survey import AnonymousSurvey
@pytest.fixture
def language_survey():
"""一个可供所有测试函数使用的 AnonymousSurvey 实例"""
question = "What language did you first learn to speak?"
language_survey = AnonymousSurvey(question)
return language_survey
def test_store_single_response(language_survey):
"""测试单个答案会被妥善地存储"""
language_survey.store_response('English')
assert 'English' in language_survey.responses
def test_store_three_responses(language_survey):
"""测试三个答案会被妥善地存储"""
responses = ['English', 'Spanish', 'Mandarin']
for response in responses:
language_survey.store_response(response)
for response in responses:
assert response in language_survey.responses