测试人社区

20200925 如何使用python如何去做接口自动化测试?

参考资料

安装

  1. pip 安装
    pip install requests
  2. pycharm 安装

使用

import requests

# 发送get请求
def test_get():
    url = "http://httpbin.ceshiren.com/get"
    r = requests.get(url)
    # text 自动解码服务器的响应数据
    print(r.text)
    # content 字节的方式展示响应数据
    print(r.content)
    # json 直接返回一个字典
    print(r.json())
    # 返回原始的内存地址
    print(r.raw)

# 获取响应的状态码
def test_status_code():
    url = "http://httpbin.ceshiren.com/get"
    r = requests.get(url)
    print(r.status_code)
    assert r.status_code == 200

# 获取响应头信息
def test_get_header():
    url = "http://httpbin.ceshiren.com/get"
    r = requests.get(url)
    print(r.headers)
    print(r.headers["Content-Type"])
    print(r.headers.get("Content-Type"))

# 发送带参数的get请求
def test_get_params():
    url = "http://httpbin.ceshiren.com/get"
    data = {
        "key1": "value1",
        "key2": ["value2", "value3"]
    }
    r = requests.get(url, params=data)
    print(r.text)

# 定制请求头信息
def test_headers():
    url = "http://httpbin.ceshiren.com/get"
    headers = {
        "User-Agent": "feier"
    }
    r = requests.get(url, headers=headers)
    print(r.text)

# 发送post请求
def test_post():
    url = "http://httpbin.ceshiren.com/post"
    r = requests.post(url)
    print(r.text)

# post请求传递表单
def test_post_data():
    url = "http://httpbin.ceshiren.com/post"
    data = {
        "key1": "value1",
        "key2": "value2"
    }
    r = requests.post(url, data=data)
    print(r.text)

# post 请求传递json格式参数
def test_post_json():
    url = "http://httpbin.ceshiren.com/post"
    data = {
        "key1": "value1",
        "key2": "value2"
    }
    r = requests.post(url, json=data)
    print(r.text)

# post 请求上传文件
def test_post_file():
    url = "http://httpbin.ceshiren.com/post"
    file_name = "file.txt"
    files = {
        'file': open(file_name, 'rb')
    }
    r = requests.post(url, files=files)
    print(r.text)

# 访问cookie
def test_get_cookie():
    url = "https://www.baidu.com"
    r = requests.get(url)
    print(r.cookies)

# 设置cookie
def test_set_cookie():
    url = "http://httpbin.ceshiren.com/cookies/set"
    cookies = {
        "my_cookie": "hogwarts"
    }
    r = requests.get(url, cookies=cookies)
    print(r.text)