Appium error using real android device - selenium

I am getting error in the appium. It is working fine in the emulator but not in the device. Please refer the code and error log below. Could anyone let me know the reason for the error.
//Code///////////////////////////////////////
public void setUp() throws Exception{
File classpathRoot = new File(System.getProperty("user.dir"));
File appDir = new File(classpathRoot, "/app");
File app = new File(appDir, "app.apk");
DesiredCapabilities capabilities = new DesiredCapabilities();
capabilities.setCapability("browserName", "");
capabilities.setCapability("platformVersion", "4.4");
capabilities.setCapability("platformName", "Android");
capabilities.setCapability("app", app.getAbsolutePath());
capabilities.setCapability("deviceName", "SCH-I535");
capabilities.setCapability("appPackage", "com.app");
capabilities.setCapability("appActivity", "com.justwink.homepage.HomePageActivity");
capabilities.setCapability("appWaitActivity", "com.app.homepage.HomePageActivity");
try {
driver = new AppiumDriver(new URL("http://127.0.0.1:4723/wd/hub"), capabilities);
} catch (Exception e) {
e.printStackTrace();
}
driver.manage().timeouts().implicitlyWait(80, TimeUnit.SECONDS);
}

I fixed it by changing the appActivity name.
Orginally I used hierarchy viewer to find the activity name.
When I used the command
aapt dump badging sample.apk it showed the original activity name.

You may first need to ignore the below code first
*File classpathRoot = new File(System.getProperty("user.dir"));
File appDir = new File(classpathRoot, "/app");
File app = new File(appDir, "justwink-usa-2.3.2.218221.69.apk");*
match your setup code with this one
DesiredCapabilities capabilities = new DesiredCapabilities();
capabilities.setCapability(CapabilityType.BROWSER_NAME, "");
capabilities.setCapability("deviceName","sony xperia Z");
capabilities.setCapability("platformVersion", "4.4");
capabilities.setCapability("platformName","Android");
capabilities.setCapability("appPackage", "com.android.calculator2");
capabilities.setCapability("appActivity", "com.android.calculator2.Calculator");
driver = new AppiumDriver(new URL("http://127.0.0.1:4723/wd/hub"), capabilities);

There is other way you can get the current activity by running following adb command
adb shell dumpsys window windows | grep -E 'mCurrentFocus|mFocusedApp'

Related

How to launch my application through winappdriver?

