Automation mobile application using appium - java

I am trying to automate an android application using Appium and Cucumber with Java.I have written the code for a functionality and it is working fine. But some times while running the script, it throws an error
org.openqa.selenium.WebDriverException: An unknown server-side error occurred while processing the command. Original err
or: Could not proxy command to remote server. Original error: Error: read ECONNRESET (WARNING: The server did not provid
e any stacktrace information)
Source code:
import com.google.common.base.Function;
import com.intel.truevr.appautomation.core.Capabilities;
import org.openqa.selenium.By;
import io.appium.java_client.MobileDriver;
import io.appium.java_client.MobileElement;
import cucumber.api.java.en.Given;
import cucumber.api.java.en.Then;
import cucumber.api.java.en.When;
import org.openqa.selenium.support.ui.Wait;
import java.util.List;
import io.appium.java_client.TouchAction;
public class C754L2D {
Capabilities c = new Capabilities();
MobileDriver driver = c.getDefaultCapabilities();
Wait wait = new Wait() {
#Override
public Object until(Function isTrue) {
return null;
}
};
#Given("^User taps the toggle button in the live 2D video playing screen$")
public void user_taps_toggle_button() throws Exception {
MobileElement allow = (MobileElement) driver.findElement(By.id("com.android.packageinstaller:id/permission_allow_button"));
allow.click();
List<MobileElement> list = driver.findElements(By.id("android:id/text1"));
for(MobileElement ele :list) {
String text = ele.getText();
if(text.equals("Live")){
ele.click();
break;
}
}
MobileElement panoramicButton = (MobileElement) driver.findElement(By.id("com.jackalopelite.simplecontainer:id/rl_select_2d"));
panoramicButton.click();
MobileElement Screen= (MobileElement) driver.findElement(By.className("android.view.View"));
TouchAction ta = new TouchAction(driver);
ta.tap(Screen, 531, 357).perform();
MobileElement toggleButton = (MobileElement) driver.findElement(By.id("com.jackalopelite.simplecontainer:id/fab_player_switch_mode"));
toggleButton.click();
}
#When("^Taps back button in the transition screen$")
public void taps_back_button() throws InterruptedException {
Thread.sleep(1000);
MobileElement backButton = (MobileElement) driver.findElement(By.id("com.jackalopelite.simplecontainer:id/iv_cardboard_back"));
backButton.click();
}
#Then("^The transition screen should dismiss and user should be navigated back to 2d live video playing screen$")
public void dismiss_transition_screen() {
try{
MobileElement cameraAngleSelectionButton = (MobileElement) driver.findElement(By.id("com.jackalopelite.simplecontainer:id/rl_player_switch_camera_parent"));
if(cameraAngleSelectionButton != null) {
System.out.println("The transition screen is dismissed and user is navigated back to 2d live video playing screen");
}
}catch(Exception e){
System.out.println("The transition screen is not dismissed and user is not navigated back to 2d live video playing screen");
}
//driver.quit();
}
}
This error gets cleared and the script works fine when I close the emulator and open it again. Can anybody help me in this?

Hey please then kill all simulator programmatically after executing testcase. Below code might help you.
/**
* Stop Simulator
*/
public void stopSimulator() {
try {
Runtime.getRuntime().exec("killall \"iOS Simulator\"");
} catch (IOException e) {
//e.printStackTrace();
}
try {
Runtime.getRuntime().exec("killall Simulator");
} catch (IOException e) {
//e.printStackTrace();
}
}
If you are openning a specific simulator you can specify this in above code.
For android simulator please use
Runtime.getRuntime().exec("adb emu kill");

Related

Appium to test Android Hybrid Mobile Application

