如何在python中配置pytest框架

  

今天就跟大家聊聊有关如何在python中配置pytest框架,可能很多人都不太了解,为了让大家更加了解,小编给大家总结了以下内容,希望大家根据这篇文章可以有所收获。

pytest执行用例命令行参数

--collect-only:罗列出所有当前目录下所有的测试模块,测试类及测试函数

如何在python中配置pytest框架

--tb=style:屏蔽测试用例执行输出的回溯信息,可以简化用例失败时的输出信息。style可以是 alt="如何在python中配置pytest框架">

--lf:当一次用例执行完成后,如果其中存在失败的测试用例,那么我们可以使用此命令重新运行失败的测试用例

我们第一次执行用例,会看到有2个用例失败

如何在python中配置pytest框架

我们使用--lf参数再次运行用例,可以发现只有之前失败的两个用例重新执行了一次

如何在python中配置pytest框架

--ff:如果上次测试用例出现失败的用例,当使用--ff后,失败的测试用例会首先执行,剩余的用例也会再次执行一次

如何在python中配置pytest框架

小结

以上就是命令行运行测试用例时经常使用到的参数,这些参数不仅可以单独使用,也可以组合一起使用,后期还会涉及到使用fixture时的一些命令,现在不需要了解。你可以使用--help来查看一些命令帮助信息!

pytest收集测试用例的规则

1)从一个或者多个目录开始查找,你可以在命令行指定文件或者目录,如果未指定那么从当前目录开始收集用例

2)在该目录和所有子目录下递归查找测试模块

3)测试模块是指文件名为test_*.py或者*_test.py的文件

4)在测试模块中查找以test_开头的函数

5)查找名字以Test开头的类。其中首先筛选掉包含__init__()函数的类,再查找类中以Test_开头的类方法

规则验证

现在我们就依次演示pytest搜索测试用例的过程

首先我们按照以下目录结构新建一个项目

如何在python中配置pytest框架

每个文件编写如下代码(我们只是为了验证规则,所以用例些的很简单,实际项目不会存在这样简单的用例)

test_测试模块1.py

, #,测试函数   ,def  test_2 ():   1,assert ==1   ,#普通函数   ,def  func_2 ():   ,打印(& # 39;普通函数& # 39;),   ,#测试类   ,class  TestClass_2(对象):   #,测试函数   def  test_class_3(自我):   assert  1,==1   #,普通函数   def  func_class_3(自我):   assert  1,==1   #,普通类   class  NoTestClass_2(对象):   #,测试函数   def  test_class_4(自我):   assert  1,==1   ,#普通函数   ,def  func_class_4(自我):   ,assert  1, 1==,

test_测试模块2。py

, #,测试函数,   ,def  test_1 ():   assert  1==1   ,#普通函数   ,def  func_1 ():   ,打印(& # 39;普通函数& # 39;)   #,测试类   class  TestClass_1(对象):   #,测试函数   def  test_class_1(自我):   assert  1==1   #,普通函数   def  func_class_1(自我):   assert  1==1   #,普通类   class  NoTestClass_1(对象):   #,测试函数   def  test_class_2(自我):   assert  1,==1   #,普通函数   def  func_class_2(自我):   assert  1, 1==,

测试用例。py

, #,测试函数   ,def  test_one ():   assert  1==1   ,#普通函数   ,def  func ():   1==1,assert 

<强>代码分析

我们现在根据理论分析并结合代码,可以大致计算出,从项目根目录执行用例,应该会执行4条有效测试用例!

我们在项目根目录下执行pytest——只收集看下情况,可以发现搜索了test_测试模块1和test_测试模块2文件,并包括TestClass_2和TestClass_1类及内部test_class_3和test_class_1和外部的测试函数test_2, test_1。

 D: \ pytest搜索测试用例规则祝辞pytest ——只收集=============================,test  session  starts =============================platform  win32 ——, Python  3.6.4,, pytest-3.8.0,, py-1.6.0, pluggy-0.7.1
  rootdir: D: \ pytest搜索测试用例规则,,inifile:
  collected  4项
  & lt; Package  & # 39; D: \ \ pytest搜索测试用例规则\ \测试用例目录1 & # 39;比;
  & lt; Module  & # 39; test_测试模块1. py # 39;比;
  & lt; Function  & # 39; test_2& # 39;比;
  & lt; Class  & # 39; TestClass_2& # 39;比;
  & lt; Instance  & # 39;() & # 39;比;
  & lt; Function  & # 39; test_class_3& # 39;比;
  & lt; Module  & # 39; test_测试模块2. py # 39;比;
  & lt; Function  & # 39; test_1& # 39;比;
  & lt; Class  & # 39; TestClass_1& # 39;比;
  & lt; Instance  & # 39;() & # 39;比;
  & lt; Function  & # 39; test_class_1& # 39;比;========================,no  tests  ran  0.14,拷贝seconds =========================

如何在python中配置pytest框架