Interface testing with unittest+ddt (1): Use yaml files to manage test data

After knowing the basic usage of ddt, practice changing the interface test cases that were previously maintained with excel files to unittest+ddt.

Here I choose yaml file to manage interface parameters. I originally wanted to use json, but json cannot add comments, so the readability is not good.

1. Add data to the yaml file

The screenshot below shows each interface in the interface document, each interface has a fixed serial number, so when designing the test data of each interface, the serial number is used to distinguish different interfaces

The content of the yaml file is as follows. It should be noted that the syntax of yaml is:

(1) The key-value pair is separated by a colon, but a space needs to be added after the colon

(2) Tab indentation is prohibited, only the space bar can be used; there is no limit to the indentation length, as long as the elements are aligned, it means that these elements belong to one level

(3) Strings can be marked without quotation marks, or they can be added with quotation marks. If you want to turn numbers into strings, you can add quotation marks.

(4) Use # to indicate comments

For details, please refer to the blog: https://blog.csdn.net/vincent_hbl/article/details/75411243

2. Simple demo: python reads the yaml file and takes out the interface parameters

import yaml

fp = open( ' ../dataconfig/information interaction module interface.yaml ' , encoding= ' utf-8 ' ) # If there are Chinese characters, add the encoding format
testdata = yaml.load (fp)
t = testdata['5.2.1.4']
print(t)

3. Complete process

(1) Encapsulate the method of reading yaml files

handle_yaml.py

import yaml

class HandleYaml:
    def __init__(self, file_path=None):
        if file_path:
            self.file_path = file_path
        else:
            self.file_path = ' E:/DDT_Interface/dataconfig/Information interaction module interface.yaml ' 
        # ​​self.data = self.get_data()

    def get_data(self):
        fp = open(self.file_path, encoding='utf-8')
        data = yaml.load(fp)
        return data


if __name__ == '__main__':
    test = HandleYaml()
    p = test.get_data()
    print(p['5.2.1.1'])

(2) Encapsulate the requests request method

# coding: utf-8
# author: Archer

import requests
import json


class RunMethod:
    def post_main(self, url, data, header=None):if header is not None:
             res = requests.post(url=url, data=data, headers=header)
        else:
            res = requests.post(url=url, data= data)
         # print(res.status_code) 
        # return res.json() 
        return res #To facilitate subsequent assertions, the server response is no longer encoded in json format

    def get_main(self, url, data=None, header=None):if header is not None:
            res = requests.get(url=url, params=data, headers=header)
        else:
            res = requests.get(url=url, params=data)
            print(res.status_code)
        # return res.json()
        return res

    def run_main(self, method, url, data=None, header=None):if method == 'POST':
            res = self.post_main(url, data, header)
        else:
            res = self.get_main(url, data, header)
         return res
         # return json.dumps(res, indent=2, sort_keys=False, ensure_ascii=False) # Use the json module to format the display results

(3) An interface test case

# coding: utf-8
# author: Archer

import unittest
import ddt
from base.run_method import RunMethod
from utils.handle_yaml import HandleYaml

get_data = HandleYaml() #Get   the parameters of the interface from the yaml file 
params = get_data.get_data()[ ' 5.2.1.4 ' ]


@ddt.ddt
class Test(unittest.TestCase):
     """ Load consultation details interface """

    def setUp(self):
        self.url = 'http://localhost:8088/ApprExclusiveInterface/api/enterprise/info/consult/loadDetail.v'
        self.run = RunMethod()

    @ddt.data(*params)
    def test(self, value):
        r = self.run.run_main("GET", self.url, value)
        print(r)
        self.assertTrue(value['assert'] in r.text)


if __name__ == '__main__':
    unittest.main()

(4) Use HTMLTestRunner to generate test reports

run_report.py

# coding: utf-8
# author: hmk

from HTMLTestRunner import HTMLTestRunner
import unittest
import time

case_dir = ' ../test_case/ '   #define the path where the case is located

"""定义discover方法"""
discover = unittest.defaultTestLoader.discover(case_dir,
                                               pattern='test*.py',
                                               top_level_dir=None)
"""
1.case_dir is the directory where the test case is located
2.pattern='test_*.py' : Indicates the matching principle of the use case file name, "*" represents any number of characters
3.top_level_dir=None: The top directory of the test module. If there is no top-level directory (that is, the test cases are not placed in a multi-level directory)
medium), the default is None
"""

if __name__ == "__main__":
    """直接加载discover"""
    now = time.strftime("%Y-%m-%d %H_%M_%S")
    filename = '../report/' + now + '_result.html'
    fp = open(filename, 'wb')
    runner = HTMLTestRunner(stream=fp,
                            title = ' Personal network enterprise network interface test report ' ,
                            description='Implementation Example with: ')
    runner.run(discover)
    fp.close()

ok, the interface test with unittest+ddt is completed. There are still many shortcomings. The yaml configuration file can continue to be designed and optimized. For example, the request url can be added.

In fact, how to design test cases and organize test data is also a very interesting thing. Many things must have a good design idea before they can go smoothly. In short, be diligent in thinking and refer to the ideas of others. Isn't there a saying, learning without thinking is worthless, thinking without learning is perilous.


2018-04-29 12:53:22

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=325117949&siteId=291194637