2026/3/20 1:26:34
网站建设
项目流程
咔咔做受视频网站,fireworks个人网站模板,html网站设计实例代码,东莞网站建设aj博客Pytest和Unittest测试框架的区别#xff1f;
如何区分这两者#xff0c;很简单unittest作为官方的测试框架#xff0c;在测试方面更加基础#xff0c;并且可以再次基础上进行二次开发#xff0c;同时在用法上格式会更加复杂#xff1b;而pytest框架作为第三方框架#…Pytest和Unittest测试框架的区别如何区分这两者很简单unittest作为官方的测试框架在测试方面更加基础并且可以再次基础上进行二次开发同时在用法上格式会更加复杂而pytest框架作为第三方框架方便的地方就在于使用更加灵活并且能够对原有unittest风格的测试用例有很好的兼容性同时在扩展上更加丰富可通过扩展的插件增加使用的场景比如一些并发测试等Pytest 安装pip安装1pip install pytest测试安装成功123pytest--helppy.test--help检查安装版本1pytest--versionPytest 示例Pytest编写规则:测试文件以test_开头以_test为结尾测试的类以Test开头测试的方法以test_开头断言使用基本的asserttest_example.py123456defcount_num(a:list)-int:returnlen(a)deftest_count():assertcount_num([1,2,3]) !3执行测试1pytest test_example.py执行结果C:\Users\libuliduobuqiuqiu\Desktop\GitProjects\PythonDemo\pytestpytest test_example.py -v test session starts platform win32 -- Python 3.6.8, pytest-6.2.5, py-1.10.0, pluggy-1.0.0 -- d:\coding\python3.6\python.execachedir: .pytest_cacherootdir: C:\Users\libuliduobuqiuqiu\Desktop\GitProjects\PythonDemo\pytestplugins: Faker-8.11.0collected 1 itemtest_example.py::test_count FAILED [100%] FAILURES _____________________________________________________________________ test_count ______________________________________________________________________def test_count(): assert count_num([1, 2, 3]) ! 3E assert 3 ! 3E where 3 count_num([1, 2, 3])test_example.py:11: AssertionError short test summary info FAILED test_example.py::test_count - assert 3 ! 3 1 failed in 0.16s 备注.代表测试通过F代表测试失败-v显示详细的测试信息 -h显示pytest命令详细的帮助信息标记默认情况下pytest会在当前目录下寻找以test_为开头以_test结尾的测试文件并且执行文件内所有以test_为开头以_test为结尾的所有函数和方法指定运行测试用例可以通过::显示标记文件名::类名::方法名文件名::函数名1pytest test_example3.py::test_odd指定一些测试用例测试运行可以使用-k模糊匹配1pytest-k example通过pytest.mark.skip()或者pytest.makr.skipif()条件表达式跳过指定的测试用例1234567891011121314importpytesttest_flagFalsepytest.mark.skip()deftest_odd():numrandom.randint(0,100)assertnum%21pytest.mark.skipif(test_flagisFalse, reasontest_flag is False)deftest_even():numrandom.randint(0,1000)assertnum%20通过pytest.raises()捕获测试用例可能抛出的异常1234567deftest_zero():num0with pytest.raises(ZeroDivisionError) as e:num1/0exc_msge.value.args[0]print(exc_msg)assertnum0预先知道测试用例会失败但是不想跳过需要显示提示信息使用pytest.mark.xfail()12345pytest.mark.xfail()deftest_sum():random_list[random.randint(0,100)forxinrange(10)]numsum(random_list)assertnum 20对测试用例进行多组数据测试每组参数都能够独立执行一次可以避免测试用例内部执行单组数据测试不通过后停止测试1234pytest.mark.parametrize(num,num2, [(1,2),(3,4)])deftest_many_odd(num:int, num2:int):assertnum%21assertnum2%20固件Fixture)固件就是一些预处理的函数pytest会在执行测试函数前或者执行后加载运行这些固件常见的应用场景就有数据库的连接和关闭设备连接和关闭简单使用12345678importpytestpytest.fixture()defpostcode():returnhellodeftest_count(postcode):assertpostcodehello按照官方的解释就是当运行测试函数会首先检测运行函数的参数搜索与参数同名的fixture一旦pytest找到就会运行这些固件获取这些固件的返回值如果有并将这些返回值作为参数传递给测试函数预处理和后处理接下来进一步验证关于官方的说法123456789101112131415161718importpytestpytest.fixture()defconnect_db():print(Connect Database in .......)yieldprint(Close Database out .......)defread_database(key:str):p_info{name:zhangsan,address:China Guangzhou,age:99}returnp_info[key]deftest_count(connect_db):assertread_database(name)zhangsan执行测试函数结果 test session starts platform win32 -- Python 3.6.8, pytest-6.2.5, py-1.10.0, pluggy-1.0.0 -- D:\Coding\Python3.6\python.execachedir: .pytest_cacherootdir: C:\Users\libuliduobuqiuqiu\Desktop\GitProjects\PythonDemo\pytestplugins: Faker-8.11.0collecting ... collected 1 itemtest_example.py::test_count Connect Database in .......PASSED [100%]Close Database out ....... 1 passed in 0.07s 备注首先从结果上看验证了官方的解释pytest执行测试函数前会寻找同名的固件加载运行connect_db固件中有yield这里pytest默认会判断yield关键词之前的代码属于预处理会在测试前执行yield之后的代码则是属于后处理将在测试后执行作用域从前面大致了解了固件的作用抽离出一些重复的工作方便复用同时pytest框架中为了更加精细化控制固件会使用作用域来进行指定固件的使用范围比如在这一模块中的测试函数执行一次即可不需要模块中的函数重复执行更加具体的例子就是数据库的连接这一连接的操作可能是耗时的我只需要在这一模块的测试函数运行一次即可不需要每次都运行。而定义固件是一般通过scop参数来声明作用常用的有function: 函数级每个测试函数都会执行一次固件class: 类级别每个测试类执行一次所有方法都可以使用module: 模块级每个模块执行一次模块内函数和方法都可使用session: 会话级一次测试只执行一次所有被找到的函数和方法都可用。12345678910111213141516171819importpytestpytest.fixture(scopefunction)deffunc_scope():print(func_scope)pytest.fixture(scopemodule)defmod_scope():print(mod_scope)pytest.fixture(scopesession)defsess_scope():print(session_scope)deftest_scope(sess_scope, mod_scope, func_scope):passdeftest_scope2(sess_scope, mod_scope, func_scope):pass执行结果 test session starts platform win32 -- Python 3.6.8, pytest-6.2.5, py-1.10.0, pluggy-1.0.0 -- D:\Coding\Python3.6\python.execachedir: .pytest_cacherootdir: C:\Users\libuliduobuqiuqiu\Desktop\GitProjects\PythonDemo\pytestplugins: Faker-8.11.0collecting ... collected 2 itemstest_example2.py::test_scope session_scopemod_scopefunc_scopePASSED [ 50%]test_example2.py::test_scope2 func_scopePASSED [100%] 2 passed in 0.07s 从这里可以看出modulesession作用域的固件只执行了一次可以验证官方的使用介绍自动执行有人可能会说这样子怎么那么麻烦unittest框架中直接定义setUp就能自动执行预处理同样的pytest框架也有类似的自动执行 pytest框架中固件一般通过参数autouse控制自动运行。123456789101112131415importpytestpytest.fixture(scopesession, autouseTrue)defconnect_db():print(Connect Database in .......)yieldprint(Close Database out .......)deftest1():print(test1)deftest2():print(test)执行结果 test session starts platform win32 -- Python 3.6.8, pytest-6.2.5, py-1.10.0, pluggy-1.0.0 -- D:\Coding\Python3.6\python.execachedir: .pytest_cacherootdir: C:\Users\libuliduobuqiuqiu\Desktop\GitProjects\PythonDemo\pytestplugins: Faker-8.11.0collecting ... collected 2 itemstest_example.py::test1 Connect Database in .......PASSED [ 50%]test1test_example.py::test2 PASSED [100%]testClose Database out ....... 2 passed in 0.07s 从结果看到测试函数运行前后自动执行了connect_db固件参数化前面简单的提到过了pytest.mark.parametrize通过参数化测试而关于固件传入参数时则需要通过pytest框架中内置的固件request并且通过request.param获取参数1234567891011121314151617181920importpytestpytest.fixture(params[(redis,6379),(elasticsearch,9200)])defparam(request):returnrequest.parampytest.fixture(autouseTrue)defdb(param):print(\nSucceed to connect %s:%s%param)yieldprint(\nSucceed to close %s:%s%param)deftest_api():assert11执行结果 test session starts platform win32 -- Python 3.6.8, pytest-6.2.5, py-1.10.0, pluggy-1.0.0 -- D:\Coding\Python3.6\python.execachedir: .pytest_cacherootdir: C:\Users\libuliduobuqiuqiu\Desktop\GitProjects\PythonDemo\pytestplugins: Faker-8.11.0collecting ... collected 2 itemstest_example.py::test_api[param0]Succeed to connect redis:6379PASSED [ 50%]Succeed to close redis:6379test_example.py::test_api[param1]Succeed to connect elasticsearch:9200PASSED [100%]Succeed to close elasticsearch:9200 2 passed in 0.07s 这里模拟连接redis和elasticsearch加载固件自动执行连接然后执行测试函数再断开连接。总结对于开发来说为什么也要学习自动化测试这一块很重要的一点就是通过自动化测试节省一些重复工作的时间同时对于优化代码结构提高代码覆盖率以及后续项目重构都是有着很重要的意义同时理解pytest和unittest在基础上有何区别有助于不同的业务场景中选择适合自己的测试工具。感谢每一个认真阅读我文章的人作为一位过来人也是希望大家少走一些弯路如果你不想再体验一次学习时找不到资料没人解答问题坚持几天便放弃的感受的话在这里我给大家分享一些自动化测试的学习资源希望能给你前进的路上带来帮助。软件测试面试文档我们学习必然是为了找到高薪的工作下面这些面试题是来自阿里、腾讯、字节等一线互联网大厂最新的面试资料并且有字节大佬给出了权威的解答刷完这一套面试资料相信大家都能找到满意的工作。视频文档获取方式这份文档和视频资料对于想从事【软件测试】的朋友来说应该是最全面最完整的备战仓库这个仓库也陪伴我走过了最艰难的路程希望也能帮助到你以上均可以分享点下方小卡片即可自行领取。