I want to automate test a basic Hybrid Mobile Application build on top of Cordova running in Android. I used Apppium for that. I followed the tutorial video to get started. I downloaded and Added Selenum, selendroid and java client .jar files to the build path of the Application.
Below is my code,
import java.net.MalformedURLException;
import java.net.URL;
import java.util.Iterator;
import java.util.Set;
import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.remote.DesiredCapabilities;
import io.appium.java_client.AppiumDriver;
import io.appium.java_client.MobileElement;
import io.appium.java_client.android.AndroidDriver;
import io.appium.java_client.remote.MobileCapabilityType;
public class AppiumTest {
public static void main(String[] args) throws MalformedURLException, InterruptedException {
URL serverAddress = new URL("http://0.0.0.0:4723/wd/hub");
WebDriver driver = new AndroidDriver<MobileElement>(serverAddress, getDesiredCapabilities());
try{
Set<String> contextNames = ((AppiumDriver<MobileElement>) driver).getContextHandles();
for (final String contextName : contextNames) {
System.out.println(contextName);
if (contextName.contains("WEBVIEW_0")) {
Thread.sleep(3000);
driver.switchTo().window("WEBVIEW_0");
}
}
//Change color to Red
driver.findElement(By.cssSelector("p.recieved")).click();
Thread.sleep(2000);
//Change color to Red
driver.findElement(By.cssSelector("recieved")).click();
Thread.sleep(2000);
driver.get("http//appium.io/");
Thread.sleep(2000);
}
finally {
driver.quit();
}
System.out.println("Driver "+driver);
}
public static DesiredCapabilities getDesiredCapabilities() {
DesiredCapabilities capability = new DesiredCapabilities();
capability.setCapability(MobileCapabilityType.AUTOMATION_NAME, "selendroid");
capability.setCapability(MobileCapabilityType.PLATFORM_NAME, "Android");
capability.setCapability("platformVersion", "4.4.4");
capability.setCapability("deviceName", "Android-Dev");
capability.setCapability("app",
"C:/Joseph/Appium/HybridProject/AppiumTest/platforms/android/build/outputs/apk/android-debug.apk");
capability.setCapability("appPackage", "com.joseph.appiumtest");
capability.setCapability("appActivity", ".MainActivity");
return capability;
}
}
I can able to get the Capabilities and Contexts. On switching the window (driver.switchTo().window("WEBVIEW_0")), I am getting error like Exception in thread "main" org.openqa.selenium.WebDriverException: CATCH_ALL: java.lang.VerifyError: io/selendroid/server/model/SelendroidWebDriver
Versions :
Android : 4.4.4
Appium : 1.6.3
Selenium : 3.0.1
Selendroid: 0.17.0
After lots of tries, got the Automation testing in Hybrid Mobile Application using Appium worked.
Basically in Capabilities, its not necessary to set the package name and activity name. Instead get the file path of the Application package name(.apk).
File app= new File("project/platforms/android/build/outputs/apk/android-debug.apk");
DesiredCapabilities capabilities= new DesiredCapabilities();
capabilities.setCapability("deviceName", "Android-Dev");
capabilities.setCapability("platformVersion", "4.4.4");
capabilities.setCapability(MobileCapabilityType.PLATFORM_NAME, "MobilePlatform.ANDROID");
capabilities.setCapability("app", app.getAbsolutePath());
Then do not explicitly switch the window to WEBVIEW. Get the context and set the dynamic context of Webview particular for the Application.
try {
Set<String> contextNames = ((AppiumDriver) driver).getContextHandles();
for (String contextName : contextNames) {
System.out.println(contextName);
if (contextName.contains("WEBVIEW")) {
((AppiumDriver<MobileElement>) driver).context(contextName);
}
}
}
catch(Exception e){
e.printStackTrace();
}
And finally with the driver set, do the action.
driver.findElement(By.xpath("//*[#id='login']")).click();

How to open a html file from a help menu button

I am try to open a javadoc html file with my new application, however I can not get the javadoc file to open, I have a class name OpenUri, which when called is supposed to open the javadoc:
package gui;
import java.awt.Desktop;
import java.net.URI;
import java.net.URISyntaxException;
import java.net.URL;
import javax.swing.JFrame;
public class OpenUri extends JFrame {
public static void openWebpage(URI uri) {
Desktop desktop = Desktop.isDesktopSupported() ? Desktop.getDesktop() : null;
if (desktop != null && desktop.isSupported(Desktop.Action.BROWSE)) {
try {
desktop.browse(uri);
} catch (Exception e) {
e.printStackTrace();
}
}
}
public static void openWebpage(URL url) {
try {
openWebpage(url.toURI());
} catch (URISyntaxException e) {
e.printStackTrace();
}
}
}
I am then calling and using this class from another class called Menu, where the help button has an action listener, etc. However when I run the code and press the help button, no javadoc appears, ie, it doesn't open the document, ie, nothing happens, no window, nothing ?
The only way I can open it is manually, by clicking on it in eclipse, here is the specific code from the Menu class I am Using:
//Help
JMenu helpMenu = new JMenu("Help");
helpMenu.setMnemonic(KeyEvent.VK_H);
helpMenu.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent event) {
try {
URI uri = new URI("file:///C:/Users/howhowhows/workspace/OPTICS_DROP_MENU/doc/index.html");
OpenUri.openWebpage(uri);
} catch (URISyntaxException e) {
e.printStackTrace();
}
}
});
If anyone has any ideas as to what I am doing wrong, ie what I need to add/change, it would be greatly appreciated.
Have you downloaded and tried the demo code from the Swing tutorial on How to Integrate With the Desktop Class.
When I used that code and pasted your URI into the text field no window is displayed and I get a "System cannot find the file" message as expected.
When I then enter a simple URI that I know exists: "c:/java/a.html" the browser opens as expected.
So I suggest you start with known working code and see if your URI works. If it does work then the problem is your code, so compare the working code to your code to see what the difference is. If it doesn't work then the problem is the URI.
If you still have problems then post a proper SSCCE that demonstrates the problem. Given that your OPenURI class extends JFrame for no reason we don't know what other strange things you might be doing in your code.

