自动化收藏

pytest之框架结构及运行方式

2021-12-11  本文已影响0人  每天进步一点点变成更好的自己

pytest的框架的测试结构相对unittest来说,更加灵活。比如从文件开始,各种前置、后置条件。

1.pytest setup和pytest teardown简介

模块级:setup_module和teardown_module(开始于模块始末,全局的)
函数级:setup_function和teardown_function(只对函数用例生效(不在类中))、
类级:setup_class和teardown_class(只在类中前后运行一次(在类中))
方法级:setup_method和teardown_method(开始于方法始末(在类中))
类里面的(setup/teardown)运行在调用方法的前后


image.png

举例

import pytest

def setup_module():
    print('整个模块.py 开始')

def teardown_module():
    print('整个模块.py 结束')


def setup_function():
    print('不在类中的函数前')

def teardown_function():
    print('不在类中的函数后')
def test_function1():
    print('不在类中的函数1')
def test_function2():
    print('不在类中的函数2')

class TestXase:
    def setup_method(self):
        print('我是方法1和2开始执行')
    def teardown_method(self):
        print('我是方法1和2结束执行')
    def setup_class(self):
        print('我是类开始执行')
    def teardown_class(self):
        print('我是类结束执行')

    def test_method1(self):
        print('我是方法1')
    def test_method2(self):
        print('我是方法2')


if __name__ == '__main__':
    pytest.main(['-s','-v','test7.py'])

返回结果显示如下:

test7.py::test_function1 整个模块.py 开始
不在类中的函数前
不在类中的函数1
PASSED不在类中的函数后

test7.py::test_function2 不在类中的函数前
不在类中的函数2
PASSED不在类中的函数后

test7.py::TestXase::test_method1 我是类开始执行
我是方法1和2开始执行
我是方法1
PASSED我是方法1和2结束执行

test7.py::TestXase::test_method2 我是方法1和2开始执行
我是方法2
PASSED我是方法1和2结束执行
我是类结束执行
整个模块.py 结束

============================== 4 passed in 0.02s ==============================

2.pytest运行方式

执行测试的方式有3种,平时我们用得比较多的方式就是main()方法的方式,其次就是命令行的方式。
1、main()方法:pytest.main(['-v','-s','test01.py']) ,如上述例子中显示。
2、命令行:pytest -s -v test.py,在命令行中,找到对应的目录。
3、调整pycharm中的值:Tools->Python Integrated tools -> Default test runner

pytest的执行原则注意事项:
1.pytest将在当前目录及其子目录中运行test_.py或test.py形式的所有文件。
2.以test
开头的函数 ,以Test开头的类,以test_开头的方法,所有package都要有init_.py文件。
3.pytest可以执行unittest框架写的用例和方法。

上一篇下一篇

猜你喜欢

热点阅读