本文将展示在Gatling测试脚本中使用正则表达式。
我们基于XML的示例Web服务是 http://www.dneonline.com。
我们将使用Web服务的Adding操作,该操作允许我们将两个数字相加并返回结果。
然后,我们将通过正则表达式提取总和值并进行验证。
定义HTTP协议
对于此示例,我们需要的只是baseUrl。
需要将Content-Type标头设置为text / xml。
object Protocols {
val httpProtocol = http
.baseUrl("http://www.dneonline.com/")
.contentTypeHeader("text/xml; charset=utf-8").build
}
向目标服务器发出POST请求
请求体是xml格式:
def xmlPath = exec(http("Addition Task")
.post("https://224926-685269-raikfcquaxqncofqfm.stackpathdns.com/calculator.asmx?op=Add")
.body(StringBody("""<?xml version="1.0" encoding="utf-8"?>
<soap:Envelope xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns:soap="http://schemas.xmlsoap.org/soap/envelope/">
<soap:Body>
<Add xmlns="http://tempuri.org/">
<intA>100</intA>
<intB>200</intB>
</Add>
</soap:Body>
</soap:Envelope>"""))
从响应中提取结果
需要用check函数获取响应数据。
通过regex函数设置正则表达式匹配规则。
def xmlPath = exec(http("Addition Task")
.post("https://224926-685269-raikfcquaxqncofqfm.stackpathdns.com/calculator.asmx?op=Add")
.body(StringBody("""<?xml version="1.0" encoding="utf-8"?>
<soap:Envelope xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns:soap="http://schemas.xmlsoap.org/soap/envelope/">
<soap:Body>
<Add xmlns="http://tempuri.org/">
<intA>100</intA>
<intB>200</intB>
</Add>
</soap:Body>
</soap:Envelope>"""))
.check( regex( "(?<=<AddResult>)(.*\\n?)(?=</AddResult>)" ).is("300") ))
设置测试场景
val xml_scenario = scenario("Execute Sample API Test").exec(Task.xmlPath)
setUp(xml_scenario.inject(rampUsers(20) during (10 seconds))).protocols(Protocols.httpProtocol)
完整的源代码如下:
package example
import scala.concurrent.duration._
import java.util.concurrent.ThreadLocalRandom
import io.gatling.core.Predef._
import io.gatling.http.Predef._
class DemoScenario extends Simulation {
object Protocols {
val httpProtocol = http
.baseUrl("http://www.dneonline.com")
.contentTypeHeader("text/xml; charset=utf-8").build
}
object Task {
def xmlPath = exec(http("Addition Task")
.post("https://224926-685269-raikfcquaxqncofqfm.stackpathdns.com/calculator.asmx?op=Add")
.body(StringBody("""<?xml version="1.0" encoding="utf-8"?>
<soap:Envelope xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns:soap="http://schemas.xmlsoap.org/soap/envelope/">
<soap:Body>
<Add xmlns="http://tempuri.org/">
<intA>100</intA>
<intB>200</intB>
</Add>
</soap:Body>
</soap:Envelope>"""))
.check( regex( "(?<=<AddResult>)(.*\\n?)(?=</AddResult>)" ).is("300") ))
val scenario_xml = scenario("Execute Sample API Test").exec(Task.xmlPath)
setUp(scenario_xml.inject(rampUsers(10) during (10 seconds))).protocols(Protocols.httpProtocol)
}
本文内容不用于商业目的,如涉及知识产权问题,请权利人联系51Testing小编(021-64471599-8017),我们将立即处理