Attempting to make the code from http://blogs.windows.com/msedgedev/2015/07/23/bringing-automated-testing-to-microsoft-edge-through-webdriver/ work.
Getting an ugly exception.
Repro steps.
Install web driver from links provided ( July 24 2015 WebDriver )
Create console app.
Nuget in Selenium.WebDriver, Selenium.Support.
Run code, console window comes up fine.
When code hits the driver.Url="https://www.bing.com" it throws an exception, as noted below.
NoSuchWindowException - An unhandled exception of type 'OpenQA.Selenium.NoSuchWindowException' occurred in WebDriver.dll
My snippet is below:
using System.IO;
using OpenQA.Selenium;
using OpenQA.Selenium.Edge;
using OpenQA.Selenium.Remote;
using OpenQA.Selenium.Chrome;
using OpenQA.Selenium.Support.UI;
namespace WebDriverPlay
{
public class msedgedev_sample
{
public static void RunMSEdgeDevSample()
{
Console.WriteLine("running MSEdgeDev Sample");
RemoteWebDriver driver = null;
string serverPath = "Microsoft Web Driver";
try
{
if (System.Environment.Is64BitOperatingSystem)
{
serverPath = Path.Combine(System.Environment.ExpandEnvironmentVariables("%ProgramFiles(x86)%"), serverPath);
}
else
{
serverPath = Path.Combine(System.Environment.ExpandEnvironmentVariables("%ProgramFiles%"), serverPath);
}
// location for MicrosoftWebDriver.exe
EdgeOptions options = new EdgeOptions();
options.PageLoadStrategy = EdgePageLoadStrategy.Eager;
driver = new EdgeDriver(serverPath, options);
//Set page load timeout to 5 seconds
driver.Manage().Timeouts().SetPageLoadTimeout(TimeSpan.FromSeconds(5));
//string _url = #"https://www.bing.com/";
string _url = #"http://www.google.com";
Console.WriteLine("_url=" + _url);
driver.Url = _url;
}
catch (Exception e)
{
Console.WriteLine(e.Message);
}
finally
{
if (driver != null)
{
driver.Close();
}
}
}
}
}
After the line:
driver = new EdgeDriver(serverPath, options);
executes, you should see a command window open and connect to Edge. If the Edge browser is already open, it will close it and open a new instance. Based on your error, I don't believe you are seeing this behavior, am I correct? If so, something may be blocking the WebDriver Server from launching locally (Defender??). Check the conditional setting serverPath. I could not get the Is64BitOperatingSystem to resolve, so I chose the correct path and removed the rest of the conditional, setting serverPath to the location of the MicrosoftWebDriver.exe.
If you have the incorrect path it will not make it past the "driver" instantiation. Somehow you are making it to the driver.Url call, I assume you are getting some resolution with that serverPath. So it is possible something on the local device is blocking MicrosoftWebDriver.exe from running.
Again, you should see a command prompt with proper communication logging displayed.
One last tip, you can go to MicrosoftWebDriver.exe and run it. Then you can go to: http://dev.modern.ie/testdrive/demos/webdriver/ and "Send Request" with the default values, which should be to create a session. You will see the results posted to the page and also see the logging of the communications in the command window.
Be sure to go to that page from a different browser than Edge since it will kill the existing Edge windows, including itself.
I have a little insight, but not a workaround or fix, yet...
in my case, the web driver server for IE conflicted with my web driver server for edge... and I still do not have a workaround... I have a cycle of tests that run on five different browsers.
when I tried to add edge, it would not run edge without crashing.
the web driver in the debug folder (for the base five including IE) name is IDENTICAL to the one that is included when I run Edge.
I do not know how to fix it and meet the testing requirements... YET.
bro mak
Related
I get up to a certain point in a desktop app that I'm automating and I need to click a link and continue automating in a browser. The link automatically goes to internet explorer.(suggestions on how to copy and paste that into chrome would be appreciated). I need to know how to switch from the desktop to the webview, automate the web view and go back to the desktop view.
So far this is the closest thing I've found that solves the problem. I'm newer to c# so I know the theory of what I'd like to do, just not how to implement it. http://appium.io/docs/en/writing-running-appium/web/hybrid/. I've got so far as to log the context to my output. I haven't been able to set or reset it yet.
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Threading;
using Microsoft.VisualStudio.TestTools.UnitTesting;
using OpenQA.Selenium.Appium;
using OpenQA.Selenium.Appium.Windows;
using OpenQA.Selenium.Remote;
namespace UnitTestProject2
{
[TestClass]
public class GoldTrakPCTest
{
[TestMethod]
public void TestMethod1()
{
AppiumOptions options = new AppiumOptions();
options.AddAdditionalCapability("deviceName", "WindowsPC");
options.AddAdditionalCapability("platformName", "Windows");
options.AddAdditionalCapability("app", "XXXX -Path to desktop app");
WindowsDriver<WindowsElement> windowsDriver = new WindowsDriver<WindowsElement>(new Uri("http://127.0.0.1:4723/"), options);
Thread.Sleep(1500);
windowsDriver.FindElementByAccessibilityId("1006").SendKeys("Username");
windowsDriver.FindElementByAccessibilityId("1003").SendKeys("Password");
windowsDriver.FindElementByAccessibilityId("1001").SendKeys("354 - B - Mariner");
windowsDriver.FindElementByAccessibilityId("1").Click();
var myVar = windowsDriver.FindElementByAccessibilityId("59393");
Thread.Sleep(4200);
//Trace.WriteLine(windowsDriver.FindElementByName("WILLY WONKA"));
windowsDriver.FindElementByName("WILLY WONKA").Click();
Thread.Sleep(1000);
windowsDriver.FindElementByAccessibilityId("1310").Click();
Thread.Sleep(4000);
windowsDriver.FindElementByName("Documents").Click();
Thread.Sleep(4000);
windowsDriver.FindElementByAccessibilityId("1011").Click();
windowsDriver.FindElementByAccessibilityId("1011").Click();
windowsDriver.FindElementByName("Doc Set - WI Esign Documents").Click();
windowsDriver.FindElementByAccessibilityId("4750").Click();
Thread.Sleep(4000);
windowsDriver.FindElementByName("OK").Click();
windowsDriver.FindElementByAccessibilityId("2034").Click();
Thread.Sleep(4000);
string Context = windowsDriver.Context;
Trace.WriteLine(Context);
/*List<string> AllContexts = new List<string>();
foreach (var context in (windowsDriver.Contexts))
{
AllContexts.Add(context);
Trace.WriteLine(context);
}*/
//Trace.WriteLine(AllContexts, "Hello");
//options.AddAdditionalCapability("")
//windowsDriver.FindElementByName("WILLY WONKA").Click();
//windowsDriver.FindElementByName("Next").Click();
Thread.Sleep(6000);
//windowsDriver.Close();
}
}
}
I need to know how to change context and if it's possible to switch between native windows desktop apps and browsers and how to do this.
It is possible. I have 2 desktop application and 1 web application all running in tandem. However, I have one question regarding "The link automatically goes to internet explorer.(suggestions on how to copy and paste that into chrome would be appreciated)."
is it because Internet Explorer is the default explorer in windows?
Switching context between apps.
As soon as u click the windowselement that opens Web (IE or chrome), you'll need to create Webdriver instance (IE/chrome)and attach it to the browser process
A test initialize method which launches/attaches to an existing session :
How to use/attach an existing browser using Selenium?
class Program
{
static void Main(string[] args)
{
IWebDriver driver = new ChromeDriver();
//Dev environment
driver.Url = /*URL*/;
var trialGroupName = driver.FindElement(By.Name("TrialGroupName"));
trialGroupName.SendKeys(/*trial group name */);
var userName = driver.FindElement(By.Name("UserName"));
userName.SendKeys(/*username*/);
var password = driver.FindElement(By.Name("UserPassword"));
password.SendKeys(/*password*/);
var loginButton = driver.FindElement(By.Id("Ok"));
loginButton.Click();
//Find and click on Browse tab
var browseTab = driver.FindElement(By.Id("17"));
browseTab.Click();
}
}
OpenQA.Selenium.NoSuchElementException: 'no such element: Unable to locate element: {"method":"id","selector":"17"}
(Session info: chrome=58.0.3029.110)
(Driver info: chromedriver=2.30.477700 (0057494ad8732195794a7b32078424f92a5fce41),platform=Windows NT 6.1.7601 SP1 x86_64)'
Here's the inspect information:
<td>
<a id="17" class="defaultMenu initMenu" href="javascript:onMenuHref(17)" notran="">Browse</a>
</td>
I've also tried running it with the XPath (both the short version from Chrome and the long version from FireBug) and I receive the same error. I've tried adding in an implicit wait and a Thread.Sleep() but still received the same error. Also tried starting on a different field and tabbing to it and then it gave me the same exception but on the new field. I also tried playing around with cssSelector this morning and couldn't get that to work either. I did try to do an explicit wait but I'll be honest, I'm still trying to digest and understand it as waits are a new concept and I don't fully understand it, so I don't think I'm doing it right.
I'm a beginner, and I'm currently just trying to write the script to get it to the actual page that needs testing. I've been teaching myself some coding and selenium as I'm the only QA person at my company right now and I really think we could benefit from automation. This portion of the page isn't actually programmed by us it's done by a third party who hosts the system we use so I'm limited to what I see in the inspect.
(I commented out the user login information and URL because it is for internal use only and the page can't be reached outside of our systems anyways. Also I'm pretty sure I'm not allowed to do so by my employer).
Any help on this would be greatly appreciated, or any additional resources I can use. I've been using google mostly so there may be other pages you are aware of that could help me that I haven't found yet.
The login button takes you to a new page, which you need to wait for it to load. Try using an explicit wait to wait for the tab to be clickable. The timeout is 10 seconds in the following example, so modify that as needed.
WebDriverWait wait = new WebDriverWait(driver, TimeSpan.FromSeconds(10));
IWebElement browseTab = wait.Until(ExpectedConditions.ElementToBeClickable(By.Id("17")));
I'm working on a Product automation(Web CMS), where element.Click() shows the inconsistent behaviour. Basically we are using,
Selenium + Nunit GUI(unit testing framework) - To run the test cases from local on a particular environment
Selenium + Asp.net web application - Multiple user's can run the test cases on different environment
Here environment I mean different levels(Dev, SIT, QA, Production).
My Concern
In one of my test cases, I want to Click a button. So for that, I have tried few code. But all are inconsistent behaviour. Here Inconsistent I mean, the code whatever I wrote for clicking a button are only working in my local or server and viceversa.
1st attempt:-
I tried all the element locator's
IWebElement element = driver.FindElement(By.Id("element id goes here"))
Working fine at my local, but not in server
Result - Failed
2nd attempt:-
driver.FindElement(By.XPath("Element XPath goes here")).SendKeys(Keys.Enter);
Working fine at server, but not in local
Result - Failed
3rd attempt:-
IWebElement element = driver.findElement(By.id("something"));
IJavaScriptExecutor executor = (IJavaScriptExecutor)driver;
executor.ExecuteScript("arguments[0].click()", element);
Not working in both(local and server)
Result - Failed
At last, I tried waiting for the element to be visible and performing action
4th attempt:-
WebDriverWait wait = new WebDriverWait(driver, TimeSpan.FromSeconds(60));
return wait.Until(ExpectedConditions.ElementIsVisible(By.XPath("element xpath goes here")));
After webdriver wait performing action on that element (element.click())
Working fine at local but not in server
Result - Failed
I'm looking for a solution, where Clicking the button should not be an inconsistent behaviour. Basically it should work fine in both (Local and Server). Your help would be greatly appreciated..Thanks in advance
FYI - I'm testing in Mozilla Firefox browser 38.5.2
I'm using Selenium in C# locally on Win7 and remotely on Win10 and MacOS with the Firefox browser and also noticed that Firefox sometimes requires special treatment for IWebElement.Click(). So I wrote myself an extension method, which works fine for me, no matter by what locator the element was found:
public static void Click(this IWebElement element, TestTarget target)
{
if (target.IsFirefox)
{
var actions = new Actions(target.Driver);
actions.MoveToElement(element);
// special workaround for the FirefoxDriver
// otherwise sometimes Exception: "Cannot press more then one button or an already pressed button"
target.Driver.Manage().Timeouts().ImplicitlyWait(TimeSpan.Zero);
// temporarily disable implicit wait
actions.Release().Build().Perform();
target.Driver.Manage().Timeouts().ImplicitlyWait(TimeSpan.FromSeconds(MyDefaultTimeoutInSeconds));
Thread.Sleep(500);
actions.MoveToElement(element);
actions.Click().Build().Perform();
}
else
{
element.Click();
}
}
If you want more stable behavior for your test cases, I would recommend using ChromeDriver. It never needs any special treatment at all, and it's also much faster than the FirefoxDriver.
We have just started working with Appium in my company, using it to automate testing on websites and webapps.
Testing Framework = Nunit 2.6.4
Language used = C#
Mobile Device = Samsung Galaxy S4
Android version = 5.0.1
I've used Selenium and Nunit to test on Desktop before on a simple website, using [Test], [TestCase] and [TestCaseSource] attributes in my tests.
Following the advice in the article of the answer to:
How to integrate Appium with C#?
(Quicker article link here:
http://blogs.technet.com/b/antino/archive/2014/09/22/how-to-set-up-a-basic-working-appium-test-environment.aspx)
An associate set up a solution that would do a simple navigation to StackOverflow, click a link and assert:
namespace AppiumTests
{
using System;
using NUnit.Framework;
using AppiumTests.Helpers;
using AppiumTest.Framework;
using OpenQA.Selenium; /* Appium is based on Selenium, we need to include it */
using OpenQA.Selenium.Appium; /* This is Appium */
using OpenQA.Selenium.Appium.Interfaces; /* Not needed for commands shown here. It might be needed in single tests for automation */
using OpenQA.Selenium.Appium.MultiTouch; /* Not needed for commands shown here. It might be needed in single tests for automation */
using OpenQA.Selenium.Interactions; /* Not needed for commands shown here. It might be needed in single tests for automation */
using OpenQA.Selenium.Remote;
using OpenQA.Selenium.Appium.Android;
[TestFixture]
public class AndroidAppiumTestSuite
{
private AppiumDriver driver;
private static Uri testServerAddress = new Uri(TestServers.WindowsServer);
private static TimeSpan INIT_TIMEOUT_SEC = TimeSpan.FromSeconds(180); /* Change this to a more reasonable value */
private static TimeSpan IMPLICIT_TIMEOUT_SEC = TimeSpan.FromSeconds(10); /* Change this to a more reasonable value */
[SetUp]
public void BeforeAll()
{
DesiredCapabilities capabilities = new DesiredCapabilities();
TestCapabilities testCapabilities = new TestCapabilities();
//testCapabilities.App = "";
testCapabilities.AutoWebView = true;
testCapabilities.AutomationName = "<just a name>";
testCapabilities.BrowserName = "Chrome"; // Leave empty otherwise you test on browsers
testCapabilities.DeviceName = "Needed if testing on IOS on a specific device. This will be the UDID";
testCapabilities.FwkVersion = "1.0"; // Not really needed
testCapabilities.Platform = TestCapabilities.DevicePlatform.Android; // Or IOS
testCapabilities.PlatformVersion = "5.0.1"; // Not really needed
testCapabilities.AssignAppiumCapabilities(ref capabilities);
driver = new AndroidDriver(testServerAddress, capabilities, INIT_TIMEOUT_SEC);
driver.Manage().Timeouts().ImplicitlyWait(IMPLICIT_TIMEOUT_SEC);
}
[TearDown]
public void AfterAll()
{
TestContext.CurrentContext.Result.ToString();
driver.Quit(); // Always quit, if you don't, next test session will fail
}
/// <summary>
/// Just a simple test to heck out Appium environment.
/// </summary>
[Test]
public void CheckTestEnvironment()
{
driver.Navigate().GoToUrl("http://stackoverflow.com");
driver.FindElementByCssSelector("body > div.topbar > div.network-items > div.login-links-container > a").Click();
Assert.AreEqual("Log in using any of the following services", (driver.FindElementByCssSelector("h2.title")).Text);
}
Many thanks to Andrea Tino for this starting point.
Now this worked fine, and my colleague who set this up and showed it to me has gone on holiday leaving me the task of adding in our existing tests and tweaking bits here and there.
I added in my testclass which requires the Webdriver.Support pacakge to be installed, which depends on Webdriver >= 2.46.0
Now, when I run my code, I get a null reference exception on this line:
driver = new AndroidDriver(testServerAddress, capabilities, INIT_TIMEOUT_SEC);
This is the error I'm getting:
AppiumTests.AndroidAppiumTestSuite.CheckTestEnvironment:
SetUp : System.NullReferenceException : Object reference not set to an instance of an object.
TearDown : System.NullReferenceException : Object reference not set to an instance of an object.
So my thought was that something in 2.46.0 meant I need to supply another capability, but I've been banging my head against this for two days now with no progress.
I have a screenshot of the appium server communication, but I'm not able to link images yet XD so here is it pasted in:
info: [debug] Device launched! Ready for commands
info: [debug] Setting command timeout to the default of 60 secs
info: [debug] Appium session started with sessionId 4575272bba7d11c85414d48cf53ac8e3
info: <-- POST /wd/hub/session 303 10828.204 ms - 70
info: --> GET /wd/hub/session/4575272bba7d11c85414d48cf53ac8e3 {}
info: Proxying [GET /wd/hub/session/4575272bba7d11c85414d48cf53ac8e3] to [GET http://127.0.0.1:9515/wd/hub/session/4575272bba7d11c85414d48cf53ac8e3] with body: {}
info: Got response with status 200: {"sessionId":"4575272bba7d11c85414d48cf53ac8e3","status":0,"value":{"acceptSslCerts":true,"applicationCacheEnabled":false,"browserConnectionEnabled":false,"browserName":"chrome","chrome":{},"cssSelect...
info: <-- GET /wd/hub/session/4575272bba7d11c85414d48cf53ac8e3 200 6.770 ms - 506
info: --> POST /wd/hub/session {"desiredCapabilities":{"javascriptEnabled":true,"device":"Android","platformName":"Android","deviceName":"d5cb5478","browserName":"Chrome","platformVersion":"5.0.1","browserVersion":"43.0.2357.93"}}
error: Failed to start an Appium session, err was: Error: Requested a new session but one was in progress
So from here I can see that its trying to start a new session when I've already started one, but I can't figure out the cause!
So here's how to get around the Appium-specific half of the problem -- I don't have an answer for your NullReferenceException.
That Appium error is caused when the port you're trying to start Appium WebDriver on is already in use.
To manually fix this
You can do $telnet ip port to figure out what Process ID you need to kill.
You can find the address/port by checking the value for what new Uri(TestServers.WindowsServer); returns.
Exit any emulators
Once you have the PID then you can do $kill -9 pid and start your Appium server like normal.
A proper solution
If you are having this problem regularly, it may be because your script is ending without quitting the Appium WebDriver.
Usually you put the teardown code for the WebDriver (driver.quit()) in the #After section of your tests, or in your base TestCase class.
I see that you have a teardown section there -- so maybe you got into this bad state during a previous session? Either way, the manual fix should get you back to working order.
I'm using selenium-rc with C# to test my asp.net mvc2 application. Currently all I am doing is opening the home page with selenium RC.
when I run my test I see the selenium remote control open in a browser and I see my application open correctly in a browser but selenium shows a 404 error and aborts the test.
In an attempt to get this working I have cut the test down to a simple console app and have changed the default selenium port here is my code:
static void Main(string[] args)
{
try
{
var _selenium = new DefaultSelenium("localhost", 1234, "*chrome", "http://localhost:6666");
_selenium.Start();
_selenium.Open("/");
try
{
_selenium.Stop();
}
catch (Exception)
{
// Ignore errors if unable to close the browser
}
}
catch (Exception e)
{
Console.WriteLine(e);
}
Console.WriteLine("Done.");
Console.ReadKey();
}
this fails with the error "XHR ERROR: URL = /localhost:6666/ Response_Code = 404 Error_Message = Not Found on session 5f2e59798ae74e7cb741d50cae7e817a"
and if you look in the running selenium console you see
15:53:16.238 INFO - Allocated session 5f2e59798ae74e7cb741d50cae7e817a for http://localhost:6666, launching...
15:53:16.265 INFO - Preparing Firefox profile...
15:53:18.325 INFO - Launching Firefox...
15:53:20.977 INFO - Got result: OK,5f2e59798ae74e7cb741d50cae7e817a on session 5f2e59798ae74e7cb741d50cae7e817a
15:53:20.980 INFO - Command request: open[/, ] on session 5f2e59798ae74e7cb741d50cae7e817a
15:53:22.654 INFO - Got result: XHR ERROR: URL = http://localhost:6666/ Response_Code = 404 Error_Message = Not Found on session 5f2e59798ae74e7cb741d50cae7e817a
Interesting things that I have tried are:
change the site to "google" - then my test works
change the site to "google" port 80 then it doesnt work.
moved my site from cassini to iis 7 - didnt work
made my site the default site on iis 7 eg http://localhost/ - didnt work
I've used fiddler to watch the session - all requests fired return successfully.
I've tried passing -avoidProxy and -ensureCleanSession when starting the RC server. Hasn't made any noticable difference.
If I reconfigure selenium to use the default port I get the following exception repeated over and over (once every 10 seconds / different sessionid each time). This doesn't happen once I've changed the default port but i've included it just in case.
16:26:38.019 WARN - POST /selenium-server/driver/?seleniumStart=true&localFrameAddress=top&seleniumWindowName=&uniqueId=sel_48694&sessionId=a87b8d6a9e444a5485a5044ef6370e2d&counterToMakeURsUniqueAndSoStopPageCachingInTheBrowser=1286810798016&sequenceNumber=4115 HTTP/1.1
java.lang.RuntimeException: sessionId a87b8d6a9e444a5485a5044ef6370e2d doesn't exist; perhaps this session was already stopped?
at org.openqa.selenium.server.FrameGroupCommandQueueSet.getQueueSet(FrameGroupCommandQueueSet.java:220)
at org.openqa.selenium.server.SeleniumDriverResourceHandler.handleBrowserResponse(SeleniumDriverResourceHandler.java:165)
at org.openqa.selenium.server.SeleniumDriverResourceHandler.handle(SeleniumDriverResourceHandler.java:131)
at org.openqa.jetty.http.HttpContext.handle(HttpContext.java:1530)
at org.openqa.jetty.http.HttpContext.handle(HttpContext.java:1482)
at org.openqa.jetty.http.HttpServer.service(HttpServer.java:909)
at org.openqa.jetty.http.HttpConnection.service(HttpConnection.java:820)
at org.openqa.jetty.http.HttpConnection.handleNext(HttpConnection.java:986)
at org.openqa.jetty.http.HttpConnection.handle(HttpConnection.java:837)
at org.openqa.jetty.http.SocketListener.handleConnection(SocketListener.java:245)
at org.openqa.jetty.util.ThreadedServer.handle(ThreadedServer.java:357)
at org.openqa.jetty.util.ThreadPool$PoolThread.run(ThreadPool.java:534)
Can anybody shed some light?
I am using C# and had similar problem with selenium.open method. I have refered the thread haroonzone posted in his answer above. and have made following changes in my code
Declare selenium as
private DefaultSelenium selenium;
instead of
private ISelenium selenium;
and call open method as
selenium.Processor.DoCommand("open", new String[] { YOUR_URL, "true" });
instead of
selenium.Open("YOUR_URL");
Additionally, you may want to call
selenium.SetTimeout("600000");
before DoCommand
What version of Selenium Server are you using? We get this problem with Selenium Server 2.0a2. It is fixed in later versions of Selenium, so if you download the latest version of the Selenium Server and run this test against it then you wont get the XHR exception. But if you cannot update the selenium version then you can do the following. The code snippet is in Java you can have a similar in C#.
The problem is with the selenium.open method. You can find more information on the following URL.
http://code.google.com/p/selenium/issues/detail?id=408
selenium = new DefaultSelenium("localhost", port, browserString, url) {
public void open(String url) {
commandProcessor.doCommand("open", new String[] {url,"true"});
}
};