Sunday, March 4, 2018

Automating Notepad with AutoIt

AutoIt - Introduction - Get Auto It, Install, Components

AutoIT tutorial 2 Run from SciTe Editor


AutoIT tutorial 3 Open notepad


AutoIT tutorial 4 Wait For window to open


AutoIT tutorial 5 type a text


AutoIT tutorial 6 Save Notepad file using File Save Menu


AutoIT tutorial 7 focus file, type name, click on save button


AutoIT tutorial 8 Close Window


Full Source Code: for Notepad Automation


      Run("notepad.exe")
      WinWaitActive("Untitled - Notepad")
      Send("This is sample text")
      WinMenuSelectItem("Untitled - Notepad","","&File","&Save")
      WinWaitActive("Save As")
      ControlFocus("Save As", "", "Edit1")
      ControlSend("Save As","","Edit1","demo3.txt")
      ControlClick("Save As","&Save","Button1")
      WinWaitActive("demo3.txt - Notepad")
      WinClose("demo3.txt - Notepad")

AutoIT tutorial 9 File Upload Dialog Automation



AutoIT tutorial 10 Integrate AutoIt Automation With WebDriver Automation


AutoIT tutorial 11 Parameterize AutoIt Script, Pass file path as argument


Full AutoIt Source Code: Upload Dialog Automation

      WinActivate("Open")
      WinWaitActive("Open")
      ControlSend("Open","","Edit1",$CmdLine[1]);
      ControlClick("Open","&Open","Button1")

WebDriver & AutoIt integration code


Text:
import java.io.IOException;
import java.util.concurrent.TimeUnit;

import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.chrome.ChromeDriver;
import org.testng.Assert;
import org.testng.annotations.Test;

/**
 * Upload file using Using AutIT
 * 
 * @author vikas
 *
 */
