当前位置: 首页 > 后端技术 > Python

实际项目中如何使用pytest进行单元测试(结合PyCharm)

时间:2023-03-26 18:23:40 Python

使用pytest进行单元测试(结合PyCharm)网上介绍pytest的文章很多,但是很少结合实际开发,大多是简单的演示。下面结合实际项目介绍如何使用。主要内容创建普通项目添加pytest依赖创建测试目录执行测试结合PyCharm引用创建普通项目创建项目根目录“pytest-demo”添加项目文件,目录结构如下pytest-demodemo\_\_init\_\_.pyutils\_\_init\_\_.pymath_helper.pymath_helper.py如下classMathHelper(object):defaddition(self,first,second):"""addition:paramfirst:firstparameter:paramsecond:secondParameters:return:添加后的结果"""#先判断传入的类型ifnotisinstance(first,(int,float)):raiseValueError("firstparametermustbeavalue")ifnotisinstance(second,(int,float)):raiseValueError("secondparametermustbeavalue")#returnresultreturnfirst+second添加pytest依赖$pipinstallpytestaddunittestdirectorycreateunittestdirectory"tests"undertherootdirectory(注意必须创建成package,方便全面测试)对应adding测试类,测试类文件名必须是test_.py或者_test.py,命名规则可以参考pytest官方文档最终目录结构如下pytest-demodemo\_\_init\_\_.pyutils\_\_init\_\_.pymath_helper.pytestsdemo\_\_init\_\_.pyutils\_\_init\_\_.pytest_math_helper.pytest_math_helper.pyimportpytestfromdemo.utils.math_helperimportMathHelperdeftest_addition():#初始化helper=MathHelper()#输入错误类型,预期会收到ValueError错误withpytest.raises(ValueError):helper.addition("1",2)withpytest.raises(ValueError):helper.addition(1,"2")#正确调用result=helper.addition(1,2)#使用assert判断结果assertresult==3执行测试用例$pytest可以执行所有测试并给出结果结合PyCharm设置默认的测试类型PyCharm打开文件>设置>工具>Python集成工具>测试>默认测试运行器修改下拉框为“pytest”右键单元测试文件,点击“运行”执行测试,出现“运行”窗口下面也有相应的测试结果设置,执行所有测试,右击“tests”文件夹,选择“运行”,然后直接运行该目录下的所有测试用例。在下面的“运行”窗口中可以看到测试信息。如果报错找不到模块,需要打开右上角编辑启动项,先删除旧信息,否则会有缓存参考pytest官方文档