I am new to the WinAppDriver Windows Based Automation. Kindly help me to launch my windows application through winappdriver.
String applicationPath = System.getProperty("user.dir")+"/Data/TestData/StudioSetup.exe";
DesiredCapabilities capabilities = new DesiredCapabilities();
capabilities.setCapability("app", applicationPath);
WindowsDriver driv = new WindowsDriver(new URL("http://127.0.0.1:4723"), capabilities);
It launches my application, but it takes long time to open the window. In the meanwhile, it throws the below exception in the 4th line: -
org.openqa.selenium.SessionNotCreatedException: Unable to create a new remote session. Please check the server log for more details. Original error: Failed to locate opened application window with appId: C:\Users\Peenu\git\Uptime/Data/TestData/StudioSetup.exe, and processId: 7208 (WARNING: The server did not provide any stacktrace information)
Command duration or timeout: 7.17 seconds
This worked for me:
AppiumOptions appOptions = new AppiumOptions();
appOptions.AddAdditionalCapability("app", "PATH TO YOUR EXE");
appOptions.AddAdditionalCapability("deviceName", "WindowsPC");
appOptions.SetLoggingPreference(OpenQA.Selenium.LogType.Server, OpenQA.Selenium.LogLevel.All); //optional
WindowsDriver<WindowsElement> driv = new WindowsDriver<WindowsElement>(new Uri("http://127.0.0.1:4723"), appOptions);
See if this works
Process.Start(#"<WinappDriver.exe path>");
DesiredCapabilities capabilities = new DesiredCapabilities();
capabilities.SetCapability("deviceName", "WindowsPC");
capabilities.SetCapability("app", #"<Path to application.exe>");
BasePage.WindowsDriver = new WindowsDriver<WindowsElement>(new Uri("http://127.0.0.1:4723"), capabilities);
Thread.Sleep(10000); //Uncomment if required
BasePage.WindowsDriver.Manage().Timeouts().ImplicitWait = TimeSpan.FromSeconds(5);
The application path is incorrect. Copy the path of your exe file using these steps:
Go to the application folder
Press the SHIFT key and right click the application icon
Select "Copy as path" from context menu
Now go back to your code and paste this value there.
Put an # before the string
For example, the path to notepad looks like the following.
#"C:\Windows\System32\notepad.exe"

Keep file with Chromedriver in chrome://downloads

I'm trying to automate the download of an XML file with Google Chrome.
I'm using:
Google Chrome v73.0.3683.75 (64 bits)
Chromedriver v73
Selenium WebDriver v3.14.0
C#
The problem comes up when a message of harmful file appears:
As I'm using Chromedriver, I can not interact with this message, so I tried to accept the download from the chrome://downloads page.
Once I open the chrome://downloads page, I click on the Keep button, but an Alert comes up again to confirm the download.
This popup is not a popup Selenium and Chromedriver can Handle with the Dismiss()/Accept()/SendKeys()/... methods. When I try to SwitchTo() it, Chromedriver crashes.
I tried to directly send the keystrokes of {TAB} and {SPACE}/{RIGHT} and {ENTER}, but Chrome seems not to catch them...
The full code is:
String currentWindow = this.Drivers[Navegador].CurrentWindowHandle;
String popupHandle = "";
((IJavaScriptExecutor)this.Drivers[Navegador]).ExecuteScript("window.open('about:blank','_blank')");
ReadOnlyCollection<String> tabs = this.Drivers[Navegador].WindowHandles;
foreach (string handle in tabs){
if (handle != currentWindow){
popupHandle = handle;
break;
}
}
this.Drivers[Navegador].SwitchTo().Window(popupHandle);
this.Drivers[Navegador].Navigate().GoToUrl("chrome://downloads");
String script = "return document.querySelector('body > downloads-manager').shadowRoot.querySelector('#downloadsList > downloads-item').shadowRoot.querySelector('#dangerous > paper-button:nth-child(2)');";
//String script = "return document.querySelector('body > downloads-manager').shadowRoot.querySelector('#downloadsList > downloads-item:nth-child(2)').shadowRoot.querySelector('#url').textContent;";
IWebElement boton = (IWebElement) ((IJavaScriptExecutor) this.Drivers[Navegador]).ExecuteScript(script);
boton.Click();
Thread.Sleep(2000);
SendKeys.Send("{TAB}{SPACE}");
Thread.Sleep(1000);
this.Drivers[Navegador].Close();
this.Drivers[Navegador].SwitchTo().Window(currentWindow);
this.Drivers[Navegador].SwitchTo().DefaultContent();
result = true;
IMPORTANT NOTE:
I tried to launch Chrome with all the flags/options/experimental_options/user_preferences/... possible and it doesn't work. These options/arguments seem to be deprecated in the latest versions of Chrome or Chromedriver.
As discussed with OP, answering the question in Java.
Encountered the same problem few months back, so this is how it worked for me, might work for you as well.
Map<String, Object> chromePreferences = new Hashtable<String, Object>();
// Below preferences will disable popup dialog while downloading the file
chromePreferences.put("profile.default_content_settings.popups", 0);
chromePreferences.put("download.prompt_for_download", "false");
// Set the customised path for downloading the file, if required
chromePreferences.put("download.default_directory", "path");
ChromeOptions chromeOptions = new ChromeOptions();
chromeOptions.setExperimentalOption("prefs", chromePreferences);
DesiredCapabilities cap = DesiredCapabilities.chrome();
cap.setCapability(CapabilityType.ACCEPT_SSL_CERTS, true);
cap.setCapability(ChromeOptions.CAPABILITY, chromeOptions);
//Now initiate ChromeDriver with the capabilities set above and continue with your automation
ChromeDriver chromeDriver = new ChromeDriver(cap);
I recently ran into this issue, and due to the deprecation of some of the methods in the ChromeDriver, the above solution didn't work.
After a lot of research I decided to switch to IE and explore an alternate option with the inspiration from this article - https://sqa.stackexchange.com/questions/3169/downloading-a-file-in-internet-explorer-through-selenium/3520 I came up with this solution in JAVA.
It is not as 'clean' but it worked for me.
public static void main(String[] args) throws NoAlertPresentException,InterruptedException {
System.setProperty("webdriver.ie.driver","C:\\selenium-java-3.141.59\\IEDriverServer.exe");
String url ="myfileurl";
WebDriver driver = new InternetExplorerDriver();
driver.get(url);
try {
Robot robot = new Robot();
Thread.sleep(2000);
//press alt+s key to save
robot.keyPress(KeyEvent.VK_ALT);
robot.keyPress(KeyEvent.VK_S);
robot.keyRelease(KeyEvent.VK_S);
robot.keyRelease(KeyEvent.VK_ALT);
Thread.sleep(2000);
}
catch (AWTException e) {
e.printStackTrace();
}
driver.close();
}

Switching between two apps in appium iOS

I have a testcase where in an iPhone I have to
1. Perform a task in app A.
2. Switch to Safari browser and perform a task
3. Switch back again to App A and continue other tasks
Currently I can perform 1 & 2 & then switch back to App A but I cannot perform any tasks in App A after switching from the safari browser. What I did is as follows.
First of all to launch the app A I used the following code
public void createAppiumDriver() throws MalformedURLException, InterruptedException {
DesiredCapabilities capabilities = new DesiredCapabilities();
capabilities.setCapability("deviceName", "iPhone 7 Plus");
capabilities.setCapability("platformName", "iOS");
capabilities.setCapability("platformVersion", "11.2");
capabilities.setCapability("autoWebView", true);
capabilities.setCapability("app", getProperties().getProperty("appURL"));
capabilities.setCapability("autoAcceptAlerts", true);
capabilities.setCapability("useNewWDA", true);
capabilities.setCapability("startIWDP",true);
iosDriver = new IOSDriver(new URL("http://0.0.0.0:4723/wd/hub"), capabilities);}
To switch from my app to Safari I started a new session using the following code to switch to safari
public void openSafari() throws MalformedURLException {
DesiredCapabilities capabilities2 = new DesiredCapabilities();
capabilities2.setCapability("deviceName", "iPhone 7 Plus");
capabilities2.setCapability("platformName", "iOS");
capabilities2.setCapability("platformVersion", "11.2");
capabilities2.setCapability("browserName", "Safari");
capabilities2.setCapability("autoAcceptAlerts", true);
capabilities2.setCapability("useNewWDA", true);
iosDriver2 = new IOSDriver(new URL("http://0.0.0.0:4723/wd/hub"), capabilities2);
iosDriver2.get("https://www.gmail.com");}
The issue now I have is to switch back to App A again from the safari browser to perform some tasks for that at the moment I have created a new session again as follows
public void switchToNutrifix() throws MalformedURLException, InterruptedException {
DesiredCapabilities capabilities3 = new DesiredCapabilities();
capabilities3.setCapability("deviceName", "iPhone 7 Plus");
capabilities3.setCapability("platformName", "iOS");
capabilities3.setCapability("platformVersion", "11.2"); //Replace this with your iOS version
capabilities3.setCapability("autoWebView", true);
capabilities3.setCapability("app", getProperties().getProperty("appURL"));
capabilities3.setCapability("autoAcceptAlerts", true);
capabilities3.setCapability("useNewWDA", true);
capabilities3.setCapability("startIWDP",true);
iosDriver3 = new IOSDriver(new URL("http://0.0.0.0:4723/wd/hub"), capabilities3);}
The issue now is that the app A opens again from Safari but it cannot identify the elements in the app. I even changed the context correctly to webview but still it cannot perform any tasks in App A after switching from Safari browser. Can someone please tell me what I'm doing wrong here or another alternative way to do this switch.
The error I usually get is
May 09, 2018 6:43:42 PM org.openqa.selenium.support.ui.ExpectedConditions findElement
WARNING: WebDriverException thrown by findElement(By.xpath: //div[#class='login-content purpose']/h2)
org.openqa.selenium.remote.SessionNotFoundException: A session is either terminated or not started (WARNING: The server did not provide any stacktrace information)
and the appium logs display
debug] [iOS] No key id found. Choosing first id from page array
[debug] [iOS] Page change not referring to currently selected app, ignoring.
public class SwitchBtnAppsiOS {
public AppiumDriver<RemoteWebElement>iosDriver;
public DesiredCapabilities createAppiumDriver()
throws MalformedURLException, InterruptedException {
DesiredCapabilities capabilities = new DesiredCapabilities();
capabilities.setCapability("deviceName", "iPhone 7 Plus");
capabilities.setCapability("platformName", "iOS");
capabilities.setCapability("platformVersion", "11.2");
capabilities.setCapability("autoWebView", true);
capabilities.setCapability("app", getProperties().getProperty("appURL"));
capabilities.setCapability("autoAcceptAlerts", true);
capabilities.setCapability("useNewWDA", true);
capabilities.setCapability("startIWDP",true);
return capabilities;
}
public DesiredCapabilities openSafari()
throws MalformedURLException {
DesiredCapabilities capabilities = new DesiredCapabilities();
capabilities.setCapability("deviceName", "iPhone 7 Plus");
capabilities.setCapability("platformName", "iOS");
capabilities.setCapability("platformVersion", "11.2");
capabilities.setCapability("browserName", "Safari");
capabilities.setCapability("autoAcceptAlerts", true);
capabilities.setCapability("useNewWDA", true);
return capabilities;
}
public void switchBetweenApps() throws MalformedURLException, InterruptedException
{
DesiredCapabilities nativeAppCaps = createAppiumDriver();
iosDriver = new IOSDriver<>(new URL("http://0.0.0.0:4723/wd/hub"), nativeAppCaps);
/**
* Perform the actions on native app
*/
DesiredCapabilities webCaps = createAppiumDriver();
iosDriver = new IOSDriver<>(new URL("http://0.0.0.0:4723/wd/hub"), webCaps);
iosDriver.get("https://www.gmail.com");
/**
* Perform the actions on safari browser
*/
// Again switch to native app
iosDriver = new IOSDriver<>(new URL("http://0.0.0.0:4723/wd/hub"), nativeAppCaps);
}
}
Where ever you are using the driver instances pass the latest instance of driver.
Use RemoteWebElement instead of MobileElement if that is the case.
Since with XCode 9 Appium support multiple sessions, I suggest using 2 simultaneous sessions: app and safari:
Create driver for native app (e.g. driver1 object)
Do want you need in app, keep driver instance alive
Hint: you may put it in background:
driver.runAppInBackground(Duration.ofMinutes(1));
Create driver for safari (e.g. driver2 object)
Do want you need in safair and close driver2 if you don't need it
Continue using driver1 for native app
There is a better way of switching b/w iOS apps instead of creating driver session again and again as suggested in above answer
IOSDriver driver = new IOSDriver<>(new URL("http://localhost:4723/wd/hub"), capabilities);
try {
HashMap<String, Object> args = new HashMap<>();
args.put("bundleId", SWITCH_APP_BUNDLE_ID);
driver.executeScript("mobile: launchApp", args);
/*
TODO code for switch app
*/
// Now reactivate AUT App
args.put("bundleId", AUT_APP_BUNDLE_ID);
driver.executeScript("mobile: activateApp", args);
/*
TODO code for AUT App
*/
}
finally {
// quit driver
}

Browsers are not launching from command prompt. Same testng File is working while running through eclipse

I am trying to run my testng test cases from command prompt. I can see browser's instance are created in task manager but it is not launching with given URL. I debugged the code and found it is failing on new ChromeDriver() below line but there is no exception.
On command line, I can see below message :
Starting ChromeDriver 2.18.343845 (73dd713ba7fbfb73cbb514e62641d8c96a94682a) on port 7108
Only local connections are allowed.
Browser instance will create in task manager but it will not launch and will not go to next line.
This issue is coming from all browsers on same line.
same code worked well in Eclipse.
Using Selenium 2.53.0 and testng 6.9.13 versions
Try this solution:
ChromeDriverService service = null;
try
{
service = new ChromeDriverService.Builder()
.usingDriverExecutable(new File(chromeDriver))
.usingAnyFreePort()
.build();
service.start();
}catch(IOException io){}
if(service.isRunning())
{
DesiredCapabilities cap = DesiredCapabilities.chrome();
try{
driver = new RemoteWebDriver(service.getUrl(), cap);
}catch (SessionNotCreatedException e)
{
}
}

Launching application using Appium

I have used the following code to launch an app. I didn't get any error log in Appium but application has not been launched.
DesiredCapabilities capabilities = new DesiredCapabilities();
capabilities.setCapability(MobileCapabilityType.DEVICE_NAME,"Android");
capabilities.setCapability(CapabilityType.BROWSER_NAME, "Chrome");
capabilities.setCapability(MobileCapabilityType.VERSION, "4.4.2");
capabilities.setCapability("platformName", "Android");
capabilities.setCapability("appPackage", "com.whatsapp");
capabilities.setCapability("appActivity", "com.whatsapp.Main");
driver = new RemoteWebDriver(new URL("http://127.0.0.1:4723/wd/hub"), capabilities);
driver.manage().timeouts().implicitlyWait(15, TimeUnit.SECONDS);
driver.quit();
Please advice
at the start you need to add this it is path of apk file
File app=new File("C:/Users/Administrator/Downloads/Appium/Appium/node_modules/appium/apk/app-release-2.0.apk");