Simple Selenium Test Gives XHR ERROR : 404 - c#

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

Related

C# not able to get console Logs from PhantomJSDriver (Selenium)

I'm using Selenium in C# with the PhantomJS Driver.
I need to click specific coordinates on a website, that works with using Javascript (im using the ExecutePhantomJS(string script) function of the selenium phantomjs driver). I also need to capture the network traffic. I used browsermob earlier to do that, but for now i cant use it because i also need to use another proxy. So i solved it like that until now:
//Hide CMD of PhantomJS.exe
var driverService = PhantomJSDriverService.CreateDefaultService();
driverService.HideCommandPromptWindow = true;
//Initialize Driver and execute Network Script to capture traffic
driver = new PhantomJSDriver(driverService);
driver.ExecutePhantomJS(networkScript);
//Call URL
driver.Navigate().GoToUrl(url);
This is the networkScript:
string networkScript = "var page = this; page.onResourceRequested = function(req) { console.log('received: ' + JSON.stringify(res, undefined, 4)); }; page.onResourceReceived = function(res) { console.log('received: ' + JSON.stringify(res, undefined, 4)); };";
The good thing:
URL is called and all network traffic is logged into the console of the PhantomJS.exe.
But I dont know how I can get these console logs now in my C# code (I need to get specific things like URLs etc.. out of the network log).
I already read the whole afternoon but couldn't find a solution until now. Some of the things I already tried:
1) Tried to use PhantomJSOptions, there u can set LoggingPreferences and later i called driver.Manager().Logs.GetLog(LogType), but there were none of the console logs
2) Dont use console.log inside networkScript. I used require('system').stdout.write(...). It was also logged into console but I cant get the standard output stream of the phantomjs.exe from my C# code.
...
I really dont know how i could solve the problem.
One way would be to log into a .txt file instead of console, but it is very much text and later there will be many opened drivers, so I want to avoid that because then i will have very much and big .txt files

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.

Edge Browser WebDriver Failure

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

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.

Problem with WebSockets Draft

I'm having some trobule with Web Sockets and Microsoft's Draft implementation. I'm using the API provided by them for the server back and as well as the Silverlight fix for browsers that don't natively support Web Sockets. The information i'm working off of comes from http://channel9.msdn.com/Events/MIX/MIX11/HTM10 and http://html5labs.interoperabilitybridges.com/prototypes/websockets/websockets/info
My code compiles okay, it starts to open the connection, then fails. Here's my backend server code (in a C# Console App)
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Microsoft.ServiceModel.WebSockets;
namespace ChatBackend
{
class Program
{
static void Main(string[] args)
{
var host = new WebSocketsHost<MessageHandler>();
host.AddWebSocketsEndpoint("ws://localhost:4502/MessageHandler");
host.Open();
Console.ReadLine();
}
}
}
Here's the MessageHandler class:
class MessageHandler : WebSocketsService
{
public override void OnMessage(string value)
{
string returnMessage = "You just said '" + value + "'";
Console.WriteLine(value);
SendMessage(returnMessage);
}
}
This backend part seems to work fine. Here's the client end:
$(document).ready(function () {
setTimeout(connect, 2050);
});
function connect() {
websocket = new WebSocketDraft("ws://localhost:4502/MessageHandler");
websocket.onopen = function() {
websocket.send("test");
};
websocket.onclose = function () {
alert("DIED");
};
websocket.onmessage = function(event) {
sendMessage(new message(0, event.data, 0));
};
}
EDIT: I checked my firewall and allowed the port i was using. Now the connection just hangs - it doesn't close, it doesn't open. Any ideas?
EDIT 2: I did some more research, turns out i need to remove the clientaccesspolicy.xml. Also turns out i never had it, but i WAS returning a custom 302 redirect instead of a 404 not found. Fixed that, but no progress. It just hangs.
EDIT 3: Tried turning off Anti-Virus and Firewall, no change
Thanks - let me know if i need anymore code or information up here.
Can you use Firebug or something and put a breakpoint on this line in jquery.slws.js (assuming its the one you're using!)
this.slws = slCtl.Content.services.createObject("websocket");
And then step through and see where it fails ?
Your URL definitely looks like it matches the setting on your server side. It's really hard to find any examples of WebSockets actually being used since it's still such a new technology, but from what I could follow of the only working example I could find (it was on the html5labs site), I think maybe you're trying to write to the socket before it's finished opening. In the example I found, it looked like they check the readyState property of the socket, and only try to send if readyState === 1. The socket in that example gets opened by tying into the $(document).ready event, and send gets called from a button click.
Finally got this working! Turns out i had to add clientaccesspolicy.xml to the root folder of the default website on my server. I thought i had to delete it - i misread some information and promptly forgot about it. Moral of the story: read the readme!

Categories