Python Unit Test unittest test framework

Source: Internet
Author: User

The topic of this article is the implementation of the automated testing framework, before implementing the knowledge about the UnitTest module:

Python has a self-contained unit test framework that is the UnitTest module, which is used for unit testing, which encapsulates some of the result methods returned by the checksum and some initialization operations before the use cases are executed.

Before you say UnitTest, say a few concepts:

TestCase is also a test case

TestSuite Multiple test cases are assembled together, that is TestSuite

Testloader is used to load testcase into Testsuite.

Testrunner is to execute a test case, the results of the test are saved to the TestResult instance, including the number of test cases that were run, the number of successes, and the number of failures.

1.yaml test Case Files

UnitTest when doing automated testing, the read test case file is a ". Yml" or ". Yaml" format of the use case file, first need to install PYYAML, direct pip install Pyyaml wait for the installation to complete;

Write the test case file in YAML format, we use a login interface as an example to write the test case, the file name is: Login.yaml The following are 3 test cases:

-URL:/api/user/login#Interface AddressMethod:post#Request MethodDetail: Normal Login#Use case DescriptionData:#Request BodyUsername:niuhanyang passwd:aa123456 Check:#Expected results-userId- Sign-URL:/api/user/Login method:post Detail: password error data:username:niuhanyang passwd:aa12333 check:-Password Error-URL:/api/user/Login Method:post Detail: Do not pass the password Data:username:niuhanyang check:-Required parameters are not filled
2. Frame Construction

(1) First of all, the framework of the path to build, I this framework in the UTP directory, the specific directory level of the UTP directory is as follows:

  

The Bin directory holds the entry file for execution;

Case_data stores the use case files of Yaml or yml;

Automatically generated python files are stored in the case directory;

The Conf directory contains configuration files;

The main program files are stored in the Lib directory;

The log file is stored in the logs directory;

The report directory contains the test reports file;

The readme is a description;

(2) Set the configuration file, in the Conf directory to create the setting.py file, the specific configuration file content is as follows:

ImportOsbase_path=Os.path.dirname (Os.path.dirname (Os.path.abspath (__file__)))#the base path is the road-strength address of the UTP.mail_host='smtp.qq.com'Mail_user='[email protected]'MAIL_PASSWRD='xxxxx'#Authorization code for the mailboxto = [    '[email protected] @qq. com',] level='Debug' #Log LevelLog_path= Os.path.join (Base_path,'logs')#the path where the log is storedCase_path = Os.path.join (Base_path,'cases')#the path where the use case is storedYaml_path = Os.path.join (Base_path,'Case_data')#the path where the Yaml file is storedCase_template = Os.path.join (Base_path,'conf','Base.txt')#path to the use case templateReport_path = Os.path.join (Base_path,' Report')#directory where test reports are storedBase_url ='http://127.0.0.1' #address of the interfaceLog_name='Utp.log' #file name of the log

(3) Write the test script of the request interface, with the login interface as the column, the test script is written in base.txt format file, the script is as follows:

Importunittest,requestsImportDDT fromBeautifulreportImportBeautifulreport as Bf fromUrllibImportParse fromConf.settingImportBASE_URL@DDT.DDTclass%s (unittest. TestCase): Base_url=base_url @ddt. File_data (R'%s')#DDT helps you read files, get file contents, loop through functions    defTest_request (self,**Kwargs): Detail= Kwargs.get ('Detail','did not write the use case description') Self._testmethoddoc= Detail#Dynamic Use-case descriptionurl = kwargs.get ('URL')#URLurl = parse.urljoin (self.base_url,url)#stitching up a good URLmethod = Kwargs.get ('Method','Get')#Request Methoddata = Kwargs.get ('Data',{})#Request ParametersHeader = Kwargs.get ('Header',{})#Request HeaderCookie = Kwargs.get ('Cookies',{})#CookiesCheck = Kwargs.get ('Check') Method= Method.lower ()#Easy to handle        Try:            ifmethod=='Get': Res= Requests.get (url,params=data,cookies=cookie,headers=header). Text#because the interface has an exception, it may not return a JSON string, error            Else: Res= Requests.post (url,data=data,cookies=cookie,headers=header). TextexceptException as E:Print('Interface Request Error') Res=e forCinchCheck:self.assertIn (c,res,msg='the expected results are not in conformity with the expected results:'+c +'actual results:'+res)

Place this base.txt file in the cases directory, followed by the test case that this file is copied into a python file as the underlying file.

In testing, if there are multiple interfaces that need to be tested, you need to write the test cases for each interface in the Case_data directory, each of which writes a YAML use case file with several use cases in each Yaml file.

For example, login interface, 1. Login successful, 2 password error, 3. Required parameters are not filled, there are 3 use cases; In the run test, the total number of use cases in all YAML files is the number of use cases executed;

