Pytest之测试命名规则的使用示例

  介绍

这篇文章主要介绍Pytest之测试命名规则的使用示例,文中介绍的非常详细,具有一定的参考价值,感兴趣的小伙伴们一定要看完!

背景:

Pytest以特定规则搜索测试用例,所以测试用例文件,测试类以及类中的方法,测试函数这些命名都必须符合规则,才能被Pytest搜索到并加入测试运行队列中。

默认搜索规则:

<李>

如果Pytest命令行有指定目录,则从该目录中开始查找测试用例文件,如果没有指定,则从当前运行目录开始查找文件。注意,该查找是递归查找,子目录中的文件也会被查找到。

<李>

并不是能够查找到目录下的所有文件,只有符合命名规则的文件才会被查找。默认规则是以test_开头或者以_t结尾的。py文件。

<李>

在测试文件中查找测试开头的类,以及类中以test_开头的方法,查找测试文件中test_开头的函数。

测试用例默认命名规则

<李>

除非pytest命令指定到测试用例文件,否则测试用例文件命名应该以test_开头或者以_t结尾。

<李>

测试函数命名,测试类的方法命名应该以test_开头。

<李>

测试类命名应当以测试开头。

提示:测试类的不应该有构造函数。

笔者习惯装测试用例的文件夹,测试用例文件,测试函数,类中的测试方法都以test_开头。建议保持一种统一的风格。

示例:

#, func.py   def 添加(a, b):   return  a + b      #,。/test_case/test_func.py   import  pytest   得到func  import  *      class  TestFunc:      ,# def  __init__(自我):   # self.a 才能=1      ,def  test_add_by_class(自我):   assert 才能添加(2、3),==5         def  test_add_by_func ():   ,assert 添加(4、6),==10      & # 39;& # 39;& # 39;   #,stdout:=============================,test  session  starts =============================platform  win32 ——, Python  3.7.0,, pytest-5.3.4,, py-1.8.1, pluggy-0.13.1   rootdir: D: \ Python3.7 \ \ pytest项目   插件:allure-pytest-2.8.9, rerunfailures - 8.0   collected  2,物品      test_case \ test_func.py  . .,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,, (100%)==============================,2,passed  0.04 s 拷贝==============================1.3 s] [Finished 拷贝;   ######################################################################   & # 39;& # 39;& # 39;

测试结果中,test_case \ test_func。py…。两个点号代表两个测试用例。

错误示范,当测试类有构造函数时:

#, func.py   def 添加(a, b):   return  a + b      #,。/test_case/test_func.py   import  pytest   得到func  import  *      class  TestFunc:      自我,def  __init__ ():   self.a 才能=1      ,def  test_add_by_class(自我):   assert 才能添加(2、3),==5         def  test_add_by_func ():   ,assert 添加(4、6),==10      & # 39;& # 39;& # 39;   #,stdout:=============================,test  session  starts =============================platform  win32 ——, Python  3.7.0,, pytest-5.3.4,, py-1.8.1, pluggy-0.13.1   rootdir: D: \ Python3.7 \ \ pytest项目   插件:allure-pytest-2.8.9, rerunfailures - 8.0   collected  1项      test_case \ test_func.py 又是;,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,(100%)==============================,warnings  summary ===============================test_case \ test_func.py: 4   项目,,D: \ Python3.7 \ \ pytest \ test_case \ test_func.py: 4:, PytestCollectionWarning:, cannot  collect  test  class  & # 39; TestFunc& # 39;, because  it  has  a  __init__  constructor  (:, test_case/test_func.py)   ,,,class  TestFunc:      ——,文档:https://docs.pytest.org/en/latest/warnings.html========================,1,,,1,warning  0.04 s 拷贝=========================1.4 s] [Finished 拷贝;   ######################################################################   & # 39;& # 39;& # 39;

会报错,pytest只能找到test_开头的函数,但是不能找开到测试头的含有构造函数的测试类。

自定义测试用例命名规则

如果因为某种需要,需要使用其他命名规则命名的测试文件,测试函数,测试类以及测试类的方法,可以通过pytest.ini配置文件做到。

Pytest之测试命名规则的使用示例