Interface automated testing implemented by jmeter+ant

jmeter+ANT interface automated testing framework

project instruction

  • This framework is a set of data-driven interface automated testing framework designed based on jmeter+Ant+Excel+Python . jmeter  is used as the executor and Ant  is used as the building tool to perform build testing. This framework does not require you to use code to write test cases. The test cases are stored in In csv, you can write interface use cases, interface assertions, and use case execution control in csv .

technology stack

  • jmeter
  • Ant
  • Python

Environment deployment

1. Install JDK
2. Install Jmeter
3. Install ANT
  • 1. Unzip apache-ant-1.10.5-bin.zip to any directory, such as E:\apache-ant-1.10.5
  • 2. Configure ANT environment variables in windows. The following is my configuration.

ANT_HOME    E:\apache-ant-1.10.5
Path        E:\apache-ant-1.10.5\bin
CLASSPATH   E:\apache-ant-1.10.5\lib
  • 3. ANT installation verification
    Verify the installation result. Enter ant -v on the command line. If the version information appears, the installation is successful, as shown in the figure.

4. Integration of ANT and Jmeter
  • 1. Configuration library file
    Copy the ant-jmeter-1.1.1.jar file in the jmeter\extras directory to the lib folder in the ant installation directory, as shown in the figure

  • 2. Configure the configuration files of ANT and Jmeter.
    Create a new compiled ant file, named build.xml, with the following contents:


<?xml version="1.0" encoding="UTF-8"?>

<project name="ant-jmeter-test" default="run" basedir=".">
    <tstamp>
        <format property="time" pattern="yyyy_MM_dd_HH_mm" />
    </tstamp>
    <!-- 需要改成自己本地的 项目路径根 目录,即jmeter安装文件所在的目录-->  
    <property name="project.home" value="..\" />
    <!-- 需要改成自己本地的 Jmeter 目录-->  
    <property name="jmeter.home" value="${project.home}\apache-jmeter-3.2" />
    <!-- jmeter生成jtl格式的结果报告的路径--> 
    <property name="jmeter.result.jtl.dir" value="${project.home}\report\jtl" />
    <!-- jmeter生成html格式的结果报告的路径-->
    <property name="jmeter.result.html.dir" value="${project.home}\report\html" />
    <!-- 生成的报告的前缀-->  
    <property name="ReportName" value="TestReport" />
    <property name="jmeter.result.jtlName" value="${jmeter.result.jtl.dir}/${ReportName}_${time}.jtl" />
    <property name="jmeter.result.all_htmlName" value="${jmeter.result.html.dir}/All_Report/All${ReportName}_${time}.html" />
    <property name="jmeter.result.detail_htmlName" value="${jmeter.result.html.dir}/Detail_Report/Detail${ReportName}_${time}.html" />	
    
    <target name="run">
        <antcall target="test" />
        <antcall target="report" />
    </target>
    
    <target name="test">
        <taskdef name="jmeter" classname="org.programmerplanet.ant.taskdefs.jmeter.JMeterTask" />
        <jmeter jmeterhome="${jmeter.home}" resultlog="${jmeter.result.jtlName}">
             <!-- 声明要运行的目录和脚本。"*.jmx"指包含此目录下的所有jmeter脚本-->
            <testplans dir="${project.home}\jmeter_Code" includes="*.jmx" />

             <property name="jmeter.save.saveservice.output_format" value="xml"/>
        </jmeter>
    </target>
    
     <path id="xslt.classpath">
        <fileset dir="${jmeter.home}/lib" includes="xalan*.jar"/>
        <fileset dir="${jmeter.home}/lib" includes="serializer*.jar"/>
     </path>
        
    <target name="report">
        <tstamp> <format property="report.datestamp" pattern="yyyy/MM/dd HH:mm" /></tstamp>    
        <xslt               
              classpathref="xslt.classpath"
              force="true"
              
              in="${jmeter.result.jtlName}"
              out="${jmeter.result.all_htmlName}"
              style="${jmeter.home}/extras/jmeter-results-detail-report_21.xsl" />  
        
        <xslt               
              classpathref="xslt.classpath"
              force="true"
              
              in="${jmeter.result.jtlName}"
              out="${jmeter.result.detail_htmlName}"
              style="${jmeter.home}/extras/jmeter.results.shanhe.me.xsl" /> 	
		
        <!-- 因为上面生成报告的时候,不会将相关的图片也一起拷贝至目标目录,所以,需要手动拷贝 --> 
        <copy todir="${jmeter.result.html.dir}/All_Report">
            <fileset dir="${jmeter.home}/extras">
                <include name="collapse.png" />
                <include name="expand.png" />
            </fileset>
        </copy>
    </target>    
    
</project>
  • Modify the build.xml file according to the actual situation. The relevant instructions are as follows

     

  • 3. Configure jmeter.properties
    • Configure the jmeter report output format to xml. jmeter.save.saveservice.output_format=csv Modify  the apache-jmeter-3.2\bin\jmeter.properties file in the jmeter root directory to  jmeter.save.saveservice.output_format=xml, and remove the preceding comment symbol #, as shown in the figure

Framework code and use case design and related instructions

1. Use case design

  • The test cases are saved in a csv file as shown in the figure

