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)
---------------------


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM