首页 > 解决方案 > 使用 pytest 时 API POST 调用抛出 401 错误

问题描述

我正在执行 API 测试并使用 pytest 框架。测试一直失败,出现 401 错误。无法弄清楚是什么问题。

这是代码:

    import requests
    import json,jsonpath
    import urllib3
    import constants
    urllib3.disable_warnings(urllib3.exceptions.InsecureRequestWarning)
    
    # variables
    dumpFile = "somepath"
    url = "someUrl"
    headers = {'Authorization' : constants.consts['siteToken'],
           'accept':'application/json',
           'content-type':'application/json'}
    #siteToken = 'Bearer jwt token'
    
    # read json input file
    input_file = open("json file path", 'r')
    json_input = input_file.read()
    request_json = json.loads(json_input)
    
    # make POST request with JSON Input Body
    r = requests.post(url, request_json, headers=headers)
    
    # Verification of the response
    assert r.status_code == 200

 def test_json_result():
    # fetch header from response
    print(r.headers.get("Date"))
    
    # parse response to JSON Format
    response_json = json.loads(r.text)
    
    # validate response using Json Path
    name = jsonpath.jsonpath(response_json, 'name')
    print(name)

标签: pythonapipytest

解决方案


我通过输入 json=your_payload 解决了这个问题。

        import requests
        import json,jsonpath
        import urllib3
        import constants
        urllib3.disable_warnings(urllib3.exceptions.InsecureRequestWarning)

        # variables
        dumpFile = "somepath"
        url = "someUrl"
        headers = {'Authorization' : constants.consts['siteToken'],
               'accept':'application/json',
               'content-type':'application/json'}
        #siteToken = 'Bearer jwt token'

        # read json input file
        input_file = open("json file path", 'r')
        json_input = input_file.read()
        request_json = json.loads(json_input)

    def test_json_result():
# make POST request with JSON Input Body
        r = requests.post(url, json=request_json, headers=headers)

        # Verification of the response
        assert r.status_code == 200
        # fetch header from response
        print(r.headers.get("Date"))

        # parse response to JSON Format
        response_json = json.loads(r.text)

        # validate response using Json Path
        name = jsonpath.jsonpath(response_json, 'name')
        print(name)

推荐阅读