Pytest-接口請求實例(GET單參數和參數化請求)


對v2ex網址查看論壇節點信息的api進行測試

請求內容如下:

Url:https://www.v2ex.com/api/nodes/show.json
Method:GET
Authentication:None
請求參數:name:節點名稱

返回結果如下:

{
    "avatar_large": "https://cdn.v2ex.com/navatar/8613/985e/90_large.png?m=1610084956",
    "name": "python",
    "avatar_normal": "https://cdn.v2ex.com/navatar/8613/985e/90_normal.png?m=1610084956",
    "title": "Python",
    "url": "https://www.v2ex.com/go/python",
    "topics": 14187,
    "footer": "",
    "header": "這里討論各種 Python 語言編程話題,也包括 Django,Tornado 等框架的討論。這里是一個能夠幫助你解決實際問題的地方。",
    "title_alternative": "Python",
    "avatar_mini": "https://cdn.v2ex.com/navatar/8613/985e/90_mini.png?m=1610084956",
    "stars": 9498,
    "aliases": [],
    "root": false,
    "id": 90,
    "parent_node_name": "programming"
}

分析:

接口測試主要驗證數據的正確性

代碼實現

import requests

class TestApi(object):
    domian = 'https://www.v2ex.com/'

    def test_node1(self):
        path = 'api/nodes/show.json?name=python'
        url = self.domian + path
        res = requests.get(url).json()
        assert res["name"] == "python"
        assert res["id"] == 90

這只是固定一個name進行請求,如果多個name呢:

代碼如下

import requests
import pytest
class TestV2exApi(object):
    domian = 'https://www.v2ex.com/'

    @pytest.fixture(params=['python','java','go','nodejs'])
    def lang(self,request):
        return request.param

    def test_node(self,lang):
        path = 'api/nodes/show.json?name=%s' %lang
        url = self.domian + path
        res = requests.get(url).json()
        assert res["name"] == lang
        assert 0 #模擬錯誤請求,查看具體參數值

如果要多個參數字段時,代碼如下

import requests
import pytest

class TestApiWithExpectation(object):
    domain = 'https://www.v2ex.com/'

    @pytest.mark.parametrize('name,node_id',[('python',90),('java', 63), ('go', 375), ('nodejs', 436)])
    def test_node2(self,name,node_id):
        path = 'api/nodes/show.json?name=%s' %(name)
        url = self.domain + path
        res = requests.get(url).json()
        assert res['name'] == name
        assert res['id'] == node_id
        assert 0

 


免責聲明!

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



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