pytest学习笔记(pytest框架结构)

一.pytest框架中使用setup、teardown、更灵活按照用例级别可以分为以下几类:

1.模块级:(setup_module、teardown_module)在模块始末调用

2.函数级:(setup_function、teardown_function)在函数始末调用 在类外部

3.类级:(setup_class、teardown_class)在类始末调用 在类中

4.方法级:(setup_method、teardown_method)在方法始末调用 在类中

5.方法级:(setup、teardown)在方法始末调用 在类中

二.调用顺序

setup_module>setup_class>setup_method>setup>teardown>teardown_method>teardown_class>teardown_module

三.实例

#!/usr/bin/env python
# _*_coding: utf-8 _*_

def setup_module():
    print("
setup_module, 只执行一次,当有多个测试类的时候使用")


def teardown_module():
    print("
teardown_module, 只执行一次,当有多个测试类的时候使用")


class TestPytest1(object):

    @classmethod
    def setup_class(cls):
        print("
setup_class1, 只执行一次")

    @classmethod
    def teardown_class(cls):
        print("
teardown_class1,只执行一次")

    def setup_method(self):
        print("
setup_method, 每个测试方法执行一次")

    def teardown_method(self):
        print("
teardown_method, 每个测试方法执行一次")

    def test_three(self):
        print("test_three, 测试用例")

    def test_four(self):
        print("test_four, 测试用例")


class TestPytest2(object):

    @classmethod
    def setup_class(cls):
        print("
setup_class2, 只执行一次")

    @classmethod
    def teardown_class(cls):
        print("
teardown_class2,只执行一次")

    def setup_method(self):
        print("
setup_method2, 每个测试方法执行一次")

    def teardown_method(self):
        print("
teardown_method2, 每个测试方法执行一次")

    def test_one(self):
        print("test_one, 测试用例")

    def test_two(self):
        print("test_two, 测试用例")

四.执行结果

 

Testing started at 15:06 ...
C:Pythonpython.exe "C:Program FilesJetBrainsPyCharm Community Edition 2019.1helperspycharm\_jb_pytest_runner.py" --path C:/Users/wanwen/PycharmProjects/vigo/xuexi/20210123/test_run_setup.py
Launching pytest with arguments C:/Users/wanwen/PycharmProjects/vigo/xuexi/20210123/test_run_setup.py in C:UserswanwenPycharmProjectsvigoxuexi20210123
============================= test session starts =============================
platform win32 -- Python 3.8.0, pytest-5.4.3, py-1.9.0, pluggy-0.13.1
rootdir: C:UserswanwenPycharmProjectsvigoxuexi20210123
plugins: html-2.1.1, metadata-1.11.0collected 4 items

test_run_setup.py
setup_module, 只执行一次,当有多个测试类的时候使用

setup_class1, 只执行一次

setup_method, 每个测试方法执行一次
.test_three, 测试用例

teardown_method, 每个测试方法执行一次

setup_method, 每个测试方法执行一次
.test_four, 测试用例

teardown_method, 每个测试方法执行一次

teardown_class1,只执行一次

setup_class2, 只执行一次

setup_method2, 每个测试方法执行一次
.test_one, 测试用例

teardown_method2, 每个测试方法执行一次

setup_method2, 每个测试方法执行一次
.test_two, 测试用例

teardown_method2, 每个测试方法执行一次

teardown_class2,只执行一次

teardown_module, 只执行一次,当有多个测试类的时候使用
[100%]

============================== 4 passed in 0.04s ==============================

Process finished with exit code 0

原文地址:https://www.cnblogs.com/vigo01/p/14321011.html