pytest学习Pytest基础

一、Pytest基础

 

Pytest特点:

1.非常容易上手,入门简单,文档丰富,文档中有很多实例可以参考
2.能够支持简单的单元测试和复杂的功能测试
3.支持参数化
4.执行测试过程中可以将某些测试跳过(skip),或者对某些预期失败的case标记成失败
5.支持重复执行(rerun)失败的case
6.支持运行由nose, unittest编写的测试case
7.可生成html报告
8.方便的和持续集成工具jenkins集成
9.可支持执行部分用例
10.具有很多第三方插件,并且可以自定义扩展。

 

Pytest安装

pip install -U pytest

查看版本:pip show pytest/pytest --version

 

举个栗子
例1、

def func(x):

    return x + 1

def test_answer():

    assert func(2) == 5

 例2、

class TestClass:

    def test_one(self):

        x = "three"

        assert 'h' in x

 

    def test_two(self):

        x = "hello"

        assert hasattr(x, 'check')  # hasattr() 函数用于判断对象是否包含对应的属性

 

备注:-s参数是为了显示用例的打印信息。 -q参数只显示结果,不显示过程

 

Pytest用例规则:

1.测试文件以test_开头(以_test结尾也可以)
2.测试类以Test开头,并且不能带有__init__方法
3.测试函数以test_开头
4.断言使用assert
5.所有的包package必须要有__init__.py文件

执行用例规则:

1.执行某个目录下所有的用例
pytest 文件名/
2.执行某一个py文件下用例
pytest 脚本名称.py
3.-k 按关键字匹配
pytest -k "MyClass and not method"
4.按节点运行
pytest test_mod.py::test_func
5.运行.py模块里面,测试类里面的某个方法
pytest test_mod.py::TestClass::test_method
6.标记表达式
pytest -m slow # 将运行用@pytest.mark.slow装饰器的所有测试
7.从包里面运行
pytest --pyargs pkg.testing # 这将导入pkg.testing并使用其文件系统位置来查找和运行测试
8.-x 遇到错误停止测试
pytest -x test_class.py

 

二、测试用例的setup和teardown

  

用例运行级别

模块级(setup_module/teardown_module)开始于模块始末,全局的

函数级(setup_function/teardown_function)只对函数用例生效(不在类中)

类级(setup_class/teardown_class)只在类中前后运行一次(在类中)例子

方法级(setup_method/teardown_method)开始于方法始末(在类中)

类里面的(setup/teardown)运行在调用方法的前后。


举个栗子

例1:

import pytest

class TestCase():

    def setup(self):

        print("setup: 每个用例开始前执行")

    def teardown(self):

        print("teardown: 每个用例结束后执行")

    def setup_class(self):

        print("setup_class:所有用例执行之前")

    def teardown_class(self):

        print("teardown_class:所有用例执行之前")

    def setup_method(self):

        print("setup_method:  每个用例开始前执行")

    def teardown_method(self):

        print("teardown_method:  每个用例结束后执行")

    def test_one(self):

        print("正在执行----test_one")

        x = "hello"

        assert 'h' in x

    def test_two(self):

        print("正在执行----test_two")

        x = "hello"

        assert hasattr(x, 'check')

    def test_three(self):

        print("正在执行----test_three")

        a = "hello"

        b = "hello world"

        assert a in b

if __name__ == "__main__":

    pytest.main(["-s", "test_class.py"])

 
原文地址:https://www.cnblogs.com/wzhqzm/p/13909127.html