Appium: failed to locate open application error - selenium

I am using C#, Appium, and WinAppDriver to automate UI tests on a desktop application, however, I continue to have an intermittent issue when launching the WPF application. I have done a lot of research on this but cannot find a solid solution.
When opening the application there is a login splash screen. When the correct login credentials are entered there is another loading splash screen for approximately 5 seconds before the application opens.
I continue to get the following exception when opening the application; it appears to be random. Every time I think I found a pattern I find another data point that conflict with the pattern I thought I identified.
Exception
Message:
OpenQA.Selenium.WebDriverException : Failed to locate opened application window with appId: C:\Program Files (x86)\path to .exe\, and processId: 14124
Stack Trace:
RemoteWebDriver.UnpackAndThrowOnError(Response errorResponse)
RemoteWebDriver.Execute(String driverCommandToExecute, Dictionary`2 parameters)
AppiumDriver`1.Execute(String driverCommandToExecute, Dictionary`2 parameters)
RemoteWebDriver.StartSession(ICapabilities desiredCapabilities)
RemoteWebDriver.ctor(ICommandExecutor commandExecutor, ICapabilities desiredCapabilities)
AppiumDriver`1.ctor(Uri remoteAddress, ICapabilities appiumOptions)
WindowsDriver`1.ctor(Uri remoteAddress, AppiumOptions AppiumOptions)
Login code
if (session == null){
AppiumOptions appOptions = new AppiumOptions();
appOptions.AddAdditionalCapability("app", Path);
appOptions.AddAdditionalCapability("platformName", "Windows");
appOptions.AddAdditionalCapability("deviceName", "WindowsPC");
Thread.Sleep(TimeSpan.FromSeconds(5));
session = new WindowsDriver<WindowsElement>(new Uri(WindowsApplicationDriverUrl), appOptions);
Assert.IsNotNull(session);
Thread.Sleep(TimeSpan.FromSeconds(10));
var allWindowHandles = session.WindowHandles;
session.SwitchTo().Window(allWindowHandles[0]);
session.Manage().Timeouts().ImplicitWait = TimeSpan.FromMinutes(1);
//Enter password and login
session.FindElementByAccessibilityId("tbPwd").SendKeys("password");
session.FindElementByAccessibilityId("btnLogin").Click();
Thread.Sleep(TimeSpan.FromSeconds(5));
session = new WindowsDriver<WindowsElement>(new Uri(WindowsApplicationDriverUrl), appOptions);
session.Manage().Timeouts().ImplicitWait = TimeSpan.FromMinutes(1);
}
Tear down code after each test case
public void TearDown()
{
AppiumOptions appOptions = new AppiumOptions();
appOptions.AddAdditionalCapability("app", "Root");
session = new WindowsDriver<WindowsElement>(new Uri(WindowsApplicationDriverUrl), appOptions);
// Use the session to control the desktop
session.Keyboard.PressKey(Keys.Command + "r");
session.Keyboard.SendKeys(Keys.Null);
session.Keyboard.SendKeys(#"C:\path of taskkill file.bat"+ Keys.Enter);
//End current session instance
session.Dispose();
}

Related

Enabling AcceptInsecureCertificates in Selenium EdgeDriver options throws an exception

Setup is Windows 10 v1903 and Visual Studio 2019 v16.2.2
I've installed the EdgeDriver using the following command:
DISM.exe /Online /Add-Capability /CapabilityName:Microsoft.WebDriver~~~~0.0.1.0
I've then created a new .NET Core console app and added the latest Selenium.WebDriver NuGet package (v3.141.0) to it. Then I've added code to Program.cs so that it looks like this:
using OpenQA.Selenium.Edge;
namespace ConsoleApp1
{
class Program
{
static void Main(string[] args)
{
var edgeOptions = new EdgeOptions { AcceptInsecureCertificates = true };
new EdgeDriver(edgeOptions);
}
}
}
When I run the console app I get the following error when executing the new EdgeDriver(edgeOptions); line.
OpenQA.Selenium.WebDriverException
HResult=0x80131500
Message=The specified arguments passed to the command are invalid.
Source=WebDriver
StackTrace:
at OpenQA.Selenium.Remote.RemoteWebDriver.UnpackAndThrowOnError(Response errorResponse)
at OpenQA.Selenium.Remote.RemoteWebDriver.Execute(String driverCommandToExecute, Dictionary`2 parameters)
at OpenQA.Selenium.Remote.RemoteWebDriver.StartSession(ICapabilities desiredCapabilities)
at OpenQA.Selenium.Remote.RemoteWebDriver..ctor(ICommandExecutor commandExecutor, ICapabilities desiredCapabilities)
at ConsoleApp1.Program.Main(String[] args) in ********\Program.cs:line 10
However if I change the value of AcceptInsecureCertificates from true to false then I get no exception and the browser opens as expected. This feels like a bug but I don't know if it's Selenium or the EdgeDriver that's at fault.
From the Microsoft Edge WebDriver document, we can see that the W3C WebDriver is still not support at present.
You could submit the Feedback at the bottom of the WebDeiver document.

The HTTP request to the remote WebDriver server for URL ... timed out after 60 seconds

I am using Selenium with the Internet Explorer Web Driver (IEDriverServer). For some reason I can't find the code base for it to open up this bug there. So if anyone can point me in that direction as well I would appreciate it.
This issue seems to be wide spread across all the drivers, which would indicate a base Selenium issue. But Selenium has already denied it is their problem. Currently there seems to be a fairly wide variety of hacks people have used to overcome the ongoing issue.
One person here on SO seems to have a similar issue, with a recommendation to overcome the issue by increasing the timeout, which sounds like a horrible idea to me because that would just slow down my tests overall.
I am getting these exceptions:
Message: The HTTP request to the remote WebDriver server for URL
http://localhost:24478/session/07896235-84ea-465e-a361-cb0ef5885ef2/url
timed out after 60 seconds. StackTrace: at
OpenQA.Selenium.Remote.HttpCommandExecutor.MakeHttpRequest(HttpRequestInfo
requestInfo) at
OpenQA.Selenium.Remote.HttpCommandExecutor.Execute(Command
commandToExecute) at
OpenQA.Selenium.Remote.DriverServiceCommandExecutor.Execute(Command
commandToExecute) at
OpenQA.Selenium.Remote.RemoteWebDriver.Execute(String
driverCommandToExecute, Dictionary`2 parameters) at
OpenQA.Selenium.Remote.RemoteWebDriver.get_Url()
and
Message: The HTTP request to the remote WebDriver server for URL
http://localhost:24478/session/07896235-84ea-465e-a361-cb0ef5885ef2/window/rect
timed out after 60 seconds. StackTrace: at
OpenQA.Selenium.Remote.HttpCommandExecutor.MakeHttpRequest(HttpRequestInfo
requestInfo) at
OpenQA.Selenium.Remote.HttpCommandExecutor.Execute(Command
commandToExecute) at
OpenQA.Selenium.Remote.DriverServiceCommandExecutor.Execute(Command
commandToExecute) at
OpenQA.Selenium.Remote.RemoteWebDriver.Execute(String
driverCommandToExecute, Dictionary`2 parameters) at
OpenQA.Selenium.Remote.RemoteWindow.get_Position()
I am getting this on a couple of different random calls to the driver. Like when I try and get the browsers current Url, or when I try and Click on an element in the browser.
In my current testing so far it looks like my tests are able to recover themselves and continue on, so future actions are still taken. I've got a few hacks I am going to try still, but it will take days to implement and test them giving the randomness of the issue.
I am using the Nuget Selenium.WebDriver package v3.141.0
with IEDriverServer v3.8. I rolled back from v3.9 due to another known issue with the driver.
Does anyone know of a fix to this issue, or a version of the IE driver that does not have it?
This is my first roll-out of Selenium. I have used CodedUI up to this point, and it has worked very well, but since Microsoft has announced it is discontinuing it I have been trying to bring the Selenium product online as a replacement. So far I have overcome most of the Selenium deficiencies to give myself back CodedUI like functionality, hopefully this is the last issue left.
Here is my basic call to start the driver:
/*
* Startup the correct Selenium browser driver.
*/
_Service = InternetExplorerDriverService.CreateDefaultService(seleniumPath);
var options = new InternetExplorerOptions()
{
// Mouse clicking takes a long time using NativeEvents, so trying turning it off
EnableNativeEvents = false
};
_Browser = new InternetExplorerDriver((InternetExplorerDriverService)_Service, options);
_Browser.Manage().Timeouts().PageLoad = new TimeSpan(0, 5, 0); // wait for 5 minutes
I have created some generic retry methods. This is a hack around a limitation in Selenium. Selenium has some built-in timeouts that can and should be used where appropriate, however not all calls to the drivers seem to honor those timeouts. Also, not all driver communication issues are a result of Selenium timing itself out after not hearing back; if the issue is due to network or permission issues then these methods will not help at all.
The main timeouts in Selenium for PageLoad, Script, and ImplicitWait should be used to fix timeout issues specific to those areas.
These methods (modified from another source) fix a very narrow set of issues where Selenium loses connection to the web driver part way through the call, or when it times out and you have no other way of extending the timeout period. They work by initiating a new call to the driver, in some instances this can result in the action being called multiple times in the browser, so use them with care.
/// <summary>
/// These retry methods are necessary because Selenium is incapable of handling timeouts
/// inside it's own system when it temporarily loses connection to the Driver.
/// Called like:
/// var return = RetryWebDriverServiceCall(f => object.method(param));
/// var return = RetryWebDriverServiceCall(f => object.attribute);
/// </summary>
/// <param name="serviceMethod"></param>
public delegate void VoidAction(params object[] oArgs);
public void RetryWebDriverServiceCall(VoidAction serviceMethod)
{
for (var loop = 0; loop < 3; loop++)
{
try
{
serviceMethod();
break;
}
catch (WebDriverException ex) // (WebDriverTimeoutException ex)
{
if (!ex.Message.Contains("timed out after 60 seconds") || loop >= 2)
throw new Exception($"UI Retry #: {loop}", ex);
System.Threading.Thread.Sleep(500);
}
}
}
public delegate T ParamsAction<T>(params object[] oArgs);
public T RetryWebDriverServiceCall<T>(ParamsAction<T> serviceMethod)
{
for (var loop = 0; loop < 3; loop++)
{
try
{
return serviceMethod();
}
catch (WebDriverException ex)
{
if (!ex.Message.Contains("timed out after 60 seconds") || loop >= 2)
throw new Exception($"UI Retry #: {loop}", ex);
}
}
throw new Exception("RetryWebDriverServiceCall failed");
}

Unexpected error launching Internet Explorer. IELaunchURL() returned HRESULT 80070012 ('There are no more files.') with IEDriver Selenium IE11

I am using VS2017 on a Win10 (17134.471) machine and I just installed Selenium. I can get Chrome, Firefox, Edge to work but not IE11 (11.471.171340). I believe that I have done all the other suggested updates but continue to get:
There are no more files.
It is not clear as to what needs to be installed I installed using NuGet and the versions are:
Selenium.WebDriver v3.141.0 (14 updates since 3.6.0.0)
Selenium.WebDriver64 v3.11.0.1
Selenium.Webdriver.MicrosoftDriver v17.17134.0
Test Name: IeMethod
Test FullName: utLearn2018.FirstTestClass.IeMethod
Test Source: C:\Users\stephan\Documents\Visual Studio 2017\Projects\utLearn2018\utLearn2018\FirstTestClass.cs : line 44
Test Outcome: Failed
Test Duration: 0:00:22.3336919
Result StackTrace:
at OpenQA.Selenium.Remote.RemoteWebDriver.UnpackAndThrowOnError(Response errorResponse)
at OpenQA.Selenium.Remote.RemoteWebDriver.Execute(String driverCommandToExecute, Dictionary`2 parameters)
at OpenQA.Selenium.Remote.RemoteWebDriver.StartSession(ICapabilities desiredCapabilities)
at OpenQA.Selenium.Remote.RemoteWebDriver..ctor(ICommandExecutor commandExecutor, ICapabilities desiredCapabilities)
at OpenQA.Selenium.IE.InternetExplorerDriver..ctor(InternetExplorerDriverService service, InternetExplorerOptions options)
at OpenQA.Selenium.IE.InternetExplorerDriver..ctor()
at utLearn2018.FirstTestClass.IeMethod() in C:\Users\stephan\Documents\Visual Studio 2017\Projects\utLearn2018\utLearn2018\FirstTestClass.cs:line 53
Result Message:
Test method utLearn2018.FirstTestClass.IeMethod threw exception:
System.InvalidOperationException: Unexpected error launching Internet Explorer. IELaunchURL() returned HRESULT 80070012 ('There are no more files.') for URL 'http://localhost:50326/' (SessionNotCreated)
My code is as follows:
using Microsoft.VisualStudio.TestTools.UnitTesting;
using OpenQA.Selenium;
using OpenQA.Selenium.Chrome;
using OpenQA.Selenium.Firefox;
using OpenQA.Selenium.Edge;
using OpenQA.Selenium.IE;
[TestMethod]
public void IeMethod()
{
InternetExplorerOptions options = new InternetExplorerOptions
{
IntroduceInstabilityByIgnoringProtectedModeSettings = true,
EnableNativeEvents = false,
EnsureCleanSession = true
};
IWebDriver driver = new InternetExplorerDriver();
driver.Navigate().GoToUrl("http://www.google.com");
driver.Manage().Window.Maximize();
driver.Close();
driver.Quit();
}
Some version of IE driver and selenium webdriver are not compatible. Worth trying different versions of IE driver and Selenium webdriver in order to launch the IE browser.

Firefox driver is not getting launch on VM machine

1. resources I used : C# , Selenium , VS 2017, Jenkins , VM machine (windows 10) , Nunit v3.9, geckoDrive v19, firefox v56/57
2. I can execute firefox / chrome browser cases on local machine
3. I can execute chrome browser cases on VM machine
4. Issue : **I can Not execute firefox cases on VM machine and its throwing below error.**
**Error Message**
OpenQA.Selenium.WebDriverException : Cannot start the driver service on http://localhost:50352/
TearDown : System.NullReferenceException : Object reference not set to an instance of an object.
I am adding few code below where issue is throwing issue
Stacktrace
at OpenQA.Selenium.DriverService.Start()
at OpenQA.Selenium.Remote.DriverServiceCommandExecutor.Execute(Command commandToExecute)
at OpenQA.Selenium.Remote.RemoteWebDriver.Execute(String driverCommandToExecute, Dictionary`2 parameters)
at OpenQA.Selenium.Remote.RemoteWebDriver.StartSession(ICapabilities desiredCapabilities)
at OpenQA.Selenium.Remote.RemoteWebDriver..ctor(ICommandExecutor commandExecutor, ICapabilities desiredCapabilities)
at OpenQA.Selenium.Firefox.FirefoxDriver..ctor(String geckoDriverDirectory, FirefoxOptions options, TimeSpan commandTimeout)
at MPAutomation.Driver.Initialize(String browser) in D:\Workspace.Automation\MPproject\MPAutomation\Utility\Driver.cs:line 79
# code on this line : Instance = new FirefoxDriver(service.FirefoxBinaryPath, options, TimeSpan.FromSeconds(10));
at MPAutomation.BaseTest.Init() in D:\Workspace.Automation\MPproject\MPAutomation\Utils\BaseTest.cs:line 54
#code here : LoginPage.GoTo(Settings.BrowserType); # I am passing "Firefox"
--TearDown
at MPAutomation.Driver.Close() in D:\Workspace.Automation\MPproject\MPAutomation\Utility\Driver.cs:line 117
# Instance.Close();
at MPAutomation.BaseTest.Cleanup() in D:\Workspace.Automation\MPproject\MPAutomation\Utils\BaseTest.cs:line 97
---------------------------------------------------------------------
firefox implemnetation looks like this in Driver.cs
- I tried with various version of Firefox too but none is working on VM
else if(browser.Equals(Constant.Firefox)) {
// driver init from here
FirefoxDriverService service = FirefoxDriverService.CreateDefaultService(DrivePath);
service.FirefoxBinaryPath = DrivePath;
var profile = new FirefoxProfile();
profile.AcceptUntrustedCertificates = true;
var options = new FirefoxOptions();
options.AcceptInsecureCertificates = true;
options.Profile = profile;
Instance = new FirefoxDriver(service.FirefoxBinaryPath, options, TimeSpan.FromSeconds(10));
Instance.Manage().Timeouts().ImplicitWait = TimeSpan.FromSeconds(10);
Utility.Logger.Write("***** Firefox Browser has been initialized now *********");
}
--------------------------------
5. We have one certificate for firefox and which has already been taken care locally and on VM
6. I am not sure why automation is not able to start firefox on VM
Finally we got the solution of this issue.
We need to set up "sandbox level" for firefox on VM.
profile.setPreference("security.sandbox.content.level", 5);
https://github.com/mozilla/geckodriver/issues/466
https://wiki.mozilla.org/Security/Sandbox

Selenium and a Non-working IEDriverServer

The IEDriverServer is throwing a OpenQA.Selenium.WebDriverException when I try a simple navigation to a page. This is working for Firefox.
It is "Unexpected error" and if I read further along it appears to be a 404 page not found.
I have already disabled protected mode for all zones and had also made IntroduceInstabilityByIgnoringProtectedModeSettings = true on the InternetExplorerOptions object.
How does one get IE working in this case?
Edit
Here is the stacktrace:
at OpenQA.Selenium.Remote.RemoteWebDriver.UnpackAndThrowOnError(Response
errorResponse) at
OpenQA.Selenium.Remote.RemoteWebDriver.Execute(String
driverCommandToExecute, Dictionary`2 parameters) at
OpenQA.Selenium.Remote.RemoteWebDriver.StartSession(ICapabilities
desiredCapabilities) at
OpenQA.Selenium.Remote.RemoteWebDriver..ctor(ICommandExecutor
commandExecutor, ICapabilities desiredCapabilities) at
OpenQA.Selenium.IE.InternetExplorerDriver..ctor(InternetExplorerDriverService
service, InternetExplorerOptions options, TimeSpan commandTimeout)
at
OpenQA.Selenium.IE.InternetExplorerDriver..ctor(InternetExplorerDriverService
service, InternetExplorerOptions options) at
CUWebinars.Selenium.Core.Ie.IeTestDriver..ctor() in
e:\TTS\BankWebinars\CUWebinars.Selenium.Core\Ie\IeTestDriver.cs:line
21 at CUWebinars.WebUi.Tests.Ie.IeBaseTest.Setup() in
e:\TTS\BankWebinars\CUWebinars.WebUi.Tests\Ie\IeBaseTest.cs:line 13
Edit 2
The following is in the constructor of the IeTestDriver (custom class)
const string ieTestDriverLocation = #"E:\";
var internetExplorerDriverService = InternetExplorerDriverService.CreateDefaultService(ieTestDriverLocation);
var internetExplorerOptions = new InternetExplorerOptions();
internetExplorerDriverService.Port = 333; // this is the port for the driver, not the webpage
port = "5556"; // in base class
webDriver = new InternetExplorerDriver(internetExplorerDriverService, internetExplorerOptions); // crashes here
webDriver.Manage().Timeouts().ImplicitlyWait(TimeSpan.FromSeconds(10));
webDriver.Manage().Timeouts().SetScriptTimeout(TimeSpan.FromSeconds(10));
The port 333 specified for the InternetExplorerDriverService falls within the well-known-port-numbers range:
On most systems, a well-known port number can only be used by a system
(root) process or by a program run by a privileged user.
Allow the driver service to select its own port by not specifying one explicitly, or provide an available port.
Double clicking IEDriverServer.exe will give you a Listening on port <number> message to see what it automatically picks up as available.