public class Example4 {

@Test
public void testCase1() {

System.setProperty("webdriver.chrome.driver", "e:\\drivers\\chromedriver.exe");
WebDriver driver = new ChromeDriver();
driver.get("https://smallpdf.com/word-to-pdf");
driver.manage().timeouts().implicitlyWait(30, TimeUnit.SECONDS);
WebElement fileUploadElement = driver.findElement(By.className("omnibox-link"));
fileUploadElement.click();
// open the upload file / open file dialog
String filePath = "C:\\Users\\vikas\\Desktop\\input.docx";
ProcessBuilder pb = new ProcessBuilder("C:\\Users\\vikas\\Desktop\\S15\\uploadfile.exe", filePath);
try {
pb.start();
Thread.sleep(10000);
WebElement downlodFileElement = driver.findElement(By.xpath("//*[text()='Download File']"));
boolean isDownloadFileOptionDisplayed = downlodFileElement.isDisplayed();
Assert.assertTrue(isDownloadFileOptionDisplayed, "Download file link was not shown");
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}

Saturday, March 3, 2018

Upload File using Robot Class



import java.awt.Robot;
import java.awt.event.KeyEvent;
import java.lang.reflect.Field;
import java.util.concurrent.TimeUnit;

import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.chrome.ChromeDriver;
import org.openqa.selenium.interactions.Actions;
import org.testng.annotations.Test;

public class UploadFileTest {

@Test
public void testFileUpload() {
System.setProperty("webdriver.chrome.driver", "e:\\drivers\\chromedriver.exe");
WebDriver driver = new ChromeDriver();
driver.get("https://smallpdf.com/word-to-pdf");
driver.manage().timeouts().implicitlyWait(30, TimeUnit.SECONDS);
WebElement btnUpload = driver.findElement(By.className("omnibox-link"));
Actions a = new Actions(driver);
btnUpload.click(); // open file upload dialog
// E:\input.docx
try {
Thread.sleep(3000);
Robot robot = new Robot();
typeKeys( "e:\\input.docx",robot);

} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}

}

public static void typeKeys(String str, Robot r) {
for (int i = 0; i < str.length(); i++) {
if(str.charAt(i)==':'){
typeCharacter(r, "SEMICOLON",true);
}
else if(str.charAt(i)=='\\'){
typeCharacter(r, "BACK_SLASH",false);
//KeyEvent.VK_BACK_SLASH
}
else if(str.charAt(i)=='.'){
typeCharacter(r, "PERIOD",false);
//KeyEvent.VK_PERIOD
}
else{
char ch =  str.charAt(i);
if(Character.isUpperCase(ch)){
typeCharacter(r,""+ch,true );
}
else{
typeCharacter(r,""+ch,false );
}

}

}
r.keyPress(KeyEvent.VK_ENTER);
}

public static void typeCharacter(Robot robot, String letter, boolean needShift) {
try {


String variableName = "VK_" + letter.toUpperCase();
Class clazz = KeyEvent.class;
Field field = clazz.getField(variableName);
int keyCode = field.getInt(null);

robot.delay(1000);

if (needShift)
robot.keyPress(KeyEvent.VK_SHIFT);

robot.keyPress(keyCode);
robot.keyRelease(keyCode);

if ( needShift)
robot.keyRelease(KeyEvent.VK_SHIFT);
} catch (Exception e) {
System.out.println(e);
}
}

}

Wednesday, February 28, 2018

WebDriver custom wait until element is present in parent


Sample code to create custom wait until element is present inside a parent element.


Method Definition:

protected void waitForElementInParent(final WebElement parent,final By locator,int timeout) {
final WebDriverWait wait = new WebDriverWait(this.driver(), timeout);
wait.until(new ExpectedCondition<WebElement>() {

@Override
public WebElement apply(WebDriver driver) {
try {
return parent.findElement(locator);
} catch (final WebDriverException e) {
// return nothing
return null;
}
}
});
}


How to Call method:


waitForElementInParent(parentElement,By.id("uname"),60);

Tuesday, January 23, 2018

Appium Prerequisites / Requirements for Mobile Automation

iOS Requirements

Appium support iOS automation only on MAC OS X.
Hardware requirement :
  • Mac BookPro - i7 Processor, 16GB RAM
  • Mac OS X 10.12 recommended
  • iPhone (if planning automation on real device)
Software Requirements:
  • Min XCode 8 recommended
  • Apple Developer Tools (iPhone simulator SDK, command line tools)
  • Appium 1.7
Requirements based on execution mode
1. Simulator
  1. With Source code base
    1. No any specific requirement for automation on Simulator.
  2. Without source code base
    1. developer signed .app or .ipa build for simulator architecture.
2. Cloud
  • A developer signed .app or .ipa file of your app
  • Cloud Service Accounts with automation auth credentials / token
3. Real Device
Below are the specific requirements for iPhone automation.
  • An Apple Developer ID with password and a valid Developer Account with a configured development certificate and provisioning profile.
  • A valid iOS Development Certificate and Provisioning Profile are necessary to test on a real device. Your app will also need to be signed. You can find information about this in the Apple documentation.
  • An iPad or iPhone with udid registered in apple account . (Enable UI Automation in settings)
  • A developer signed .app or .ipa file of your app, or the source code to build one.
  • Some extra software tools : carthage, libmobiledevice, ios-deploy
_______________________________________________________________________________

Android Requirements

