soapui groovy脚本汇总

出处:https://www.jianshu.com/p/ce6f8a1f66f4

一、一些内部元件的访问

testRunner.testCase开头

1、向下访问

testRunner.testCase.testSteps[testStepName]
testRunner.testCase.getTestStepByName("新增一个空间")

2、向上访问,用于访问同一项目中的其他testSuites 和 testCase下的元素

testRunner.testCase.testSuite.project.testSuites[testSuiteName].testCases[testCaseName].testSteps[testStepName]

3、几乎所有元件都有get 和set属性的方法

setPropertyValue getPropertyValue
//在下面的4,5,6点中,几乎所有的属性值都可以和对应的get方法互相替换等价

4、获取响应体

myResponse=testRunner.testCase.getTestStepByName("新增一个空间").testRequest.response
myRequest=testRunner.testCase.getTestStepByName("新增一个空间").testRequest
可以替换使用:getTestRequest(),testSteps[testStepName],getResponse()等。
比较特殊的2个
获取响应作为String
myResponse.contentAsString 或者 myRequest.getResponseContentAsString()
获取响应作为Xml
myResponse.contentAsXml 或者myRequest.getResponseContentAsXml()

5、响应头和请求头

响应头:

testRunner.testCase.getTestStepByName("新增一个空间").testRequest.response.responseHeaders["Location"]
或者testRunner.testCase.getTestStepByName("查询空间详情").testRequest.getResponse().getResponseHeaders("Location")

请求头:

testRunner.testCase.getTestStepByName("查询空间详情").testRequest.requestHeaders
testRunner.testCase.getTestStepByName("查询空间详情").testRequest.getRequestHeaders("Location")

设置请求头

def headerMap = new StringToStringMap()   //
headerMap.put("headerKeyName","HeaderKeyWord")           //添加到map
testRunner.testCase.getTestStepByName("查询空间详情").testRequest.setRequestHeaders(headerMap)

6、获取请求地址

testRunner.testCase.getTestStepByName("查询空间详情").testRequest.path

7、getAt(String) 方法,传入property名字,检索出值

针对testRunner下的所有对象,都可以通过此方法直接获取到 属性,例如:
testRunner.testCase.getTestStepByName("查询空间详情").testRequest.getAt("path")
对应:testRunner.testCase.getTestStepByName("查询空间详情").testRequest.path
testRunner.testCase.getTestStepByName("查询空间详情").testRequest.response.getAt("responseHeaders")
对应:testRunner.testCase.getTestStepByName("查询空间详情").testRequest.requestHeaders

8、获取全部用例并循环

def  testCaseList = testRunner.testCase.testSuite.getTestCaseList()
testCaseList.each{
    if(it.testSteps["Input"])
        it.testSteps["Input"].setPropertyValue("spaceid",uid)
    }

9、相对的获取用例数,getTestCaseCount()

 for(int i=0; i<testSuite.getTestCaseCount(); i++) {
     if (!testSuite.getTestCaseAt(i).isDisabled()) {
     if (!(testSuite.getTestCaseAt(i).getTestStepByName("stepName")).equals()){
   .....
         }
      }
   }

10、获取getTestSuiteCount()

testRunner.testCase.testSuite.project.getTestSuiteCount()

11、获取名称

部分元件只有Label和Name中的一个,测试一下就知道了。
    getLabel() 和getName()大多数情况是等价的
    a. 取test case的名称
    def tc = testRunner.testCase;
    log.info (tc.getLabel());
    b. 取test suite的名称
    def ts = testRunner.testCase.testSuite;
    log.info (ts.getLabel());
  getName()
   取project 名称
   def tp = testRunner.testCase.testSuite.project;
   log.info (tp.getName());

12、在断言中需要使用用例对象的话

messageExchange.modelItem.testCase.testSteps["Properties"].getPropertyValue("userId")

13、全局属性变量访问

对于项目中的属性可分为这么几个级别Global, Project,TestSuite, TestCase
即全局变量、项目级别、用例集级别、单个用例级别
要获得如项目级别的属性变量的话,可以用以下方法
def time_num=context.expand('${#Project#time_num}')        //##号内为定义哪个级别的属性变量,后面为属性名

二、json操作

1、json builder