Our idea is that there are several YAML test case files in the Case_data directory, The Base.txt file is automatically generated by several Python test files, the name of the Python test file is the file name of Yaml, and then all the Python test files are executed once,

Then the test report is drawn and the final test results are sent. In order to see the effect, I wrote a registered interface in the Case_data directory Yaml test case file, called Reg.yaml, this file only write a use case, as follows:

-  /api/user/user_reg  method:post  Detail: User name has been registered  data:    Username:niuhanyang    passwd:aa123456    cpasswd:aa123456  check:    -user already exists

(4) According to the number of YAML files in the Case_data directory, create a new tools.py file in the Lib directory, write the code to automatically generate the Python test file, the general principal code is written in the Lib directory, as follows:

Importdatetime,os,yagmail,unittest fromConfImportsetting fromBeautifulreportImportBeautifulreport as BfdefMakecase ():#This function automatically generates Python filesAll_yaml = Os.listdir (setting. Yaml_path)#get to the file under the Yaml_path pathBASE_CASE_STR = open (setting. case_template,encoding='Utf-8'). Read ()#to read something in a file.     forYamlinchAll_yaml:ifYaml.endswith ('. Yaml')orYaml.endswith ('. Yml'):#determine if it is a yml fileClass_name = Yaml.replace ('. Yml',"'). Replace ('. Yaml',"'). Capitalize ()#gets the name of the Yaml file as the class name, with the first letter capitalizedfile_name = Os.path.join (setting. YAML_PATH,YAML)#the absolute path of the stitching use case Yaml fileContent = base_case_str%(Class_name,file_name)#assign the character formatting to the read file to the class name and file name of the Python file that is about to be generatedPy_file_name = Os.path.join (setting. Case_path,class_name)#to spell the absolute path of a python fileOpen'%s.py'%py_file_name,'W', encoding='Utf-8'). Write (content)#write a file, content is written

The above already based on the number of YAML files 2, automatically generated 2 Python test files, and placed under the cases directory, login.py is testing the login interface, reg.py is testing the registration interface. As follows:

(6) Then write the code in tools.py to execute the test case file under cases and generate the test report, as follows:

defRun_all_case ():#This function is to run all test cases and generate test reportsSuite = UnitTest. TestSuite ()#Build a Test collectionAll_py = Unittest.defaultTestLoader.discover (setting. Case_path,'*.py')    #Find all Python files in the Case_path directory[Suite.addtests (PY) forPyinchAll_py]#list generation, add the case inside the file to the test setRUN=BF (Suite)#Executing test CasesToday = Datetime.datetime.today (). Strftime ('%y%m%d%h%m%s')#take the date of the day, exactly to the secondtitle ='%s_ Interface test report. HTML'%today#the file name of the test reportReport_abs_path = Os.path.join (setting. Report_path,title)#the path where the test report is storedRun.report (title,filename=title,log_path=setting. Report_path)returnRun.success_count,run.failure_count,report_abs_path#returns the number of successes and failures, along with the path to the test report

(7) When the use case is finished, the test report is generated, the next step is to send the test results to the mail, or continue to write the code in the tools.py file to send the message, as follows:

def SendMail (title,content,attrs=none):# This function sends the test result message    m = yagmail. SMTP (host=setting. mail_host,user=setting. Mail_user                 , password=setting. MAIL_PASSWRD                , Smtp_ssl=true)# invokes configuration data for configuration file    m.send (to=setting. to,subject=title,           contents=content,           attachments=attrs)#setting . To invoke configuration data for the configuration file

(8) The main code is basically finished, the next step is to write the execution of the file, that is, the code from which calls coherent execution, need to provide an execution of the portal, the portal file is placed in the bin directory,

We have named the file that executes the entry name run.py, the specific code:

ImportOs,sysImportDatetimebase_path=Os.path.dirname (Os.path.dirname (Os.path.abspath (__file__)) ) Sys.path.insert (0,base_path)#adding a UTP directory to an environment variable fromLibImportToolsdefMail (): Tools.makecase ()#calling functions to automatically generate Python filesPass_count,fail_count,abs_path =tools.run_all_case ()#call the function to run the use case and assign the returned result to Pass_count,fail_count,abs_pathmsg=" "Hello, everyone!    The results of this interface test are as follows: By use case:%s Article failure case:%s For details see attachment '%s '. " "%(Pass_count,fail_count,os.path.basename (abs_path))#gets the last level of Abs_path, which is the name of the reportToday = Datetime.datetime.today (). Strftime ('%y%m%d%h%m%s') Title='Interface Test Report _%s'%today#message HeaderTools.sendmail (Title,msg,abs_path)#Send mailMail ()

At this point, an automated testing framework is basically complete, if there are errors, welcome points!

Python Unit Test unittest test framework

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.