  • Appium supports android automation on Windows, Mac OS X, Linux.
Hardware requirements:
  • For real device automation:  i7 Processor + 8GB
  • For Emulator automation: i7 Processor + 16GB RAM
  • Android device (Phone / Tablet)
Software Requirements:
  • Android SDK with below tools and libs
    • Platforms (lib)
    • Platform-tools
    • Build-tools
  • Appium Desktop or Appium on Node.js installed.
Requirements based on execution mode
1. Execution on Android Emulator
  • Android system images
  • Create AVD (Android virtual device)
  • APK file / already installed app on emulator
2. Execution on cloud
  • APK app file.
  • Valid cloud service auth credentials / token
3. Execution on real device
  • Device (Android 4.4+) with developer options and USB debugging enabled
  • Android ADB Interface drivers installed
  • Adb devices shows device installed.

ElasticSearch and Kibana for Test Automation Reporting Dashboard


A Way to Capture and Analyze Historic Automation Test report to support decisions
Author: Vikas Thange
Problem Statement:
Test reporting is crucial part in any automation test framework. Most of the test automation framework generate test report for last run including test name, status, failure messages, snaps. Few framework tools also helps in storing report for all automation test execution cycles including historic one. for example Klove (aka ExtentX). The biggest problem is these tools are only storing the predefined meta data about test case e.g. test name, class name, test status, duration etc. In practical scenarios just capturing this predefined data do not help in taking decisions.
This white paper is answer to the problem mentioned above. 
Proposal:
I am proposing a generic reporting system which not only captures historic test execution data including custom fields but also helps in depicting in graphical dashboard to support decisions.
Solutions:

Example:
Sample Dashboard

Architecture:  
High Level Architecture

It is a one time process that includes 3 major steps as below.
Step 1: Set up ElasticSearch Database, Define indexes with schema. Setup Kibana and set ElasticSearch as source
Step 2: Save Test result statistics to Elastic Search
In Automation framework, develop a plugin for testing framework which captures all data including test result meta data and custom fields values from test framework and save all data to ElasticSearch database using REST APIs. 
This can be done with any of 2 options
  1. Direct JSON object to Elastic Search
    1. Create POJO with test result meta data and custom fields. 
    2. On test execution, Create instances of POJO classes with assigning values to all fields. 
    3. Convert object to JSON and class elastic search REST API to save in database cluster.
  2. LogStash
    1. Modify framework logger to follow LogStash format
    2. Feed log to LogStash and then ElasticSeach with indexes.
Step 3: Create UI Visualization for any meaningful data in with you are interested. and add it to Kibana dashboard. Analyze the Dashboard graphs, trends to take decisions.
The meaning full data can be any filter query based on the parameters stored in Elastic Search.
Below are the few sample examples scenarios to create visualization
  1. Test execution trend with test status, test count and environment in given specific time
  2. Which test case is getting maximum times skipped? or failed?
  3. Which is the most occurring execution / failure message?
  4. Which machine execute most of the test cases?
  5. Filter test trend for one specific platform, test case, failure message etc.
  6. Test execution trend on one particular machine

References: https://www.elastic.co/



Saturday, January 13, 2018

Appium Setup


Mobile Automation with Appium
  1. Android SDK
  2. Android Device (configuration)
  3. Eclipse / Java
  4. Appium


Setting up Android SDK

Step 2: Scroll to “Get just the command line tools”  
(* You can download Android Studio also instead of SDK Tools but for testing SDK tools is sufficient)
Step 3: Download SDK Tools for respective platform

Step 4: Extract download zip
Step 5: Open “cmd” and navigate to the tools folder in SDK.
Step 6: commands
  1. Sdkmanager.bat --list
  2. Sdkmanager.bat platforms;android-26
  3. Sdkmanager.bat build-tools;26.0.3
  4. sdkmanager.bat platform-tools


Step 7: set environment variable.

  1. ANDROID_HOME    =    path to sdk folder
  2. PATH  $ANDROID_HOME/build-tools/25.0.2;$ANDROID_HOME/platform-tools;$ANDROID_HOME/tools;

* Note - Update path according your installation
Step 8. Close all CMD and start again. Execute adb device command. If you get error for adb then check installation.


Device Set Up configuration:
  1. Enable developer option
  2. Enable usb debugging
  3. Connect device to computer via usb and check “adb devices” shows device connected.

Appium Set Up
  1. Download and Install Node.js https://nodejs.org/en/
  2. Open Node Js command prompt and execute below command
    1. npm install appium -g
  3. Verify appium installed with below command
    1. appium -v




Locating elements for native app -

Locating Android elements - Id, Xpath

IOS - Name, Xpath

Automating already existing App using Appium.

Step 1:Get package name and activity from the Application.
I. Start app. Launch screen
Ii. Execute below 2 commands

adb shell
dumpsys window windows

Search for ‘mCurrentFocus=’  Get the package name /activity name (check snap)

Package name: com.android.settings
Activity name:com.android.settings.settings

Step 2.
Set both to desired capabilities

DesiredCapabilities capabilities=new DesiredCapabilities();
   capabilities.setCapability("deviceName", "Your device Name");
   capabilities.setCapability("appPackage", "com.android.settings");
   capabilities.setCapability("appActivity", "com.android.settings.Settings");
That’s all you need…Now you can create driver instance and use it for automation.