目录
pytest框架的优势
- 简单灵活,容易上手;支持参数化; 测试用例的skip和xfail处理;
- 能够支持简单的单元测试和复杂的功能测试,还可以做selenium/appnium等自动化测试、接口自动化测试(pytest+requests);
- pytest具有很多第三方插件,并且可以自定义扩展, 较好的如pytest-allure(完美html测试报告生成)、pytest-xdist(多 CPU分发)等;
- 可以很好的和jenkins集成;
pytest框架的规范
- 首先要import pytest
- 与Unittest使用方法相同的setUp和tearDown
- 在命令行中,可以使用如下命令:
pytest --v(最高级别信息)
pytest -v -s 文件名(带控制台输出结果) - 测试文件名称以 test_ 开头(以 _test 结尾也可以)
- 测试类名称以 Test 开头,并且不能带有 init 方法
- 测试方法名称以 test_ 开头
测试文件的运行
import pytest
pycharm运行
在main下
pytest.main([’-s’,‘文件名’])
控制台运行
pytest -s 文件名
前端自动化应用
登录
- 场景:测试用例执行时,有些需要登录执行,有些不需要
- 在登录函数前加@pytest.fixture(),需要登录的在测试方法中传入登录函数,范围默认函数级别
@pytest.fixture()
def login():
print('login')
def test_l(login):
print('case1:l')
def test_nl():
print('case2:nl')
if __name__=='__main__':
pytest.main(['-s','test_fitt.py'])
conftest
yield
- 场景:测试方法后销毁清除数据,范围是模块级别,类似setupClass
- 在同一模块中加入yield关键字,第一次调用返回结果,第二次执行yield后面的语句
- 在登录方法中加yield,之后加销毁清除的步骤
- 希望返回值使用addfinalizer
fixture的自动应用
- 场景:不想原测试方法有任何改动,或全部都自动实现自动应用,没有特例,也不需要返回值
- @pytest.fixture(autouse=true)
- @pytest.mark.usefixtures(‘自动实现的函数’)
@pytest.fixture(scope='module',autouse=True)#一整段都自动应用
def open_browser():
print('dakai ')
yield
print('teardown')
print('guanbi')
@pytest.fixture()
def login():
print('login')
def test_l(login):
print('case1:l')
def test_nl():
print('case2:nl')
if __name__ == '__main__':
pytest.main(['-s', 'test_fitt.py'])
@pytest.fixture()
def open_browser():
print('dakai ')
yield
print('teardown')
print('guanbi')
@pytest.mark.usefixtures('open_browser')#加了此句的自动应用
def