pytest学习笔记

1.安装,查看版本

pip install -U pytest
pytest --version

2.在pycharm上以pytest的方式运行,修改默认的运行方式

路径:Settings-Tools-Python Integrated Tools 

configurations中也设置一下

3.用pytest方法运行的测试类需要以Test 打头,测试方法以test打头

4.pycharm运行和命令行运行,读取配置文件报错。(因为pycharm运行时会将当前项目根节点加入path中,命令行运行时是当前路径)注意运行的目录。

5.两种方式运行,pytest在运行的时候不会输出print语句,执行的时候带上-s就可以了

#1、测试类主函数,会运行test.py 文件中所有满足命名条件的方法
#注意:以pytest方式运行不会执行main函数
if __name__=='__main__':
    pytest.main("-s test.py")
#2、命令行运行
pytest test.py 
#-q 使用quiet模式执行
pytest -q test.py
#通过关键字过滤测试方法,会匹配类名、文件名、方法名
pytest test.py -k "testy and not b"
#指定方法名或者类名执行
pytest test.py::TESTClass::testy
#失败一次就停止执行
pytest -x
#失败n次就停止执行
pytest --maxfail=n
#通过@pytest.mark.deco装饰器来指定执行,会执行所有被deco装饰的测试用例
pytest -m deco 
#得到测试概要信息,可以在r后面加上a,f等,具体意思见pytest官方文档
pytest -r  

6.pytest的setup和teardown函数

作用于类,setup_class()  teardown_class(),一个测试类执行前后执行

作用于函数 setup()  teardown() 在每个测试函数执行前后执行

7.pytest中还可以打断点,两种方式

  1. python import pdb; pdb.set_trace()

  2. breakpoint()

8.测试时间,显示最慢的3个测试步骤

pytest --duration=3

9.断言,常用的assert ,会在测试结果中显示实际值和对比值

10.fixture,作为函数入参使用,被fixture修饰的会创建一个函数实例,其他的函数可以进行调用

@pytest.fixture
def test_1():
    a=1
    return a
def test_2(test_1):
    assert test_1==2

11.conftest.py(文件名固定)文件可以用来放fixture函数的合集,在执行测试类的时候,pytest会检索里面的文件。

@pytest.fixture(scope='module')
def test_1():
    a=1
    return a

scope的值有function, class, module, package 和 session,代表不同的作用域去调用test_1()这个函数,只调用一次,避免了多个测试函数反复去创建实例。(scope越大越早创建)

12.fixture 调用结束执行清理,yield的功能类似于return,先返回a的值。然后在fixture退出作用域时会继续执行后面的语句。(这里程序最后会执行print语句)

@pytest.fixture
def test_1():
    a=1
    yield a
    print('hha')
​
def test_2(test_1):
    assert test_1==1

13.fixture 参数化

#parametrize('参数名','list')   注意参数名里面的变量长度要同list的长度一致。

ids里面的数量要和list的数量保持一致

#data['namedata'] 是读取了yaml里面的数据,数据格式就列表['cathy','expect','正常新增']

@pytest.mark.parametrize("datay,expecty,explain",data['namedata'],ids=['正常新增','名字为空','名字超长','重名'])

def test_name(self,datay,expecty,explain):

        #中间就不写了

        pass

14.怎么取消以pytest的方式执行

Edit configuration中把pytest方式运行去掉,然后+python运行方式,apply

15.使用allure查看测试报告

#生成报告结果数据
pytest test.py --alluredir ../report/tmp
#生成报告html
allure generate ../report/tmp -o ../report/html --clean

16.注意,在main函数下,不能使用pytest执行,因为不会执行main函数

if __name__=='main':
    pytest.main['test.py','--alluredir','../report/tmp']
    os.system('allure generate ../report/tmp -o ../report/html --clean')

17.pytest执行是没有顺序的,可以通过命名来,z-a,9-1从上到下,或者安装一个

pip install pytest-ordering
@pytest.mark.run(order=1)
def test_1():
    pass

18.allure常使用的几种方式。

@allure.dynamic.title("标题名")
@allure.dynamic.decription("简介")
@allure.step("步骤")
#写在方法外面要加@,写在里面不用加@,@是修饰符,用在函数定义之前

ps:(最后附上pytest官方文档链接:完整的Pytest文档 — pytest documentation

  • 2
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值