Sunday, December 14, 2014

How to get coordinates or dimensions of web element with Python using Selenium Webdriver

driver = webdriver.Firefox()
e = driver.find_element_by_xpath("//someXpath")
location = e.location
size = e.size
print(location)
print(size)

{'y': 202, 'x': 165}
{'width': 77, 'height': 22}

Sunday, December 7, 2014

How to download files in Mozilla using Selenium Webdriver

FirefoxProfile firefoxProfile = new FirefoxProfile();

firefoxProfile.setPreference("browser.download.folderList",2);
firefoxProfile.setPreference("browser.download.manager.showWhenStarting",false);
firefoxProfile.setPreference("browser.download.dir","c:\\downloads");
firefoxProfile.setPreference("browser.helperApps.neverAsk.saveToDisk","text/csv");

Here text/csv is a mime type, change this mime type depending on the file type you want to download

Popular mine types

PDF => application/pdf
Text file => text/plain
.exe => application/octet-stream
MS Doc => application/msword
xls => application/excel
.zip => application/x-compressed
.tgz => application/gnutar

How to download files in IE using Selenium Webdriver

public void clickAndSaveFileIE(WebElement element) throws AWTException, InterruptedException {

    Robot robot = new Robot();

    // Get the focus on the element..don't use click since it stalls the driver        
    element.sendKeys("");

    //simulate pressing enter          
    robot.keyPress(KeyEvent.VK_ENTER);
    robot.keyRelease(KeyEvent.VK_ENTER);

    // Wait for the download manager to open          
    Thread.sleep(2000);

    // Switch to download manager tray via Alt+N
    robot.keyPress(KeyEvent.VK_ALT);
    robot.keyPress(KeyEvent.VK_N);
    robot.keyRelease(KeyEvent.VK_N);
    robot.keyRelease(KeyEvent.VK_ALT);

    // Press S key to save          
    robot.keyPress(KeyEvent.VK_S);
    robot.keyRelease(KeyEvent.VK_S);
    Thread.sleep(2000);

    // Switch back to download manager tray via Alt+N
    robot.keyPress(KeyEvent.VK_ALT);
    robot.keyPress(KeyEvent.VK_N);
    robot.keyRelease(KeyEvent.VK_N);
    robot.keyRelease(KeyEvent.VK_ALT);

    // Tab to X exit key
    robot.keyPress(KeyEvent.VK_TAB);
    robot.keyRelease(KeyEvent.VK_TAB);

    robot.keyPress(KeyEvent.VK_TAB);
    robot.keyRelease(KeyEvent.VK_TAB);

    robot.keyPress(KeyEvent.VK_TAB);
    robot.keyRelease(KeyEvent.VK_TAB);

    // Press Enter to close the Download Manager
    robot.keyPress(KeyEvent.VK_ENTER);
    robot.keyRelease(KeyEvent.VK_ENTER);

}

How to download files in Chrome using Selenium Webdriver

//Get Chrome Driver
System.setProperty("webdriver.chrome.driver", "/path/to/chromedriver");
String downloadFilepath = "/path/to/download";

//Save Chrome Preferences in Hash Map
HashMap<String, Object> chromePrefs = new HashMap<String, Object>();
chromePrefs.put("profile.default_content_settings.popups", 0);
chromePrefs.put("download.default_directory", downloadFilepath);

//Save Chrome Opions
ChromeOptions options = new ChromeOptions();
HashMap<String, Object> chromeOptionsMap = new HashMap<String, Object>();
options.setExperimentalOptions("prefs", chromePrefs);
options.addArguments("--test-type");

//Set desired capability
DesiredCapabilities cap = DesiredCapabilities.chrome();
cap.setCapability(ChromeOptions.CAPABILITY, chromeOptionsMap);
cap.setCapability(CapabilityType.ACCEPT_SSL_CERTS, true);
cap.setCapability(ChromeOptions.CAPABILITY, options);

//Start Chrome Driver
WebDriver driver = new ChromeDriver(cap);

Sunday, November 30, 2014

If there is a pop-up coming on the page for a fraction of second, and if you have to capture the text appearing on it, how would you capture it?

Answer to a question from LinkedIn

https://www.linkedin.com/groups/If-there-is-popup-coming-4285318.S.5942940576692314114?view=&item=5942940576692314114&type=member&gid=4285318&trk=eml-b2_anet_digest-hero-4-hero-disc-disc-0&midToken=AQHTpw42IOK2Ew&fromEmail=fromEmail&ut=3htuvU3cBnrSw1

If you using webdriver, then does not matter if what you see on screen or how long it actually appears
Selenium Webdriver just works on the source of your web page, Since you said it is a pop up, either it is alert msg or a javascript pop up.

