快速API自动化测试

  • 2019 年 11 月 30 日
  • 筆記

我们平时写API,时效性太慢了。而且花费的成本代价太高。特别是有严重的滞后性。当平台多,业务多,迭代多的时候,接口自动化实现出来的时候,黄花菜都凉了。

有没有一个方式能够快速测试API呢?

最近实践了一下httprunner, 可以作为我们的API自动化测试的一个补充,高低搭配。

HttpRunner 是一个基于 Python 开发的测试框架,可以运行在 macOS、Linux、Windows 系统平台上。

它的原理也很简单 总体的思想就是用代理工具录制,然后生成我们常见的json格式,通过设置变量,替换一些常量,加上一些验证点,批量发送请求,生成测试报告,从而达到测试接口的目的。

安装:

pip install httprunnerorpip install -U HttpRunner

录制:

用charles录制,保存成har文件格式。

运行:

生成用例har2case Documents/cae1/UAT_Cool.harhar2case Documents/cae1/UAT_Cool.har -2y  运行用例hrun Documents/cae1/UAT_Cool.jsonhrun Documents/cae1/UAT_Cool.yml

image.png

然后就可以在report中看测试报告了。

以上是一个很简单的过程,一般对于正规的测试框架来说,我们需要继续以下一些步骤来整理我们的数据。

整理

生成测试用例 参数关联 变量声明与应用 抽取公共变量 参数化数据 优化测试结果

对于有些变量,需要上下文的,这个框架可以用extract来获取,然后用变量替换

这个过程如果用手工的话,比较麻烦,可以写个脚本来自动实现

import reimport json    json_file = "/Users/anderson/work/api/case1/UAT_Cool.json"    def rewrite_file():    with open(json_file, 'r') as load_f:        load_dict = json.load(load_f)          load_dict["config"]["base_url"] = "http://m.cn"        load_dict["config"]["verify"] = False        value = {"userName": "t74951", "password": "111111"}        (load_dict["config"]["variables"]).update(value)          if "name" in load_dict["teststeps"][0]:            load_dict["teststeps"][0]["extract"] = [                {"token": "content.serviceResponse.token", "sessionId": "content.serviceResponse.sessionId"}]            if "userName" and "password" in load_dict["teststeps"][0]["request"]["json"][            "serviceRequest"]:            load_dict["teststeps"][0]["request"]["json"]["serviceRequest"]["userName"] = "$userName"            load_dict["teststeps"][0]["request"]["json"]["serviceRequest"]["password"] = "$password"      for i in range(len(load_dict["teststeps"])):        if "url" in load_dict["teststeps"][i]["request"]:            load_dict["teststeps"][i]["request"]["url"] = re.sub("[a-zA-z]+://.*.(com|cn)", "",                                                                 load_dict["teststeps"][i]["request"]["url"])      str = json.dumps(load_dict)    obj = re.compile(r'"sessionId": "(w+)"')    ret = obj.findall(str)    for i in ret:        str = str.replace(i, "$sessionId")      obj = re.compile(r'"token": "(w+)"')    ret = obj.findall(str)    for i in ret:        str = str.replace(i, "$token")      str = json.loads(str)      with open(json_file, "w") as dump_f:        json.dump(str, dump_f, indent=4)    rewrite_file()

增加checkpoint:

现在还有一个问题,就是checkpoint太少了,只是检测了状态是否200,如果手动增加,则太慢了。有一个办法就是自动增加。可以写yaml文件,将需要检测的部分,都放到文件里面。例如:

oneapp:  coursestructure:    api: /services/api/mobile/service/coursestructure    eq:       - ["content.serviceResponse.level.levelCode", "0A"]
import jsonimport osimport reimport shutil  har_dir = '/Users/anderson/Documents/case1'json_dir = '/Users/anderson/Documents/case1'  import json  import yaml    class YAML():    # Write YAML file    def write_yml(self, save_path, data):        with open(save_path, 'w', encoding='utf8') as outfile:            try:                yaml.safe_dump(data, outfile, default_flow_style=False, allow_unicode=True)            except yaml.YAMLError as exc:                print(exc)                  # Read YAML file      def read_yml(self, load_path):        with open(load_path, 'r') as stream:            try:                data_loaded = yaml.safe_load(stream)            except yaml.YAMLError as exc:                print(exc)        return data_loaded    def add_checkpoint(target_file):    file_path = "/Users/anderson/Documents/api.yml"    yaml_file = YAML().read_yml(file_path)["oneapp"]      json_raw = open(target_file, "r")      json_file=json.loads(json_raw.read())    print(json_file)    name_list = []    for i, ele in enumerate(json_file["teststeps"]):        name_list.append(ele["name"])      for key in yaml_file.keys():        if yaml_file[key]["api"] in name_list:            index = name_list.index(yaml_file[key]["api"])              if len(yaml_file[key]["eq"]):                for checks in yaml_file[key]["eq"]:                    (json_file["teststeps"][index]["validate"]).append({"eq": checks})      # json_file = json.dumps(json_file, indent=4)    with open(target_file, "w") as dump_f:        json.dump(json_file, dump_f, indent=4)      print(json_file)    json_raw.close()    def run_case(path):    run_cmd = "hrun {} --failfast --log-level info".format(path)    os.system(run_cmd)    # rewrite_file()  if __name__ == "__main__":      #check_folder(json_dir)    extract_har(har_dir)    source_json = [x for x in os.listdir(har_dir) if x.endswith('json')]    if len(source_json):        for source in source_json:            rewrite_file(os.path.join(har_dir, source), os.path.join(json_dir, source))      target= os.path.join(json_dir, source_json[0])    print(target)    add_checkpoint(target)      if is_json_exist:        json_file = [x for x in os.listdir(json_dir) if x.endswith('json')]          for source in json_file:            run_case(os.path.join(json_dir, source))

我们可以写个脚本,自动增加需要测试的点,效率增加很多。

这样,生成的report里面也可以看到这个checkpoint点了。

管理case:

工具用了一个命令来管理case. 按照这种格式,就很容易管理case了。

如果有多个环境的话,再增加一点代码,用来数据管理和环境管理,可以结合jenkins一起使用。如果接口有变的话,重新录制一套也不需要花多少时间,这样的话,就能快速迭代了。