https://docs.pytest.org/en/latest/contents.html#toc
# fixture
import pytest
@pytest.fixture()
def login():
print("登录函数")
def test_case1(login):
print("test_case1,需login")
pass
def test_case2():
print("test_case2,无需login")
pass
def test_case3(login):
print("test_case3,需login")
pass
if __name__ == '__main__':
pytest.main()
# fixture、yield
import pytest
@pytest.fixture(scope='module')
def login():
print("登录函数")
yield
print("执行teardown!关闭浏览器")
def test_case1(login):
print("test_case1,需login")
def test_case2():
print("test_case2,无需login")
def test_case3(login):
print("test_case3,需login")
if __name__ == '__main__':
pytest.main()
import pytest
@pytest.fixture(autose=True)
def login():
print("登录函数")
yield
print("执行teardown!关闭浏览器")
def test_case1(login):
print("test_case1,需login")
def test_case2():
print("test_case2,无需login")
def test_case3(login):
print("test_case3,需login")
if __name__ == '__main__':
pytest.main()
# @pytest.mark.parametrize 参数化
import pytest
# 参数化,前两个变量,后面是对应的数据
# 3+5 -> expression,8 -> result
@pytest.mark.parametrize("expression,result",[('3+5',8),('2+5',9),('2+8',10)])
def test_eval(expression,result):
# eval 将字符串str当成有效的表达式来求值,并返回结果
assert eval(expression) == result
# 参数组合
@pytest.mark.parametrize("x",[1,2])
@pytest.mark.parametrize("y",[8,9,10])
def test_foo(x,y):
print(f"测试数据组合x:{x},y:{y}")
# 模拟登录
login_user=['tom','amy']
@pytest.fixture(scope='module')
def login(request):
user = request.param
print(f"\n准备登录,登录用户:{user}")
return user
# indirect=True,把传过来的参数当作函数执行
@pytest.mark.parametrize('login',login_user,indirect=True)
def test_login(login):
a = login
print(f"\n测试用例中login的返回值:{a}")
assert a != ""
# 跳过执行某个用例
@pytest.mark.skip("此次测试不执行登录“)
# 加入条件
@pytest.mark.skipif(sys.platform == 'darwin', reason = "不在macos上执行")
# @pytest.xfail
@pytest.mark.xfail
@pytest.mark.parametrize('login',login_user,indirect=True)
def test_login(login):
a = login
print(f"\n测试用例中login的返回值:{a}")
assert a != ""
raise NameError
import pytest
@pytest.mark.search
def test_search1():
print("test_search1")
raise NameError
pass
@pytest.mark.search
def test_search2():
print("test_search2")
pass
@pytest.mark.search
def test_search3():
print("test_search3")
pass
@pytest.mark.login
def test_login1():
print("test_login1")
pass
@pytest.mark.login
def test_login2():
print("test_login2")
pass
if __name__ == '__main__':
pytest.main()
在terminal里执行上面的命令,但是会报warning
这时候要去conftest.py
里加入
def pytest_configure(config):
mark_list = ['search','login']
for markers in mark_list:
config.addinivalue_line(
"markers",markers
)