Simulate page click with coordinates (x,y)

How do I simulate a click with coordinates on HtmlPage then get the result a HtmlPage?
I want to click a button without an id or a name
I'm using the library com.gargoylesoftware.htmlunit
not sure about specific system or browser settings, but in general you can do this by following:
import java.awt.event.*;
import java.awt.Robot;
public class test {
int xparam=50;
int yparam=100;
public static void main(String args[]) {
Robot mybot = null;
try {
mybot = new Robot();
} catch (Exception failed) {
System.err.println("Failed instant. Robot: " + failed);
}
int maske = InputEvent.BUTTON1_DOWN_MASK;
mybot.mouseMove(xparam,yparam);
mybot.mousePress(maske);
mybot.mouseRelease(maske);
}
}
For a smoother solution take a look at this ;
No,You can't click button with coordinates(X,Y).
Please specify the element other attributes because it can be click with help of other attribute

Is there any way we can also take the screenshot of entire page including the page which is there in down (scrollbar) using wedriver

I need to capture the full page of IE browser. I am using web driver. Pls help me.
below code is used to capture the present window only.
File scrFile = ((TakesScreenshot)driver).getScreenshotAs(OutputType.FILE);
// Now you can do whatever you need to do with it, for example copy somewhere
FileUtils.copyFile(scrFile, new File("c:\\tmp\\screenshot.png"));
You can change the browser to full screen before taking the screenshot. This is the code:
private void changeToFullScreen() {
try {
Robot r;
r = new Robot();
r.keyPress(java.awt.event.KeyEvent.VK_F11);
r.keyRelease(java.awt.event.KeyEvent.VK_F11);
driver.sleep(2);
} catch (AWTException e) {
log.error("It was not possible to maximize", e)
driver.manage().window().maximize();
}
}
If you don't want to change the screen size, you can obtain the browser height and take screenShots while you scroll down until the bottom (can be done with Robot):
int numberOfScrolls = pageHeight / browserHeight;
for(int i = 0 ; i < numberOfScrolls ; i++){
takeScreenshot();
scrollDown(browserHeight);
}
concatenateScreenshots();
import java.io.File;
import javax.imageio.ImageIO;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.firefox.FirefoxDriver;
import ru.yandex.qatools.ashot.AShot;
import ru.yandex.qatools.ashot.Screenshot;
import ru.yandex.qatools.ashot.shooting.ShootingStrategies;
public class TakeScreenshotWithScroll {
static WebDriver driver;
public static void main(String args[]) throws Exception{
String key = "webdriver.gecko.driver";
String value = "driver/geckodriver.exe";
driver = new FirefoxDriver();
System.setProperty(key, value);
driver.get("ENTER THE URL HERE");
Thread.sleep(2000);
Screenshot fpScreenshot = new AShot().shootingStrategy(ShootingStrategies.viewportPasting(1000)).takeScreenshot(driver);
ImageIO.write(fpScreenshot.getImage(),"PNG",new File("D:///FullPageScreenshot.png"));
}
}
Here is the download link of aShot Jar file

Selenium HtmlUnitDriver hangs randomly in random places

