一、安装pytest
安装:pip install pytest
检查是否安装了正确的版本:pytest --version
二、新建一个python项目
打开pycharm,点击create new python project
location是指你的项目所在路径,建议放在除系统盘外的空间较大的盘中,路径选好以后,就是创建一个项目所需要的虚拟环境(一般是用于安装python的一些支持库)
选择“new environment using”,location的地址选择你项目的所在地址下,base interpreter选择你Python所在的地址即可,点击create之后,pycharm会自动为你创建虚拟环境。
三、新建testcase文件夹,用于存放你的测试脚本
四、新建一个测试用例(moudle)
1)pytest框架的命名规则
---测试文件名必须为test_开头或_test结尾,例如:
test_Add.py 或 Add_test.py
---测试函数、测试类方法应该命名为test_Function或test_Method,例如:
test_Add()
---测试类须命令为Test,例如:
TestPerson()
2)在testcase下满新建一个test_xxx.py的文件(这个是你的测试用例)
五、断言
assert 关键字后面可以跟一个表达式,只要是表达式结果为True ,断言通过,用例执行成功,否则执行失败
Pytest的断言方式及应用场景:
1)比较大小与是否相等:
assert a == b:判断a等于b
assert a !=b:判断a不等于b
2)判断包含或不包含:
assert a in b:判断b包含a
assert a not in b:判断b不包含a
提示:b可以是字符串,可以是列表,元组等都可以。
3)对类型的判断:
assert isinstance(a,int):判断a是否是int类型数据。
4)判断方法或者函数的返回值是否为真:
assert xx:判断xx结果为真。
assert not xx:判断xx结果不为真。
六、命令行执行
指定测试文件:pytest test_mod.py
指定测试目录:pytest testing/
指定测试关键字:pytest -k 'MyClass and not method' (关键字可以是文件名,类名,函数名或者参数名)
七、跳过测试
@pytest.mark.skip()
@pytest.mark.skipif(session=="",reason='session 不存在')满足条件则跳过,不满足条件则执行
在执行自动化的时候,会有这种情况,知道该功能存在稳定性问题,不想要执行,但是也不想要跳过。这个时候我们就可以使用xfail,xfail表示测试期望是失败的,不会影响测试用例的执行,如果执行成功则报xpass,如果失败就会报xfail。
八、参数化
pytest.mark.parametrize(argnames, argvalues)
1)如验证密码长度大于等于8,小于等于16位:
@pytest.mark.parametrize('passwd', ['123','12345678','1234567890123456','12345678901234561'])
def test_passwd_length(passwd):
assert len(passwd) >= 8
assert len(passwd)<=16
2)多个参数时:
@pytest.mark.parametrize('user,passwd', [('leizi','123'),('leizi','12345678'),('lei','1234567890123456'),('leizishuoceshikaifa','12345678901234561')])
def test_userpasswd_length(user,passwd):
assert len(passwd) >= 8
assert len(passwd)<=16
assert user=='leizi'
3)实际的工作中呢,很多时候的参数都是实时读取的。这些参数数据都是动态读取来的,那么看下如何给参数动态传递呢,这里获取数据,写了一个demo。
def getparame()->list: ''' 返回用例如有入参 :return:'''
return [('leizi','123'),('leizi','12345678'),('lei','1234567890123456'),('leizishuoceshikaifa','12345678901234561')]
@pytest.mark.parametrize('user,passwd',
getparame())
def test_passwd_length(user,passwd):
assert len(passwd) >= 8
assert len(passwd)<=16
assert user=='leizi'
九、pytest Fixture
1)基本应用
固件(Fixture)是一些函数,pytest 会在执行测试函数之前(或之后)加载运行它们。我们可以用它做一些事情,比如数据库的链接操作之类的。如何使用呢。
import pytest
@pytest.fixture()
def post_code():
return '010'
def test_postcode(post_code):
assert post_code == '010'
Pytest 使用 yield 关键词将固件分为两部分,yield 之前的代码属于预处理,会在测试前执行;yield 之后的代码属于后处理,将在测试完成后执行。
以下测试模拟数据库查询,使用固件来模拟数据库的连接关闭:
import pytest
@pytest.fixture()
def db():
print('Connection success')
yield
print(' closed')
def search_user(user_id):
d = {
'002': 'leizi'
}
return d[user_id]
def test_search(db):
assert search_user('002') == 'leizi'
2)作用域
function: 函数级,每个测试函数都会执行一次固件;
class: 类级别,每个测试类执行一次,所有方法都可以使用;
module: 模块级,每个模块执行一次,模块内函数和方法都可使用;
session: 会话级,一次测试只执行一次,所有被找到的函数和方法都可用。
import pytest
@pytest.fixture(scope='function')
def func_scope():
print("function")
@pytest.fixture(scope='module')
def mod_scope():
print("module")
@pytest.fixture(scope='session')
def sess_scope():
print("session")
@pytest.fixture(scope='class')
def class_scope():
print("class")
def test_multi_scope(sess_scope, mod_scope, func_scope):
pass
3)对于类使用作用域,需要使用 pytest.mark.usefixtures (对函数和方法也适用)
@pytest.mark.usefixtures('class_scope')
class TestClassScope:
def test_1(self):
pass
def test_2(self):
pass
4)自动执行
目前为止,所有固件的使用都是手动指定,或者作为参数,或者使用 usefixtures。
如果我们想让固件自动执行,可以在定义时指定 autouse 参数。
下面是两个自动计时固件,一个用于统计每个函数运行时间(function 作用域),一个用于计算测试总耗时(session 作用域)
date = '%Y-%m-%d %H:%M:%S'
@pytest.fixture(scope='session', autouse=True)
def timer_session_scope():
start = time.time()
print('\nstart: {}'.format(time.strftime(date, time.localtime(start))))
yield
finished = time.time()
print('finished: {}'.format(time.strftime(date, time.localtime(finished))))
print('Total time cost: {:.3f}s'.format(finished - start))
@pytest.fixture(autouse=True)
def timer_function_scope():
start = time.time()
yield
print(' Time cost: {:.3f}s'.format(time.time() - start))
注意下面的两个测试函数并都没有使用固件:
def test_one():
time.sleep(1)
def test_one():
time.sleep(2)
我们可以看到,我们选择自动执行,即使我们没有选择使用,pytest也会给自动执行的。执行到对应的function级别。
5) 重命名
固件的名称默认为定义时的函数名,如果不想使用默认,可以通过 name 选项指定名称:
@pytest.fixture(name='name')
def calculate_average():
return 28
def test_age(name):
assert name == 28
if __name__ == '__main__':
pytest.main()
6)显示用例的运行时间
conftest.py 的文件中添加
import pytest
import time
@pytest.fixture(autouse=True)
def timer(request):
start_time = time.time()
yield
duration = time.time() - start_time
print(f"Test '{request.node.name}' took {duration:.2f} seconds")
十、Log
(一)普通log
打开PyCharm并导航到项目的根目录。
在菜单栏中选择"Run"(运行)-> "Edit Configurations"(编辑配置)。
在弹出的对话框中,选择你要编辑的pytest配置。
在"Configuration"(配置)选项卡中,找到"Logging"(日志)部分。
勾选"Save console output to file"(将控制台输出保存到文件)复选框。
在"Path"(路径)字段中输入你想要保存日志的文件路径。
点击"OK"保存配置。 现在,当你在PyCharm中运行pytest时,日志将会被输出到指定的文件中。
(二)定制log
pytest.ini文件配置下:
[pytest]
log_cli = True
log_file =./pytest_log.txt
log_cli_level = INFO
log_cli_format = %(asctime)s [%(levelname)s] | %(filename)s:%(lineno)s | %(message)s
log_cli_date_format = %Y-%m-%d %H:%M:%S
log_file_level = INFO
log_file_date_format = %Y-%m-%d %H:%M:%S
log_file_format = %(asctime)s [ %(levelname)s ] %(filename)s:%(lineno)s | %(message)s
将except中的日志写入log:
def test_answer():
try:
assert int(2) == 3
except Exception as e:
# 配置日志记录器
logging.basicConfig(filename='../log/pytest_log.txt', level=logging.ERROR)
# 将错误信息写入日志文件
logging.error("断言失败: %s", str(e))
# 用例中将其标记为失败用例,如无此句,则用例pass,测试报告不准
pytest.fail("断言失败")
其中配置日志记录器可以在任何位置
十一、生成测试报告
(一)普通报告
1. 首先,确保已经安装了pytest和pytest-html插件。你可以使用以下命令来安装它们:
pip install pytest-html
2. 在PyCharm中,打开项目的根目录。
3. 在菜单栏中选择"Run"(运行)-> "Edit Configurations"(编辑配置)。
4. 在弹出的对话框中,选择你要编辑的pytest配置。
5. 在"Additional Arguments"(附加参数)字段中添加 --html=<报告文件路径> 选项,指定生成测试报告的文件路径。例如:
--html=report.html
6. 点击"OK"保存配置。
7. 运行pytest测试。测试运行完成后,会在指定的报告文件路径生成一个HTML格式的测试报告。
8. 在PyCharm中,你可以直接打开生成的测试报告文件,或者在浏览器中打开它,以查看详细的测试结果。
(二)allure报告
1)产生报告
确保已经安装了pytest、pytest-allure和allure-pytest插件。你可以使用以下命令来安装它们:
pip install pytest
pip install pytest-allure-adaptor
pip install allure-pytest
在pytest.ini文件中添加:
[pytest] addopts = --alluredir=./allure-results
2)下载allure 安装包:https://github.com/allure-framework/allure2/releases 并安装
配置环境变量到bin目录
重启电脑
3)pycharm中配置
1.在根目录创建allure-results、allure-report文件夹
2. 在PyCharm中,打开项目的根目录。
3. 在菜单栏中选择"Run"(运行)-> "Edit Configurations"(编辑配置)。
4. 在弹出的对话框中,选择你要编辑的pytest配置。
5. 在"Additional Arguments"(附加参数)字段中添加 --alluredir=<报告目录路径> 选项,指定生成测试报告的目录路径。例如:
--alluredir=allure-results
6. 点击"OK"保存配置。
7. 运行pytest测试。测试运行完成后,会在指定的报告目录路径生成allure测试报告相关的文件。
8. 打开终端或命令行工具,导航到报告目录路径。
9. 运行以下命令来生成allure测试报告:
在json文件上级目录,cmd输入下面命令
allure serve allure-results 生存后不保存文件,直接打开
或者:allure generate ./allure-results/ -o ./allure-report/ --clean 生成后保存到allure-report文件夹中
10.报告中添加环境变量
测试结果json文件中添加environment.properties文件,文件中为环境变量信息,如:
Browser=chrome Browser.Version=77 Stand=HJ_teach ApiUrl=127.0.0.1/login python.Version=3.6