程序師世界是廣大編程愛好者互助、分享、學習的平台,程序師世界有你更精彩!
首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫知識
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
您现在的位置: 程式師世界 >> 編程語言 >  >> 更多編程語言 >> Python

The latest and most complete Python implementation of HTTP interface automated test (perfect version) is useless

編輯:Python
  • Today, let's share a simple Python Script , Use python Conduct http Automated testing of interfaces , The script is simple , Logic is : Read excel Well written test cases , And then according to excel Call the use case content in , Judge whether the return value in the expected result is consistent with the value in the return message , If not, put bug Submitted to the bug Management system , the bug The management system is bugfree. Finally, count the test results : How many use cases are executed in total 、 How many use cases , How many use cases failed , Email title plus current time , Send the test results to the specified mailbox .

    Implementation steps :

                   1、 Read excel, Save the contents of the test case , Here we need to define a read excel Function of readExcel();

                   2、 according to excel The request url And parameter splicing request message , Call interface , And save the return message , Here you need to define a function that converts the requested data into a dictionary param_To_Dic();

                   3、 Read the return message , Compare with the expected results , Inconsistent going bugfree Write an entry in the database bug, And send the request message 、 The return message and test results are written into the test case excel in , Here you need to define a function that compares the expected result with the returned result contrastRes(), A to bugfree Submit bug Function of writeBug(), One writes the test results into excel Function of copy_excel(), You also need to define a function requested by the interface interfaceTest().

                   4、 Count the test results , Send a test email . Need to define a send_email() Function of .

    http The two most commonly used request methods for interfaces ,POST and GET The two methods , What this blog shares is the simplest and most commonly used url request . for example :http://192.168.21.129/bugfree/index.php/info/edit?type=bug&action=opened&product_id=1

    There are several modules that need to be used :requests、xlrd( Read excel)、xlutils( Write excel)、pymysql( Connect to database )、yagmail( Send E-mail ) These five modules are all third-party modules , You need to install it yourself .

    First, in the excel Write use cases in , Required fields project 、 Use cases id、 The name of the interface 、 Use case description 、 Request mode 、 request url、 Request data ( Multiple parameters are used & Semicolons separate )、 Expected results 、 Request message 、 Return message 、 Testers 、 test result

    First, we will build the project framework , As shown in the figure below :

    cases In the directory is put excel The test case ,conf Folders are configuration files ,lib The directory stores the main logic ,logs There are log files in the directory ,bin Under the directory is the startup file , function start.py You can run the project

    1.excel The writing format of test cases in is shown in the following figure :

    2. We write lib The main logic in , Write the required functions analyzed above in common.py in , The code is as follows :

    class OpCase(object):
    def get_case(self,file_path):
    cases = [] # Store all case
    if file_path.endswith('.xls') or file_path.endswith('.xlsx'):
    try:
    book = xlrd.open_workbook(file_path)
    sheet = book.sheet_by_index(0)
    for i in range(1,sheet.nrows):
    row_data = sheet.row_values(i)
    cases.append(row_data[4:11])
    atp_log.info(' Read together %s Use cases '%(len(cases)))
    self.file_path = file_path
    except Exception as e:
    atp_log.error('【%s】 Case acquisition failed , error message :%s'%(file_path,e))
    else:
    atp_log.error(' The use case file is illegal ,%s'%file_path)
    return cases
    def my_request(self,url,method,data=None,cookie=None,header=None,files=None,is_json=False ):
    method = method.upper()
    data = self.dataToDict(data)
    cookie = self.dataToDict(cookie)
    header = self.dataToDict(header)
    files = self.dataToDict(files)
    atp_log.debug('【files After turning into a dictionary :%s】' % files)
    data = data if data else {}
    cookie = cookie if cookie else {}
    header = header if header else {}
    if files:
    files = {
    "file":open(files['files'],"rb")
    }
    else:
    files = {}
    try :
    if method=='POST':
    try:
    if is_json:
    res = requests.post(url, json=data, cookies=cookie, headers=header, files=files,verify=False).text
    else:
    res = requests.post(url, data=data, cookies=cookie, headers=header, files=files,verify=False).text
    atp_log.debug('【 Interface returns data :%s】' % res)
    print('res...', res)
    except Exception as e:
    res = str(e) # If the interface call goes wrong , Then return a dictionary with error information
    atp_log.error(' Abnormal information : Interface call failed ! url 【%s】 data 【%s】 The actual result is 【%s】' % (url, data, res))
    elif method=='GET':
    try:
    # verify=False It means https Access to
    res = requests.get(url, params=data, cookies=cookie, headers=header, verify=False).text
    atp_log.debug('【 Interface returns data :%s】' % res)
    except Exception as e:
    res = str(e) # If the interface call goes wrong , Then return a dictionary with error information
    atp_log.error(' Abnormal information : Interface call failed ! url 【%s】 data 【%s】 The actual result is 【%s】' % (url, data,res))
    return res
    else:
    atp_log.warning(' This request method does not support ..')
    res = ' This request method does not support ..'
    except Exception as e:
    msg = '【%s】 Interface call failed ,%s'%(url,e)
    atp_log.error(msg)
    res = msg
    return res
    def check_res(self,res,check):
    res = res.replace('": "','=').replace('": ','=')
    for c in check.split(','):
    if c not in res:
    atp_log.info(' Results verification failed , Expected results :【%s】, The actual result 【%s】'%(c,res))
    return ' Failure '
    return ' success '
    def write_excel(self,cases_res):
    # [ ['dsfd'," adopt "] ,['sdfsdf',' Failure '] ]
    book = xlrd.open_workbook(self.file_path)
    new_book = copy.copy(book)
    sheet = new_book.get_sheet(0)
    row = 1
    for case_case in cases_res:
    sheet.write(row,11,case_case[0]) # Write the first 11 Column
    sheet.write(row,12,case_case[1]) # Write the first 12 Column
    row+=1
    new_book.save(self.file_path.replace('xlsx','xls'))
    def dataToDict(self,data=None):
    if data:
    # Turn the data into a dictionary
    res = {}
    data = data.split(',')
    for d in data:
    #a=
    k,v = d.split('=')
    res[k]=v
    return res

     3. Log writing module , The code is as follows :

        You can quote a simple log modular , It only needs pip install nnlog You can use , For detailed tutorials, please refer to Niuniu blog :www:nnzhp.cn/archives/646

    class MyLogger():
    def __init__(self,file_name,level='info',backCount=5,when='D'):
    logger = logging.getLogger() # Instantiate a logger object , First create an office
    logger.setLevel(self.get_level(level)) # People who set the level of logs
    cl = logging.StreamHandler() # The person responsible for outputting to the console
    bl = handlers.TimedRotatingFileHandler(filename=file_name, when=when, interval=1, backupCount=backCount, encoding='utf-8')
    fmt = logging.Formatter('%(asctime)s - %(pathname)s[line:%(lineno)d] - %(levelname)s: %(message)s')
    cl.setFormatter(fmt) # Set the log format of console output
    bl.setFormatter(fmt) # Set the log format written in the file
    logger.addHandler(cl)
    logger.addHandler(bl)
    self.logger = logger
    def get_level(self,str):
    level = {
    'debug':logging.DEBUG,
    'info':logging.INFO,
    'warn':logging.WARNING,
    'error':logging.ERROR
    }
    str = str.lower()
    return level.get(str)
    path = os.path.join(setting.LOG_PATH,setting.LOG_NAME) # Spell the absolute path of the log
    atp_log = MyLogger(path,setting.LEVEL).logger
    # Instantiate directly here , There is no need to instantiate when using 

    4. Send mail function , The code is as follows :

    def sendmail(title,content,attrs=None):
    m = yagmail.SMTP(host=setting.MAIL_HOST,user=setting.MAIL_USER
    ,password=setting.MAIL_PASSWORD,smtp_ssl=True
    )
    m.send(to=setting.TO,subject=title,
    contents=content,
    attachments=attrs)
    atp_log.info(' Sending mail completed ')

    5.conf Configure parameters in the configuration file , Detailed as follows :

    import os
    BASE_PATH = os.path.dirname(
    os.path.dirname(os.path.abspath(__file__))
    )
    MAIL_HOST='smtp.qq.com'
    MAIL_USER='[email protected]'
    MAIL_PASSWORD = 'xxxxxxxxxxx'
    TO = [
    '[email protected]',
    ]
    LEVEL = 'debug' # The level of logging
    LOG_PATH = os.path.join(BASE_PATH,'logs') # The path to store the log
    CASE_PATH = os.path.join(BASE_PATH,'cases') # The path to store the log
    LOG_NAME='atp.log' # The file name of the log 

    6. The last is bin Running files in the directory start.py, The code is as follows :

    BASE_PATH = os.path.dirname(
    os.path.dirname(os.path.abspath(__file__))
    )
    sys.path.insert(0,BASE_PATH)
    from lib.common import OpCase
    from lib.send_mail import sendmail
    from conf import setting
    class CaseRun(object):
    def find_cases(self):
    op = OpCase()
    for f in os.listdir(setting.CASE_PATH):# Read one for each cycle excel
    abs_path = os.path.join(setting.CASE_PATH,f)
    case_list = op.get_case(abs_path)
    res_list = []
    pass_count,fail_count = 0,0
    for case in case_list:# Cycle each excel All use cases inside
    url,method,req_data,cookie,header,files,check = case
    res = op.my_request(url, method, req_data, cookie, header, files) # The result returned after calling the interface
    status = op.check_res(res,check)
    res_list.append([res,status])
    if status==' success ':
    pass_count+=1
    else:
    fail_count+=1
    op.write_excel(res_list) # write in excel
    msg = '''
    xx Hello :
    A total of %s Use cases , adopt %s strip , Failure %s strip .
    '''%(len(res_list),pass_count,fail_count)
    # sendmail(' Test case running results ',content=msg,attrs=abs_path)
    CaseRun().find_cases()

    7. in addition readme Inside, you can briefly introduce the running environment of the framework , Dependent modules , Simple ideas and sequence .

    Since then , The data-driven interface automation testing framework has been built successfully , You can try it yourself ....


  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式師世界 All Rights Reserved