C#
.Net 4.5
VS 2013
NUnit 3.2.1
Webdriver and Webdriver.Support 2.53
So my issue is I am trying navigating to ebay's sandbox login page and login. This seems simple enough but I am struggling to get the page to fully load before giving me a System.Net.WebException timeout error.
Here is the link I am trying to go to
https://signin.sandbox.ebay.com/
And Here is what my code looks like that is doing this.
var EbaySandboxPage = new EbaySandboxLoginPageModel(Driver);
Driver.Manage().Timeouts().SetPageLoadTimeout(TimeSpan.FromSeconds(200));
Driver.Navigate().GoToUrl(EbaySandboxLoginPageModel.sandboxUrl);
And here is the exception that is getting thrown every time I try this in Firefox.
Test Name: VerifyItemsSold
Test FullName: POMAuctivaTest.TestSuite.PostSaleTestSuite<FirefoxDriver>.VerifyItemsSold
Test Source: c:\git\POMAuctivaTest\POMAuctivaTest.TestSuite\PostSaleTestSuite.cs : line 204
Test Outcome: Failed
Test Duration: 0:00:00.0000001
Result Message:
OneTimeSetUp: OpenQA.Selenium.WebDriverException : The HTTP request to the remote WebDriver server for URL http://localhost:7055/hub/session/80efbcbe-841d-4a53-a422-5e7498a0438b/element timed out after 60 seconds.
----> System.Net.WebException : The operation has timed out
So my question is how to I change the System.Net.WebRequest.Timeout property? I am not using an instance of webrequest. I guess webdriver is but I would imagine there is a way for me to change this value. As you can see I have already upped the SetPageLoadTimeout() value to exceed 2 min. Which in my manual testing has been more than enough.
Here was my attempt at #Buaban's solution although mine was still throwing the exception.
Driver.Manage().Timeouts().SetPageLoadTimeout(TimeSpan.FromSeconds(120));
try
{
Driver.Navigate().GoToUrl(EbaySandboxLoginPageModel.sandboxUrl);
}
catch (WebDriverException)
{
}
EbaySandboxPage.WaitForElementVisible(Driver, EbaySandboxLoginPageModel.usernameFieldSelector);
Here is what the WaitForElementVisible() method looks like.
public void WaitForElementVisible(IWebDriver driver, By element)
{
try
{
WebDriverWait wait = new WebDriverWait(driver, TimeSpan.FromSeconds(90));
wait.Until(ExpectedConditions.ElementIsVisible(element));
}
catch (WebDriverTimeoutException)
{
TakeScreenshot(Driver);
Console.Write("Test failed trying to wait for this element " + element.ToString() + " to be visible ");
}
}
Here is the definition of the usernameFieldSelector
public static By usernameFieldSelector = By.CssSelector("#userid");
So thank your #Florent and #Buaban, with your help I was able to figure out a solution to this. Ill post it here but award the answer to your Buaban as I am not sure I would have been able to get to this as quickly without your help.
Driver.Manage().Timeouts().SetPageLoadTimeout(TimeSpan.FromSeconds(30));
try
{
Driver.Navigate().GoToUrl(#"https://signin.sandbox.ebay.com/");
}
catch (Exception)
{
System.Diagnostics.Debug.WriteLine("Some resources are dead!");
}
var attempts = 0;
while (attempts < 2)
{
try
{
IWait<IWebDriver> wait = new DefaultWait<IWebDriver>(Driver);
wait.Timeout = TimeSpan.FromSeconds(20);
wait.PollingInterval = TimeSpan.FromMilliseconds(300);
wait.Until(d => d.FindElements(By.XPath("//span[text()='SIGN IN']")).Count > 0);
break;
}
catch (WebDriverException)
{
attempts++;
}
}
As Florent B. mentioned in comment, some page resources are dead. You have to ignore the exception then wait for an element on the page. See example below:
Driver.Manage().Timeouts().SetPageLoadTimeout(TimeSpan.FromSeconds(30));
try
{
Driver.Navigate().GoToUrl(#"https://signin.sandbox.ebay.com/");
}
catch (Exception)
{
System.Diagnostics.Debug.WriteLine("Some resources are dead!");
}
IWait<IWebDriver> wait = new DefaultWait<IWebDriver>(Driver);
wait.Timeout = TimeSpan.FromSeconds(10);
wait.PollingInterval = TimeSpan.FromMilliseconds(300);
wait.Until(d => d.FindElements(By.XPath("//span[text()='SIGN IN']")).Count > 0);
System.Diagnostics.Debug.WriteLine("SIGN IN textbox is loaded");
Related
I have been trying to find ways to catch this error in my selenium webdriver c#.Is any method which will catch this error in my test case ? There is system error or Server Error but I am unable to retrieve my error and fail my test cases. All my test cases which have these error (System/Server) end with the result = "Test Passed" instead of showing of the Error.
Eg: Click to View ServerError
Eg: Click to View System Error
[Test]
public void TestYamaha()
{
driver = new ChromeDriver();
driver.Navigate().GoToUrl("http://192.161.0.1/iels-admin-dev/Login/Login.aspx");
driver.Manage().Window.Maximize();
driver.Manage().Timeouts().ImplicitWait = TimeSpan.FromSeconds(5);
driver.FindElement(By.Id("ctl00_MainContent_ucLogin_txtUserID")).Click();
driver.FindElement(By.Id("ctl00_MainContent_ucLogin_txtUserID")).Click();
driver.FindElement(By.Id("ctl00_MainContent_ucLogin_txtUserID")).SendKeys("manteng");
driver.FindElement(By.Id("ctl00_MainContent_ucLogin_txtPassword")).SendKeys("Nic15742368");
driver.FindElement(By.Id("ctl00_MainContent_ucLogin_cmdLogin")).Click();
Thread.Sleep(2000);
driver.Navigate().GoToUrl("http://192.161.0.1/iels-admin-dev/Announcement_News/Announcement_News_Search.aspx");
Thread.Sleep(2000);
driver.FindElement(By.CssSelector(".ui-datepicker-trigger:nth-child(2)")).Click();
Thread.Sleep(2000);
driver.FindElement(By.CssSelector(".ui-icon-circle-triangle-w")).Click();
Thread.Sleep(2000);
driver.FindElement(By.LinkText("1")).Click();
Thread.Sleep(2000);
driver.FindElement(By.Id("ctl00_MainContent_cmdSubmit")).Click();
Thread.Sleep(2000);
driver.FindElement(By.CssSelector(".clsDataGridAltData a:nth-child(2) > img")).Click();
Thread.Sleep(2000);
driver.FindElement(By.Id("ctl00_MainContent_cmdSubmit")).Click();
Thread.Sleep(2000);
}
This code shows System Error (As shown in the picture) but how I show in my test case.
Use try-catch block to handle any exception and if required then you can log it in catch block. You should use any assertion library for making it pass/fail.
Note: Don't write everything into Test class.
I can only think of if the URL contain "Error", it will screenshot and fail the test case .
if (url.Contains("error") || url.Contains("Error") == true)
{
Base.ErrorMessage(driver, element); // screenshot the page
throw new SystemException("Webpage throw error");
//Console.WriteLine("Got");
}
else
{
Console.WriteLine("Passed");
}
}
I'm trying to take a screenshot on test failure.
[TearDown]
public void TearDown()
{
var status = TestContext.CurrentContext.Result.Outcome.Status;
var stackTrace = "<pre>" + TestContext.CurrentContext.Result.Message + "</pre>";
var errorMessage = TestContext.CurrentContext.Result.Message;
if (status == NUnit.Framework.Interfaces.TestStatus.Failed)
{
test.Log(LogStatus.Fail, status + errorMessage);
var ScreenShotPath = GetScreenShot.Capture(_webdriverChrome);
test.Log(LogStatus.Fail, "Screen Shot Below: "+test.AddScreenCapture(ScreenShotPath));
}
else if (status == NUnit.Framework.Interfaces.TestStatus.Passed)
{
test.Log(LogStatus.Pass, status + errorMessage);
}
extent.EndTest(test);
_webdriverChrome.Quit();}
and the capture function is
public static string Capture(IWebDriver Webdrievr)
{
string pth = System.Reflection.Assembly.GetCallingAssembly().CodeBase;
string actualPath = pth.Substring(0, pth.LastIndexOf("bin"));
string projectPath = new Uri(actualPath).LocalPath;
Screenshot ss = ((ITakesScreenshot)Webdrievr).GetScreenshot();
string screenshot = ss.AsBase64EncodedString;
byte[] screenshotAsByteArray = ss.AsByteArray;
ss.SaveAsFile(projectPath + "ErrorReportScreenshot\\ErrorScreenshot.jpeg", ScreenshotImageFormat.Jpeg); //use any of the built in image formating
string _fullPathToReturn = projectPath + "ErrorReportScreenshot";
return _fullPathToReturn;
}
I'm getting an error
Result Message:
OpenQA.Selenium.WebDriverException : The HTTP request to the remote WebDriver server for URL http://localhost:56184/session/1aaf976356898c52e5cd57d17d44df15/element timed out after 60 seconds.
----> System.Net.WebException : The operation has timed out
TearDown : OpenQA.Selenium.WebDriverException : The HTTP request to the remote WebDriver server for URL http://localhost:56184/session/1aaf976356898c52e5cd57d17d44df15/screenshot timed out after 60 seconds.
----> System.Net.WebException : The operation has timed out
The thing is that it fails taking the screenshots as long as I'm calling the capture() method from TearDown().
If I'm just calling the capture() by running it within a new test, it works like a charm.
In debugging mode, I can see it fails on this row: Screenshot ss = ((ITakesScreenshot)Webdrievr).GetScreenshot();
what am I missing?
EDIT:
I have watched the ((ITakesScreenshot)Webdrievr) and getting an error:
error CS0103: The name 'Webdrievr' does not exist in the current context
Call Stack:
> Assign_Represnt.dll!Assign_Represnt.GetScreenShot.Capture(OpenQA.Selenium.IWebDriver Webdrievr) Line 22 C#
I found the problem . for some reason the following caused all of this
var options = new ChromeOptions();
options.AddArgument("no-sandbox");
_webdriverChrome = new ChromeDriver(options);
I just used the chromedriver without options and it works now.
_webdriverChrome = new ChromeDriver();
I am having similar issue while trying to take screenshot upon test failure. I get timed out error when I try to take the screenshot on failure condition. It works fine in try block but timed out in catch block. I am not using Chrome options as the solution provided above. Any help would be appreciated.
Below is the method to take screenshot:
public class Logging
{
public static void ErrorScreenshot()
{
//Take the screenshot
Screenshot ssh = ((ITakesScreenshot)Driver.BrowserInstance).GetScreenshot();
//Save the screenshot
ssh.SaveAsFile("C:/Users/", ScreenshotImageFormat.Png);
}
}
This is my test method
public static bool FindElement
{
get
{
try
{
var element = Driver.BrowserInstance.FindElement(By.XPath(" "));
if (element != null)
{
return true;
}
}
catch (Exception ex)
{
Logging.ErrorScreenshot();
Logging.Error("Not able to find element" + ex.ToString());
}
return false;
}
}
when it is not able to find the element it goes to catch block and there Logging.ErrorScreenshot method throws a timed out exception.
Error details below:
OpenQA.Selenium.WebDriverException
HResult=0x80131500
Message=The HTTP request to the remote WebDriver server for URL http://localhost:55418/session/f3dbde1645dd91e453c5823d72199ea9/screenshot timed out after 60 seconds.
Source=WebDriver
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.GetScreenshot()
at Logging.ErrorScreenshot() in C:\Users\Logging.cs:line 66
at DashboardPage.get_Verifylogin() in C:\Users\DasboardPage.cs:line 65
at Tests() in C:\Users\SmokeTests\Tests.cs:line 33
Inner Exception 1:
WebException: The operation has timed out
I have many test cases, where I need to wait until the page is loaded. I'm using explicit wait as the load times vary.
WebDriverWait _wait = new WebDriverWait(Drivers._driverInstance, new TimeSpan(0, 2, 0));
_wait.Until(D => D.Title);
It throws No session ID exception. I have a table that takes time to load in the page, so I tried using
_wait.Until(ExpectedConditions.ElementIsVisible(By.TagName("table")));
Even this throws the same error. The tests pass when I run each one individually and running all of them as suite raises this exception.
private static void InitialUpload(string filename)
{
SDDirectPage.filePath = filename;
SDDirectPage.filename = Path.GetFileNameWithoutExtension(SDDirectPage.filePath);
SDDirectPage.UploadButton.Click();
Drivers._driverInstance.SwitchTo();
SDDirectPage.FileReference = SDDirectPage.filename;
SDDirectPage.UploadTheFile();
//Check whether 404 occurred or the uploading file is smooth
if (Drivers._driverInstance.Title == "404 - File or directory not found.") //A bug at the moment, it uploads corrupted files most of the times.
{
Assert.Fail("404 error occurred. File might be corrupted or file mightnot be in the specified location..!");
return;
}
else
{
Drivers._driverInstance.SwitchTo().ParentFrame();
// SDDirectPage._wait.Until(D => D.Title);
SDDirectPage._wait.Until(ExpectedConditions.ElementIsVisible(By.TagName("table")));
Assert.AreEqual(SDDirectPage.filename + " - SmartDebit Front End Portal", Drivers._driverInstance.Title);
}
}
This is the function where I'm getting the exception. In some test cases, I have Assert.AreEqual, where I compare the titles. In those test cases, driver.Title raises the same error.
Here is the exception:
Test FullName: SDTestAutomation.SDDirectPage_Tests.FixInvalidRows_Search
Test Source: c:\Git\AutomationTest\automationtest\AutomationTest\SDTestAutomation\SDDirectPage_Tests.cs : line 249
Test Outcome: Failed
Test Duration: 0:02:19.2199494
Result Message:
Test method SDTestAutomation.SDDirectPage_Tests.FixInvalidRows_Search threw exception:
System.InvalidOperationException: No session ID specified
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.FindElement(String mechanism, String value)
at OpenQA.Selenium.Remote.RemoteWebDriver.FindElementByTagName(String tagName)
at OpenQA.Selenium.By.<>c__DisplayClass1a.<TagName>b__18(ISearchContext context)
at OpenQA.Selenium.By.FindElement(ISearchContext context)
at OpenQA.Selenium.Remote.RemoteWebDriver.FindElement(By by)
at OpenQA.Selenium.Support.UI.ExpectedConditions.<>c__DisplayClass13.<ElementIsVisible>b__12(IWebDriver driver)
at OpenQA.Selenium.Support.UI.DefaultWait`1.Until[TResult](Func`2 condition)
at SDTestAutomation.SDDirectPage_Tests.InitialUpload(String filename) in c:\Git\AutomationTest\automationtest\AutomationTest\SDTestAutomation\SDDirectPage_Tests.cs:line 483
at SDTestAutomation.SDDirectPage_Tests.FixInvalidRows_Search() in c:\Git\AutomationTest\automationtest\AutomationTest\SDTestAutomation\SDDirectPage_Tests.cs:line 250
Here is the drivers class:
public class Drivers
{
static string path = #"C:\SmartDebit\SmartDebitTestAutomation\SmartDebitFramework\DriverResources\";
public static IWebDriver _driverInstance { get; set; }
public static void Initialize(string browser)
{
if (browser == "FF")
{
_driverInstance = new FirefoxDriver();
_driverInstance.Manage().Timeouts().ImplicitlyWait(TimeSpan.FromSeconds(5000));
}
if (browser == "IE")
{
_driverInstance = new InternetExplorerDriver(path);
_driverInstance.Manage().Timeouts().ImplicitlyWait(TimeSpan.FromSeconds(5000));
}
if (browser == "Chrome")
{
_driverInstance = new ChromeDriver(path);
_driverInstance.Manage().Timeouts().ImplicitlyWait(TimeSpan.FromSeconds(5000));
}
}
}
Code for initialising the browser instance:
[ClassInitialize]
public static void BrowserInstance(TestContext t)
{
loginPage = new LoginPage();
loginPage.Init("FF");
loginPage.Goto("url of the application");
Assert.AreEqual("Login Page", Drivers._driverInstance.Title, "Login page titles doesn't match");
}
[TestInitialize]
public void Init()
{
try
{
Login();
}
catch (Exception ex)
{
Console.WriteLine("Exception:" + ex);
Assert.Fail("ValidLogin() test failed in HomePage_Tests.cs");
loginPage.QuitBrowser();
}
}
private static void Login()
{
loginPage.LoginName = "username";
loginPage.Password = "password";
loginPage.LoginButton();
SDDirectPage._wait.Until(d=>Drivers._driverInstance.Title);
Assert.AreEqual("Home Page - Front End Portal", Drivers._driverInstance.Title, "Home page title doesn't match");
Assert.IsTrue(HomePage.loggedInUserText.Contains("username"));
}
I'm using Firefox 43.0.2
Could someone help be to overcome this situation.
Thanks.
System.InvalidOperationException: No session ID specified occurs when you don't have valid driver instance in the method.
Please check Drivers._driverInstance is properly instantiated in your code. If possible post the Drivers class' relevant portions in the question.
Refer another SO question where the same problem is discussed: Disabling browser javascript with Selenium webdriver + specflow + c# + Pageobject + pagefactory
I am basically from Java, but observing the code and exception, i am excepting WebDriverWait is defined in SDDirectPage and calling here.right?
SDDirectPage._wait.Until(ExpectedConditions.ElementIsVisible(By.TagName("table")));
When you are calling defined wait method, you are not passing webdriver instance here. So i am expecting on switching to this method driver loosing the session. For sake of confirm, can you try executing the same by commenting this wait line (and my use something equivalent to Thread.sleep(5000) in Java for once to check this issue)
Thanks
I wrote code in C# use Selenium which tests functional. The goal is to put some text in a field, press a button and wait until the site after few times show additional forms. But my code works very strangely. If time very short: it works perfectly. But if the time is more than 30 sec, it throws exception. Here is part of my code, which wait when page loaded by Ajax data and show in the page:
while (true)
{
try
{
driver.Manage().Timeouts().ImplicitlyWait(TimeSpan.FromSeconds(5));
IWebElement myDynamicElement = driver.FindElement(By.Id("smapxml"));
Console.WriteLine("Done");
if (myDynamicElement != null)
{
Console.WriteLine("Ok. Element not null. Follow next step.");
break;
}
}
catch (Exception error)
{
Console.WriteLine("error."+error.ToString());
return;
}
}
Exception:
OpenQA.Selenium.NoSuchElementException: Unable to locate element: {"method":"id","selector":"smapxml"}
in OpenQA.Selenium.Remote.RemoteWebDriver.UnpackAndThrowOnError(Response errorResponse) in c:\Projects\webdriver\dotnet\src\webdriver\Remote\RemoteWebDriver.cs:line 1092
So how do I fix this?
To explain the title.. Selenium RC keeps insisting that
A system shutdown has already been scheduled
and refusing to conduct automated tests because of this.. I can understand the logic here, I mean you're not going to do your homework if you thought the world would end with a nuclear holocaust...
However.. this is not the Cold War and when I inspect several basic things (such as using shutdown \a, completing a full restart) I find that this is actually not the case!
How can I convince selenium that the world is not going to end and that it should probably do the work I'm telling it to?
N.B. Here, selenium has "refused" to initialise any instance of IE, and will continue to hang until it times out, regardless of clicking Yes or No. I'm using NUnit, c#/.net4.0 to control the tests.
To fix this I replaced the default "runSeleniumTest" function with the below patched version as a user extension:
function runSeleniumTest() {
runOptions = new RemoteRunnerOptions();
var testAppWindow;
if (runOptions.isMultiWindowMode()) {
try{
testAppWindow = openSeparateApplicationWindow('Blank.html', true);
}
catch (e) {
window.onunload = function () { };
window.location.reload();
return;
}
} else if (sel$('selenium_myiframe') != null) {
var myiframe = sel$('selenium_myiframe');
if (myiframe) {
testAppWindow = myiframe.contentWindow;
}
}
else {
proxyInjectionMode = true;
testAppWindow = window;
}
selenium = Selenium.createForWindow(testAppWindow, proxyInjectionMode);
if (runOptions.getBaseUrl()) {
selenium.browserbot.baseUrl = runOptions.getBaseUrl();
}
if (!debugMode) {
debugMode = runOptions.isDebugMode();
}
if (proxyInjectionMode) {
LOG.logHook = logToRc;
selenium.browserbot._modifyWindow(testAppWindow);
}
else if (debugMode) {
LOG.logHook = logToRc;
}
window.selenium = selenium;
commandFactory = new CommandHandlerFactory();
commandFactory.registerAll(selenium);
currentTest = new RemoteRunner(commandFactory);
var doContinue = runOptions.getContinue();
if (doContinue != null) postResult = "OK";
currentTest.start();
}
I found that the "a system shutdown has already been scheduled" error occurred inside of "openSeparateApplicationWindow". I also found that refreshing the selenium test runner window after the error occurred would "restart" the test without the error. Therefore, I patched the "runSeleniumTest" with the following try catch statement so the test runner window reloads if there's an error in "openSeparateApplicationWindow":
try{
testAppWindow = openSeparateApplicationWindow('Blank.html', true);
}
catch (e) {
window.onunload = function () { };
window.location.reload();
return;
}
I also used my blog post for a more specific example of selenium user extensions
Selenium isn't doing anything in this case. That's the IE HTA agent (a built-in Windows process) that's preventing you from doing anything. Perhaps rebooting the machine will do the trick? It looks like you may just have a pending Windows update that's scheduled a future reboot.