pytest单元测试框架
一、 pytest单元测框架
1、 什么是单元测试框架:
单元测试是指在软件开发当中,针对软件的最小单位(函数、方法)进行正确性的检查测试
2、 单元测试框架:
java:Junit和testng
Python:unittest和pytest
3、 单元测试框架主要做:
(1) 测试发现:从多个文件里面去找到测试用例
(2) 测试执行:按照一定的顺序和规则去执行,并生成结果
(3) 测试判断:通过断言判断预期结果和实际结果的差异
(4) 测试报告:统计测试用例进度,耗时,通过率,生成测试报告
二、 单元测试框架和自动化测试框架有什么关系?
1、 什么是自动化测试框架
2、 作用:
(1) 提高测试效率、降低维护成本(2)减少人工干预。提高测试的准确性,增加代码的重用性(3)核心思想:让不懂代码的人也能够通过这个框架实现自动化测试
3、pytest单元测试框架和自动化测试框架的关系
单元测试框架:属于自动化测试框架组成部分之一
pom设计模式:属于自动化测试框架的组成之一
数据驱动、关键自驱动、全局配置文件的封装、日志监控、selenium、requests二次封装、断言、报告邮件
三、 pytest简介
pip install -r requirement.txt
pytest
pytest-html
pytest-xdist
pytest-ordering
pytest-rerunfailures
allure-pytest
四、 pytest,默认的测试用例的规则以及基础应用
1、 模块名必须以test_开头或者_test结尾
2、 测试类必须以Test开头,并且不能有init方法
3、 测试方法必须以test开头
五、 pytest测试用例的运行方式
1、 主函数模式
(1) 执行所有
if name == ‘main’:
pytest.main()
(2)指定模块运行
pytest.main([’-vs’,‘test_pytest’])
(3)指定目录
pytest.main([’-vs’,’./pytest_study’])
(4)通过nodeid的指定用例运行:nodeid由模块名、分隔符、类名、方法名、函数名组成
pytest.main([’-vs’,’./pytest_study/test_pytest.py::Test_password’])
pytest.main([’-vs’,’./pytest_study/test_pytest.py::Test_password::test_C001001’])
2、 命令模式
(1) 运行所有:pytest
(2) 指定模块:pytest -vs test_pytest
(3) 指定目录:pytest -vs ./pytest_study
(4) 指定类名:pytest -vs ./pytest_study/test_pytest.py::Test_password
参数详情:
-s:表示输出调试信息,包括print打印的信息pytest.main([’-s’])
-v:显示更详细的信息
-vs:两个参数一起作用
-n:支持多线程或者分布式运行测试用例
例如:pytest -vs ./testcase/test_login.py -n 2
pytest.main([’-vs’,’./testcase’,’-n=2’])
-reruns num:失败用例重跑
-x表示有一个报错测试停止
–maxfail=2 出现两个用例失败就停止
-k:
3、 通过读取pytest.ini配置文件运行
[pytest]
addopts=addopts=-vs -m smoke #指定标签用例
testpaths=./testcases
python_files=test*.py
python_classes=Test*
python_function=test_*
markers=
smoke:冒烟测试
增加标记后只执行带标记的用例
六、测试用例的前后置,固件、夹具
def setup(self):
print('在每个用例之前执行一次:初始化日志对象,初始化数据库连接')
def teardown(self):
print('在每个用例之后执行一次:关闭日志对象,关闭数据库连接')
def setup_class(self):
print('在每个类之前执行')
def teardown_class(self):
print('在每个类之后执行')
@pytest.fixtrue装饰器可以实现部分用例前后置
@pytest.fixtrue(scope="",params="",autous="",name="")
scope: 作用域
function ,class, module,package/session
如果说scope=function,那么可以在用例的参数后面单独调用
如果scope=class,可以在类上面通过@pytest.mark.usefixtures(“exl_sql”)
fixtrue结合conftest.py文件使用
六、 接口自动化测试框架关于接口关联的封装
策略:去掉全局变量
#读取
def read_yaml(key):
with open(os.getcwd()+"/extract.yaml",mode='r',encoding='utf-8') as f:
value=yaml.load(stream=f,Loader=yaml.FullLoader)
return value[key]
#写入
def write_yaml(data):
with open(os.getcwd()+"/extract.yaml",mode='a',encoding='utf-8') as f:
yaml.dump(data,stream=f,allow_unicode=True)
#清空
def clear_yaml():
with open(os.getcwd()+"/extract.yaml",mode='w',encoding='utf-8') as f:
f.truncate()
1、首先写入write_yaml({“search_token”:res.json().get(‘result’).get(‘priceItinerarys’)[0].get(‘products’)[0].get(‘token’)})
2、读取
“token”:read_yaml(“search_token”)
实际使用