使用Python实现接口自动化测试

1,548 阅读1分钟

很多时候我们使用第三方工具进行接口测试的需要自己手动操作,在某些情况下是比较费劲费时间的,我们其实可以自己编写程序来对接口进行自动化测试

下面我们用Python实现对接口进行周期性自动测试,这里我使用PyCharm开发工具编写程序,源代码如下:

# 导入必要的库,引入后才可以在你的代码中使用对应的类以及成员函数
import requests
import time

# 新建目标接口url变量
url_hello = 'http://116.85.59.109/hello'

# 每隔3秒请求一次接口,请求10次
for n in range(0, 10):
    # 调用requests类的get方法,也就是HTTP的GET请求方式,访问了url_hello指向的地址,返回结果存到了response_hello中
    response_hello = requests.get(url_hello)
    response_hello.encoding = 'utf-8'
    # response_hello对象的text属性存储了访问接口的response信息,下面打印输出
    print('response内容:' + response_hello.text)
    # 线程休眠3秒钟
    time.sleep(3)

下面运行测试程序,可以看到,程序会每隔3秒请求一次接口,请求10次

image.png