def createAuthorId = context.expand( '${查询空间详情#Response#$.createAuthorId}' )
def flag = "1"
import groovy.json.JsonBuilder
def json = new JsonBuilder()
json {
userID  createAuthorId
fileflag  flag}
return json

2、json 解析

    如json为:
        {"calendar": [         {"calendar_id":"1705","showtime":"1288927800","endshowtime":"1288931400","allDay":false},
{"calendar_id":"1706","showtime":"1288933200","endshowtime":"1288936800","allDay":false},
{"calendar_id":"1709","showtime":"1288935600","endshowtime":"1288938900","allDay":false}
] }

import groovy.json.JsonSlurper  
def xresponse = testRunner.testCase.testSteps["getCalendarListByCoid"].testRequest.response.contentAsString  
def slurper = new JsonSlurper()  
def re = slurper.parseText(xresponse)  
//访问顶级元素,返回的是一个列表使用size 获得长度
re.calendar   re.calendar.size()
//访问元素模式  
re.calendar.calendar_id     re.calendar.calendar_id[index]
//另一种访问形式
re['calendar']['calendar_id'][index]
//查找过滤
re.calendar.calendar_id.find{it=='1706'}  //获得的结果是 calendar_id  1706
re.calendar.find{it.calendar_id=='1706'}  //获得的是calendar元素

三、XML操作(解析)

ef groovyUtils = new com.eviware.soapui.support.GroovyUtils(context )
//获取上下文对象,转化成groovyUtils对象
defwsdlResponse=testRunner.testCase.testSteps["发贴"].getTestRequest().getResponseContentAsXml()
log.info("wsdlResponse==="+wsdlResponse)
//获取指定步骤的返回信息并转化成xml
holder = groovyUtils.getXmlHolder(wsdlResponse)
//获取指定节点的值
defmessage=holder.getNodeValue("//ns1:Response[1]/ns1:response[1]/ns1:e[1]/ns1:message[1]")
log.info("获得节点对应的值是"+message)
deffandom_creator_sn=holder.getNodeValue("//ns1:fandom_creator_sn")
log.info("获得节点对应的值是"+fandom_creator_sn)

四、文件操作

直接百度groovy文件操作就好了,用得少不收集了

五、各级别的集合操作

1、TestSteps的操作

testRunner.testCase.testSuite.project.testSuites["互动空间测试用例"].testCases["空间管理测试"].testSteps
=getTestSteps()。都是获取用例下的testStep列表,返回的是 key=object 形式的字典map

getTestStepList() 获取用例下的testStep列表,纯列表

getTestStepCount() 获取数量
getTestStepAt(int)  getTestStepById(java.util.UUID)  通过位置和UUID 查找step

getTestStepsOfType(com.eviware.soapui.impl.wsdl.teststeps.RestTestRequestStep.class) 通过类型过滤查找得到 testSteps列表。

2、testCases操作

testRunner.testCase.testSuite.project.testSuites["互动空间测试用例"].testCases=getTestCases()
返回的是 key=object 形式的字典map

getTestCaseList(), 获取的列表,纯列表
getTestCaseCount(),  获取数量
getTestCaseAt(int), getTestCaseById(java.util.UUID) 通过位置和UUID

3、testSuites操作

testRunner.testCase.testSuite.project.testSuites=getTestSuites()
返回的是 key=object 形式的字典map

getTestSuiteList(),获取的列表,纯列表
getTestSuiteCount() 获取数量
,getTestSuiteAt(int), getTestSuiteById(java.util.UUID) 通过位置和UUID

4、返回是list时操作

testCaseList=testRunner.testCase.testSuite.project.testSuites["互动空间测试用例"].getTestCaseList()
log.info testCaseList[0]  //使用 index访问
//each循环
testCaseList.each{
    it.xxxxx
}

5、返回是map时操作

testStepsMap=testRunner.testCase.testSuite.project.testSuites["互动空间测试用例"].testCases["空间管理测试"].testSteps
//使用名称key访问
log.info testStepsMap["新增一个空间"]  
log.info testStepsMap.get("新增一个空间")
//遍历 使用默认闭包it
testStepsMap.each{
    log.info it.key+"  "+it.value
}
//使用自定义闭包名称遍历
testStepsMap.each{myp->
    log.info myp.key+"  "+myp.value
}

