> 文章列表 > 【pytest】

【pytest】

【pytest】

pytest

1、环境安装

1、pip install pytest -i https://pypi.tuna.tsinghua.edu.cn/simple --target=C:\\Dpan-app\\ceshirenenv\\Lib\\site-packages
2、pycharm安装

2、assert

>>> assert True
>>>
>>> assert False
Traceback (most recent call last):File "<stdin>", line 1, in <module>
AssertionError
>>>
>>>
>>> assert False,"这里有错误"
Traceback (most recent call last):File "<stdin>", line 1, in <module>
AssertionError: 这里有错误

3、pytest参数化实现

装饰器

@pytest.mark.parametrize

eg.

@pytest.mark.parametrize("username,password",[["right","right"],["wrong","wrong"]])
def test_param(username,password):login(username,password)

ids

ids : 给测试用例起别名

@pytest.mark.parametrize("username, password", [["rightusername","right username"],["wrong username","wrong password"],[" ","password"],["right username", ""]],ids=["right username and password", "wrong username and password", "username is Null","password is Null"])
def test_login(username, password):print(f"登录的用户名:{username}, 密码:{password}")

ids为中文

@pytest.mark.parametrize("username, password", [["rightusername","right username"],["wrong username","wrong password"],[" ","password"],["right username", ""]],ids=["正常的用户和正确的密码", "错误的用户名和错误的密码", "用户名为为","password is Null"])
def test_login1(username, password):print(f"登录的用户名:{username}, 密码:{password}")

需要在同一路径下配置一个conftest.py文件

def pytest_collection_modifyitems(items):"""测试用例收集完成时,将收集到的用例名name和用例标识nodeid的中文信息显示在控制台上"""for i in items:i.name=i.name.encode("utf-8").decode("unicode_escape")i._nodeid=i.nodeid.encode("utf-8").decode("unicode_escape")

笛卡尔

@pytest.mark.parametrize("c",["appium","selenium","pytest"])
@pytest.mark.parametrize("b",["a","b","c"])
@pytest.mark.parametrize("a",[1,2,3])
def test_param1(a,b,c):print(f"笛卡积形式的参数化中 a={a} , b={b}  ,c={c}")

笛卡尔积 , 产生测试用例个数 3 x 3 x 3 = 27

4、pytest 标记测试用例

给测试用例命名

eg.

#此处skip为自己命名的用例名
@pytest.mark.skip
def test_aaa():print("代码未开发完")assert True

执行指令
eg.
匹配测试用例名skip
pytest .py文件名 -vs -m “skip”

去除警告方法

【pytest】

建文件pytest.ini,文件内容里markers = 所有自己命名的测试用例名

[pytest]
markers =   strbignumfloatintminuszero	 

5、pytest命令行常用参数

–help
-x : (常用与回归测试前的冒烟测试)按顺序执行用例,用例一旦fail,立即停止执行
–maxfail=num : 允许有num个测试用例执行fail
-m : 给用例加标签,运行代码时,只执行某一些自己标记的用例
-k : 执行(函数名)包含某个关键字的测试用例
eg.
pytest .py -v -k “str” 执行包含str的用例
pytest .py -v -k “not str” 反选,执行函数名(测试用例名)中不包含str的用例
-v : 打印详细日志
eg.
看不出来哪条测试用例成功,哪条用例失败了。(执行后,pass只显示绿色的点,fail只显示红色的F)
-s : 打印输出日志
eg.
打印出函数(测试用例)里print的内容
–collect-only : 收集测试用例展示到前端界面,但不执行
eg.
执行指令 pytest --collect-only

6、python代码执行pytest

7、异常处理

try … except

异常捕获

法一:
try … except

try:a = int(input("输入被除数:"))b = int(input("输入除数:"))c = a / bprint("您输入的两个数相除的结果是:", c )
except (ValueError, ArithmeticError):print("程序发生了数字格式异常、算术异常之一")
except :print("未知异常")
print("程序继续运行")

法二:
pytest.raises

import pytestdef test_raise():with pytest.raises((ZeroDivisionError,ValueError)):       #直接执行1/0会报错出现异常,ZeroDivisionError,将此错误记为异常,并且只捕获,不报错raise ZeroDivisionError("除数为0")
def test_raise1():with pytest.raises(ValueError, match = 'must be 0 or None'):raise ValueError("value must be 0 or None")
def test_raise1():with pytest.raises(ValueError) as exc_info:  #给异常命名,从而获取到异常的一些信息raise ValueError("value must be 42")assert exc_info.type is ValueErrorassert exc_info.value.args[0] == "value must be 42"

茶叶知识