It cannot be a alert since it appeard for a fraction of second and withtout user input it goes away, so it must be a Javascipt pop up.

To capture this there are two ways.
First, directly invoke the javascript from selenium and capture it seperately and then use them in your actual scipt
Second, Use any Man in the middle Software such as Fiddler(for asp .net but can be used for jsp as well) and stop the screen when the particular Javascript is called so you can capture it.

Tuesday, November 25, 2014

How to execute SoapUI Project from Command Line

SoapUI currently comes with the following command line tools for running TestCases and LoadTests

loadtestrunner.bat => To run Load test
mockservicerunner.bat => to run mock services
securitytestrunner.bat => to run security test
testrunner.bat => Used to run your soapui testcases
toolruner.bat => Runs any of the configured Code Generation tools for specified project and interface
wargenerator.bat => used to generate war files

Syntax to run command line tools is

<command line tool> <parameters> <report(optional)> <project>
eg
testrunner.bat     -FPDF     -R"Project Report"     c:\projects\my-soapui-project.xml

Another example
Here we will pass the property which will be  used in run the test

1)testrunner.bat -P username=ss123 Cc:\projects\my-soapui-project.xml
-P => Sets project property with name=value which can be used to run testsuites

2)testrunner.bat -r c:\projects\my-soapui-project.xml
-r => prints a small report in console

SoapUI 5.0.0 TestCaseRunner Summary
-----------------------------
Time Taken: 5301ms
Total TestSuites: 2
Total TestCases: 2 (1 failed)
Total TestSteps: 3
Total Request Assertions: 2
Total Failed Assertions: 0
Total Exported Results: 1

3)testrunner.bat -j c:\projects\my-soapui-project.xml
-j will create Junit style reports, the xml generated will be in the bin folder of SoapUI

4)testrunner.bat -e www.google.com  c:\projects\my-soapui-project.xml
-e => set end point url, overrides the endpoint set in the project file

5)testrunner.bat -h www.google.com:9001  c:\projects\my-soapui-project.xml
 -h => overrides only the host part of the endpoint set in the project file

Sunday, November 23, 2014

getNodeValues in XmlHolder for SoapUI

def request = '''<xml>
   <node>
      <val1>pqr</val1>
      <val2>abc</val2>
   </node>
   <node>
      <val1>xyz</val1>
      <val2>lmn</val2>
   </node>
</xml>'''


def groovyUtils = new com.eviware.soapui.support.GroovyUtils( context )
def holder = new com.eviware.soapui.support.XmlHolder( request )


// loop item nodes in response message

//get All occurance of node/val1
log.info "--------First For loop------------"
for( item in holder.getNodeValues( "//node/val1" ))
log.info "Node : [$item]"

OUTPUT

Sun Nov 23 19:51:36 IST 2014:INFO:--------First For loop------------
Sun Nov 23 19:51:36 IST 2014:INFO:Node : [pqr]
Sun Nov 23 19:51:36 IST 2014:INFO:Node : [xyz]
Sun Nov 23 19:51:36 IST 2014:INFO:--------Second For loop------------
Sun Nov 23 19:51:36 IST 2014:INFO:Node : [pqr]

How to removenodes from Request/Response for assertion

import com.eviware.soapui.support.*
def soapmessage = '''<ns:basket xmlns:ns="http://example.com">
                    <ns:fruit>
                    <ns:name>banana</ns:name>
                          <ns:color>yellow</ns:color>
                         </ns:fruit>
                       <ns:fruit>
                          <ns:name>apple</ns:name>
                          <ns:color>green</ns:color>
                         </ns:fruit>
                       <ns:fruit>
                         <ns:name>strawberry</ns:name>
                          <ns:color>red</ns:color>
                         </ns:fruit>
                    </ns:basket>'''


def groovyUtils = new com.eviware.soapui.support.GroovyUtils( context )

def holder = new com.eviware.soapui.support.XmlHolder( soapmessage )
  //holder.namespaces["ns"] = "http://example.com"
  //holder.declareNamespace("ns", "http://example.com")

assert holder.getNodeValue("//ns:fruit[2]/ns:color[1]") == "green"

holder.removeDomNodes("//*:fruit[2]")

assert holder.getNodeValue("//ns:fruit[2]/ns:color[1]") == "red"
log.info "Done"

How to access property in Script Assertion in SoapUI using Groovy Script

//Set Property
messageExchange.modelItem.testStep.testCase.setPropertyValue("MyProp", someValue)

//Get Property
def testCaseProperty = messageExchange.modelItem.testStep.testCase.getPropertyValue("MyProp")

Setting and Getting properties at all levels in SoapUI with Groovy Script

Getting Properties…

