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

pytest使用ABC

时间:2023-03-25 21:15:36 Python

什么是pytest?pytest是一个python单元测试框架。可用于为函数、类等编写单元测试文件。快速安装:pipinstallpytest#test_sample.pydefinc(x)的内容:returnx+1deftest_answer():assertinc(3)==5执行:$pytestresult:============================测试会话开始===============================平台linux--Python3.x.y,pytest-7.x.y,pluggy-1.x.yrootdir:/home/sweet/projectcollected1itemtest_sample.pyF[100%]===================================失败====================================____________________________________________________________________________________________________deftest_answer():>assertinc(3)==5Eassert4==5E+其中4=inc(3)test_sample.py:6:AssertionError==========================简短测试摘要信息=============================FAILEDtest_sample.py::test_answer-断言4==5==============================1failedin0.12s==============================注意:测试文件和测试函数都要以test_开头。常见问题1。如何只测试一部分功能?两种方法:方法一:使用pytest.mark通过mark标记所有的函数,然后在运行test命令的时候指定运行哪些。#test_with_mark.py@pytest.mark.finisheddeftest_func1():assert1==1@pytest.mark.unfinisheddeftest_func2():assert1!=1Run:$pytest-mfinishedtests/test_with_mark.py为了unit仅测试标记为已完成的功能。方法二(推荐):使用pytest.mark.skip在不想做测试的函数上使用pytest.mark.skip标记跳过测试。#test_skip.py@pytest.mark.skip(reason='out-of-dateapi')deftest_connect():passrun:$pytesttests/test_skip.pyPytest也支持使用pytest.mark.skipif指定测试函数要忽略的条件。@pytest.mark.skipif(conn.__version__<'0.2.0',reason='不支持直到v0.2.0')deftest_api():pass2。如何给测试函数批量传参?案例一:传递一个参数#test_parametrize.py@pytest.mark.parametrize('passwd',['123456','abcdefdfs','as52345fasdf4'])deftest_passwd_length(passwd):assertlen(passwd)>=8cases2:传递多个参数):db={'jack':'e8dc4081b13434b45189a720b77b6818','tom':'1702a132e769a623c1adb78353fc9503'}importhashlibasserthashlib.md5(passwd.encode()).hexdigest(:$pytest-vtests/test-function.test_parametrizepy::test_passwd_md53.如果函数使用数据库,如何处理数据库的连接和关闭?数据库的连接和关闭可以在固件中处理。#test_db.py@pytest.fixture()defdb():print('连接成功')yieldprint('连接关闭')defsearch_user(user_id):d={'001':'xiaoming'}returnd[user_id]deftest_search(db):assertsearch_user('001')=='xiaoming'如果您想更详细地跟踪固件执行情况,可以使用--setup-show选项$pytest--setup-showtests/夹具/测试数据库。py