测试用例setup和teardown

2019-04-14 17:42发布

1、用例运行级别: 模块级:所有用例开始前只执行一次,结束后只执行一次 # 模块级:setup_module/teardown_module import pytest def setup_module(): print("setup_module:整个.py模块只执行一次") print("比如:所有用例开始前只打开一次浏览器!") def teardown_module(): print("setup_module:整个.py模块只执行一次") print("比如:所有用例开始前只关闭一次浏览器!") 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_modulesetUp.py"])   函数级:每个用例开始和结束调用一次 用例的执行顺序是: setup_function》用例1》teardown_function》,setup_function》用例2》teardown_function》,setup_function》用例3》teardown_function》 # 函数式:setup_function/teardown_function import pytest def setup_function(): print("setup_function:每个用例开始前都会执行!") def teardown_function(): print("setup_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_functionsetUp.py"]) 类级和方法级 执行顺序:setup_class》setup_method》setup》用例》teardown》teardown_method》teardown_class import pytest class TestCase(): def setup(self): print("1setup:每个用例开始前都执行!") def teardown(self): print("1teardown:每个用例结束后都执行!") def setup_class(self): print("2setup_class:所有用例执行之前") def teardown_class(self): print("2teardown_class:所有用例执行之后") def setup_method(self): print("3setup_method:每个用例执行之前") def teardown_method(self): print("3teardown_method:每个用例执行之后") def test_one(self): print("正在执行——test_one") x = "this" assert 'h' in x def test_two(self): print("正在执行——test_two") x = "hello" assert hasattr(x, "check") def test_three(self): print("正在执行——test_three") a = "hello" b = "hello world" assert a in b if __name__=="__main__": pytest.main(["-s","test_classsetUp.py"]) 2、混合 setup_module/teardown_module优先级最高、setup_class和setup_function不干涉