2. Script code description

  • Define user variables in the test plan for use by subsequent scripts, as shown in the figure

  • The loop controller is set to loop forever, as shown in the figure

  • A new CSV Data Set ConFig control is added under the loop controller to loop through the test cases in the use case file, as shown in the figure

  • Allow quoted data?: Whether to allow data with double quotes

  1. This item actually controls whether the double quotes in the csv file are valid characters;
  2. If the data has double quotes and this item is set to TRUE, the quotes in the data will be automatically removed so that the data can be read normally, and even if the content between the quotes contains delimiters, it will still be treated as a whole without being separated;
  3. If the data has quotation marks and this item is set to FALSE, an error will be reported when reading the data;
  4. If you want a double quote field to contain double quotes, you need to add two double quotes to represent a single double quote.
  5. For example, when this item is set to true, "2,3"-->2,3; "4""5"-->4"5
  • Sharing mode: sharing mode
  1. All threads: For all threads in all thread groups, the value of each thread is different, and the next line in the csv file is taken in turn. That is, whether it is a single thread group or multiple thread groups, each thread takes one row in turn.
  2. Current thread group: Current thread group. Taking the thread group as a unit, the threads in each thread group will start to take the value from the 1st line and proceed downwards in sequence.
  3. Current thread: current thread. Each thread will start to get the value from line 1 and proceed downwards in sequence. In the same loop, all threads will get the same value.
  • Add an execution controller to filter test case execution, as shown below. All test cases can be executed, some of them can be executed, or test cases can be executed according to the priority of the use cases.

  • Select the request method according to the calling method.
    Distinguish the GET and POST method requests through the if selector, and configure the http request, as shown in the figure.

  • Post request configuration method: post request parameters are placed in body data

  • The response result configuration is as shown in the figure

  • Configuration method of Get request: The parameters of the get request are configured behind the url, as shown in the figure

  • Combined with Python to send test reports to email

#encoding=utf-8

import time
import smtplib
import email
from email.mime.text import MIMEText
from email.mime.multipart import MIMEMultipart
import sys
import os.path 
reload(sys)
sys.setdefaultencoding('utf-8')

#收件箱,如果是list请以逗号分隔
mailto_list=['[email protected]','[email protected]']
#发件箱
mail_host="smtp.126.com"
mail_user="XXXXtest"
mail_pass="XXXXXX"
mail_postfix="126.com"

def send_mail(attfile1, attfile2):

	today = time.strftime('%Y-%m-%d',time.localtime(time.time()))
	detailTime = time.strftime('%H:%M:%S',time.localtime(time.time()))
	todaytime = today + ' 00:00:00'
	selectres = todaytime
	send_header = "[demo项目][线上环境][自动化用例测试报告]- ".encode("utf-8") + today +" "+detailTime
	me= mail_user+"@"+mail_postfix
	msg = MIMEMultipart()
	msg['Subject'] = send_header
	msg['From'] = me
	msg['To'] = ";".join(mailto_list)
	
	#正文
	fp = open(attfile1,"r")
	content1 = fp.read()
	fp.close()
	
	content2 = '<html><h3>测试结果及更多详情请查看邮件附件【All_Report.html】和【Detail_Report.html】!!!</h3></html>'
	
	msg.attach(MIMEText(content1 + content2, 'html', 'utf-8'))

	#总体报告目录
	att1 = MIMEText(open(attfile1, 'rb').read(), 'base64', 'gb2312')
	att1["Content-Type"] = 'application/octet-stream'
	att1["Content-Disposition"] = 'attachment; filename="All_Report.html"'
	msg.attach(att1)

	#详细报告目录
	att2 = MIMEText(open(attfile2, 'rb').read(), 'base64', 'gb2312')
	att2["Content-Type"] = 'application/octet-stream'
	att2["Content-Disposition"] = 'attachment; filename="Detail_Report.html"'
	msg.attach(att2)

	try:
		server = smtplib.SMTP()
		server.connect(mail_host)
		server.ehlo()
		server.starttls()
		server.login(mail_user,mail_pass)
		server.sendmail(me, mailto_list, msg.as_string())
		server.quit()
		return True
	except Exception, e:
		print str(e)
		return False

#======查找测试报告目录,找到最新生成的测试报告文件====
def new_report(testreport):
	result_dir = testreport
	#获取该目录下的所有文件,将文件存到列表lists里
	lists=os.listdir(result_dir)
	#重新按时间先后对目录下(列表lists里)的文件进行排列,最新文件排末尾
	lists.sort(key=lambda fn: os.path.getmtime(result_dir+"\\"+fn))
	#找到最新生成的文件,并加上路径,lists(-1)倒数第一个
	file_new = os.path.join(result_dir,lists[-1])
	return file_new

if __name__ == '__main__':
	
	report_dir1 = "../report/html/Detail_Report"   #详细报告目录
	report_dir2 = "../report/html/All_Report"   #总体报告目录

	#找到生成的最新的测试报告
	file_new1 = new_report(report_dir1)
	file_new2 = new_report(report_dir2)
	print(file_new2)

	if send_mail(file_new2, file_new1):
		print u"测试报告邮件发送成功!"
	else:  
		print u"测试报告邮件发送失败!"

3. Execute the test and view the results

  • The build configuration file is placed in the same directory as the test script

  • Execute tests

  1. Command line cd to the directory where the build.xml file is located, enter  ant run , and execute the test, as shown in the figure

  2. If you see build successful, it means the build test is successful.
  • testing report
  1. The summary report is as follows

  2. The detailed report is as follows

     

2023 latest Jmeter interface testing from entry to proficiency (full set of project practical tutorials)

Guess you like

Origin blog.csdn.net/ada4656/article/details/134296904