大话性能 python 新手学习 - 必须掌握的 Python Requests 库接口测试

大话性能 · September 08, 2023 · 2735 hits

在进行接口测试时,Python requests 库是一个非常方便的工具。下面,我会详细描述使用 Python requests 库进行接口测试的全过程,并提供相应的代码实例。

更多内容可以学习《测试工程师 Python 工具开发实战》书籍《大话性能测试 JMeter 实战》书籍

1. 安装 Python requests 库

在使用 Python requests 库进行接口测试之前,需要先安装该库。可以使用以下命令在命令行中安装:

pip install requests

2. 发送请求

使用 Python requests 库发送请求非常简单,只需要调用 requests 库中的 get、post 等方法即可。以发送一个 GET 请求为例:

import requests
# 发送GET请求
response = requests.get('https://jsonplaceholder.typicode.com/posts/1')

# 输出响应内容
print(response.content)

以上代码会发送一个 GET 请求,并输出响应内容。其中,https://jsonplaceholder.typicode.com/posts/1URL。是请求的

3. 添加请求头

在进行接口测试时,通常需要添加请求头。可以使用 requests 库中的 headers 参数来添加请求头。以添加一个 User-Agent 请求头为例:

import requests
# 添加User-Agent请求头
headers = {'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/58.0.3029.110 Safari/537.3'}
# 发送GET请求
response = requests.get('https://jsonplaceholder.typicode.com/posts/1', headers=headers)
# 输出响应内容
print(response.content)

以上代码会添加一个 User-Agent 请求头,并发送一个 GET 请求。

4. 添加请求参数

在进行接口测试时,通常需要添加请求参数。可以使用 requests 库中的 params 参数来添加请求参数。以添加一个 id 参数为 1 的请求参数为例:

import requests

# 添加请求参数
params = {'id': 1}

# 发送GET请求
response = requests.get('https://jsonplaceholder.typicode.com/posts', params=params)

# 输出响应内容
print(response.content)

以上代码会添加一个 id 为 1 的请求参数,并发送一个 GET 请求。

5. 发送 POST 请求

在进行接口测试时,通常需要发送 POST 请求。可以使用 requests 库中的 post 方法来发送 POST 请求。以发送一个 JSON 格式的 POST 请求为例:

import requests
import json
# 请求头
headers = {'Content-Type': 'application/json'}
# 请求参数
data = {'title': 'foo', 'body': 'bar', 'userId': 1}
# 发送POST请求
response = requests.post('https://jsonplaceholder.typicode.com/posts', headers=headers, data=json.dumps(data))
# 输出响应内容
print(response.content)

以上代码会发送一个 JSON 格式的 POST 请求,并输出响应内容。

6. 断言响应内容

在进行接口测试时,通常需要对响应内容进行断言。可以使用 Python 自带的 unittest 库或第三方的 pytest 库等进行断言。以使用 unittest 库进行断言为例:

import requests
import unittest

class TestApi(unittest.TestCase):
    def test_get_post(self):
        # 发送GET请求
        response = requests.get('https://jsonplaceholder.typicode.com/posts/1')

        # 断言响应状态码是否为200
        self.assertEqual(response.status_code, 200)
        # 断言响应内容是否包含"title"
        self.assertIn('title', response.json())

if __name__ == '__main__':
    unittest.main()

以上代码会发送一个 GET 请求,并断言响应状态码和响应内容。

总之,使用 Python requests 库进行接口测试非常方便和灵活,可以根据实际需要进行添加请求头、请求参数、发送 POST 请求等操作,并使用 unittest 库或 pytest 库等进行断言。
更多内容可以学习《测试工程师 Python 工具开发实战》书籍《大话性能测试 JMeter 实战》书籍

No Reply at the moment.
需要 Sign In 后方可回复, 如果你还没有账号请点击这里 Sign Up