示例一:
文件:test_py_demo.py
import pytest
#放在类外,对函数起作用
def setup_function(self):
print("before_function")
#放在类外,对函数起作用
def teardown_function(self):
print("after_function")
#放在类外,对整个模块起作用
def setup_module(self):
print("before_module")
#放在类外,对整个模块起作用
def teardown_module(self):
print("after_module")
#类名必须以Test开头
class TestDemo:
def setup_class(self):
print("before_class")
def teardown_class(self):
print("after_class")
def setup_method(self):
print("before_method")
def teardown_method(self):
print("after_method")
#测试方法名必须以test开头
#预期失败,结果失败
@pytest.mark.xfail(True,reason="预期失败")
def test_01(self):
print("test01")
assert 0
# 预期失败,结果成功
#测试方法名必须以test开头
@pytest.mark.xfail(True,reason="预期失败")
def test_03(self):
print("test03")
assert 1
# 预期成功,结果失败
@pytest.mark.xfail(False,reason="预期成功")
def test_04(self):
print("test04")
assert 0
# 预期成功,结果成功
#测试方法名必须以test开头
@pytest.mark.xfail(False,reason="预期成功")
def test_05(self):
print("test05")
assert 1
#如果为真,则跳过此测试用例。
@pytest.mark.skipif(True,reason="条件为真跳过测试")
def test_02(self):
print("test02")
assert 0
#参数化(单个参数)
@pytest.mark.parametrize("mobile",[110,120,12306,119,999])
def test_06(self,mobile):
print(mobile)
#此条为失败用例。有如下参数,则会重新再执行几次失败的用例。--reruns = 2
assert 0
# 参数化(多个参数)
@pytest.mark.parametrize("mobile,name",[(110,"sophia"),(120,"lily"),(119,"xj")])
def test_07(self,mobile,name):
print(mobile,"\t",name)
assert 1
@pytest.fixture()
def login(self):
print("login start")
yield
print("login end")
return "登录成功"
#把上面的登陆方法当成参数传过来
def test_shopping(self,login):
print("i would like to go shopping")
#会打印出登陆成功,说明@pytest.fixture()也能传参数,进行参数化。
print(login)
#调整测试用例执行顺序
@pytest.mark.run(order=1)
def test_a(self):
print("a")
@pytest.mark.run(order=0)
def test_b(self):
print("b")
if __name__ == '__main__':
pytest.main(["-s","test_py_demo.py"])
配置文件pytest.ini,与以上文件在同一目录下
[pytest]
addopts = -v -s --html=report/report.html --reruns=2
testpaths = scripts
python_files = test_*.py
python_classes = Test*
python_functions = test*
示例二:conftest.py的用法.以下文件必须在同一目录下
运行后发现只启动了一次浏览器,正合我意。
contest.py:
from selenium import webdriver
import pytest
@pytest.fixture(scope="session")
def openPage():
driver = webdriver.Chrome();
driver.get("http://www.baidu.com")
return driver
news_page.py
from time import sleep
def test_news(openPage):
openPage.find_element_by_name("tj_trnews").click()
sleep(3)
video_page.py
from time import sleep
def test_video(openPage):
openPage.find_element_by_name("tj_trvideo").click()
sleep(3)
更多详细资料请参看简书文章,某一大神的呕心力作。竟然是个系列性的文章,已经够全了。https://www.jianshu.com/nb/33805779
其实推荐看官方文档,无奈英语是个硬伤。什么时候能越过英语这个槛,我也就心满意足了。
生命不息,奋斗不止。。。。。。