测试用例setup和teardown
测试用例setup和teardown
用例运行级别
模块级:setup_module()和teardown_module(),开始于模块始末
函数级:setup_function()和teardown_function(),
类级:setup_class()和teardown_class()只在类中前后运行一次
方法级:setup_method()和teardown_method()开始于方法始末
import pytest
def setup_module():
print("整个.py模块只执行一次setup_module")
def teardown_module():
print("整个只执行一次setup_module")
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 hasattr(x, 'check')
def test_three():
print("正在执行test_three")
a = "hello"
b = "hello world"
assert a in b
if __name__ == "__main__":
pytest.main(["-s", "test_fixt.py"])
注:运行时如果选中范围在某条用例中,则剩余用例不会运行
如下所示,只会运行test_one用例
函数和类混合使用
import pytest def setup_module(): print("整个.py模块只执行一次setup_module") def teardown_module(): print("整个.py模块只执行一次teardown_module") def setup_function(): print("每个用例开始前都会执行setup_function") def teardown_function(): print("每个用例结束前都会执行teardown_function") def test_one(): print("正在执行test_one") print(1 == 1) def test_two(): print("正在执行test_two") print(1 == 2) class TestCase(): def setup_class(self): print("所有用例执行之前setup_class") def teardown_class(self): print("所有用例执行之前teardown_class") def test_three(self): print("正在执行test_three") print(1 == 1) def test_four(self): print("正在执行test_four") print(1 == 2) if __name__ == "__main__": pytest.main(["-s", "test_get.py"])
类中使用
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") print(1 == 1) def test_two(self): print("正在执行test_two") print(1 == 2) def test_three(self): print("正在执行test_three") assert 1 == 2 if __name__ == "__main__": pytest.main(["-s", "test_get.py"])