The company's new two girls have been spit trough this interface test case with Excel maintenance very cost brain trouble, and relatively low (heart very agree but can not overturn their own), Sister said Excel is very troublesome tool, so secretly carried out two times revision.
The contents of the changes are as follows:
Image.png
- 2. New test Report Web version and version management
- 3. New use case code
One, encapsulates a module to obtain a use case image.png
use cases can be written in accordance with the Yml file, the suffix of the file can be. conf,. config,. ini. [] In the test case scenario, the following parameter contents correspond to the interface use case parameters. A brief introduction to the Python built-in module Configparser:
Configparser is the package that is used to read the configuration file. The format of the configuration file is as follows: the brackets "[]" are included in the section. section below is a configuration content similar to Key:value. (key = value can also be specific method this time not to expand, then write again about the use of configparser, understand the principle will make the work easier.) )
Here's why the configuration is written on the outermost layer, and if you write to a folder, you can't read the configuration. Python requires an. ini file in the same folder as the run file when executing the Run command. So it should be caused by a path problem, and then try to fix the bug.
(Fix this bug by manipulating the absolute path)
This change code is implemented as follows:
#!/usr/bin/python#-*-Coding:utf-8-*-# Base Package: Configuring ServicesImport configparserconfig = Configparser.configparser ()DefGet_config(filename):"" "Get File Configuration:p Aram FileName: Profile name: Return:none" ""Global ConfigTry:config.read (filename)ReturnTrueExcept Exception, E:Print ("Read configuration failed%s"% e)DefGet_data(title, key): "" " parameter Configuration:p Aram Title: Header information for configuration file:p Aram key: Config file key value: Return: The Profile value" "" Try:value = confi G.get (title, key) return value except Exception, E: print ("Get parameter failed%s"% e)def get_title_list (): "" " gets all Title:return:title list" "" Try:title = config.sections () return str (title). Decode ("str Ing_escape ") except Exception, E: print (" Get title information failed%s ", e)
Second, the module that encapsulates a log
this time the log was changed: the contents of the test case returned to the result file are written, and the file generates the test report through Mkdocs. Company's micro-services, so there is a certain amount of Docker to dabble. The official offers a mkdocs image. Pull the image of the official website and attach the data volume to the host where the test report is carried, and you can access it. You only need to maintain the test cases of the code and automatically update the test reports.
Look at the display effect:
Image.png
The code is as follows:
#!/usr/bin/python# -*- coding: UTF-8 -*-# 基础包:日志服务import loggingimport constants as csimport logging.handlersdef get_logger(name=‘report‘): FORMAT = ‘%(message)s‘ filename = cs.REPORT_PATH + name + cs.NOW logging.basicConfig(level=logging.WARNING, format=FORMAT, filename=filename, filemode=‘w‘) return logging
Third, call the interface requests
The code is as follows:
#!/usr/bin/python#-*-Coding:utf-8-*-# Base Pack: Encapsulation of interface TestsImport requestsImport JSONDefChange_type(value):"" "The Dict type is recognized in Chinese:p Aram value: The data value passed: return: The value after transcoding" "" Result = eval (json.dumps (value, ensure_ascii=False, encoding="UTF-8"))return resultDefApi(method, URL, data, headers):"" defines a method for requesting an interface and the required parameters:p Aram method: Request type:p Aram URL: Request address:p Aram data: Request parameter:p Aram headers: request Headers:return:code Code "" " Global results Try: If method = = (" POST " or " POST "): results = requests.post (URL, data, header S=headers) If method = = ("Get" or "get"): results = requests.get (URL, data, headers=headers) response = R Esults.json () code = response.get ("code") return code except Exception, E: print ("request failed%s"% e) /c15>
Iv. Business Package Call Encapsulation Package (common.py)
#!/usr/bin/python#-*-Coding:utf-8-*-# Business Package: General functionsImport Lib.tezmysqlAs MySQLImport Lib.tezlogAs LogImport Lib.tezrequestAs requestImport Lib.tezconfigAs ConfImport constantsAs CSImport OSDefPrepare_data(Host, user, password, DB, SQL):"" "Data preparation, add test data:p Aram Host: Service address:p Aram User: User:p Aram Password: password:p Aram DB: Database name:p Aram sql: Sql:return executed:" "mysq L.connect (host, user, password, db) res = mysql.execute (sql) Mysql.close ()Print ("Run sql:the row number affected is%s"% res)return resDefGet_prepare_sql(filename, key):"" Gets the SQL:p Aram Title: Profile Header information:p Aram key: Profile value: Return:value "" "Try:conf.get_config (filename) value = Conf.get_data (Title=cs. TITLE, Key=key)return valueExcept Exception, E:Print ("Get use case parameter value failed%s"% e)DefReset_report(filename):Try:result = os.path.exists (cs. Report_path)if result = =True:conf.get_config (filename) ReportName = eval (Conf.get_data (Title=cs. Report_name, Key=cs. Report) Report_name = eval (Conf.get_data (TITLE=CS). Report_name, Key=cs. r_name)) file = Open (cs. Yml_report,' r ') List_con = file.readlines () content = str (list_con). Decode ("String_escape") Filecontent ="-[%s,%s]" row ="\ n" con = row + filecontent% (ReportName + cs). Now, Report_name)If filecontent% (ReportName + cs. Now, Report_name)NotIn content:f = open (cs. Yml_report,' A + ') f.write (Con)ElsePrint ("Content already exists%s"% con)Except Exception, E:Print ("File path does not exist%s", E)DefRun_test(filename): conf.get_config (filename) List = eval (conf.get_title_list ()) ReportName = eval (Conf.get_data (CS). Report_name, Key=cs. report)) logging = Log.get_logger (ReportName)For IIn range (2, Len (list): title = list[i] Number = eval (conf.get_data (title, Key=cs). Number)) name = str (conf.get_data (title, Key=cs.name)) method = str (conf.get_data (title, Key=cs. METHOD)) url = str (conf.get_data (title, Key=cs). URL) data = Request.change_type (Conf.get_data (title, Key=cs. DATA) headers = eval (conf.get_data (title, Key=cs). HEADERS)) Testurl = cs. Test_url + URL Actualcode = Request.api (method, Testurl, data, headers) Expectcode = Conf.get_data (title, Key=cs. CODE)If Actualcode! = Expectcode:Print"Failinfo"Print Number logging.warning ("-<font color= #FFB5C5 size=3>failcase:%s", name) logging.warning ("-<font color= #FFB5C5 size=3>number:%s", number) logging.warning ("-<font color= #FFB5C5 Size=3>method:%s", Method) logging.warning ("-<font color= #FFB5C5 size=3>url:%s", Testurl) logging.warning ("-Data: </br> '%s '", data) Logging.warning ("-Headers: </br> '%s '", Headers) logging.warning ("-<font color= #FFB5C5 size=3 > Expected value:%s ", Expectcode) logging.warning ("-<font color= #FFB5C5 size=3> actuals:%s ", str (actualcode)) Logging.wa Rning ("*****************") else: print number print "Trueinfo" logging.warning ("-<font color= #3cc8b4 size=3> truecase%s ", name) logging.warning (" ***************** ")
V. Implementation package (RUN.PY)
import util.common as commonimport sys# FILENAME = sys.argv[1]FILENAME = "proUser.ini""""1.新建测试报告目录"""common.reset_report(filename=FILENAME)"""2.执行测试用例"""common.run_test(filename=FILENAME)
PS: There is a global variable package constant.py, inside see is the parameter catalog file related
Hepburn Z
Links: Https://www.jianshu.com/p/459e578f86e6
Source: Pinterest
Copyright belongs to the author. Commercial reprint please contact the author for authorization, non-commercial reprint please specify the source.
Python API Interface Automation test framework code write use case