六、数据库操作

1、普通的jdbc编程

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
public class JDBCExample1 {
public static void main(String[] args) {
   Connection con = null;
   Statement stmt = null;
   ResultSet rs = null;
   try{
     Class.forName("org.gjt.mm.mysql.Driver");
     con = DriverManager.getConnection("jdbc:mysql://localhost:3306/words",
          "words", "words");
     stmt = con.createStatement();
     rs = stmt.executeQuery("select * from word");
     while (rs.next()) {
       System.out.println("word id: " + rs.getLong(1) +
           " spelling: " + rs.getString(2) +
           " part of speech: " + rs.getString(3));
     }
   }catch(SQLException e){
     e.printStackTrace();
   }catch(ClassNotFoundException e){
     e.printStackTrace();
   }finally{
     try{rs.close();}catch(Exception e){}
     try{stmt.close();}catch(Exception e){}
     try{con.close();}catch(Exception e){}
  }
}
}

2、grrovy sql

import groovy.sql.Sql
   sql = Sql.newInstance("jdbc:mysql://localhost:3306/words", "words",
          "words", "org.gjt.mm.mysql.Driver")

查出所有行

 sql.eachRow("select * from word"){ row |
      println row.word_id + " " + row.spelling + " " + row.part_of_speech
   }

执行插入操作

