pytest应用基础

pytest环境部署

python环境安装成功后
pip install pytest

pytest命令

  • pytest默认寻找当前路径下所有的文件与子文件夹中以test开头的文件夹、文件、函数作为识别对象。
  • pytest默认不输出任何打印信息,如果要有打印信息,需要在运行时加-s的指令,多条指令同运行时,在main函数中,通过,进行分割。
    -s 打印信息
    -v 用于详细显示日志信息
    -rA 测试结果简单统计
    -m 分类执行
if __name__=='__main__':
    pytest.main(['-s','-v'])

预置函数(用于前期的数据准备)

  • 一般可以通过一个配置文件进行管理:配置文件命名一定要是conftest.py,不能是其他的。
  • scope参数定义了4种等级
    session:在本次session级别中只执行一次。
    module:在模块级别中只执行一次。
    class:在类级别中只执行一次。
    function:在函数级别中执行一次。
    默认等级是function

conftest.py(配置文件的文件名)

@pytest.fixture(scope='calss')
def A():

测试函数传参A
测试函数
def test_case(A)

前置与后置条件

函数级别的前置条件和后置条件
def setup_function():
    print('前置条件')
def teardown_function():
    print('后置条件')
模块级别的前置条件和后置条件
def setup_module():
    print('模块前置条件')
def teardown_module():
    print('模块后置条件')

pytest中calss对象的定义:建议以test开头

class TestDemo:
    def test_d1(self):
        print('执行类的函数1')
    def test_d2(self):
        print('执行类的函数2')
    def setup(self):
        print('类内函数前置条件')
    def teardown(self):
        print('类内函数后置条件')
    def setup_class(self):
        print('类内class级别前置条件')
    def teardown_class(self):
        print('类内class级别后置条件')
    def setup_method(self):
        print('类内method级别前置条件')
    def teardown_method(self):
        print('类内method级别后置条件')

在class中前置后置函数的运行顺序等级:
setup class
setup method
setup
teardowm
teardown method
teardown class

测试用例管理手段Mark

可以通过mark装饰器对所有的用例进行标记,不同的标记区分进行管理

@pytest.mark.标签名(英文)
测试用例代码

执行命令
pytest -s   test_case.py -m 标签名

运行多个标签的测试用例
pytest -m "p1 or p2" 运行有p1标签或者p2标签的用例
pytest -m "p1 and p2" 运行有p1标签并且有p2标签的用例
pytest -m "not p2" 运行有除了p2标签以外的用例
pytest -m "p1 and not p2" 运行有p1标签并且没有p2标签的用例

注意-m命令后面不能带’ ‘号(单引号),只能带” “号(双引号),不然识别不了。

pytest框架下的核心配置文件

配置在工程的根路径下,可以全局生效,文件名pytest.ini,可以定义各种pytest的运行规则。
仅使用@pytest.mark.标签名,会有warning提示,加上配置文件,可以消除warning提示。

[pytest]
#声明定义标签名
markers =
    webui : automation for webui
    interface : automation for information
    temp : just for fun

#定义读取识别对象的文件名规范,多个文件名之间空格隔开
python_files = cema*.py test*.py

#定义读取识别类(class对象)的命名规范
python_classes = cema*

#制定一个特定的路径去运行
testpaths = test_demo

#定义读取函数的指定名称
python_functions = vip*

#运行时增加的默认指令
addopts = -s -v --html =./report/report.html --self-contained-html

断言机制:assert

assert 条件语句 ,’报错信息’

测试报告

#html报告命令
--html =./report/report.html --self-contained-html

#html后面都有一个空格,上面命令中有两处
#终端命令,命令后面加--self***一串命令为将报告内容和html格式合为一个文件,不加的话,还会有一个html格式文件
pytest --html =./report/report.html --self-contained-html

Original: https://blog.csdn.net/weixin_46960820/article/details/118859525
Author: 此人已懒死
Title: pytest应用基础

原创文章受到原创版权保护。转载请注明出处:https://www.johngo689.com/775682/

转载文章受原作者版权保护。转载请注明原作者出处!

(0)

大家都在看

亲爱的 Coder【最近整理,可免费获取】👉 最新必读书单  | 👏 面试题下载  | 🌎 免费的AI知识星球