Pytest单元测试框架之setup/teardown模块示例操作

"""
模块级(setup_module/teardown_module)开始于模块始末,全局的
函数级(setup_function/teardown_function)只对函数用例生效(不在类中)
类级(setup_class/teardown_class)只在类中用例之前或之后运行一次(在类中)
方法级(setup_method/teardown_method)开始于方法始末(在类中)
类里面的(setup/teardown)运行在调用方法的前后
"""
# setup_module 及 teardown_module模块,代码示例
import pytest

def setup_module():
print("setup_module:整个*.py只执行一次")
print('比如浏览器打开的动作')

def teardown_module():
print("teardown_module:整个*.py只执行一次")
print('比如浏览器关闭的动作')

def test_one():
print("正在执行------test_one")
AA = 'this'
assert 'i' in AA

def test_two():
print("正在执行------test_two")
BB = 'Str'
AA = 'Str'
assert AA == BB

def test_three():
print("正在执行------test_three")
AA = 'one'
assert 'i' != AA

if __name__ == '__main__':
pytest.main()

运行代码结果:

# setup_function及tear_function 函数级模块,代码示例如下:

import pytest
def setup_function():
print("setup_function:每个用例开始前都会执行")

def teardown_function():
print("teardown_function:每个用例结束前都会执行")

def test_one():
print("正在执行------test_one")
AA = 'this'
assert 'i' in AA

def test_two():
print("正在执行------test_two")
BB = 'Str'
AA = 'Str'
assert AA == BB

def test_three():
print("正在执行------test_three")
AA = 'one'
assert 'i' != AA

if __name__ == '__main__':
pytest.main()

# 运行结果如下:

优先级划分: setUp_class  》 setUp_module 》setUp

# 类和方法
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 = "this"
assert 'h' in x

def test_two(self):
print("正在执行----test_two")
x = "hello"
assert 'hello' == x

def test_three(self):
print("正在执行----test_three")
a = "hello"
b = "hello world"
assert a in b

if __name__ == '__main__':
pytest.main()

代码执行结果如下:

先执行函数 --> 方法 --> 再执行class类里面的类方法

#函数和类混合
def setup_module():
print("setup_module:整个.py模块只执行一次")
print("比如:所有用例开始前只打开一次浏览器")

def teardown_module():
print("teardown_module:整个.py模块只执行一次")
print("比如:所有用例结束只最后关闭浏览器")

def setup_function():
print("setup_function:每个用例开始前都会执行")

def teardown_function():
print("teardown_function:每个用例结束前都会执行")

def test_one():
print("正在执行----test_one")
x = "this"
assert 'h' in x

def test_two():
print("正在执行----test_two")
x = "hello"
assert x != 'check'

class TestCase():

def setup_class(self):
print("setup_class:类中所有用例开始执前执行")

def teardown_class(self):
print("teardown_class:类中所有用例结束后执行")

def test_three(self):
print("正在执行----test_three")
x = "this"
assert 'h' in x

if __name__ == "__main__":
pytest.main()

原文地址:https://www.cnblogs.com/Teachertao/p/14674155.html