pytest实现自动化测试的基本操作

python自动化测试的pytest基本操作

安装pytest模块
pip install pytest#安装pytest模块

pytest --version #查看安装的版本 验证是否安装成功
编写pytest文件规则
  • 测试文件test开头(以test结尾也可以
  • 测试Test开头,并且不能带有 init 方法
  • 测试函数test_开头
1、创建一个文件为:test_case.py
# -*- coding: utf-8 -*- 
def test_1():
	a=1
	b=1 
	assert a==b 
2.运行

运行有两种方式

第一种,通过dos命令或者pycharm的命令窗口输入pytest

此方法会执行当前目录下识别到的所有符合pytest文件编写规则的用例

若要指定某个py文件执行则要输入pytest 文件名.py
结果如下

============================================================== 
test session starts 
===============================================================
platform win32 -- Python 3.7.3, pytest-5.4.3, 
py-1.9.0, pluggy-0.13.1c
rootdir: 
E:\Program Files\PycharmProjects\untitled\day2\pytest_day1
plugins: allure-pytest-2.8.16
collected 1 item                                                                                                                                  

test_case.py .                                                                                                                              [100%]

=============================================================== 
1 passed in 0.02s
================================================================
pytest收集用例的规则

1.默认从当前目录中搜索case,即在哪个目录下运行pytest命令,则从哪个目录中搜索
2.可以通过 pytest 地址 指定搜索的目录

第二种:通过主函数在代码中运行

注意:需要导包

# -*- coding: utf-8 -*- 
import pytest
def test_1():
	a=1
	b=1 
	assert a==b 
if __name__ == '__main__': 
pytest.main()
mark功能

在运行测试用例的时候。由于创建了测试类,而每个测试类中包含了用例。我们往往不会将用例全部执行。常常会筛选用例进行执行.
这个时候我们可以通过pytest.mark将用例进行分类,从而到达筛选用例的功能

使用方法:

1.创建标签名
2.在测试用例/测试类前加上标记 @pytest.mark.标记名

标签名如何创建
设置pytest.ini文件,在文件中按照以下格式添加标签名:
[pytest] 
markers= 
smoking:smoke test 
mood:mood test

注意:smoking为标签名(不支持中文),冒号后面是对该标记的解释(不支持中文)方便管理员进行查看

执行用例
import pytest 
@pytest.mark.smoking 
def test_1():
	a=1
	b=1 
	assert a==b 
pytest之fixture功能
基本使用
import pytest
def test_2(aa): 
	#选择执行那个fixture 
	a=1
	b=1 
	assert a==b  
	print("先执行上式代码") 

@pytest.fixture() 
def aa(): 
	a=1
	b=1 
	assert a==b 
	print("先执行上面代码") 
	yield #类似分隔符号 yield 上面的代码表示用例执行前 下面的表示用例执 行之后
	pass
	print("再执行yield后面代码")

test_case.py文件

@pytest.mark.usefixtures("aa") #表示调用方法名为aa的前置后置 
def test_2(): 
	assert 1!=0 
测试用例参数化
test_data=[('admin','123456'),('root','123456')]

@pytest.mark.parametrize('name,passwd',test_data)#会传两次参
def test_01(name,passwd):
	 print(name,passwd,ex)

(转载注明出处)

  • 2
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值