Friday, September 23, 2016

SoapUi: Reusable methods , functions

Reusable methods , functions

https://community.smartbear.com/t5/SoapUI-NG/How-to-write-a-reusable-script-Library/td-p/29499

Reusable methods:


Create project as  :- Library(TestSuite-disabled) > module-name(TC) >Example(groovy Script)

In Example file(groovy Script) copy paste:
context.setProperty( "example", new Example( log, context, testRunner) )
class Example{
 def log
 def context
 def testRunner
 public  Example(logIn,contextIn,testRunnerIn){
  this.log=logIn
  this.context = contextIn
    this.testRunner = testRunnerIn
 }
 public String execute(message) { 
       return message
 }
}

Create another testsuite >testcase>groovyscript and paste below code and Run:

library = testRunner.testCase.testSuite.project.testSuites["Library"]
module = library.testCases["module-name"].testSteps["Example"]
module.run(testRunner, context)

// get the instance of example from the context.
def example = context.example
log.info(example.execute("hi"))

Saturday, September 17, 2016

SOAPUI : Using Selenium in SoapUi

Using Selenium in SoapUi


  1. Download Selenium.jar files from the following link,  (http://www.seleniumhq.org/download/)
  2. Download the Java language version of the Jars, once that is done a ZIP folder should be downloaded onto your PC.
  3. Unzip the Selenium – Java-'version no' folder.
  4. Open the unzipped folder.
  5. Copy the selenium-java-2.52.0.jar and selenium-java-2.52.0-srcs.jar from the folder.
  6. Open the SoapUI directory folder (In the previous chapter I opted for a default location, such as C:\Project\SoapUI. Refer to this location).
  7. Place these jars in the following locations: ext folder and lib folders
  8.  Once you have pasted the Jars in the ext folder you also need to paste them in the lib folder of SoapUI as well.
  9. After this step we are done with the setup we now need to work on the Groovy script.
    Following is sample Groovy script for invoking a UI from SoapUI using Groovy script enabled by Selenium Jars:

    import com.eviware.soapui.model.*
    import com.eviware.soapui.model.testsuite.Assertable
    import com.eviware.soapui.support.XmlHolder
    import java.io.File;
     
     def regLogger = org.apache.log4j.Logger.getLogger("RegressionTestLoger");
    def groovyUtils = new com.eviware.soapui.support.GroovyUtils( context )
    def properties = new java.util.Properties();
     
     import org.openqa.selenium.remote.CapabilityType;
    import org.openqa.selenium.remote.DesiredCapabilities;
    import com.thoughtworks.selenium.Selenium;
    
    WebDriver driver = new FirefoxDriver();
    driver.manage().deleteAllCookies();
    driver.manage().window().maximize();
      WebDriver driver = new FirefoxDriver();  
      driver.get("http://www.google.com ");
     
     
    sample script for UI automation using the Chrome driver:
    Chrome:
    you need to install the Chrome driver and set the path of the chrome driver in the path of the system or uncomment  "System.setProperty" from the code below:
     
    import org.openqa.selenium.*;
    import org.openqa.selenium.JavascriptExecutor;
    import org.openqa.selenium.firefox.FirefoxDriver;
    import org.openqa.selenium.interactions.Actions;
    import org.openqa.selenium.ie.InternetExplorerDriver;
    import com.eviware.soapui.model.*
    import org.openqa.selenium.chrome.ChromeDriver;
    import com.eviware.soapui.model.testsuite.Assertable
    import com.eviware.soapui.support.XmlHolder
    import java.io.File;
    //import java.util.*;
    //import jxl.write.*
    //import jxl.*
    def regLogger = org.apache.log4j.Logger.getLogger("RegressionTestLoger");
    def groovyUtils = new com.eviware.soapui.support.GroovyUtils( context )
    def properties = new java.util.Properties();
    import org.openqa.selenium.remote.CapabilityType;
    import org.openqa.selenium.remote.DesiredCapabilities;
    import com.thoughtworks.selenium.Selenium;
    
    //System.setProperty("webdriver.chrome.driver", "C:\\Program Files\\SmartBear\\SoapUI-5.0.0\\bin\\ext\\chromedriver.exe");
    //WebDriver driver = new ChromeDriver();
                         driver.manage().deleteAllCookies();
     driver.get("http://www.google.com ");
     
     
 

Sunday, August 28, 2016

SoapUi : SoapUi Basics

SoapUi Basic


WSDL - WEB Service Def lang
XML file in webservice = wsdl file
https://www.soapui.org/rest-testing/understanding-rest-parameters.html
https://www.soapui.org/tutorials/flickr.html
http://www.omdbapi.com/
http://www.jsontest.com/
http://headers.jsontest.com/
http://date.jsontest.com/
https://learnsoapui.wordpress.com/2011/07/17/10-groovy-scripts-on-your-finger-tips-soapui/
https://www.soapui.org/scripting-properties/tips-tricks.html

SoapUI
When project is created it automatically creates a scratch pad for request response testing.
User has to manually create testSuite>testcase>testStep

1. Groovy = Java
2. log.error("")  //to log errorand log file in soapui>bin>error.log
3. log.info("")   //to log info soapui>bin
4. to change path of log file soapui\bin\log4j.xml
5. Project>testSuite>testcase> test step(groovy step)
6. see variable =
int x=100
log.info("$x") or log.info(x)"
7. SoapUI saves project as xml
8. to open saved project , File>Import xml
9. Loops ,Conditional statements = Java
10. Normal java like initialization can be used or "def" is also used declare or initialize a variable

11. Access SoapUI methods and functions inside a class

Eg:
planet.log=log   
planet.printdata()

class planet{
  def static log  //declare using def
   public static void printdata(){log.info("hi")}
}

or

obj=new A(testRunner,log)

class A{
def testRunner,log

A(testRunner,log){
this.testRunner=testRunner
this.log=log
}
}


12. Assertions are added to  Response steps only :
(https://www.youtube.com/watch?v=ssOfIyAD8ZI)
(http://www.softwaretestinghelp.com/soapui-tutorial-13-soap-vs-rest-services/)
https://www.youtube.com/watch?v=1QMCZ3x227U   -- namespace
a. Valid response
b. Data
c. tag names
d. Data count
e. Time taken
f. Status (Eg:200 OK)
g. Assertions can only be added test step

13. To add an assersion :
a. Create Rest Project for URL
http://www.softwaretestinghelp.com/soapui-tutorial-13-soap-vs-rest-services/
"http://maps.googleapis.com/maps/api/geocode/xml?address=1600+Amphitheatre+Parkway,+Mountain+View,+CA&sensor=false"
b. Run > User will get a response
c. Ck Project>Add test Suite > add a test case >
d.  rt click on test Case>Add step> add REST request >OK >OK
e. In Rest Request Window > Below the screen ,Click Assertions  > Click "+"
f. Add Assertion window > property Content>Contains> "Mountain View"  (without quotes)>Add
g. Result in green - valid
h. Repeat above step with "Deepak" = Result is Red - Failed
- user can add tag names , anything from the request etc., as Well for validation

14. Assertion :Xpath match  (http://www.w3schools.com/xsl/xsl_functions.asp)
a. To validate Xpath - exists(//status) and press Select current button
b. To count tagnames- count(//name) and press Select current button 
c. to validte if tagname "type" exists - exists(//result/type)   and press test
(User can write true or false in Expected result and validate the result)
d. to valiate a pattern - matches(//result/formatted_address,'[a-zA-Z]*')
e. for validating functions - matches(//result/type,'\d')
-- XQuery not frequently used(Google XQuery)

15 . Xquery

16. Extract Json values
import groovy.json.JsonSlurper
responseContent = testRunner.testCase.getTestStepByName("testStepname").getPropertyValue("response")
slurperresponse = new JsonSlurper().parseText(responseContent)
log.info(slurperresponse.node)

17. Extract XML values
responseContent = testRunner.testCase.getTestStepByName("Authorize").getPropertyValue("response")
def result=new XmlSlurper().parseText(responseContent)
log.info result


or

def groovyUtils = new com.eviware.soapui.support.GroovyUtils( context )
responseContent = testRunner.testCase.getTestStepByName("TestStepname").getPropertyValue("response")
//"response" is keyword
def holder = groovyUtils.getXmlHolder(responseContent)
log.info holder.getNodeValue("//locale/recordId")  // "locale/recordId" = //Parentnode/node


18 .Properties :
Create
com.eviware.soapui.SoapUI.globalProperties.setPropertyValue( "prjFromCurrency", "USD" )//global
testRunner.testCase.testSuite.project.setPropertyValue( "Project_Level_Property",value.toString( ))
testRunner.testCase.testSuite.setPropertyValue( "Testsuite_Property",value.toString( ))
testRunner.testCase.setPropertyValue( "Auth", result.toString() )


Retreive Property in Groovy Script
testRunner.testCase.testSuite.getPropertyValue("Auth")

Retreive property in Request
${#Scope#Property-name[#xpath-expression]}  // Access property in request
Eg :
 ${UserName}  -- Global
${#Project#UserName}  -- Project level
${#TestSuite#UserName} -- test Suite Level
${#TestCase#UserName} -- test Case Level
${TestStep-name#Property-name}    -- Named TestStep


Remove
testRunner.testCase.removeProperty( "Testcase_Property" );


19. SLA Assersion - To check the response time
Eg : if 200 is entered then the result is pass or Fail , if the response if below or above 200 ms

20. Security Assertion
SoapUi will search the added keyword in the response , if the added data is present in the response then the test will fail

21 Compliance ,Status and Standards(important)
REST always works on top of Http
a. Invalid Http Codes - Enter 4xx codes Eg:404 etc., If the response does not contain the mentioned invalid codes then it will pass.
B.valid Http Codes - Enter 2xx codes Eg:200 etc., If the response contain the mentioned invalid codes then it will pass.

22. To Create a new step with different Request Parameters:
In the scratch pad , goto the request which gets added correctly in the test step
In the same scratch pad request, click on "+" button to add a new parameter
Once added , when u create a new test step that paramter gets automatically  added

23. Adding Quotes values stored in Property files :
testRunner.testCase.setPropertyValue("token","\"${result}\"")


24. Properties Step (Storing value for global access):
    testRunner.testCase.getTestStepByName(""propertyname"").setPropertyValue(""usn"",""Value"")
    ${property#usr}
    val=myTestCase.getTestStepByName(""propertyname"").getPropertyValue(""usn"")



25 .Header
    Accept:application/json

26. Class in groovy :
    p=new planet()
    p.test1()
    log.info p.s

    class planet{
    String s;
    public void test1()
     {
         s=""hi""
         }
    }

27. Using Apache POI in SOAP-UI
    import java.io.File;
    import java.io.FileInputStream;
    import java.io.FileNotFoundException;
    import org.apache.poi.hssf.usermodel.HSSFSheet
    import org.apache.poi.hssf.usermodel.HSSFWorkbook
    import org.apache.poi.ss.usermodel.Cell
    import org.apache.poi.ss.usermodel.Row
    import org.apache.poi.ss.usermodel.Sheet
    import org.apache.poi.ss.usermodel.Workbook
    import org.apache.poi.ss.usermodel.WorkbookFactory

     Workbook wb = WorkbookFactory.create(new FileInputStream(""D:\\Work_related\\soapUI\\Framework\\framework.xls""));
     Sheet Sheet_integration = wb.getSheet(""integration"");
     Sheet Sheet_authentication = wb.getSheet(""authentication"");
     log.info( sheet.getRow(0).getCell(0).getRichStringCellValue() ); // Read Cell



 28.Goto or Jump
    testRunner.gotoStepByName("data driver") //setStartStep

29.To String and To Integer
    counter = propTestStep.getPropertyValue(""Count"").toString()
    counter = counter.toInteger()


30. context keyword :
The main usage for this is to store values or objects that can be used in subsequent TestSteps or related scripts.
Eg:
    context.myProperty = ""Hello""
    log.info( context.myProperty )

(will create a property named ""myProperty"" in the context and assign it the string value ""Hello")


31. Reuseable methods (https://community.smartbear.com/t5/SoapUI-NG/How-to-write-a-reusable-script-Library/td-p/29499):
    Create project as  :- Library(TestSuite-disabled) > module-name(TC) >Example(groovy Script)

    In Example file copy paste:
        context.setProperty( ""example"", new Example( log, context, testRunner) )
        class Example{
         def log
         def context
         def testRunner
         public  Example(logIn,contextIn,testRunnerIn){
          this.log=logIn
          this.context = contextIn
            this.testRunner = testRunnerIn
         }
         public String execute(message) { 
               return message
         }
        }
Create another testsuite >testcase>groovyscript and paste below code and Run:
        library = testRunner.testCase.testSuite.project.testSuites[""Library""]
        module = library.testCases[""module-name""].testSteps[""Example""]
        module.run(testRunner, context)


        // get the instance of example from the context.
        def example = context.example
        log.info(example.execute(""hi""))


32. Access Properties from another TestSuite:
    library = testRunner.testCase.testSuite.project.testSuites[""Library""]
    prop= library.testCases[""module-name""].testSteps[""Properties""]
    log.info(prop.getPropertyValue(""a""))

 


33. Passing objects to different script file :Groovy Script file 1:
def kmauthtoken_list=new ArrayList<String>();
context.setProperty( "kmauthtoken_list", kmauthtoken_list)

 
Groovy script file 2:
def kmauthtoken_list=context.kmauthtoken_list
kmauthtoken_list.add("somevalue")

SoapUi : Read and Write xls (excel)

SOAPUI: Read and Write xls




 


1. Download and jexcel.zip
2. Unzip and copy paste jxl.jar into SoapUI\lib
3. Restart SoapUI .
4. Create a new Rest Project in soapui
5. Create a new testsuite>testcase>Add 2 steps = groovystep , properties step
6. Rename properties as "property
7. Add 2 property: usn , pass
8. Create a new xls file in "D:login.xls" drive like above screenshot
9. Add below script into "Groovy Step"

 Script :

import com.eviware.soapui.support.XmlHolder
import jxl.*
import jxl.write.*

// DECLARE THE VARIABLES

def myTestCase = context.testCase //myTestCase contains the test case
def counter,next,previous,size //Variables used to handle the loop and to move inside the file

propTestStep = myTestCase.getTestStepByName("property") // get the Property TestStep object

Workbook workbook1 = Workbook.getWorkbook(new File("d:\\login.xls")) //file containing the data
Sheet sheet1 = workbook1.getSheet(0) //save the first sheet in sheet1
size= sheet1.getRows().toInteger() //get the number of rows, each row is a data set

for(int i=0;i<=size-1;i++){
Cell uData = sheet1.getCell(0,i) // getCell(column,row) //obtains user
Cell pData = sheet1.getCell(1,i) // obtains password

propTestStep.setPropertyValue("usn", uData.getContents()) //the value is saved in the property
propTestStep.setPropertyValue("pass", pData.getContents()) //the value is saved in the property
Thread.sleep(2000)
}
workbook1.close()

To call the properties into request :

${property#usr}
${property#pass}