pytest里面的setup和teardown有以下几种:
import pytest
# 模块中的方法
def setup_module():
print(
"setup_module:整个test_module.py模块只执行一次"
)
# 测试模块中的用例1
def test_one():
print("正在执行测试模块----test_one")
# 测试模块中的用例2
def test_two():
print("正在执行测试模块----test_two")
运行结果:
setup_module--》 test_one
setup_module--》 test_two
#test_Pytest.py文件
#coding=utf-8
import pytest
def setup_function():
print("setup_function方法执行")
def test_one():
print("test_one方法执行")
assert 1==1
def test_two():
print("test_two方法执行")
assert "o" in "love"
if __name__=="__main__":
pytest.main([‘-s‘,‘test_Pytest.py‘])
运行结果
setup_function--》 test_one--》 test_two
import pytest
class TestClass:
def setup_class(self): # 仅类开始之前执行一次
print("---setup_class---")
def test_one(self):
print("test_a")
def test_two(self):
print("test_b")
if __name__ == "__main__":
pytest.main(["-s","pytest_class.py"])
运行结果:
setup_class--》 test_one--》 test_two
# coding:utf-8
import pytest
class Test():
def setup_method(self):
print(‘setup_method‘)
def test_one(self):
print(‘test_one‘)
def test_two(self):
print(‘ test_two‘)
if __name__ == ‘__main__‘:
pytest.main([‘-s‘,‘test_pytest.py‘])
运行结果
setup_method--》 test_one
setup_method--》 test_two
import pytest
def setup():
print(‘setup‘)
def test_one():
print(‘test_one‘)
def test_two():
print(‘test_two‘)
if __name__ == ‘__main__‘:
pytest.main([‘-s‘,‘test_pytest.py‘])
运行结果
setup--》 test_one
setup--》 test_two
原文:https://blog.51cto.com/u_13025170/3134205