如何使用pytest测试Python类的already_exists方法并关联列表值?
pytest 测试
already_exists 函数指南 核心思路
already_exists 是 control_Centre 类的实例方法,逻辑完全依赖实例的 storm_list 属性。测试时只需创建 control_Centre 实例,给 storm_list 填充不同的 Storm 对象,再调用方法验证返回值是否符合预期即可。
测试场景与代码示例
先确保导入必要的模块和类:
from abc import ABC import pytest # 假设你的业务代码保存在 storm.py 文件中,从这里导入类 from storm import Storm, control_Centre
1. 空列表场景
当 storm_list 为空时,任何名字都应返回 False:
def test_already_exists_empty_list(): centre = control_Centre() assert centre.already_exists("Katrina") is False assert centre.already_exists("") is False
2. 列表中存在目标风暴
给 storm_list 添加指定名字的 Storm,调用方法应返回 True:
def test_already_exists_storm_present(): centre = control_Centre() centre.storm_list.append(Storm("Harvey", 120)) assert centre.already_exists("Harvey") is True
3. 列表中不存在目标风暴
列表中有其他风暴,但没有目标名字,应返回 False:
def test_already_exists_storm_not_present(): centre = control_Centre() centre.storm_list.append(Storm("Irma", 150)) assert centre.already_exists("Maria") is False
4. 多风暴列表匹配场景
列表中有多个风暴,只要其中一个匹配就返回 True:
def test_already_exists_multiple_storms(): centre = control_Centre() centre.storm_list.extend([ Storm("Andrew", 175), Storm("Sandy", 110), Storm("Ian", 155) ]) assert centre.already_exists("Sandy") is True assert centre.already_exists("Florence") is False
运行测试
直接在终端执行命令:
pytest test_storm.py -v
内容的提问来源于stack exchange,提问作者Reina297
相关产品推荐
相关产品推荐