-From a Groovy Script test step
def testCaseProperty = testRunner.testCase.getPropertyValue("MyProp")
def testSuiteProperty = testRunner.testCase.testSuite.getPropertyValue("MyProp")
def projectProperty = testRunner.testCase.testSuite.project.getPropertyValue("MyProp")
def globalProperty = com.eviware.soapui.SoapUI.globalProperties.getPropertyValue("MyProp")

Setting Properties…

-From a Groovy Script test step:
testRunner.testCase.setPropertyValue("MyProp", someValue)
testRunner.testCase.testSuite.setPropertyValue("MyProp", someValue)
testRunner.testCase.testSuite.project.setPropertyValue("MyProp", someValue)
com.eviware.soapui.SoapUI.globalProperties.setPropertyValue("MyProp", someValue)

How to save all Test Case properties in a Map using Groovy Script

def tcProps = testRunner.testCase.getProperties()
def map = [:]

//grab all the properties from the test case and put them in a map as long as they aren't empty
for(p in tcProps){    
            if (p.value.getValue() != "") {
            map.put(p.key, p.value.getValue())            
    } 
}

XML Parser in SoapUI

def studentRecords = ''' 
        <students> 
              <student name='sname' id='sid' college='collegename' /> 
        </students> 
    ''' 
def records = new XmlParser().parseText(studentRecords) 
def requiredMap = records.student[0].attributes()


log.info "entrySet() shows name value pairs ==> "+requiredMap.entrySet()
// An EntrySet is just a thin wrapper providing a view of objects that already exist inside the HashMap
log.info "keySet() shows only keys ==> "+requiredMap.keySet()
log.info "containsKey, check if id tag is present ==> "+requiredMap.containsKey("id")
log.info "conatinsValue, check if id tag VALUE is present ==> "+requiredMap.containsValue("sid")
log.info "get value of the key id ==> "+requiredMap.get("id")
log.info "check if map is empty ==> "+requiredMap.isEmpty()
log.info "add value to map ==> "+requiredMap.put("sagar" , "singh")
log.info "entrySet() values are ==> "+requiredMap.entrySet()
//log.info "remove from map ==> "+requiredMap.remove("sagar")
//log.info "entrySet() values are ==> "+requiredMap.entrySet()

OUTPUT

Sun Nov 23 19:11:59 IST 2014:INFO:entrySet() shows name value pairs ==> [name=sname, id=sid, college=collegename]
Sun Nov 23 19:11:59 IST 2014:INFO:keySet() shows only keys ==> [name, id, college]
Sun Nov 23 19:11:59 IST 2014:INFO:containsKey, check if id tag is present ==> true
Sun Nov 23 19:11:59 IST 2014:INFO:conatinsValue, check if id tag VALUE is present ==> true
Sun Nov 23 19:11:59 IST 2014:INFO:get value of the key id ==> sid
Sun Nov 23 19:11:59 IST 2014:INFO:check if map is empty ==> false
Sun Nov 23 19:11:59 IST 2014:INFO:add value to map ==> null
Sun Nov 23 19:11:59 IST 2014:INFO:entrySet() values are ==> [name=sname, id=sid, college=collegename, sagar=singh]
Sun Nov 23 19:11:59 IST 2014:INFO:remove from map ==> singh
Sun Nov 23 19:11:59 IST 2014:INFO:entrySet() values are ==> [name=sname, id=sid, college=collegename]

How to transfer property proerty to all Test Cases in Test Suite an access it

Transfer property to all TC

def ABC = testRunner.testCase.testSuite.project.getTestSuiteList()
def DEF = testRunner.testCase.testSuite.getPropertyValue("w2_SessionID")

for (testSuite in ABC){
for (testCase in testSuite.getTestCaseList()){
testCase.setPropertyValue("w2_SessionID", DEF)
}
}


Access property in each Test Case

def abdProjProp = context.expand( '${#Project#abdProjProp}' )

How to run a TestCase located in another project

def prj = testRunner.testCase.testSuite.project.workspace.getProjectByName("ProjectName")

2.tCase = prj.testSuites['TestSuiteName'].testCases['TestCaseName']

3.tStep = tCase.getTestStepByName("TestStepName")

4.def runner = tStep.run(testRunner, context)

How to transfer properties between projects

//get test case from other project
project = testRunner.getTestCase().getTestSuite().getProject().getWorkspace().getProjectByName(project_name)
testSuite = project.getTestSuiteByName(suite_name);
testCase = testSuite.getTestCaseByName(testcase_name);

//set properties
testRunner.testCase.setPropertyValue(property_name, property_value);
testRunner.testCase.setPropertyValue(another_property_name, another_property_value);

// run test case
runner = testCase.run(new com.eviware.soapui.support.types.StringToObjectMap(), false);