Python接口自动化是指使用Python编写脚本来自动化测试和调用接口的过程。Python是一种简单易学的编程语言,具备丰富的第三方库和工具,使其成为接口自动化测试的首选语言。
一、环境搭建
1、安装Python:下载Python的最新版本,并按照安装向导进行安装。
print("Hello, World!")
2、安装依赖库:使用pip命令安装requests、jsonpath等必要的依赖库。
pip install requests
pip install jsonpath
二、接口调用
1、发送GET请求:通过requests库发送GET请求,并使用jsonpath解析返回的响应数据。
import requests
import jsonpath
url = "https://api.example.com/users"
response = requests.get(url)
data = response.json()
usernames = jsonpath.jsonpath(data, "$..username")
print(usernames)
2、发送POST请求:通过requests库发送POST请求,并使用jsonpath解析返回的响应数据。
import requests
import jsonpath
url = "https://api.example.com/login"
data = {
"username": "example",
"password": "password"
}
response = requests.post(url, data=data)
token = jsonpath.jsonpath(response.json(), "$.token")
print(token)
三、断言和报告
1、断言响应数据:使用assert语句对接口返回的数据进行断言,判断接口是否返回了预期的结果。
import requests
response = requests.get("https://api.example.com/users")
assert response.status_code == 200
assert response.json()["code"] == 0
2、生成测试报告:使用HTMLTestRunner等第三方库生成漂亮的测试报告,方便查看测试结果。
import unittest
import HTMLTestRunner
class APITest(unittest.TestCase):
def test_login(self):
# Test login API
pass
def test_get_users(self):
# Test get users API
pass
if __name__ == '__main__':
suite = unittest.TestLoader().loadTestsFromTestCase(APITest)
with open('test_report.html', 'wb') as report_file:
runner = HTMLTestRunner.HTMLTestRunner(stream=report_file)
runner.run(suite)
四、数据驱动测试
1、使用Excel作为数据源:通过读取Excel文件中的测试数据,编写循环来执行接口测试并生成测试报告。
import requests
import xlrd
def read_excel():
# Read test data from Excel
pass
def run_test(url, data):
# Run test with given data
pass
def generate_report():
# Generate test report
pass
test_data = read_excel()
for data in test_data:
run_test(data['url'], data['data'])
generate_report()
2、使用CSV作为数据源:类似Excel,通过读取CSV文件中的测试数据来执行接口测试。
import requests
import csv
def read_csv():
# Read test data from CSV
pass
def run_test(url, data):
# Run test with given data
pass
def generate_report():
# Generate test report
pass
test_data = read_csv()
for data in test_data:
run_test(data['url'], data['data'])
generate_report()
五、性能测试
1、使用Locust进行性能测试:使用Locust库编写测试脚本,并使用其内置的Web界面来监控接口的性能。
from locust import HttpUser, task, between
class APIUser(HttpUser):
wait_time = between(1, 3)
@task
def test_get_users(self):
self.client.get("/users")
@task
def test_post_data(self):
self.client.post("/data", json={"name": "example"})
if __name__ == '__main__':
APIUser.locustfile = "test_script.py"
APIUser.host = "https://api.example.com"
APIUser.run()
2、使用wrk进行压力测试:使用wrk命令行工具进行压力测试,并生成报告以分析接口的性能。
wrk -t4 -c100 -d10s -H "Authorization: Bearer {token}" -s test_script.lua https://api.example.com/users
以上是关于Python接口自动化的一些介绍和示例代码,通过使用Python编写脚本实现接口自动化测试和调用,可以提升开发效率和测试准确性。