测试人社区

20201021_用python做接口自动化测试

参考资料

课堂演练代码

# -*- coding: utf-8 -*-
# @Time    : 2020-10-21 20:07
# @Author  : feier
# @File    : test_interface.py



import requests

# 第一个接口请求
def test_requests():
    # 定义变量 r 接收请求的响应数据
    # 快速导包:alt+enter
    # 调用get方法,发起一次请求
    r = requests.get("https://ceshiren.com/categories.json")
    # 获取响应状态码
    print(r.status_code)
    # 获取响应内容
    print(r.json())
    # 断言,判断响应状态码是否等于200
    assert r.status_code == 200


# 发起带query的get请求
def test_get_query():
    url = "http://httpbin.ceshiren.com/get"
    data = {
        "a": 1,
        "b": 2,
        "c": "ccccc"
    }
    r = requests.get(url, params=data)
    print(r.text)
    assert r.status_code == 200

# post请求,form表单
def test_post_form():
    url = "http://httpbin.ceshiren.com/post"
    # 定义请求参数,字典格式
    data = {
        "a": 1,
        "b": 2,
        "c": "ccccc"
    }
    # 发起post请求
    r = requests.post(url, data=data)
    # 打印json格式的响应数据
    print(r.text)
    assert r.status_code == 200

# post请求,上传文件
def test_post_upload():
    url = "http://httpbin.ceshiren.com/post"
    # 定义文件
    file = {
        "file": open("file.txt",'rb')
    }
    # 定义头信息
    header = {
        "Name": "hogwarts"
    }
    # 通过headers传入头信息
    r = requests.post(url, files=file, headers=header)
    print(r.text)
    assert r.status_code == 200


# post请求,传递json格式数据
def test_post_json():
    proxies = {
        "http": "http://127.0.0.1:8888",
        "https": "http://127.0.0.1:8888",
    }
    url = "http://httpbin.ceshiren.com/post"
    # 定义请求参数,字典格式
    data = {
        "a": 1,
        "b": 2,
        "c": "ccccc"
    }
    r = requests.post(url, json=data, proxies=proxies)
    print(r.text)
    assert r.status_code == 200

# 设置cookie
def test_set_cookie():
    url = "http://httpbin.ceshiren.com/cookies/set"
    # 定义cookie,字典格式
    cookie = {
        "my_cookie": "lagou"
    }
    r = requests.get(url, cookies=cookie)
    print(r.text)
    assert r.status_code == 200

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

# 加代理
def test_proxy():
    proxies = {
        "http": "http://127.0.0.1:8888",
        "https": "http://127.0.0.1:8888",
    }

    url = "https://httpbin.ceshiren.com/get"

    data = {
        "query": 1111
    }

    r = requests.get(url, params=data, proxies=proxies, verify=False)
    print(r.text)