directory

  • apiAutoTest

  • The current function

  • Major updates (personal opinion)

  • This update

    • An opportunity to

    • The fundamental

    • How to record

      • Recorded use cases
    • Execute recorded use cases

      • The execution result
    • Realize the source

  • The resources

apiAutoTest

ApiAutoTest is an interface testing tool project involving individuals and a number of testing peers (providing new requirements).

Gitee: gitee.com/zy7y/apiAut…

Making: github.com/zy7y/apiAut…

The current function

  • [x] Before and after the test database backup operation, personal understanding of data cleaning
  • [x] Test data dependencies between interfaces
  • [x] Custom extension function definition, solve part of the encryption algorithm
  • [x] post-sql, resulting in dependencies or assertions (The SELECT statement can only find the first one) 1. * *
  • [X] Actual results can be extracted dynamically, and expected results absolutely= =
  • [x] Optional case failure rerun mechanism
  • [x] Generate use-case files based on mitmProxy recording interface

Major updates (personal opinion)

${} = ${} = ${} = ${} = ${}

${} is used for both dependent and custom methods. To avoid redundancy in the use case of extracting jSONPath expressions every time another interface returns (and perhaps improve performance, as previous versions saved the entire response), extracting parameters are added to the use case in the form shown below

{
    ${id} ${id} ${id}
    "id": "$.data.id" // $.data.id actually extracts the id value from the current response for the jsonPATH expression
}
Copy the code

Related documentation: Check out the online documentation in the source readme. md file

This update

** This update uses the demo video: Click to visit station B **

An opportunity to

Some comrades wish to have a recording function to reduce the time of writing parameters

The fundamental

Based on mitmProxy, the packet capture wechat applets use the extended API provided by mitmProxy to realize the proxy and capture the HTTP/HTTPS request, and add the appended form of the request to Excel. When the recording is completed, be sure to use CTRL + C to close the recording. A completed use case data file will be generated

You can specify the recording interface that contains the request address

How to record

  1. Precondition: www.cnblogs.com/zy7y/p/1479…

  2. Open the local agent

  3. Modify tools\recording.py to configure the packet capture request address and use case generation path

  4. ApiAutoTest run in the root directory

    mitmweb -s tools\recording.py
    Copy the code

  5. Just use it normally, Ctrl + C in the above window to stop recording when no longer needed, then close the local agent

Recorded use cases

** Because the default recorded URL is a complete URL, so if you use this file directly, please change the serve dev base address in config/config.yaml to “”. At present, I have personally tested the recording of Graphql** standard interface and the recording of RestFul standard interface. It is not ruled out that other use case files cannot be completely generated

Note the Excel cell character limit problem. The Graphql specification interface is very prone to writing problems, which should not occur from the business interface alone

Execute recorded use cases

config/config.yamlModify base Addressdevfor""To specify the use case files to use for recording

server:
  # Local interface service
  test: http://127.0.0.1:8888/
  # https://space.bilibili.com/283273603 demo project from the back-end service
# dev: http://www.ysqorz.top:8888/api/private/v1/
  dev: ' '
Baseline request header information
request_headers: {}
file_path:
  test_case: data/case_data1.xls	# specify which use case to use. Recorded use cases are used here
  report: report/
  log: log/run{time}.log
.
Copy the code

The execution result

Realize the source

#! /usr/bin/env/ python3
# -*- coding:utf-8 -*-
""" @Project: apiAutoTest @File :recording.py @Author:zy7y @Date :2021/5/21 22:07 @Desc : Record interface, generate use case file based on MITmProxy implementation reference:  https://blog.wolfogre.com/posts/usage-of-mitmproxy/ https://www.cnblogs.com/liuwanqiu/p/10697373.html """

import json

import mitmproxy.http
import xlwt

Exception: String longer than 32767 characters Exception: String longer than 32767 characters
from mitmproxy import ctx


class Counter:
    def __init__(self, filter_url: str, filename: str = "data/case_data1.xls") :
        Generate use case data based on mitmProxy packet capture :param filter_URL: url to be filtered :param filename: path to generate use case file
        self.url = filter_url
        self.excel_row = [
            'number'.'Use Case Title'.'Request header'.'Interface address'.'Executed or not'.'Request mode'.'Input keyword'.'Upload file'.'Request data'.'Extract parameters'.'the rear SQL'.'Expected Results']
        self.cases = [self.excel_row]
        self.counter = 1
        self.file = filename

    def response(self, flow: mitmproxy.http.HTTPFlow) :
        """ MitmProxy packet capture processing response, here summarizes the required data :param flow: :return: ""
        if self.url in flow.request.url:
            # number
            number = "C" + str(self.counter)
            # titles
            title = "Mitmproxy recording interface" + str(self.counter)
            try:
                token = flow.request.headers["Authorization"]
            except KeyError:
                token = ' '
            header = json.dumps({"Authorization": token})
            data = flow.request.text
            # request address, config.yaml reference environment address write empty string
            method = flow.request.method.lower()
            url = flow.request.url
            try:
                content_type = flow.request.headers['Content-Type']
            except KeyError:
                content_type = ' '
            if 'form' in content_type:
                data_type = "data"
            elif 'json' in content_type:
                data_type = 'json'
            else:
                data_type = 'params'
                if '? ' in url:
                    data = url.split('? ') [1]
            data = self.handle_form(data)
            # Expected results
            expect = json.dumps(
                {".": json.loads(flow.response.text)}, ensure_ascii=False)

            # log
            ctx.log.info(url)
            ctx.log.info(header)
            ctx.log.info(content_type)
            ctx.log.info(method)
            ctx.log.info(data)
            ctx.log.info(flow.response.text)
            case = [
                number,
                title,
                header,
                url.split('? ') [0]."Yes",
                method,
                data_type,
                "",
                data,
                ""."",
                expect]
            self.cases.append(case)
            self.counter += 1
            # Append to end of file
            self.excel_cases()

    def excel_cases(self) :
        """ Loops through the two-dimensional list of cases and writes them to cells :return: """
        workbook = xlwt.Workbook()
        worksheet = workbook.add_sheet('Use Case Data')
        for x in range(len(self.cases)):
            for y in range(len(self.cases[x])):
                worksheet.write(x, y, self.cases[x][y])
        try:
            workbook.save(self.file)
        except Exception as e:
            print(e)

    def handle_form(self, data: str) :
        Content-type: application/x-www-form-urlencoded default generated data username=admin&password=123456 :param data: application/x-www-form-urlencoded default generated data username=admin&password=123456 :param data: Username =admin&password=123456 :return: ""
        data_dict = {}
        if data.startswith('{') and data.endswith('} ') :return data
        try:
            for i in data.split('&'):
                data_dict[i.split('=') [0]] = i.split('=') [1]
            return json.dumps(data_dict)
        except IndexError:
            return ' '


addons = [
    Counter("http://www.ysqorz.top:8888/api/private/v1/")]""" MitmWeb -s tools records. py starts CTRL + C to stop and generate a complete use case ""
Copy the code

The resources

Docs.mitmproxy.org/stable/ blog.wolfogre.com/posts/usage… www.cnblogs.com/liuwanqiu/p…