Wednesday, March 9, 2016

Useful Groovy Scripts for SoapUI

Basics of Groovy Script…

1.       To Print in the console
log.info(“Print Groovy”)

OutPut :- Print Groovy



2.       To get Test Case Name
Type 1 - log.info(testRunner.testCase.name)
Type 2 - log.info(context.getTestCase().name)
Type 3 - log.info(context.testCase.name)

OutPut :- Test Case 1



3.       To get Test Suite Name
Type 1 - log.info(context.testCase.testSuite.name)
Type 2 - log.info(context.getTestCase().getTestSuite().name)
Type 3 - log.info(testRunner.testCase.testSuite.name)

OutPut :- Test Suite 1



4.       To get Project Name
Type 1 - log.info(context.testCase.project.name)
Type 2 - log.info(context.testCase.testSuite.project.name)
Type 3 - log.info(context.getTestCase().getProject().name)
Type 4 - log.info(context.getTestCase().getTestSuite().getProject().name)
Type 5 - log.info(testRunner.testCase.project.name)
Type 6 - log.info(testRunner.getTestCase().getProject().name)
Type 7 - log.info(testRunner.testCase.testSuite.project.name)
Type 8 - log.info(testRunner.getTestCase().getTestSuite().getProject().name)

OutPut :- tempconvert (P.S. Same output for all above query)



5.       To get Test Case Count and Test Case Name
def testCases = context.testCase.testSuite.getTestCaseList()
log.info("Number Test Cases Present :- "+testCases.size())
testCases.each  {
        log.info("Test Cases Name :- "+it.name)
}

OutPut :- Number Test Cases Present :- 2
                           Test Cases Name :- TestCase 1
   Test Cases Name :- TestCase 2



6.       To get Test Suite Count and Test Suite Name
def testSuites = context.testCase.project.getTestSuiteList()
log.info("Number Test Suites Present :- "+testSuites.size())
testSuites.each  {
        log.info("Test Suite Name :- "+it.name)
}

OutPut :- Number Test Suites Present :- 2
                           Test Suite Name :- TestSuite 1
   Test Suite Name :- TestSuite 2



7.       To get Project Count and Project Name
def getProjectsList = testRunner.testCase.testSuite.project.workspace.getProjectList()
log.info("Number of Projects :- " +getProjectsList.size)
for(i in 0..getProjectsList.size-1 ){
        log.info("Project name :- "+getProjectsList.getAt(i).name)
}

        OutPut :- Number of Projects :- 5
   Project name :- Project1
   Project name :- Project2
   Project name :- Project3
   Project name :- Project4
   Project name :- Project5



8.       To get count of blank spaces
def val = "Groovy Scripting Language is used for SOAPUI"
def sval = val.replaceAll(" ","")
def sCount =  val.size() - sval.size()
 log.info("Count of Blank (' ') spaces is = $sCount")

OutPut :- Count of Blank(‘ ‘) spaces is = 6



9.       To get count of SAME Char repeated
def val = "Groovy"
def sval = val.replaceAll("o","")
def sCount =  val.size() - sval.size()
 log.info("The Char 'o' Repeats = $sCount Times")

        OutPut :- The Char 'o' Repeats = 2 Times



10.   To set project property values

testRunner.testCase.testSuite.project.setPropertyValue("ProjectProp"," ProjectProp Value")
context.getTestCase().getTestSuite().getProject().setPropertyValue("ProjectProp", " ProjectProp Value")



11.   To get project property values

def projPropValue = testRunner.testCase.testSuite.project.getPropertyValue("ProjectProp")
log.info(projPropValue)

def projPropValue1 = context.getTestCase().getTestSuite().getProject().getPropertyValue("ProjectProp")
log.info(projPropValue1)

OutPut :- ProjectProp Value 1
           ProjectProp Value 2




12.   To set TestSuite property values

testRunner.testCase.testSuite.setPropertyValue("TestSuiteProp","TestSuite Property Value")
context.getTestCase().getTestSuite().setPropertyValue("TestSuiteProp","TestSuite Property Value")




13.   To get TestSuite property values

def testSuitePropValue = testRunner.testCase.testSuite.getPropertyValue("TestSuiteProp")
log.info(testSuitePropValue)

