1、pycharm设置pytest
- 1、选择File-setting,搜索框中搜索pytest,
- 2、可以看到Tools-Python IntegratedTools,有个Testing选项下Default test runner,选择pytest,点击Apply,点击OK
2、pycharm运行pytest
- 1、直接右击空白处,点击‘Run ‘pytest in *’’
- 2、运行单个类或者方法,点击左侧的绿色三角箭头
3、pytest fixture的用法
-
fixture 用法
- Fixture 是为了测试⽤例的执⾏,初始化⼀些数据和⽅法
- 实现了 unittest ⾥面的 setUp, tearDown 功能,但⽐ setUp, tearDown 更灵活
- 直接通过函数名字调⽤或usefixtures
- 允许使用多个fixture
- 使用 autouse,如果要返回值,需要传fixture函数名
- -setup-show 回溯 fixture 的执行过程
-
fixture 作用域
- fixture 里面有一个参数 scope,默认scope=“function”,通过 scope 可以控制 fixture 的作用范围,根据作用范围大小划分:session> module> class> function,具体作用范围如下:
- function 函数或者方法级别都会被调用
- class 类级别调用一次
- module 模块级别调用一次
- session 是多个文件调用一次(可以跨.py文件调用,每个.py文件就是module)
- fixture 里面有一个参数 scope,默认scope=“function”,通过 scope 可以控制 fixture 的作用范围,根据作用范围大小划分:session> module> class> function,具体作用范围如下:
-
conftest.py配置需要注意:
-
conftest.py文件名是不能换的
-
conftest.py与运行的用例要在同一个package下,并且有__init__.py文件
-
不需要import导入conftest.py,pytest用例会自动查找
-
所有同目录测试文件运行前都会执行conftest.py文件
-
全局的配置和前期工作都可以写在这里,放在某个包下,就是这 个包数据共享的地方。
-
如果不同层级的包下都有conftest.py文件,那么内层目录的conftest.py文件中的方法会覆盖外部的conftest.py文件中的方法(重名的方法)
-
yield 相当于执行teardown
- yield遇到异常不影响后面用例
-
4、pytest参数化
- @pytest.mark.paramertize装饰器可以使用测试用例参数化
- argnames: 要参数化的变量(可以是字符,多个用逗号分割,list,tuple)
- argvalues: 要参数化的值(值需要和变量一一对应)
@pytest.mark.parametrize(("a,b"),[[10,20],(30,40),(31,40),(32,40)])
def test_param(a, b):
print(a + b)
.30
.70
.71
.72
- 若要获得多个参数化参数的所有组合,可以堆叠参数化装饰器
@pytest.mark.parametrize("x",[1,2])
@pytest.mark.parametrize("y",[4,5])
def test_param1(x,y):
print(x + y)
5、命令行传参
1.首先需要在contetest.py添加命令行选项,命令行传入参数”—cmdopt“, 用例如果需要用到从命令行传入的参数,就调用cmdopt函数:(不理解,先记住)
def pytest_addoption(parser):
parser.addoption(
"--cmdopt",action="store", default="type1",help="my option:type1 or type2"
)
@pytest.fixture()
def cmdopt(request):
return request.config.getoption("--cmdopt")
import pytest
def test_answer(cmdopt):
if cmdopt == 'type1':
print("first1")
elif cmdopt == "type2":
print("first2")
- 1.如果不带参数执行,那么传默认的default=”type1”
(venv) E:\pythonCode\pytest_demo>pytest -s test_sample.py
test_sample.py first1
.
- 2、在命令行带上参数去执行
(venv) E:\pythonCode\pytest_demo>pytest -s test_sample.py --cmdopt type2
test_sample.py first2
.
6、常用断言
- assert xx 判断xx为真
- assert not xx 判断xx不为真
- assert a in b 判断b包含a
- assert a == b 判断a等于b
- assert a != b 判断a不等于b
7、跳过用例
import pytest
def test_01():
print("\ncase 01")
@pytest.mark.skip(reason="跳过当前用例")
def test_02():
print("case 02")
def test_03():
print("case 03")
if __name__ == '__main__':
pytest.main(["-s", "test_skip.py"])
----------执行结果---------
test_skip.py .
case 01
s
Skipped: 跳过当前用例
.case 03