接口测试脚本

写了个简单的接口测试的脚本,实现的功能是:

  • 多个接口,多组参数值测试
  • 打印url、输入参数、断言内容
  • 断言正确就返回结果Pass,断言错误就返回结果Fail,最后统计通过和失败的用例数

数据、程序分离,详情如下:

程序:

#encoding=utf-8
# e5 多接口多参数组合
# R  2018/11/2 23:22

import requests
import json
import os
import hashlib
import pickle
from conf import *   # 文件,定义register,url

static_data={}
pass_num=0
fail_num=0
total_num=0

def send_request(interface,value):
    r = requests.post(interface,data=value)
    return r

def print_response_info(response_obj):
    print("测试url是:    ",interface)
    print("测试参数是:   ",value)
    print("断言内容:     ",assert_content)
    print()
    print("返回码是:     ",response_obj.status_code)
    print("返回字符串是: ",response_obj.text)

def assert_response(response_obj,assert_content):
    try:
        assert assert_content in response_obj.text
        return 1
    except:
        return 0  

with open(r"D:\data\test_data.txt",'r+') as f:
    for line in f:
        no=eval(line.split("|")[0])
        interface=eval(line.split("|")[1])
        value=json.dumps(eval(line.split("|")[2]))
        assert_content= line.strip().split("|")[3]
        
        print('..............register',no,'..............')
        print()
        r = send_request(interface,value)
        print_response_info(r)
        assert_response(r,assert_content)
        flag = assert_response(r,assert_content)  # 要把返回值传回来,否则flag一直是0

        # 判断并统计正确、错误的个数
        if flag==1:
            pass_num +=1
            print ("测试结果:      Pass")
        elif flag==0:
            print ("测试结果:      Fail")
            fail_num +=1  
        print()

total_num=pass_num+fail_num
print ("本次接口测试共执行用例:%d, 通过:%d, 失败:%d " %(total_num,pass_num,fail_num))

数据:

  • 一个文档conf.py 写url: (与脚本在同一路径下)

# -*- coding: cp936 -*-

ip="xxxx"

port="8080"

# 定义多个接口url

register="http://"+ip+":"+port+"/register/"

register1="http://"+ip+":"+port+"/register1/"

  • 一个文档test_data.txt 写数据:

# 定义用例号、url、输入参数、断言内容()因为是自己写用来测试的接口,返回值不是很规范,简单示意一下)

1|register|{'username': '', 'password': 'candy12345', 'email': '[email protected]'}|{"username": ""

2|register|{'username': 'candy', 'password': '', 'email': '[email protected]'}|"username": "candy",

3|registera|{'username': '', 'password': 'candy12345', 'email': '[email protected]'}|{"username": "can"

4|register1|{'username': 'candy', 'password': '', 'email': '[email protected]'}|"username": "candy",

执行结果:

猜你喜欢

转载自blog.csdn.net/test121210/article/details/83663027