Selenium .Click() inconsistent behavior across machines in firefox using C# - c#

I am using Firefox 28, Web Driver v2.41, and C#.
I have the following simple test (anyone can replicate. I have added the horrible wait to demonstrate that this is not an issue related to the page not being ready):
[TestMethod]
public void TestMethod1()
{
var FF = new FirefoxDriver();
FF.Navigate().GoToUrl(#"http://www.bing.com");
FF.FindElement(By.Id("sb_form_q")).SendKeys("Stack Overflow");
Thread.Sleep(5000);
FF.FindElement(By.Id("sb_form_go")).Click();
}
The test behaves as expected in machine A.
The test fails to perform the click on the last line in machine B (Lenovo W530). The click method is not working with ANY of my tests on this machine.
If I switch the .Click() for .SenKeys(Keys.Enter) then the problem is solved.

Related

Selenium/Protractor .NET test hangs when using BrowserStack iPhone on remote website

I'm having issues testing iPhone on BrowserStack with tests written in C# with Selenium and Protractor-net.
The test starts running and after it opens the webpage to my website, it just hangs and never moves on to the StringAssert step. There are no errors when this happens. I must manually stop my test and the session in BrowserStack to continue.
I tried turning on logging from within BrowserStack's capabilities, but no errors are returning and the console log is empty. I've tried multiple configs of iPhones too.
Note, this sample test works fine with Android Google Pixel 2 and Windows 10 testing on BrowserStack, just iPhone's are giving me this problem.
Here is my sample test:
class Class1
{
[Test]
public static void FirstTest()
{
IWebDriver driver;
DesiredCapabilities capability = new DesiredCapabilities();
capability.SetCapability("browserName", "iPhone");
capability.SetCapability("device", "iPhone 6S");
capability.SetCapability("realMobile", "true");
capability.SetCapability("os_version", "11.4");
capability.SetCapability("browserstack.console", "errors");
capability.SetCapability("browserstack.user", "");
capability.SetCapability("browserstack.key", "");
driver = new RemoteWebDriver(new Uri("http://hub-cloud.browserstack.com/wd/hub/"), capability);
driver.Manage().Timeouts().AsynchronousJavaScript = TimeSpan.FromSeconds(10);
NgWebDriver ngdriver = new NgWebDriver(driver);
ngdriver.Navigate().GoToUrl("https://myproduction.website/");
StringAssert.Contains("MyTitle", ngdriver.Title);
NgWebElement query = ngdriver.FindElement(NgBy.Model("employeeCode"));
query.Clear();
query.SendKeys("Browserstack");
Console.WriteLine(ngdriver.Title);
ngdriver.Quit();
}
}
I understand you are running Protractor tests on real iOS devices. Protractor injects JavaScripts using execute_async method. The execute_async method is not fully supported by Appium due to which you may be seeing failures. You will find more details on the issue at the links below:
https://github.com/angular/protractor/issues/2840
https://github.com/angular/protractor/issues/1736

actions.MoveToElement() not working on ie 11

The same method used in the test automation project I wrote in c # does not work in internet explorer 11 even though the movement method I use is chrome, firefox and edge. It does not give any errors, but the next action is fail
log.Debug("fare " + by + " üzeriine dogru haraket ediyor, webelement label ");
IWebElement element = GetElement(by);
Actions Actions = new Actions(Driver);
WaitElementToClickable(Driver, by, 5);
Actions.MoveToElement(element);
Actions.Perform();
WaitElementToClickable(Driver, by, 5);
I spent a long time trying to get actions to work across all browsers, and for IE I found the following helped.
Selenium webdriver v2.29.0 (https://github.com/SeleniumHQ/selenium/blob/master/java/CHANGELOG) added:
IEDriver supports "requireWindowFocus" desired capability. When
using this and native events, the IE driver will demand focus and
user interactions will use SendInput() for simulating user
interactions. Note that this will mean you MUST NOT use the
machine running IE for anything else as the tests are running.
When I set the IEDriver I use:
InternetExplorerOptions options = new InternetExplorerOptions();
options.requireWindowFocus();
webDriver = new InternetExplorerDriver(options);
And all my move to and click events work fine. I'm using IE11.125-11.309 and Selenium (java bindings) 3.7.1.

Inconsistent behaviour of Click() in Selenium

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.

Updating from Selenium.Webdriver 2.44 to 2.46 causes NullReferenceException

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.

Simple Selenium Test Gives XHR ERROR : 404

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"});
}
};

Categories