wid = 999
spelling = "Nefarious"
pospeech = "Adjective"
sql.execute("insert into word (word_id, spelling, part_of_speech)
  values (${wid}, ${spelling}, ${pospeech})")

使用位置参数

val = sql.execute("select * from word where word_id = ?", [5])

更新

nid = 5
spelling = "Nefarious"
sql.executeUpdate("update word set word_id = ? where spelling = ?", [nid, spelling])

删除

sql.execute("delete from word where word_id = ?" , [5])

创建数据集

sql = Sql.newInstance("jdbc:mysql://localhost:3306/words", "words",
         "words", "org.gjt.mm.mysql.Driver")
   words = sql.dataSet("word")
   words.each{ word |
    println word.word_id + " " + word.spelling
   }
   words.add(word_id:"9999", spelling:"clerisy", part_of_speech:"Noun")

查询结果集的访问

sql.eachRow("select * from word"){ grs |
  println "-1  = " + grs.getAt(-1) //使用索引访问最后一个
  println "2  = " + grs.getAt(2) //使用索引访问第三个
   grs.columName //通过列名访问
}

七、流程控制方面

testRunner.testCase  //可以访问和操作项目中的所有对象
testRunner.fail(....)  testRunner.cancel,结束测试执行
testRunner.gotoTestStepByname("Groovy Script") // goto 表示跳转到哪一步开始执行,会等待当前脚本执行完成再跳转到对应步骤执行
testRunner.runTestStepByname("Groovy Script") //脚本会先去执行这个步骤,然后继续执行当前脚本
context.myProperty="aaaa" //会在上下文中创建一个名为myProperty的属性,赋值为aaa

八、脚本返回值和引用

return UUID.randomUUID()  \\return 返回数据
${Groovy Script#result} \\引用
def result = context.expand( '${Groovy Script#result}' ) \\引用

九、抄的两个实例之一----为所有RestTestRequestStep设置请求头(Cookie,session),以及编码

import com.eviware.soapui.support.types.StringToStringMap
def cookiesList = testRunner.testCase.getTestStepByName("登录").testRequest.response.responseHeaders["Set-Cookie"]   //获得登陆后返回响应中的set-cookie
log.info "cookiesList:" + cookiesList  
def cookieNew =""
cookiesList.each{
     cookieNew = cookieNew+it.split(";")[0]+";";    //拆分得到 SESSION
    }
log.info "Cookie:"+cookieNew
def cookieMap = new StringToStringMap()   //cookiemap
cookieMap.put("Cookie",cookieNew)           //添加到map
//Pass cookie to all testSteps of the project
//将cookieMap设置到项目中的所有RestTestRequestStep,顺带设置编码
def testSuiteList =  testRunner.testCase.testSuite.project.getTestSuiteList()
def testCaseList
def testStepList
testSuiteList.each{
    testCaseList = it.getTestCaseList()
    testCaseList.each{
        //获得RestTestRequestStep类型的testStepList
         testStepList = it.getTestStepsOfType(com.eviware.soapui.impl.wsdl.teststeps.RestTestRequestStep.class)
         testStepList.each{
            if(it.name!="登录"){
                   it.testRequest.setRequestHeaders(cookieMap)
                   it.testRequest.setEncoding("UTF-8")
                  }
        }
    }    
}
log.info "==========Cookie:"+ cookieMap.get("Cookie");

十、抄的两个实例之二----数据库验证

import com.eviware.soapui.support.types.StringToStringMap
def Location= testRunner.testCase.getTestStepByName("新增一个教材册次").testRequest.response.responseHeaders["Location"]
log.info "Location:" + Location[0]
def uid = Location[0].split("/")[-1]
testRunner.testCase.testSteps["Input"].setPropertyValue("uid",uid)
log.info "uid:" + uid
import groovy.sql.Sql
//获取testSuite对象,以获取其中参数
def DBProperties = testRunner.testCase.testSuite
//获取数据库对象
def sql = Sql.newInstance(DBProperties.getPropertyValue( "connection-url" ),DBProperties.getPropertyValue( "sysdb-user-name" ),
          DBProperties.getPropertyValue( "sysdb-password" ),DBProperties.getPropertyValue( "driver-class" ))
def  query = "Select * From inf_book_second Where inf_book_second.uid = '"+ uid +"'"
def raw = sql.firstRow(query )
log.info query
def expect_name  = testRunner.testCase.getTestStepByName( "Properties" ).getPropertyValue('name')
log.info "expect_name: "+expect_name
def actual_name = raw.name
log.info "actual_name: "+actual_name
//断言
assert actual_name ==expect_name

原文地址:https://www.cnblogs.com/MasterMonkInTemple/p/10437112.html

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。

相关推荐


背景:    8月29日,凌晨4点左右,某服务告警,其中一个节点直接down掉,收到告警的同事让运维重启。    9点左右,内存监控上发现内存异常,堆内存涨速很快,即便GC也没有什么效果,频繁GC。    9点38,服务各种超时,影响整个app使用。处理方式:    当时由于很想要
https://support.smartbear.comeadyapi/docs/soapui/steps/groovy.htmlGettestcaseobjectToobtaintheobjectwhichreferstothecontainingtestcase,usethefollowingcodesnippet:Groovy def case=testRunner.testCase; Byusingthe tes
有几个选项可用于执行自定义JMeter脚本并扩展基线JMeter功能。查看最流行的扩展机制,比较性能并分析哪一个是最好的。  这是乐队之战,JMeter风格。 BeanshellV.JSR223V.JavaRequestSampler 在我们之前的帖子中,  JMeterPerformance和TuningTips  ( 由fantastik
Scala和Java为静态语言,Groovy为动态语言Scala:函数式编程,同时支持面向对象Groovy:jvm上的脚本,较好兼容java语法,Groovy加强了Java集成。 可配置化的优势,可以将一些简单的逻辑公开给外部编辑和使用,增强了互操作性,复杂逻辑来说,可配置化代码的调试则会比较麻烦 Scala和Java
出处:https://www.jianshu.com/p/ce6f8a1f66f4一、一些内部元件的访问testRunner.testCase开头1、向下访问testRunner.testCase.testSteps[testStepName]testRunner.testCase.getTestStepByName("新增一个空间")2、向上访问,用于访问同一项目中的其他testSuites和testCase下
在运行groovy的junit方法时,报了这个错误:java.lang.ExceptionInInitializerError atorg.codehaus.groovy.reflection.ClassInfo.isValidWeakMetaClass(ClassInfo.java:271) atorg.codehaus.groovy.reflection.ClassInfo.getMetaClassForClass(ClassInfo.java:241) atorg.codeha
基本语法1.Grovvy的注释分为//和/**/和java的一样.2.Grovvy语法可以不已分号结尾.3.单引号,里面的内容严格的对应java中的String,不对$符号进行转义.defs1='iamastudent$'printlns1iamastudent$4.双引号“”的内容中如果有$号的话,会先对表达式先求值.de
Tiobe发布了最新一期(3月份)编程语言欢迎度榜单,其榜单根据互联网上有经验的程序员、课程和第三方厂商的数量,并使用搜索引擎(如Google、Bing、Yahoo!)以及Wikipedia、Amazon、YouTube统计出排名数据。TOP5几乎没有变化,Java和C语言牢牢占据前两名。Python相较去年上升一位进入TOP3,C++下
我有一个Google地图组件,作者可以在其中指定纬度和经度.我正在使用带有正则表达式的常规“输入”类型控件来验证它们是否是数字,但是,当试图解决指定范围的问题时(经度验证该值在[-180,180]内并且纬度[-90,90])但是,通过正则表达式进行验证似乎很麻烦,而且利用inputtype=“numb
我正在为未来的应用程序评估SpringBoot,并希望使用Groovy模板来实现其纯粹的可读性.不幸的是,我在迭代我添加到控制器返回的ModelAndView对象的对象列表时遇到了麻烦.这是我的控制器:@RestController@RequestMapping("/ships")publicclassShipsController{@Autowired
我有一个基于Spring的java应用程序,其中包含一些有用的组件.作为系统的一部分,我有一个groovy脚本,来处理一些报告.我想从groovy脚本中调用spring组件.当我用Java编写时,我需要在@Component中使用@Autowired注释,即@ComponentclassReporter{@AutowiredSearchServicesearchS
在Grailsi18n插件definedthusly中定义了一个messageSourcebean:messageSource(PluginAwareResourceBundleMessageSource){basenames=baseNames.toArray()fallbackToSystemLocale=falsepluginManager=manager....}是否可以覆盖我的resources.groovy中的fa
我正在寻找一种方法来反向工程RDBMS表(MSSQLServer)并生成JPA@EntityGroovy类.我们目前没有选择使用Grails和/或GORM,因此Grailsdb-reverse-engineer插件似乎很接近但不太正确.它生成符合GORM的类而不是JPA实体类.我们目前有一个gradle构建,它利用org.hibernate.tool.ant.Hibe
https://blog.csdn.net/Gdeer/article/details/83062523一、直接运行groovy程序因为groovy插件和android插件不兼容,所以不能在原始项目上使用groovy。 新建module,创一个JavaLibrary,取名lib。  修改lib/build.gradleapplyplugin:'java-library'depe
一、自动生成GET请求脚本1、配置Createascript在ngrinder管理台主页,点击script–>Createascript,并填写脚本名称和请求的url,如下所示:点击Create按钮,nGrinder会自动生成对应的脚本结构,如果没有参数需要设置的话,可以直接运行了。二、详细解析GET请求脚本ngrinder自动生成的脚本
我正在关注使用列表和地图作为构造函数的this博文.为什么以下列表无法强制反对?classTest{staticclassTestObject{privateinta=1;protectedintb=2;publicintc=3;intd=4;Strings="s";}stati
Information:java:Errorsoccurredwhilecompilingmodule'security'Information:javac1.8.0_131wasusedtocompilejavasourcesInformation:2019/6/98:31-Buildcompletedwith1errorand0warningsin3s116msError:java:读取E:\repository\org
ngrinder中的groovy脚本结构类似junit,同时在junit的基础之上封装了自己的注解,用来控制脚本的运行。一、运行逻辑图如下:此处只列出了groovy脚本的逻辑,jython脚本是类似的,在此不再单独介绍。二、各注解的使用比较三、关注点在ngrinder中,通常使用单进程多线程就足够大部分测试了,所以:
我有一个switch语句来处理javaenumfoo,并使用spock编写一些groovy单元测试.我已经添加了一个测试,它验证当前是否处理了每种类型的foo而没有抛出异常.现在我想测试一个无法识别的foo类型会导致抛出异常.要做到这一点,我将不得不嘲笑枚举,并已经看到这里概述的解决方案:MockingJ
我有一个groovy实体ClientInvoiceAttachmentExt,它扩展了java实体ClientInvoiceAttachment.ClientInvoiceAttachment具有@Id注释,但仍然看到“没有为实体指定的标识符”错误这是我的堆栈跟踪[Mar0317:11:54]ERROR|org.springframework.web.context.ContextLoader|Contex