I used SeleniumHQ to record my actions and then exported them to Java Unity WebDrive. Then I edited exported code and added many small extra things like looping over array, time-stamps, etc.
My code does following:
Log into my site.
Goto my profile.
Delete my previous announcement.
Post new announcement.
Log out.
I have tried using FirefoxDriver and HtmlUnitDriver, but every single of them gives me this weird problem. My code start doing its work and randomly stops in random spot and hangs there forever.
For example it could log in -> goto profile -> delete previous and then stop, or it could hang right in the login. I loop over those steps over and over again, and more I loop more likely it is to get stuck.
First loops success rate is 90% second loop is around 40% etc. Also which Driver I use also affects this. It is most likely to hang with HtmlUnitDriver and I would really want to use HtmlUnitDrive because I want to run my code headless on Ubuntu Server.
Has anyone else had similar problems?
EDIT : Now after many hours of testing, I noticed that its only HtmlUnitDriver that hangs and not Firefox. When using Firefox I can see what it is doing and it is doing everything as it should. Problem occurs with HtmlUnitDriver.
And here is the code itself:
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.util.concurrent.TimeUnit;
import org.junit.*;
import static org.junit.Assert.*;
import org.openqa.selenium.*;
import org.openqa.selenium.htmlunit.HtmlUnitDriver;
public class WebUpdater {
private WebDriver driver;
private String baseUrl;
private boolean acceptNextAlert = true;
private StringBuffer verificationErrors = new StringBuffer();
#Before
public void setUp() throws Exception {
driver = new HtmlUnitDriver(true); // JavaScript enabled.
baseUrl = "http://exampleurl.com";
driver.manage().timeouts().implicitlyWait(30, TimeUnit.SECONDS);
}
#Test
public void testUnity() throws Exception {
openAndLogin();
gotoProfile();
deletePreviousPost();
uploadPost();
logOut();
System.out.println("Done!");
}
private void openAndLogin() {
driver.get(baseUrl);
driver.findElement(By.linkText("Login")).click();
driver.findElement(By.id("jsid-login-id")).clear();
driver.findElement(By.id("jsid-login-id")).sendKeys("bilgeis.babayan#gmail.com");
driver.findElement(By.id("jsid-login-password")).clear();
driver.findElement(By.id("jsid-login-password")).sendKeys("volume1991");
driver.findElement(By.cssSelector("input.right")).click();
}
private void gotoProfile() {
driver.findElement(By.cssSelector("img[alt=\"Profile\"]")).click();
}
private void deletePreviousPost() {
try {
driver.findElement(By.cssSelector("img[alt=\"ExampleName\"]")).click();
driver.findElement(By.linkText("Delete")).click();
assertTrue(closeAlertAndGetItsText().matches("^Confirm to delete this post[\\s\\S]$"));
} catch (Exception e) {
System.out.println(e);
}
}
private void uploadPost() {
driver.findElement(By.linkText("ExampleAction")).click();
driver.findElement(By.id("example_url")).clear();
driver.findElement(By.id("example_url")).sendKeys("Example text that gets typed in textfield.");
driver.findElement(By.cssSelector("input[name=\"example\"]")).clear();
driver.findElement(By.cssSelector("input[name=\"example\"]")).sendKeys("ExampleName");
driver.findElement(By.linkText("ExampleAction2")).click();
System.out.println("Done");
}
private void logOut() {
driver.get("http://exampleurl.com/logout");
System.out.println("Logged out.");
}
#After
public void tearDown() throws Exception {
driver.quit();
String verificationErrorString = verificationErrors.toString();
if (!"".equals(verificationErrorString)) {
fail(verificationErrorString);
}
}
private boolean isElementPresent(By by) {
try {
driver.findElement(by);
return true;
} catch (NoSuchElementException e) {
return false;
}
}
private String closeAlertAndGetItsText() {
try {
Alert alert = driver.switchTo().alert();
if (acceptNextAlert) {
alert.accept();
} else {
alert.dismiss();
}
return alert.getText();
} finally {
acceptNextAlert = true;
}
}
}
in my main class I call WebUpdater class like this:
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.logging.Level;
import java.util.logging.Logger;
public class Main {
public static void main(String[] args) {
Logger logger = Logger.getLogger("");
logger.setLevel(Level.OFF);
scan();
}
private static void scan() {
while (true) {
try {
// Test if connection is available and target url is up.
URL url = new URL("http://exampleurl.com");
HttpURLConnection urlConn = (HttpURLConnection) url.openConnection();
urlConn.connect();
// Start tests.
WebUpdater updater = new WebUpdater();
updater.setUp();
updater.testUnity();
updater.tearDown();
} catch (Exception ex) {
System.out.println(ex);
}
try {
Thread.sleep(12000);
} catch (InterruptedException e) {
}
}
}
}
I had a bad experience with HtmlUnitDriver. Some time ago I wrote testing framework which were supposed to be fired at Hudson, and finally I decided to use Firefox driver which was more predictable and easier to debug. The point is that in my case it was a page full of javascripts - dynamically loaded fields, etc., and working with HtmlUnitDriver was really a can of worms.
If you really need to use HtmlUnitDriver try do debug 'pagesource' which is accessible for Selenium in 'current' (hanging) moment.
HtmlUnit 2.11 is flawed (see here and here), and since HtmlUnit 2.12 went live march 6th, the current version of HtmlUnitDriver is probably still based on HtmlUnit 2.11.
If you post your "http://exampleurl.com/" source code (or just give me a working url to the page if it's public) I could run the page with scripts through HtmlUnit 2.12.

Categories