目录
1. 用例运行级别
-
模块级(setup_module/teardown_module)开始于模块始末,全局的
-
函数级(setup_function/teardown_function)只对函数用例生效(不在类中)
-
类级(setup_class/teardown_class)只在类中前后运行一次(在类中)
-
方法级(setup_method/teardown_method)开始于方法始末(在类中)
-
类里面的(setup/teardown)运行在调用方法的前后
2. 函数式
- setup_function/teardown_function:每个用例开始和结束调用一次
# -*- coding: utf-8 -*-
# @Time : 2021/1/18
# @Author : 大海
import os
import pytest
# 函数式
def setup_function():
print("setup_function:每个用例开始前都会执行")
def teardown_function():
print("teardown_function:每个用例结束后都会执行")
def test_one():
print("正在执行----test_one")
x = "this"
y = "this is pytest"
assert x in y
def test_two():
print("这是用例2")
x = "selenium"
assert "m" in x
def test_three():
print("这是用例3")
a = 1
b = 2
assert a < b
if __name__ == "__main__":
file_path = os.path.abspath(__file__)
# print(file_path)
pytest.main(["-s", file_path])
- setup_module/teardown_module:所有用例开始执行前执行一次/所有用例执行结束后执行一次
# -*- coding: utf-8 -*-
# @Time : 2021/1/18
# @Author : 大海
import os
import pytest
# 函数式
def setup_function():
print("setup_function:每个用例开始前都会执行" + '22')
def teardown_function():
print("teardown_function:每个用例结束后都会执行" + '222')
def setup_module():
print("setup_module:所有用例执行前执行一次" + '11')
def teardown_module():
print("teardown_module:所有用例执行后执行一次" + '111')
def test_one():
print("这是用例1")
x = "this"
y = "this is pytest"
assert x in y
def test_two():
print("这是用例2")
x = "selenium"
assert "m" in x
def test_three():
print("这是用例3")
a = 1
b = 2
assert a < b
if __name__ == "__main__":
file_path = os.path.abspath(__file__)
# print(file_path)
pytest.main(["-s", file_path])
3. 类中使用
- setup/teardown:同unittest里面的setup/teardown的功能
- setup_class/teardown_class:同unittest里面的setupClass和teardownClass功能
# -*- coding: utf-8 -*-
# @Time : 2021/1/18
# @Author : 大海
import os
import pytest
# 类中使用
class TestCase():
def setup(self):
print("setup:每个用例开始前都会执行" + '11')
def teardown(self):
print("teardown:每个用例结束后都会执行" + '222')
def setup_class(self):
print("setup_class:所有用例执行前执行一次" + '11')
def teardown_class(self):
print("teardown_class:所有用例执行后执行一次" + '111')
def setup_method(self):
print("setup_method:每个用例开始前都会执行" + '111')
def teardown_method(self):
print("teardown_method:每个用例执行后执行一次" + '11')
def test_one(self):
print("这是用例1")
x = "this"
y = "this is pytest"
assert x in y
def test_two(self):
print("这是用例2")
x = "selenium"
assert "m" in x
def test_three(self):
print("这是用例3")
a = 1
b = 2
assert a < b
if __name__ == "__main__":
file_path = os.path.abspath(__file__)
pytest.main(["-s", file_path])