python+pytest+request 接口自动化测试

一、环境配置
1.安装python3
brew update
brew install pyenv
然后在 .bash_profile 文件中添加 eval “$(pyenv init -)”
pyenv install 3.5.3 -v
pyenv rehash 安装完成后,更新数据库
pyenv versions  查看目前系统已安装的 Python 版本
pyenv global 3.5.3  切换 Python 版本
python -V,查看 Python 版本
2.安装pytest及其他所需安装包:
pip install -U pytest
pip install -U requests
pip install -U pytest-pythonpath
pip install -U pytest-capturelog
pip install PyYAML
pip install configparser
pip install pyopenssl

二、pytest框架
setup_module(module):  #开始测试前执行一次,目前无实际使用
setup_function(function):  #每个测试用开始前执行一次,用于检查、准备测试环境
teardown_function(function):  #每个测试用例执行完执行一次,用于清除生成的测试数据
teardown_module(module):  #每次测试完成执行一次,用于还原测试环境
@pytest.mark.parametrize(‘mycase’, case.list,ids=case.name)  #装饰器,用来将list格式的测试用例分开执行
pytest.skip("skip testcase: (%s)" % mycase['Name']) #跳过测试用例
pytest.xfail("previous test failed (%s)" % mycase['Name']) #跳过会失败的测试用例

三、测试报告
python -m pytest -s -q  控制台输出每一步结果
1.allure
安装:

sudo pip install pytest-allure-adaptor
brew tap qatools/formulas
brew install allure-commandline

执行:

python -m pytest -s -q --alluredir ./report  #控制台也输出每一步结果
python -m pytest --alluredir ./report  #控制台只输出成功/失败和失败报的错误
allure generate report/ -o report/html  #生成报告,可直接打卡看

2.pytest-html
安装:

sudo pip install pytest-html

执行:

python -m pytest -s -q --html=./report.html  #控制台也输出每一步结果

python -m pytest --html=./report.html #控制台只输出成功/失败和失败报的错误

四、Demo
# coding: utf-8
import pytest
import public
import read_testcase
import record
 
#获取一个账号token,全局变量
public.getalltoken()
#测试用例实例化
testcase=read_testcase.case()
 
#所有测试用例开始前执行的文件,只执行一次
def setup_module(module):#每次开始测试执行一次
    print ("setup_module")
#所有测试用例结束后执行的文件,只执行一次
def teardown_module(module):#每次测试完成执行一次
    print ("teardown_module")
#每个测试用开始执行一次
def setup_function(function):
    print ("setup_function")
#每个测试用例执行完执行一次
def teardown_function(function):
    print ("teardown_function")
#装饰器 pytest 整合的测试用例生成多个结果
@pytest.mark.parametrize('mycase', testcase.testcase_list,ids=testcase.testcasename)
def test_all(mycase):
    testcase=mycase['Testcase_name']+str(mycase['Testcase_ID'])+'.'+str(mycase['ID'])+":"+mycase['Name']
    #print(mycase['Name'])
    #pytest.skip("skip testcase: (%s)" % mycase['Name'])
    #pytest.xfail("previous test skip (%s)" % mycase['Name'])
    mycase = public.get_Precondition(mycase)
 
    #执行接口的测试
    r=public.request_method(mycase)
    try:
        print(r.status_code)
        print(r.json())
    except Exception as e:
        print(r.content)
        print(e)
    #对返回数据进行断言
    public.assert_method(r, mycase)
    #记录测试用例名称存储log
    record.record_testcase_name(testcase)
    #记录测试时使用的数据
    record.record_testcase_msg(mycase)

https://blog.csdn.net/u013511989/article/details/79755030

你可能感兴趣的:(自动化测试,Python)