def testSuitePropValue1 = context.getTestCase().getTestSuite().getPropertyValue("TestSuiteProp")
log.info(testSuitePropValue)

OutPut :- TestSuite Property Value
           TestSuite Property Value 




14.   To set TestCase property values

testRunner.testCase.setPropertyValue("TestCaseProp", "TestCase Property Value")
context.getTestCase().setPropertyValue("TestCaseProp", "TestCase Property Value")




15.   To get TestCase property values

def testCasePropValue = testRunner.testCase.getPropertyValue("TestCaseProp")
log.info(testCasePropValue)

def testCasePropValue2 = context.getTestCase().getPropertyValue("TestCaseProp")
log.info(testCasePropValue2)

OutPut :- TestCase Property Value
           TestCase Property Value




 ******************* Sample Request XML **************************
Note :-  Here I have taken sample request xml from “SendSMSToIndia” service (http://www.webservicex.net/SendSMS.asmx)
<soapenv:Envelope xmlns:soapenv="http://schemas.xmlsoap.org/soap/envelope/" xmlns:web="http://www.webserviceX.NET">
   <soapenv:Header/>
   <soapenv:Body>
      <web:SendSMSToIndia>
         <web:MobileNumber>9879879785465</web:MobileNumber>
         <web:FromEmailAddress>mail@email.com</web:FromEmailAddress>
         <web:Message>Hi Hello!!!!!</web:Message>
      </web:SendSMSToIndia>
   </soapenv:Body>
</soapenv:Envelope>
************************************************************************


16.   To get Request Content
                        def groovyUtils = new com.eviware.soapui.support.GroovyUtils(context)
def reqHolder = groovyUtils.getXmlHolder("OperationName#Request")

                    reqHolder holds all the request XML content.
      
     Note :- “reqHolder” we will use same variable in our next scripts.




17.   To get or Read request XML tag/Element value
Consider above sample request xml, in that we have three fields 1. MobileNumber, 2. FormEmailAddress and 3. Message.

To get value from each filed use below code.
Syntax :- holder.getNodevalue(“XPATH of xml element name”)
log.info(reqHolder.getNodeValue(“//*:MobileNumber”))
log.info(reqHolder.getNodeValue(“//*:FromEmailAddress”))
log.info(reqHolder.getNodeValue(“//*:Message”))

OutPut :-     9879879785465
                        mail@email.com
Hi Hello!!!!!




18.   To Set values to Request XML tag/element

Syntax :- holder.setNodevalue(“XPATH of xml element name”,”String value”)
reqHolder.setNodeValue(“//*:MobileNumber”, ”2487987646”)
reqHolder.setNodeValue(“//*:FromEmailAddress”, ”email@mailer.com”)
reqHolder.setNodeValue(“//*:Message”, ”Hello World”)
reqHolder.updateProperty ()       // this line of code will save the request xml.

19.   To Get count of xml tag/element

Syntax :- holder[Count(“xml element xpath”)]
log.info(reqHolder["count(//*:MobileNumber)"])
log.info(reqHolder["count(//*:FromEmailAddress)"])
log.info(reqHolder["count(//*:Message)"])

OutPut :- 1
          1
     1






20.   Reading response
******************* Sample Response XML *************************
Note :-  Here I have taken sample response xml from “SendSMSToIndia” service (http://www.webservicex.net/SendSMS.asmx)
<soap:Envelope xmlns:soap="http://schemas.xmlsoap.org/soap/envelope/" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema">
   <soap:Body>
      <SendSMSToIndiaResponse xmlns="http://www.webserviceX.NET">
         <SendSMSToIndiaResult>
            <FromEmailAddress>mail@gmail.com</FromEmailAddress>
            <MobileNumber>9879879785465</MobileNumber>
            <Provider>Not Covered</Provider>
            <State>Not Covered</State>
            <Status>Not Covered</Status>
         </SendSMSToIndiaResult>
      </SendSMSToIndiaResponse>
   </soap:Body>
</soap:Envelope>*********************************************************

Note :- Here we will use same groovyutills class object as we are already created (groovyUtils) object above in at section 16.
def resHolder = groovyUtils.getXmlHolder("OperationName#Response")

resHolder holds all the response XML content.

Note :- “resHolder” we will use same variable in our next scripts.


To read or get value from response xml
Syntax :- holder.getNodevalue(“XPATH of xml element name”)
log.info(resHolder.getNodeValue(“//*:FromEmailAddress”))
log.info(resHolder.getNodeValue(“//*:MobileNumber”))
log.info(resHolder.getNodeValue(“//*:Provider”))
log.info(resHolder.getNodeValue(“//*:State”))
log.info(resHolder.getNodeValue(“//*:Status”))

OutPut :- mail@gmail.com
                9879879785465
    Not Covered
    Not Covered
    Not Covered
  
21.   If… else condition.

Syntax :-  If(condition){
                                      …….
     }
       else{
        …….
}

If(“Groovy”.equals(“Groovy”)){
  log.info(“Pass”)
}else{
  log.info(“Fail”)
}
if(“Groovy”.equals(“Groovi”)){
  log.info(“Pass”)
}else{
  log.info(“Fail”)
}
OutPut :- Pass
OutPut :- Fail
If(10==10){
  log.info(“Pass”)
}else{
  log.info(“Fail”)
}
if(5==8){
  log.info(“Pass”)
}else{
  log.info(“Fail”)
}
OutPut :- Pass
OutPut :- Fail

22.   If …. else if…else condition

Syntax :-  If(condition){
                        …….
     }
       else if{
        …….
}
       else if{
        …….
}
       else{
        …….
}

If(“Groovy”.equals(“Groovy”)){
  log.info(“Groovy”)
}else if(“SoapUI”.equals(“SoapUI”)){
  log.info(“SoapUI”)
}
else{
  log.info(“Fail”)
}
If(“Groovy”.equals(“Groov”)){
  log.info(“Groovy”)
}else if(“SoapUI”.equals(“Soap”)){
  log.info(“SoapUI”)
}
else{
  log.info(“Condition Not Met”)
}
OutPut :- Groovy or SoapUI
OutPut :- Condition Not Met
If(25==25){
  log.info(25)
}else if(48==48){
  log.info(48)
}
else{
  log.info(“Fail”)
}
If(25==50){
  log.info(25)
}else if(48==84){
  log.info(48)
}
else{
  log.info(“Condition Not Met”)
}
OutPut :- 25 or 48
OutPut :- Condition Not Met


23.   For loop
Syntax :-  for(initialization ; condition ; statement){
                        Statement block
}

for(int i = 1; i<=5;i++){
        log.info(i)
}

  OutPut :- 1
     2
     3
     4
     5


24.   How to remove attributes present in XMLtag element
For example:- To configure or set values to element or tag which has ‘nil’ attributes.
Follow the below steps to remove the ‘nil’ attribute from xml tag/element and provide values to it.

Consider sample request xml tag which ‘nil’ attribute as below,
  <sendSMSMessage xsi:nil="true" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"/>

        def sendSMSMessageNode = reqHolder.getDomNode("//*:sendSMSMessage ")                         
        sendSMSMessageNode.attributes.removeNamedItem("xsi:nil")
        sendSMSMessageNode.attributes.removeNamedItem("xmlns:xsi")   
        reqHolder.setNodeValue("//*:sendSMSMessage ", “Hi Hello!!!!!!” )

Here sendSMSMessageNode.attributes.removeNamedItem(“….”) removes attributes present in xml tag.




                         That’s all Folks.


Monday, December 8, 2014

Working With Mock Services (Dynamic Mock Services) in SOAPUI



In my last post, we have seen that what is mock service and how to use it. In the previous blog (http://lgsofttest.blogspot.no/2014/07/web-service-testing-using-mock-service.html) I have described about static mock response, meaning only one response for different inputs in request. Now in this post I am going to describe about dynamic mock response, which gives different response for each different input in request.


Let us start, Create project and test suite, and add Request to Mock Service, as described in my previous blog (http://lgsofttest.blogspot.no/2014/07/web-service-testing-using-mock-service.html). The project structure looks like below, we can see here Default mock response also created.

















Before going to next step, we need to prepare the Input and output test data. We need input data to feed the request xml and same we need output data to configure the mock response. Below is sample test date I have prepared for this post and it look like below,







Now we need to write some groovy script to configure the Mock Response to do this, follow the steps.

Go to “GetGeoIP” request in Mock Service open it by right click or double click on it, Mock Service request editor opens, it will looks like below,




















Now in the above screen we can see Mock response, and Interface and Operation name. In addition, in below pane we can see Dispatch and value as “SEQUENCE”; this is use for passing value or configuring the mock response. Now to configure mock response as per our predefined response values we need to write groovy script, hence select Dispatch value as “SCRIPT”. Once you selected Dispatch as “SCRIPT” and Default Response will be “Response 1”, which is same as mock response, which created when we added our request to mock services. Below is screenshot how it looks like,



















As shown in above screenshot, in Script editor need to write groovy script to configure the mock response. Below is the code to configure the mock response xml.

Mock response has five fields looks like below,
Now write groovy script to pass value to these five fields in mock response.





















Now let us describe the groovy script, in simple steps I will try to explain the script.

Step 1 :- Import all necessary packages the groovy, groovy Utils and excel packages.
Step 2 :- Create objects groovyutil to read the response xml. Using requestxmlholder read all the tags in the response xml.
Step 3 :- Read the excel file from the path, and by using for loop condition we can iterate the excel file until its last row.
Step 4 :- Now assign each cell value to a variable.
Step 5 :- Set variable to response xml tag, the value is the variable will set the by this statement.

Once script is ready save the project, and now add above created variable to response xml tag as below,


In above screenshot we can see mapping of the variables to respective xml tags in mock response xml.

Now we are done with mock response xml configuration dynamically. The groovy script will assign new value every time when the mock response when called by the services. With this, we will get different value in response with this we can assume our service is working fine.
Now run the Test Suite to check request and response for different input to different output. Import the excel file which we have created above to Data Source, and map the fields to request xml.
Start the mock service on the host and port as configured (Refer my previous blog to configure the mock service with host and port name http://lgsofttest.blogspot.no/2014/07/web-service-testing-using-mock-service.html).
Running mock service will look like below,















Below screenshot shows, the request xml is running on the mock service (Mock Service Endpoint in address bar), and value configured from Data source for request xml field.




















Now open the Test Case and run the test case,

















Once the test case running completed verify the request and response xml, to validate the result.




















Click on any of the request to check input data in request xml and output data in response xml.

Request XML with Input data,
















Response xml from Mock response which configured by Groovy script,






















Finally, we are done with mock service testing for our request.

In my next post, I will describe another way of Dynamic mock service.



                             That’s all Folks.


Friday, July 25, 2014

Web Service Testing Using Mock Service in SoapUI.



In This post, I am going to describe you on the very most useful features of SOAPUI, i.e. “Mock Services”.  
First, we should know what “Mock Service” is.
Here Mocking means verifying or testing the actual functionality of a product before testing the product on real service.

In short, when we do not have access to the real web service or server, then simulating or creating stub or local service to check the actual functionality of the service is working fine.

To mock the service please follow the steps,

In this post, I will describe the different ways of testing the service using Mock Service features of SoapUI.
There are two types of Mock Services,
1.      Static Mock Response.
2.      Dynamic Mock Response.

In Static Mock Response, we will get only one kind of response,
In Dynamic Mock Response, Different Mock Response for each or different request receive. Just like live service.

Now let us start with creating Mock Service in SoapUI. Here for my post purpose I am using ‘geoipservice’ (http://www.webservicex.net/geoipservice.asmx?WSDL).

By using above WSDL, create Project as described in my previous post (http://lgsofttest.blogspot.no/2013/12/basics-of-webservice-testing-tool-soapui.html) once you create project, in SoapUI it looks likes as shown in below,

 Now expand the service ‘GetIPServiceSoap’, there you will find the Request or Operations, and create test suite and test case for the request “GetGeoIP”. Please refer my previous blog (http://lgsofttest.blogspot.no/2013/12/basics-of-webservice-testing-tool-soapui.html) to create the Test Suite, Test Case and how to add Test Steps.

In addition, add Data Source and Data Source Loop steps to the Test Step.
Once you done with creating Test Suite and Test Case along with Request in Test Step, the project structure looks like below.


Now it is time to add our request to Mock Service, select the request of the “GetGeoIP”, right click on it, and select ‘Add to MockService’, as below.





















When you select the ‘Add to MockService’ then you will one smaller window, which ask for the name that you want to give it to the mock service. Here I will rename the service as “Test Mock Service” and Click on ‘OK’ button, then SoapUI will add request to Mock Service with default Response attached to it, once you done with it and looks like below;

OR
In a case where we do not have, any default response then have to add our own response valid xml format.
For the post purpose, here I will use the default response.

Now most important thing to do is, creating Test data for our request, in our request there is only one field is present, where need to enter the IP address, along with this need to Response data to the same file (or you can use different file as per your requirements).

Here I will add Test data and response data into the same file and finally the excel file looks like below,

Import this excel file into the Data Source in the Test Step, Refer my previous blog (http://lgsofttest.blogspot.no/2013/04/datadriven-testing-from-soapui-using.html) for how to import excel file to Data Source and mapping the fields.

Once importing the excel file and mapping to fields is done then Data Source and our Request looks like below;

DataSource:-
Request:-
Now it is time to move on to the Mock Service section,

Open the Mock Service that we have created above with the name as ‘Test Mock Service’. Open it by double click or Right Click and select ‘Show MockService Editor’. Mock Service editor opens there you will see the Request Name as ‘GetGeoIP’; this is the request which we have added to Mock Service.
It is time to start the Mock Service, by clicking the ‘Start’ button, but before that, we need to configure the Mock Response. To do that Click on the Request, which is present under Mock Service editor, now you will see Response 1 in GetGeoIP request.


Option I :- Static Mock Response
Provide the values as per your requirement in the default response xml. Here I have provided or configured the Mock Response or Default Response xml with some sample values and it looks like below,

Now we all set to test our service/Request using Mock Service with Mock Response.

Click on Setting buttonto configure the Mock Service details, such as Port Number, Host Name and other stuffs as per your needs, please find the below screen shot which I have configured the mock service. Once configuration is done Click on OK.


Click thebutton to start the Mock Server/Service. The Mock Service will run on the Host and Port on which you provided in settings.
Once you start the mock service, you can see the service running status in Mock Service Editor bar as below,


Once you confirmed that the Mock Service is running, and then go to Test Suite where request is present open the request and add the new endpoint as same as which you configured in Mock Service settings box. This New endpoint you can get from browser address bar when you click the button in Mock Service editor (as shown in above screenshot.), follow the steps to add new endpoint or server address as below,


Once you select the Option as “add new endpoint” one-popup box opens, there need to enter the new endpoint and click ok, new endpoint will looks like below and its visible in address bar;


Make sure the Mock Service is running , and now Click thebutton to Run the request, once the request executed successfully in right hand side pane you will see the response which is same as you configured in Mock Services section.

Open the Test Case Editor to execute all your test cases, in the Right hand side pane of the Test Case editor you can see test steps arranged as Data Source, Test Request and Data Source loop.


Click thebutton to run the Test Case, SoapUI will run all the test case, which are present in Data Source until last row.

Once the Test case execution is done you will see the status as “Finished” and in below pane you will see the logs how the test case executed in order, click on the Request in logs pane to see the request and response xmls.

Click on the any “GetGeoIP - Request 1” step in logs pane, a new window opens there you will see Request and Response tabs, click on respected tab to view the details,

Below is the Request XML, which sent with IPAddress,

Response xml, which got from Service/Server, here Server/Service, is our own created Mock Service; the response is same for all the test case, as we have created Static Mock response as below,



Yes, now you are done with Testing of service with use of Mock Service, Here I have done Mock Service testing of service for static values in Mock Response, in my next post I will describe about Dynamic Mock Response.

Please note :-  This is for SoapUI Pro version not SoapUI Open source, It can be done with SoapUI Open Source also only thing is in SoapUI open source there is no Data Source and Data Source Loop feature available. Other than Data Source and Data Source Loop, Adding Request to the Mock Service, configuring the Mock Response with our own values and changing the Mock Service sever settings like Port and Host name is available in SoapUI open source.

So In SoapUI Open Source add request to Mock Service and configure settings and Mock Response, start the mock service/server and change the End Point in request address bar and Run the request, you will see the mock response.
With This…

That’s all Folks.